diff --git a/background.js b/background.js index 1e605b4..ca6482b 100644 --- a/background.js +++ b/background.js @@ -18,12 +18,17 @@ importScripts( 'background/logging-status.js', 'background/steps/registry.js', 'data/step-definitions.js', + 'data/address-sources.js', 'background/steps/open-chatgpt.js', 'background/steps/submit-signup-email.js', 'background/steps/fill-password.js', 'background/steps/fetch-signup-code.js', 'background/steps/fill-profile.js', 'background/steps/clear-login-cookies.js', + 'background/steps/create-plus-checkout.js', + 'background/steps/fill-plus-checkout.js', + 'background/steps/paypal-approve.js', + 'background/steps/plus-return-confirm.js', 'background/steps/oauth-login.js', 'background/steps/fetch-login-code.js', 'background/steps/confirm-oauth.js', @@ -37,12 +42,28 @@ importScripts( 'content/activation-utils.js' ); -const SHARED_STEP_DEFINITIONS = self.MultiPageStepDefinitions?.getSteps?.() || []; -const STEP_IDS = SHARED_STEP_DEFINITIONS +const NORMAL_STEP_DEFINITIONS = self.MultiPageStepDefinitions?.getSteps?.({ plusModeEnabled: false }) || []; +const PLUS_STEP_DEFINITIONS = self.MultiPageStepDefinitions?.getSteps?.({ plusModeEnabled: true }) || NORMAL_STEP_DEFINITIONS; +const ALL_STEP_DEFINITIONS = self.MultiPageStepDefinitions?.getAllSteps?.() || [ + ...NORMAL_STEP_DEFINITIONS, + ...PLUS_STEP_DEFINITIONS, +]; +const STEP_IDS = Array.from(new Set(ALL_STEP_DEFINITIONS + .map((definition) => Number(definition?.id)) + .filter(Number.isFinite))) + .sort((left, right) => left - right); +const NORMAL_STEP_IDS = NORMAL_STEP_DEFINITIONS .map((definition) => Number(definition?.id)) .filter(Number.isFinite) .sort((left, right) => left - right); -const LAST_STEP_ID = STEP_IDS[STEP_IDS.length - 1] || 10; +const PLUS_STEP_IDS = PLUS_STEP_DEFINITIONS + .map((definition) => Number(definition?.id)) + .filter(Number.isFinite) + .sort((left, right) => left - right); +const LAST_STEP_ID = Math.max( + NORMAL_STEP_IDS[NORMAL_STEP_IDS.length - 1] || 10, + PLUS_STEP_IDS[PLUS_STEP_IDS.length - 1] || 10 +); const FINAL_OAUTH_CHAIN_START_STEP = 7; const { @@ -218,6 +239,32 @@ const CONTRIBUTION_RUNTIME_DEFAULTS = self.MultiPageBackgroundContributionOAuth? const CONTRIBUTION_RUNTIME_KEYS = self.MultiPageBackgroundContributionOAuth?.RUNTIME_KEYS || Object.keys(CONTRIBUTION_RUNTIME_DEFAULTS); +function isPlusModeState(state = {}) { + return Boolean(state?.plusModeEnabled); +} + +function getStepDefinitionsForState(state = {}) { + return isPlusModeState(state) ? PLUS_STEP_DEFINITIONS : NORMAL_STEP_DEFINITIONS; +} + +function getStepIdsForState(state = {}) { + return isPlusModeState(state) ? PLUS_STEP_IDS : NORMAL_STEP_IDS; +} + +function getLastStepIdForState(state = {}) { + const ids = getStepIdsForState(state); + return ids[ids.length - 1] || 10; +} + +function getAuthChainStartStepId(state = {}) { + return isPlusModeState(state) ? 10 : FINAL_OAUTH_CHAIN_START_STEP; +} + +function getStepDefinitionForState(step, state = {}) { + const numericStep = Number(step); + return getStepDefinitionsForState(state).find((definition) => Number(definition.id) === numericStep) || null; +} + initializeSessionStorageAccess(); setupDeclarativeNetRequestRules(); @@ -264,6 +311,9 @@ const PERSISTED_SETTING_DEFAULTS = { codex2apiUrl: DEFAULT_CODEX2API_URL, codex2apiAdminKey: '', customPassword: '', + plusModeEnabled: false, + paypalEmail: '', + paypalPassword: '', autoRunSkipFailures: false, autoRunFallbackThreadIntervalMinutes: 0, autoRunDelayEnabled: false, @@ -350,6 +400,14 @@ const DEFAULT_STATE = { sub2apiProxyId: null, // SUB2API 本轮使用的代理 ID。 codex2apiSessionId: null, // Codex2API OAuth 会话 ID。 codex2apiOAuthState: null, // Codex2API OAuth state。 + plusCheckoutTabId: null, // Plus checkout / PayPal 标签页 ID。 + plusCheckoutUrl: null, // Plus checkout 运行时短链,不写入持久配置。 + plusCheckoutCountry: 'DE', + plusCheckoutCurrency: 'EUR', + plusBillingCountryText: '', + plusBillingAddress: null, + plusPaypalApprovedAt: null, + plusReturnUrl: '', flowStartTime: null, // 当前流程开始时间。 tabRegistry: {}, // 程序维护的标签页注册表。 sourceLastUrls: {}, // 各来源页面最近一次打开的地址记录。 @@ -973,9 +1031,14 @@ function normalizePersistentSettingValue(key, value) { return String(value || '').trim(); case 'customPassword': return String(value || ''); + case 'paypalEmail': + return String(value || '').trim(); + case 'paypalPassword': + return String(value || ''); case 'autoRunSkipFailures': case 'autoRunDelayEnabled': case 'phoneVerificationEnabled': + case 'plusModeEnabled': return Boolean(value); case 'autoRunFallbackThreadIntervalMinutes': return normalizeAutoRunFallbackThreadIntervalMinutes(value); @@ -1138,7 +1201,7 @@ async function getState() { getPersistedAliasState(), accountRunHistoryHelpers?.getPersistedAccountRunHistory?.() || [], ]); - return { ...DEFAULT_STATE, ...persistedSettings, ...persistedAliasState, accountRunHistory, ...state }; + return { ...DEFAULT_STATE, ...persistedSettings, ...persistedAliasState, ...state, accountRunHistory }; } async function initializeSessionStorageAccess() { @@ -3968,6 +4031,21 @@ async function waitForTabUrlMatch(tabId, matcher, options = {}) { return tabRuntime.waitForTabUrlMatch(tabId, matcher, options); } +async function waitForTabUrlMatchUntilStopped(tabId, matcher, options = {}) { + const retryDelayMs = Math.max(100, Math.floor(Number(options.retryDelayMs) || 300)); + while (true) { + throwIfStopped(); + const tab = await chrome.tabs.get(tabId).catch(() => null); + if (!tab) { + throw new Error('目标标签页已关闭,无法继续等待页面跳转。'); + } + if (typeof matcher === 'function' && matcher(tab.url || '', tab)) { + return tab; + } + await sleepWithStop(retryDelayMs); + } +} + async function waitForTabComplete(tabId, options = {}) { return tabRuntime.waitForTabComplete(tabId, options); } @@ -3976,10 +4054,78 @@ async function waitForTabStableComplete(tabId, options = {}) { return tabRuntime.waitForTabStableComplete(tabId, options); } +async function waitForTabCompleteUntilStopped(tabId, options = {}) { + const retryDelayMs = Math.max(100, Math.floor(Number(options.retryDelayMs) || 300)); + while (true) { + throwIfStopped(); + const tab = await chrome.tabs.get(tabId).catch(() => null); + if (!tab) { + throw new Error('目标标签页已关闭,无法继续等待页面加载完成。'); + } + if (tab.status === 'complete') { + return tab; + } + await sleepWithStop(retryDelayMs); + } +} + async function ensureContentScriptReadyOnTab(source, tabId, options = {}) { return tabRuntime.ensureContentScriptReadyOnTab(source, tabId, options); } +async function ensureContentScriptReadyOnTabUntilStopped(source, tabId, options = {}) { + const { + inject = null, + injectSource = null, + retryDelayMs = 700, + logMessage = '', + } = options; + let logged = false; + + while (true) { + throwIfStopped(); + const pong = await pingContentScriptOnTab(tabId); + if (pong?.ok && (!pong.source || pong.source === source)) { + await registerTab(source, tabId); + return; + } + + if (!inject || !inject.length) { + throw new Error(`${getSourceLabel(source)} 内容脚本未就绪,且未提供可用的注入文件。`); + } + + try { + if (injectSource) { + await chrome.scripting.executeScript({ + target: { tabId }, + func: (injectedSource) => { + window.__MULTIPAGE_SOURCE = injectedSource; + }, + args: [injectSource], + }); + } + await chrome.scripting.executeScript({ + target: { tabId }, + files: inject, + }); + } catch (error) { + console.warn(LOG_PREFIX, `[ensureContentScriptReadyOnTabUntilStopped] inject failed for ${source}:`, error?.message || error); + } + + const pongAfterInject = await pingContentScriptOnTab(tabId); + if (pongAfterInject?.ok && (!pongAfterInject.source || pongAfterInject.source === source)) { + await registerTab(source, tabId); + return; + } + + if (logMessage && !logged) { + logged = true; + await addLog(logMessage, 'warn'); + } + await sleepWithStop(retryDelayMs); + } +} + // ============================================================ // Command Queue (for content scripts not yet ready) // ============================================================ @@ -4002,6 +4148,21 @@ function sendTabMessageWithTimeout(tabId, source, message, responseTimeoutMs = g return tabRuntime.sendTabMessageWithTimeout(tabId, source, message, responseTimeoutMs); } +async function sendTabMessageUntilStopped(tabId, source, message, options = {}) { + const retryDelayMs = Math.max(100, Math.floor(Number(options.retryDelayMs) || 300)); + while (true) { + throwIfStopped(); + try { + return await chrome.tabs.sendMessage(tabId, message); + } catch (error) { + if (!isRetryableContentScriptTransportError(error)) { + throw error; + } + await sleepWithStop(retryDelayMs); + } + } +} + function queueCommand(source, message, timeout = 15000) { return tabRuntime.queueCommand(source, message, timeout); } @@ -4095,6 +4256,8 @@ function getSourceLabel(source) { 'hotmail-api': 'Hotmail(API对接/本地助手)', 'luckmail-api': 'LuckMail(API 购邮)', 'cloudflare-temp-email': 'Cloudflare Temp Email', + 'plus-checkout': 'Plus Checkout', + 'paypal-flow': 'PayPal 授权页', }; return labels[source] || source || '未知来源'; } @@ -4257,7 +4420,6 @@ function getLoginAuthStateLabel(state) { if (typeof loggingStatus !== 'undefined' && loggingStatus?.getLoginAuthStateLabel) { return loggingStatus.getLoginAuthStateLabel(state); } - state = state === 'oauth_consent_page' ? 'unknown' : state; switch (state) { case 'verification_page': return '登录验证码页'; case 'password_page': return '密码页'; @@ -4300,26 +4462,46 @@ function isStepDoneStatus(status) { return status === 'completed' || status === 'manual_completed' || status === 'skipped'; } -function getFirstUnfinishedStep(statuses = {}) { - if (typeof loggingStatus !== 'undefined' && loggingStatus?.getFirstUnfinishedStep) { - return loggingStatus.getFirstUnfinishedStep(statuses); - } - for (const step of STEP_IDS) { +function getFirstUnfinishedStep(statuses = {}, stateOverride = null) { + const state = stateOverride || {}; + const activeStepIds = typeof getStepIdsForState === 'function' + ? getStepIdsForState(state) + : (typeof STEP_IDS !== 'undefined' && Array.isArray(STEP_IDS) && STEP_IDS.length + ? STEP_IDS + : Array.from({ length: typeof LAST_STEP_ID === 'number' ? LAST_STEP_ID : 10 }, (_, index) => index + 1)); + for (const step of activeStepIds) { if (!isStepDoneStatus(statuses[step] || 'pending')) return step; } return null; } -function hasSavedProgress(statuses = {}) { - if (typeof loggingStatus !== 'undefined' && loggingStatus?.hasSavedProgress) { - return loggingStatus.hasSavedProgress(statuses); - } - return Object.values({ ...DEFAULT_STATE.stepStatuses, ...statuses }).some((status) => status !== 'pending'); +function hasSavedProgress(statuses = {}, stateOverride = null) { + const state = stateOverride || {}; + const merged = { ...DEFAULT_STATE.stepStatuses, ...statuses }; + const activeStepIds = typeof getStepIdsForState === 'function' + ? getStepIdsForState(state) + : (typeof STEP_IDS !== 'undefined' && Array.isArray(STEP_IDS) && STEP_IDS.length + ? STEP_IDS + : Array.from({ length: typeof LAST_STEP_ID === 'number' ? LAST_STEP_ID : 10 }, (_, index) => index + 1)); + return activeStepIds.some((step) => (merged[step] || 'pending') !== 'pending'); } -function getDownstreamStateResets(step) { +function getDownstreamStateResets(step, state = {}) { + const stepKey = getStepExecutionKeyForState(step, state); + const plusRuntimeResets = { + plusCheckoutTabId: null, + plusCheckoutUrl: null, + plusCheckoutCountry: 'DE', + plusCheckoutCurrency: 'EUR', + plusBillingCountryText: '', + plusBillingAddress: null, + plusPaypalApprovedAt: null, + plusReturnUrl: '', + }; + if (step <= 1) { return { + ...plusRuntimeResets, oauthUrl: null, sub2apiSessionId: null, sub2apiOAuthState: null, @@ -4341,6 +4523,7 @@ function getDownstreamStateResets(step) { } if (step === 2) { return { + ...plusRuntimeResets, password: null, lastEmailTimestamp: null, signupVerificationRequestedAt: null, @@ -4354,6 +4537,7 @@ function getDownstreamStateResets(step) { } if (step === 3 || step === 4) { return { + ...plusRuntimeResets, lastEmailTimestamp: null, signupVerificationRequestedAt: null, loginVerificationRequestedAt: null, @@ -4366,6 +4550,17 @@ function getDownstreamStateResets(step) { } if (step === 5 || step === 6 || step === 7 || step === 8) { return { + ...(step <= 6 ? plusRuntimeResets : {}), + ...(step === 7 ? { + plusBillingCountryText: '', + plusBillingAddress: null, + plusPaypalApprovedAt: null, + plusReturnUrl: '', + } : {}), + ...(step === 8 ? { + plusPaypalApprovedAt: null, + plusReturnUrl: '', + } : {}), lastLoginCode: null, loginVerificationRequestedAt: null, oauthFlowDeadlineAt: null, @@ -4374,6 +4569,21 @@ function getDownstreamStateResets(step) { }; } if (step === 9) { + return { + plusReturnUrl: '', + localhostUrl: null, + }; + } + if (stepKey === 'oauth-login' || stepKey === 'fetch-login-code') { + return { + lastLoginCode: null, + loginVerificationRequestedAt: null, + oauthFlowDeadlineAt: null, + oauthFlowDeadlineSourceUrl: null, + localhostUrl: null, + }; + } + if (stepKey === 'confirm-oauth') { return { localhostUrl: null, }; @@ -4387,7 +4597,15 @@ async function invalidateDownstreamAfterStepRestart(step, options = {}) { const statuses = { ...(state.stepStatuses || {}) }; const changedSteps = []; - for (let downstream = step + 1; downstream <= LAST_STEP_ID; downstream++) { + const activeStepIds = typeof getStepIdsForState === 'function' + ? getStepIdsForState(state) + : (typeof STEP_IDS !== 'undefined' && Array.isArray(STEP_IDS) && STEP_IDS.length + ? STEP_IDS + : Array.from({ length: typeof LAST_STEP_ID === 'number' ? LAST_STEP_ID : 10 }, (_, index) => index + 1)); + for (const downstream of activeStepIds) { + if (downstream <= step) { + continue; + } if (statuses[downstream] !== 'pending') { statuses[downstream] = 'pending'; changedSteps.push(downstream); @@ -4405,7 +4623,7 @@ async function invalidateDownstreamAfterStepRestart(step, options = {}) { await addLog(`${logLabel},已重置后续步骤状态:${changedSteps.join(', ')}`, 'warn'); } - const resets = getDownstreamStateResets(step); + const resets = getDownstreamStateResets(step, state); if (Object.keys(resets).length) { await setState(resets); broadcastDataUpdate(resets); @@ -4416,22 +4634,26 @@ function clearStopRequest() { stopRequested = false; } -function getRunningSteps(statuses = {}) { - if (typeof loggingStatus !== 'undefined' && loggingStatus?.getRunningSteps) { - return loggingStatus.getRunningSteps(statuses); - } - return Object.entries({ ...DEFAULT_STATE.stepStatuses, ...statuses }) - .filter(([, status]) => status === 'running') - .map(([step]) => Number(step)) +function getRunningSteps(statuses = {}, stateOverride = null) { + const state = stateOverride || {}; + const merged = { ...DEFAULT_STATE.stepStatuses, ...statuses }; + const activeStepIds = typeof getStepIdsForState === 'function' + ? getStepIdsForState(state) + : (typeof STEP_IDS !== 'undefined' && Array.isArray(STEP_IDS) && STEP_IDS.length + ? STEP_IDS + : Array.from({ length: typeof LAST_STEP_ID === 'number' ? LAST_STEP_ID : 10 }, (_, index) => index + 1)); + return activeStepIds + .filter((step) => merged[step] === 'running') .sort((a, b) => a - b); } function inferStoppedRecordStep(state = {}) { const statuses = { ...DEFAULT_STATE.stepStatuses, ...(state?.stepStatuses || {}) }; - const stepIds = Object.keys(statuses) - .map((step) => Number(step)) - .filter(Number.isFinite) - .sort((left, right) => left - right); + const stepIds = typeof getStepIdsForState === 'function' + ? getStepIdsForState(state) + : (typeof STEP_IDS !== 'undefined' && Array.isArray(STEP_IDS) && STEP_IDS.length + ? STEP_IDS + : Array.from({ length: typeof LAST_STEP_ID === 'number' ? LAST_STEP_ID : 10 }, (_, index) => index + 1)); const runningSteps = stepIds.filter((step) => statuses[step] === 'running'); if (runningSteps.length) { @@ -4932,8 +5154,13 @@ async function ensureManualInteractionAllowed(actionLabel) { async function skipStep(step) { const state = await ensureManualInteractionAllowed('跳过步骤'); + const activeStepIds = typeof getStepIdsForState === 'function' + ? getStepIdsForState(state) + : (typeof STEP_IDS !== 'undefined' && Array.isArray(STEP_IDS) && STEP_IDS.length + ? STEP_IDS + : Array.from({ length: typeof LAST_STEP_ID === 'number' ? LAST_STEP_ID : 10 }, (_, index) => index + 1)); - if (!Number.isInteger(step) || !STEP_IDS.includes(step)) { + if (!Number.isInteger(step) || !activeStepIds.includes(step)) { throw new Error(`无效步骤:${step}`); } @@ -4946,10 +5173,12 @@ async function skipStep(step) { throw new Error(`步骤 ${step} 已完成,无需再跳过。`); } - if (step > 1) { - const prevStatus = statuses[step - 1]; + const currentIndex = activeStepIds.indexOf(step); + if (currentIndex > 0) { + const prevStep = activeStepIds[currentIndex - 1]; + const prevStatus = statuses[prevStep]; if (!isStepDoneStatus(prevStatus)) { - throw new Error(`请先完成步骤 ${step - 1},再跳过步骤 ${step}。`); + throw new Error(`请先完成步骤 ${prevStep},再跳过步骤 ${step}。`); } } @@ -5220,7 +5449,25 @@ const stepWaiters = new Map(); let resumeWaiter = null; const AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS = 120000; const AUTO_RUN_BACKGROUND_COMPLETED_STEPS = new Set([1, 2, 4, 6, 7, 8, 9]); -const STEP_COMPLETION_SIGNAL_STEPS = new Set([3, 5, 10]); +const STEP_COMPLETION_SIGNAL_STEPS = new Set([3, 5, 10, 12]); +const AUTO_RUN_BACKGROUND_COMPLETED_STEP_KEYS = new Set([ + 'open-chatgpt', + 'submit-signup-email', + 'fetch-signup-code', + 'clear-login-cookies', + 'plus-checkout-create', + 'plus-checkout-billing', + 'paypal-approve', + 'plus-checkout-return', + 'oauth-login', + 'fetch-login-code', + 'confirm-oauth', +]); +const STEP_COMPLETION_SIGNAL_STEP_KEYS = new Set([ + 'fill-password', + 'fill-profile', + 'platform-verify', +]); function waitForStepComplete(step, timeoutMs = 120000) { return new Promise((resolve, reject) => { @@ -5242,7 +5489,26 @@ function waitForStepComplete(step, timeoutMs = 120000) { }); } -function doesStepUseCompletionSignal(step) { +function getStepExecutionKeyForState(step, state = {}) { + if (typeof getStepDefinitionForState !== 'function') { + return ''; + } + return String(getStepDefinitionForState(step, state)?.key || '').trim(); +} + +function doesStepUseBackgroundCompletion(step, state = {}) { + const stepKey = getStepExecutionKeyForState(step, state); + if (stepKey) { + return AUTO_RUN_BACKGROUND_COMPLETED_STEP_KEYS.has(stepKey); + } + return AUTO_RUN_BACKGROUND_COMPLETED_STEPS.has(step); +} + +function doesStepUseCompletionSignal(step, state = {}) { + const stepKey = getStepExecutionKeyForState(step, state); + if (stepKey) { + return STEP_COMPLETION_SIGNAL_STEP_KEYS.has(stepKey); + } return STEP_COMPLETION_SIGNAL_STEPS.has(step); } @@ -5266,11 +5532,15 @@ async function completeStepFromBackground(step, payload = {}) { return; } - const completionState = step === LAST_STEP_ID ? await getState() : null; + const latestState = await getState(); + const lastStepId = typeof getLastStepIdForState === 'function' + ? getLastStepIdForState(latestState) + : (typeof LAST_STEP_ID === 'number' ? LAST_STEP_ID : 10); + const completionState = step === lastStepId ? latestState : null; await setStepStatus(step, 'completed'); await addLog(`步骤 ${step} 已完成`, 'ok'); await handleStepData(step, payload); - if (step === LAST_STEP_ID) { + if (step === lastStepId) { await appendAndBroadcastAccountRunRecord('success', completionState); } notifyStepComplete(step, payload); @@ -5349,7 +5619,7 @@ async function executeStepViaCompletionSignal(step, timeoutMs = AUTO_RUN_SIGNAL_ async function waitForRunningStepsToFinish(payload = {}) { let currentState = await getState(); - let runningSteps = getRunningSteps(currentState.stepStatuses); + let runningSteps = getRunningSteps(currentState.stepStatuses, currentState); if (!runningSteps.length) { return currentState; } @@ -5360,23 +5630,35 @@ async function waitForRunningStepsToFinish(payload = {}) { while (runningSteps.length) { await sleepWithStop(250); currentState = await getState(); - runningSteps = getRunningSteps(currentState.stepStatuses); + runningSteps = getRunningSteps(currentState.stepStatuses, currentState); } await addLog('自动继续:当前运行步骤已结束,准备按最新进度继续自动流程...', 'info'); return currentState; } -const AUTH_CHAIN_STEP_IDS = new Set([7, 8, 9, 10]); +const AUTH_CHAIN_STEP_IDS = new Set([7, 8, 9, 10, 11, 12, 13]); +const AUTH_CHAIN_STEP_KEYS = new Set([ + 'oauth-login', + 'fetch-login-code', + 'confirm-oauth', + 'platform-verify', +]); let activeTopLevelAuthChainExecution = null; -function isAuthChainStep(step) { +function isAuthChainStep(step, state = {}) { + const stepKey = typeof getStepDefinitionForState === 'function' + ? String(getStepDefinitionForState(step, state)?.key || '').trim() + : ''; + if (stepKey && typeof AUTH_CHAIN_STEP_KEYS !== 'undefined') { + return AUTH_CHAIN_STEP_KEYS.has(stepKey); + } return AUTH_CHAIN_STEP_IDS.has(Number(step)); } -async function acquireTopLevelAuthChainExecution(step) { +async function acquireTopLevelAuthChainExecution(step, state = {}) { const normalizedStep = Number(step); - if (!isAuthChainStep(normalizedStep)) { + if (!isAuthChainStep(normalizedStep, state)) { return { joined: false, release() {}, @@ -5422,7 +5704,7 @@ async function acquireTopLevelAuthChainExecution(step) { async function markRunningStepsStopped() { const state = await getState(); - const runningSteps = getRunningSteps(state.stepStatuses); + const runningSteps = getRunningSteps(state.stepStatuses, state); for (const step of runningSteps) { await setStepStatus(step, 'stopped'); @@ -5432,7 +5714,7 @@ async function markRunningStepsStopped() { async function requestStop(options = {}) { const { logMessage = '已收到停止请求,正在取消当前操作...' } = options; const state = await getState(); - const runningSteps = getRunningSteps(state.stepStatuses); + const runningSteps = getRunningSteps(state.stepStatuses, state); const inferredStopStep = inferStoppedRecordStep(state); const timerPlan = getPendingAutoRunTimerPlan(state); @@ -5516,7 +5798,8 @@ async function requestStop(options = {}) { async function executeStep(step, options = {}) { const { deferRetryableTransportError = false } = options; console.log(LOG_PREFIX, `Executing step ${step}`); - const authChainClaim = await acquireTopLevelAuthChainExecution(step); + let state = await getState(); + const authChainClaim = await acquireTopLevelAuthChainExecution(step, state); if (authChainClaim.joined) { return; } @@ -5528,21 +5811,29 @@ async function executeStep(step, options = {}) { await addLog(`步骤 ${step} 开始执行`); await humanStepDelay(); - const state = await getState(); + state = await getState(); // Set flow start time on first step if (step === 1 && !state.flowStartTime) { await setState({ flowStartTime: Date.now() }); } - await stepRegistry.executeStep(step, state); + const activeStepRegistry = getStepRegistryForState(state); + if (!activeStepRegistry?.getStepDefinition?.(step)) { + throw new Error(`当前模式下不存在步骤:${step}`); + } + await activeStepRegistry.executeStep(step, { + ...state, + visibleStep: Number(step), + stepDefinition: getStepDefinitionForState(step, state), + }); } catch (err) { executionError = err; - const state = await getState(); + const errorState = await getState(); if (isStopError(err)) { await setStepStatus(step, 'stopped'); await addLog(`步骤 ${step} 已被用户停止`, 'warn'); - await appendManualAccountRunRecordIfNeeded(`step${step}_stopped`, state, getErrorMessage(err)); + await appendManualAccountRunRecordIfNeeded(`step${step}_stopped`, errorState, getErrorMessage(err)); throw err; } if (isTerminalSecurityBlockedError(err)) { @@ -5553,10 +5844,10 @@ async function executeStep(step, options = {}) { await handleBrowserSwitchRequired(err); throw new Error(STOP_ERROR_MESSAGE); } - if (!(deferRetryableTransportError && doesStepUseCompletionSignal(step) && isRetryableContentScriptTransportError(err))) { + if (!(deferRetryableTransportError && doesStepUseCompletionSignal(step, errorState) && isRetryableContentScriptTransportError(err))) { await setStepStatus(step, 'failed'); await addLog(`步骤 ${step} 失败:${err.message}`, 'error'); - await appendManualAccountRunRecordIfNeeded(`step${step}_failed`, state, getErrorMessage(err)); + await appendManualAccountRunRecordIfNeeded(`step${step}_failed`, errorState, getErrorMessage(err)); } else { console.warn( LOG_PREFIX, @@ -5586,12 +5877,13 @@ async function executeStepAndWait(step, delayAfter = 2000) { await sleepWithStop(delaySeconds * 1000); } - if (AUTO_RUN_BACKGROUND_COMPLETED_STEPS.has(step)) { + const executionState = await getState(); + if (doesStepUseBackgroundCompletion(step, executionState)) { await addLog(`自动运行:步骤 ${step} 由后台流程负责收尾,执行函数返回后将直接进入下一步。`, 'info'); await executeStep(step); const latestState = await getState(); await addLog(`自动运行:步骤 ${step} 已执行返回,当前状态为 ${latestState.stepStatuses?.[step] || 'pending'},准备继续后续步骤。`, 'info'); - } else if (doesStepUseCompletionSignal(step)) { + } else if (doesStepUseCompletionSignal(step, executionState)) { await addLog(`自动运行:步骤 ${step} 已发起,正在等待完成信号(超时 ${AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS / 1000} 秒)。`, 'info'); await executeStepViaCompletionSignal(step, AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS); await addLog(`自动运行:步骤 ${step} 已收到完成信号,准备继续后续步骤。`, 'info'); @@ -6272,8 +6564,14 @@ async function runAutoSequenceFromStep(startStep, context = {}) { let restartFromStep1WithCurrentEmail = false; let step = Math.max(currentStartStep, 4); - while (step <= LAST_STEP_ID) { + while (step <= (typeof getLastStepIdForState === 'function' + ? getLastStepIdForState(await getState()) + : (typeof LAST_STEP_ID === 'number' ? LAST_STEP_ID : 10))) { const latestState = await getState(); + if (typeof getStepDefinitionForState === 'function' && !getStepDefinitionForState(step, latestState)) { + step += 1; + continue; + } const currentStatus = latestState.stepStatuses?.[step] || 'pending'; if (isStepDoneStatus(currentStatus)) { await addLog(`自动运行:步骤 ${step} 当前状态为 ${currentStatus},将直接继续后续流程。`, 'info'); @@ -6323,6 +6621,11 @@ async function runAutoSequenceFromStep(startStep, context = {}) { const restartDecision = await getPostStep6AutoRestartDecision(step, err); if (restartDecision.shouldRestart) { postStep7RestartCount += 1; + const restartStep = restartDecision.restartStep + || (typeof getAuthChainStartStepId === 'function' + ? getAuthChainStartStepId(await getState()) + : FINAL_OAUTH_CHAIN_START_STEP); + const resetAfterStep = Math.max(1, restartStep - 1); const authState = restartDecision.authState; const authStateLabel = authState?.state ? getLoginAuthStateLabel(authState.state) : '未知页面'; const authStateSuffix = authState?.url @@ -6331,19 +6634,22 @@ async function runAutoSequenceFromStep(startStep, context = {}) { ? `当前认证页:${authStateLabel}` : '未获取到认证页状态'; await addLog( - `步骤 ${step}:检测到报错且当前未进入 add-phone,正在回到步骤 7 重新开始授权流程(第 ${postStep7RestartCount} 次重开)。${authStateSuffix};原因:${restartDecision.errorMessage || '未知错误'}`, + `步骤 ${step}:检测到报错且当前未进入 add-phone,正在回到步骤 ${restartStep} 重新开始授权流程(第 ${postStep7RestartCount} 次重开)。${authStateSuffix};原因:${restartDecision.errorMessage || '未知错误'}`, 'warn' ); - await invalidateDownstreamAfterStepRestart(6, { - logLabel: `步骤 ${step} 报错后准备回到步骤 7 重试(第 ${postStep7RestartCount} 次重开)`, + await invalidateDownstreamAfterStepRestart(resetAfterStep, { + logLabel: `步骤 ${step} 报错后准备回到步骤 ${restartStep} 重试(第 ${postStep7RestartCount} 次重开)`, }); - step = 7; + step = restartStep; continue; } if (restartDecision.blockedByAddPhone) { const addPhoneUrl = restartDecision.authState?.url || 'https://auth.openai.com/add-phone'; - await addLog(`步骤 ${step}:检测到认证流程进入 add-phone(${addPhoneUrl}),停止自动回到步骤 7 重开。`, 'warn'); + const authChainStartStep = typeof getAuthChainStartStepId === 'function' + ? getAuthChainStartStepId(await getState()) + : FINAL_OAUTH_CHAIN_START_STEP; + await addLog(`步骤 ${step}:检测到认证流程进入 add-phone(${addPhoneUrl}),停止自动回到步骤 ${authChainStartStep} 重开。`, 'warn'); } throw err; } @@ -6670,6 +6976,56 @@ const step8Executor = self.MultiPageBackgroundStep8?.createStep8Executor({ STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS, throwIfStopped, }); +const plusCheckoutCreateExecutor = self.MultiPageBackgroundPlusCheckoutCreate?.createPlusCheckoutCreateExecutor({ + addLog, + chrome, + completeStepFromBackground, + ensureContentScriptReadyOnTabUntilStopped, + reuseOrCreateTab, + sendTabMessageUntilStopped, + setState, + sleepWithStop, + waitForTabCompleteUntilStopped, +}); +const plusCheckoutBillingExecutor = self.MultiPageBackgroundPlusCheckoutBilling?.createPlusCheckoutBillingExecutor({ + addLog, + chrome, + completeStepFromBackground, + ensureContentScriptReadyOnTabUntilStopped, + fetch: typeof fetch === 'function' ? fetch.bind(globalThis) : null, + generateRandomName, + getAddressSeedForCountry: self.MultiPageAddressSources?.getAddressSeedForCountry, + getTabId, + isTabAlive, + sendTabMessageUntilStopped, + setState, + sleepWithStop, + waitForTabCompleteUntilStopped, + waitForTabUrlMatchUntilStopped, +}); +const payPalApproveExecutor = self.MultiPageBackgroundPayPalApprove?.createPayPalApproveExecutor({ + addLog, + chrome, + completeStepFromBackground, + ensureContentScriptReadyOnTabUntilStopped, + getTabId, + isTabAlive, + sendTabMessageUntilStopped, + setState, + sleepWithStop, + waitForTabCompleteUntilStopped, + waitForTabUrlMatchUntilStopped, +}); +const plusReturnConfirmExecutor = self.MultiPageBackgroundPlusReturnConfirm?.createPlusReturnConfirmExecutor({ + addLog, + completeStepFromBackground, + getTabId, + isTabAlive, + setState, + sleepWithStop, + waitForTabCompleteUntilStopped, + waitForTabUrlMatchUntilStopped, +}); const step10Executor = self.MultiPageBackgroundStep10?.createStep10Executor({ addLog, chrome, @@ -6689,7 +7045,6 @@ const step10Executor = self.MultiPageBackgroundStep10?.createStep10Executor({ shouldBypassStep9ForLocalCpa, SUB2API_STEP9_RESPONSE_TIMEOUT_MS, }); -const stepDefinitions = SHARED_STEP_DEFINITIONS; const stepExecutorsByKey = { 'open-chatgpt': () => step1Executor.executeStep1(), 'submit-signup-email': (state) => step2Executor.executeStep2(state), @@ -6697,6 +7052,10 @@ const stepExecutorsByKey = { 'fetch-signup-code': (state) => step4Executor.executeStep4(state), 'fill-profile': (state) => step5Executor.executeStep5(state), 'clear-login-cookies': () => step6Executor.executeStep6(), + 'plus-checkout-create': (state) => plusCheckoutCreateExecutor.executePlusCheckoutCreate(state), + 'plus-checkout-billing': (state) => plusCheckoutBillingExecutor.executePlusCheckoutBilling(state), + 'paypal-approve': (state) => payPalApproveExecutor.executePayPalApprove(state), + 'plus-checkout-return': (state) => plusReturnConfirmExecutor.executePlusReturnConfirm(state), 'oauth-login': (state) => step7Executor.executeStep7(state), 'fetch-login-code': (state) => step8Executor.executeStep8(state), 'confirm-oauth': (state) => step9Executor.executeStep9(state), @@ -6747,6 +7106,9 @@ const messageRouter = self.MultiPageBackgroundMessageRouter?.createMessageRouter getPendingAutoRunTimerPlan, getSourceLabel, getState, + getStepDefinitionForState, + getStepIdsForState, + getLastStepIdForState, getTabId, getStopRequested: () => stopRequested, handleCloudflareSecurityBlocked, @@ -6804,12 +7166,22 @@ const messageRouter = self.MultiPageBackgroundMessageRouter?.createMessageRouter upsertHotmailAccount, verifyHotmailAccount, }); -const stepRegistry = self.MultiPageBackgroundStepRegistry?.createStepRegistry( - stepDefinitions.map((definition) => ({ - ...definition, - execute: stepExecutorsByKey[definition.key], - })) -); + +function buildStepRegistry(definitions = []) { + return self.MultiPageBackgroundStepRegistry?.createStepRegistry( + definitions.map((definition) => ({ + ...definition, + execute: stepExecutorsByKey[definition.key], + })) + ); +} + +const normalStepRegistry = buildStepRegistry(NORMAL_STEP_DEFINITIONS); +const plusStepRegistry = buildStepRegistry(PLUS_STEP_DEFINITIONS); + +function getStepRegistryForState(state = {}) { + return isPlusModeState(state) ? plusStepRegistry : normalStepRegistry; +} async function requestOAuthUrlFromPanel(state, options = {}) { return panelBridge.requestOAuthUrlFromPanel(state, options); @@ -7136,12 +7508,13 @@ async function runPreStep6CookieCleanup() { // Step 7: Login and ensure the auth page reaches the login verification page // ============================================================ -async function refreshOAuthUrlBeforeStep6(state) { +async function refreshOAuthUrlBeforeStep6(state, options = {}) { + const visibleStep = Number(options.visibleStep) || Number(state?.visibleStep) || 7; if (state?.contributionModeExpected && !state?.contributionMode) { - throw new Error('步骤 7:当前自动流程预期使用贡献模式,但运行态 contributionMode 已丢失,已阻止回退到普通 CPA / SUB2API / Codex2API 链路。请重新进入贡献模式后再点击自动。'); + throw new Error(`步骤 ${visibleStep}:当前自动流程预期使用贡献模式,但运行态 contributionMode 已丢失,已阻止回退到普通 CPA / SUB2API / Codex2API 链路。请重新进入贡献模式后再点击自动。`); } if (state?.contributionMode && contributionOAuthManager?.startContributionFlow) { - await addLog('步骤 7:contributionMode=true,走公开贡献接口,正在申请 OAuth 登录地址...', 'info'); + await addLog(`步骤 ${visibleStep}:contributionMode=true,走公开贡献接口,正在申请 OAuth 登录地址...`, 'info'); const contributionState = await contributionOAuthManager.startContributionFlow({ nickname: state.contributionNickname || '', openAuthTab: false, @@ -7154,9 +7527,9 @@ async function refreshOAuthUrlBeforeStep6(state) { await handleStepData(1, { oauthUrl }); return oauthUrl; } - await addLog(`步骤 7:contributionMode=false,走普通 CPA / SUB2API / Codex2API 链路(当前面板:${getPanelModeLabel(state)}),正在刷新 OAuth 登录地址...`, 'info'); + await addLog(`步骤 ${visibleStep}:contributionMode=false,走普通 CPA / SUB2API / Codex2API 链路(当前面板:${getPanelModeLabel(state)}),正在刷新 OAuth 登录地址...`, 'info'); console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] requesting fresh OAuth directly from panel'); - const refreshResult = await requestOAuthUrlFromPanel(state, { logLabel: '步骤 7' }); + const refreshResult = await requestOAuthUrlFromPanel(state, { logLabel: `步骤 ${visibleStep}` }); await handleStepData(1, refreshResult); if (!refreshResult?.oauthUrl) { @@ -7166,9 +7539,12 @@ async function refreshOAuthUrlBeforeStep6(state) { return refreshResult.oauthUrl; } -function buildOAuthFlowTimeoutError(step, actionLabel = '后续授权流程') { +function buildOAuthFlowTimeoutError(step, actionLabel = '后续授权流程', state = {}) { + const restartStep = typeof getAuthChainStartStepId === 'function' + ? getAuthChainStartStepId(state) + : FINAL_OAUTH_CHAIN_START_STEP; return new Error( - `步骤 ${step}:从拿到 OAuth 登录地址开始,${Math.round(OAUTH_FLOW_TIMEOUT_MS / 60000)} 分钟内未完成${actionLabel},结束当前链路,准备从步骤 7 重新开始。` + `步骤 ${step}:从拿到 OAuth 登录地址开始,${Math.round(OAUTH_FLOW_TIMEOUT_MS / 60000)} 分钟内未完成${actionLabel},结束当前链路,准备从步骤 ${restartStep} 重新开始。` ); } @@ -7219,7 +7595,7 @@ async function getOAuthFlowRemainingMs(options = {}) { const remainingMs = deadlineAt - Date.now(); if (remainingMs <= 0) { - throw buildOAuthFlowTimeoutError(step, actionLabel); + throw buildOAuthFlowTimeoutError(step, actionLabel, state); } return remainingMs; @@ -7235,9 +7611,11 @@ async function getOAuthFlowStepTimeoutMs(defaultTimeoutMs, options = {}) { const budgetMs = remainingMs - reserveMs; if (budgetMs <= 0) { + const stateForError = options.state || await getState(); throw buildOAuthFlowTimeoutError( Number(options.step) || 7, - String(options.actionLabel || '后续授权流程').trim() || '后续授权流程' + String(options.actionLabel || '后续授权流程').trim() || '后续授权流程', + stateForError ); } @@ -7268,11 +7646,19 @@ async function getPostStep6AutoRestartDecision(step, error) { const normalizedStep = Number(step); const errorMessage = getErrorMessage(error); const shouldForceRestartFromStep7 = /restart step 7 with a new number/i.test(errorMessage); - if (!Number.isFinite(normalizedStep) || normalizedStep < 7 || normalizedStep > LAST_STEP_ID) { + const latestState = await getState(); + const authChainStartStep = typeof getAuthChainStartStepId === 'function' + ? getAuthChainStartStepId(latestState) + : FINAL_OAUTH_CHAIN_START_STEP; + const lastStepId = typeof getLastStepIdForState === 'function' + ? getLastStepIdForState(latestState) + : (typeof LAST_STEP_ID === 'number' ? LAST_STEP_ID : 10); + if (!Number.isFinite(normalizedStep) || normalizedStep < authChainStartStep || normalizedStep > lastStepId) { return { shouldRestart: false, blockedByAddPhone: false, forcedByPhoneVerificationTimeout: false, + restartStep: authChainStartStep, errorMessage, authState: null, }; @@ -7283,6 +7669,7 @@ async function getPostStep6AutoRestartDecision(step, error) { shouldRestart: true, blockedByAddPhone: false, forcedByPhoneVerificationTimeout: true, + restartStep: authChainStartStep, errorMessage, authState: null, }; @@ -7293,6 +7680,7 @@ async function getPostStep6AutoRestartDecision(step, error) { shouldRestart: false, blockedByAddPhone: true, forcedByPhoneVerificationTimeout: false, + restartStep: authChainStartStep, errorMessage, authState: null, }; @@ -7301,7 +7689,7 @@ async function getPostStep6AutoRestartDecision(step, error) { let authState = null; try { authState = await getLoginAuthStateFromContent({ - logMessage: `步骤 ${normalizedStep}:正在确认当前认证页状态,以决定是否回到步骤 7 重开...`, + logMessage: `步骤 ${normalizedStep}:正在确认当前认证页状态,以决定是否回到步骤 ${authChainStartStep} 重开...`, }); } catch (inspectError) { console.warn(LOG_PREFIX, '[AutoRun] failed to inspect login auth state after post-step6 error', { @@ -7316,6 +7704,7 @@ async function getPostStep6AutoRestartDecision(step, error) { shouldRestart: false, blockedByAddPhone: true, forcedByPhoneVerificationTimeout: false, + restartStep: authChainStartStep, errorMessage, authState, }; @@ -7325,6 +7714,7 @@ async function getPostStep6AutoRestartDecision(step, error) { shouldRestart: true, blockedByAddPhone: false, forcedByPhoneVerificationTimeout: false, + restartStep: authChainStartStep, errorMessage, authState, }; @@ -7355,6 +7745,8 @@ async function getLoginAuthStateFromContent(options = {}) { } async function ensureStep8VerificationPageReady(options = {}) { + const visibleStep = Number(options.visibleStep) || 8; + const authLoginStep = Number(options.authLoginStep) || (visibleStep >= 11 ? 10 : 7); const pageState = await getLoginAuthStateFromContent(options); if (pageState.state === 'verification_page') { return pageState; @@ -7366,17 +7758,17 @@ async function ensureStep8VerificationPageReady(options = {}) { if (pageState.state === 'login_timeout_error_page') { const urlPart = pageState.url ? ` URL: ${pageState.url}` : ''; - throw new Error(`STEP8_RESTART_STEP7::步骤 8:当前认证页进入登录超时报错页,请回到步骤 7 重新开始。${urlPart}`.trim()); + throw new Error(`STEP8_RESTART_STEP7::步骤 ${visibleStep}:当前认证页进入登录超时报错页,请回到步骤 ${authLoginStep} 重新开始。${urlPart}`.trim()); } if (pageState.state === 'add_phone_page') { const urlPart = pageState.url ? ` URL: ${pageState.url}` : ''; - throw new Error(`步骤 8:当前认证页进入手机号页面,当前流程无法继续自动授权。${urlPart}`.trim()); + throw new Error(`步骤 ${visibleStep}:当前认证页进入手机号页面,当前流程无法继续自动授权。${urlPart}`.trim()); } const stateLabel = getLoginAuthStateLabel(pageState.state); const urlPart = pageState.url ? ` URL: ${pageState.url}` : ''; - throw new Error(`当前未进入登录验证码页面,请先重新完成步骤 7。当前状态:${stateLabel}.${urlPart}`.trim()); + throw new Error(`当前未进入登录验证码页面,请先重新完成步骤 ${authLoginStep}。当前状态:${stateLabel}.${urlPart}`.trim()); } async function rerunStep7ForStep8Recovery(options = {}) { @@ -7387,27 +7779,33 @@ async function rerunStep7ForStep8Recovery(options = {}) { throwIfStopped(); const initialState = await getState(); + const authLoginStep = typeof getAuthChainStartStepId === 'function' + ? getAuthChainStartStepId(initialState) + : FINAL_OAUTH_CHAIN_START_STEP; await addLog(logMessage, 'warn'); - await setStepStatus(7, 'running'); - await addLog('步骤 7 开始执行'); + await setStepStatus(authLoginStep, 'running'); + await addLog(`步骤 ${authLoginStep} 开始执行`); try { - await step7Executor.executeStep7(initialState); + await step7Executor.executeStep7({ + ...initialState, + visibleStep: authLoginStep, + }); } catch (err) { const latestState = await getState(); if (isStopError(err)) { - await setStepStatus(7, 'stopped'); - await addLog('步骤 7 已被用户停止', 'warn'); - await appendManualAccountRunRecordIfNeeded('step7_stopped', latestState, getErrorMessage(err)); + await setStepStatus(authLoginStep, 'stopped'); + await addLog(`步骤 ${authLoginStep} 已被用户停止`, 'warn'); + await appendManualAccountRunRecordIfNeeded(`step${authLoginStep}_stopped`, latestState, getErrorMessage(err)); throw err; } if (isTerminalSecurityBlockedError(err)) { await handleCloudflareSecurityBlocked(err); throw new Error(STOP_ERROR_MESSAGE); } - await setStepStatus(7, 'failed'); - await addLog(`步骤 7 失败:${getErrorMessage(err)}`, 'error'); - await appendManualAccountRunRecordIfNeeded('step7_failed', latestState, getErrorMessage(err)); + await setStepStatus(authLoginStep, 'failed'); + await addLog(`步骤 ${authLoginStep} 失败:${getErrorMessage(err)}`, 'error'); + await appendManualAccountRunRecordIfNeeded(`step${authLoginStep}_failed`, latestState, getErrorMessage(err)); throw err; } diff --git a/background/auto-run-controller.js b/background/auto-run-controller.js index 761a3e4..37705a9 100644 --- a/background/auto-run-controller.js +++ b/background/auto-run-controller.js @@ -311,7 +311,7 @@ let successfulRuns = roundSummaries.filter((item) => item.status === 'success').length; const initialState = await getState(); - const initialPhase = continueCurrentOnFirstAttempt && getRunningSteps(initialState.stepStatuses).length + const initialPhase = continueCurrentOnFirstAttempt && getRunningSteps(initialState.stepStatuses, initialState).length ? 'waiting_step' : 'running'; const showResumePosition = continueCurrentOnFirstAttempt || resumeCurrentRun > 1 || resumeAttemptRun > 1; @@ -351,18 +351,18 @@ if (reuseExistingProgress) { let currentState = await getState(); - if (getRunningSteps(currentState.stepStatuses).length) { + if (getRunningSteps(currentState.stepStatuses, currentState).length) { currentState = await waitForRunningStepsToFinish({ currentRun: targetRun, totalRuns, attemptRun, }); } - const resumeStep = getFirstUnfinishedStep(currentState.stepStatuses); - if (resumeStep && hasSavedProgress(currentState.stepStatuses)) { + const resumeStep = getFirstUnfinishedStep(currentState.stepStatuses, currentState); + if (resumeStep && hasSavedProgress(currentState.stepStatuses, currentState)) { startStep = resumeStep; useExistingProgress = true; - } else if (hasSavedProgress(currentState.stepStatuses)) { + } else if (hasSavedProgress(currentState.stepStatuses, currentState)) { await addLog('检测到当前流程已处理完成,本轮将改为从步骤 1 重新开始。', 'info'); } } @@ -373,6 +373,9 @@ vpsUrl: prevState.vpsUrl, vpsPassword: prevState.vpsPassword, customPassword: prevState.customPassword, + plusModeEnabled: prevState.plusModeEnabled, + paypalEmail: prevState.paypalEmail, + paypalPassword: prevState.paypalPassword, autoRunSkipFailures: prevState.autoRunSkipFailures, autoRunFallbackThreadIntervalMinutes: prevState.autoRunFallbackThreadIntervalMinutes, autoRunDelayEnabled: prevState.autoRunDelayEnabled, diff --git a/background/logging-status.js b/background/logging-status.js index 47d3c2c..15aeff7 100644 --- a/background/logging-status.js +++ b/background/logging-status.js @@ -70,7 +70,6 @@ } function getLoginAuthStateLabel(state) { - state = state === 'oauth_consent_page' ? 'unknown' : state; switch (state) { case 'verification_page': return '登录验证码页'; diff --git a/background/message-router.js b/background/message-router.js index 15c503d..a95bf59 100644 --- a/background/message-router.js +++ b/background/message-router.js @@ -40,6 +40,9 @@ getPendingAutoRunTimerPlan, getSourceLabel, getState, + getStepDefinitionForState, + getStepIdsForState, + getLastStepIdForState, getTabId, getStopRequested, handleAutoRunLoopUnhandledError, @@ -127,7 +130,122 @@ } } + function getStepKeyForState(step, state = {}) { + if (typeof getStepDefinitionForState === 'function') { + return String(getStepDefinitionForState(step, state)?.key || '').trim(); + } + return ''; + } + + function isStepProtectedFromAutoSkip(status) { + return status === 'running' + || status === 'completed' + || status === 'manual_completed' + || status === 'skipped'; + } + + function findStepByKeyAfter(currentStep, targetKey, state = {}) { + const activeStepIds = typeof getStepIdsForState === 'function' + ? getStepIdsForState(state) + : []; + const candidates = activeStepIds.length ? activeStepIds : [Number(currentStep) + 1, 8]; + return candidates.find((stepId) => { + const numericStep = Number(stepId); + if (!Number.isFinite(numericStep) || numericStep <= Number(currentStep)) { + return false; + } + const stepKey = getStepKeyForState(numericStep, state); + if (stepKey) { + return stepKey === targetKey; + } + return targetKey === 'fetch-login-code' && Number(currentStep) === 7 && numericStep === 8; + }) || null; + } + + async function handlePlatformVerifyStepData(payload) { + if (payload.localhostUrl) { + await closeLocalhostCallbackTabs(payload.localhostUrl); + } + const latestState = await getState(); + if (latestState.currentHotmailAccountId && isHotmailProvider(latestState)) { + await patchHotmailAccount(latestState.currentHotmailAccountId, { + used: true, + lastUsedAt: Date.now(), + }); + await addLog('当前 Hotmail 账号已自动标记为已用。', 'ok'); + } + if (String(latestState.mailProvider || '').trim().toLowerCase() === '2925' && latestState.currentMail2925AccountId) { + await patchMail2925Account(latestState.currentMail2925AccountId, { + lastUsedAt: Date.now(), + lastError: '', + }); + await addLog('当前 2925 账号已记录最近使用时间。', 'ok'); + } + if (isLuckmailProvider(latestState)) { + const currentPurchase = getCurrentLuckmailPurchase(latestState); + if (currentPurchase?.id) { + await setLuckmailPurchaseUsedState(currentPurchase.id, true); + await addLog(`当前 LuckMail 邮箱 ${currentPurchase.email_address} 已在本地标记为已用。`, 'ok'); + } + await clearLuckmailRuntimeState({ clearEmail: true }); + await addLog('当前 LuckMail 邮箱运行态已清空,下轮将优先复用未用邮箱或重新购买邮箱。', 'ok'); + } + const localhostPrefix = buildLocalhostCleanupPrefix(payload.localhostUrl); + if (localhostPrefix) { + await closeTabsByUrlPrefix(localhostPrefix, { + excludeUrls: [payload.localhostUrl], + excludeLocalhostCallbacks: true, + }); + } + await finalizeIcloudAliasAfterSuccessfulFlow(latestState); + } + async function handleStepData(step, payload) { + const stateForStep = await getState(); + const stepKey = getStepKeyForState(step, stateForStep); + + if (stepKey === 'oauth-login') { + if (payload.skipLoginVerificationStep) { + await setState({ loginVerificationRequestedAt: null }); + const latestState = await getState(); + const loginCodeStep = findStepByKeyAfter(step, 'fetch-login-code', latestState); + if (loginCodeStep) { + const currentStatus = latestState.stepStatuses?.[loginCodeStep]; + if (!isStepProtectedFromAutoSkip(currentStatus)) { + await setStepStatus(loginCodeStep, 'skipped'); + await addLog(`步骤 ${step}:认证页已直接进入 OAuth 授权页,已自动跳过步骤 ${loginCodeStep} 的登录验证码。`, 'warn'); + } + } + } else if (payload.loginVerificationRequestedAt) { + await setState({ loginVerificationRequestedAt: payload.loginVerificationRequestedAt }); + } + return; + } + + if (stepKey === 'fetch-login-code') { + await setState({ + lastEmailTimestamp: payload.emailTimestamp || null, + loginVerificationRequestedAt: null, + }); + return; + } + + if (stepKey === 'confirm-oauth') { + if (payload.localhostUrl) { + if (!isLocalhostOAuthCallbackUrl(payload.localhostUrl)) { + throw new Error(`步骤 ${step} 返回了无效的 localhost OAuth 回调地址。`); + } + await setState({ localhostUrl: payload.localhostUrl }); + broadcastDataUpdate({ localhostUrl: payload.localhostUrl }); + } + return; + } + + if (stepKey === 'platform-verify') { + await handlePlatformVerifyStepData(payload); + return; + } + switch (step) { case 1: { const updates = {}; @@ -181,11 +299,6 @@ await setState({ loginVerificationRequestedAt: payload.loginVerificationRequestedAt }); } break; - case 7: - if (payload.loginVerificationRequestedAt) { - await setState({ loginVerificationRequestedAt: payload.loginVerificationRequestedAt }); - } - break; case 4: await setState({ lastEmailTimestamp: payload.emailTimestamp || null, @@ -200,59 +313,6 @@ } } break; - case 8: - await setState({ - lastEmailTimestamp: payload.emailTimestamp || null, - loginVerificationRequestedAt: null, - }); - break; - case 9: - if (payload.localhostUrl) { - if (!isLocalhostOAuthCallbackUrl(payload.localhostUrl)) { - throw new Error('步骤 9 返回了无效的 localhost OAuth 回调地址。'); - } - await setState({ localhostUrl: payload.localhostUrl }); - broadcastDataUpdate({ localhostUrl: payload.localhostUrl }); - } - break; - case 10: { - if (payload.localhostUrl) { - await closeLocalhostCallbackTabs(payload.localhostUrl); - } - const latestState = await getState(); - if (latestState.currentHotmailAccountId && isHotmailProvider(latestState)) { - await patchHotmailAccount(latestState.currentHotmailAccountId, { - used: true, - lastUsedAt: Date.now(), - }); - await addLog('当前 Hotmail 账号已自动标记为已用。', 'ok'); - } - if (String(latestState.mailProvider || '').trim().toLowerCase() === '2925' && latestState.currentMail2925AccountId) { - await patchMail2925Account(latestState.currentMail2925AccountId, { - lastUsedAt: Date.now(), - lastError: '', - }); - await addLog('当前 2925 账号已记录最近使用时间。', 'ok'); - } - if (isLuckmailProvider(latestState)) { - const currentPurchase = getCurrentLuckmailPurchase(latestState); - if (currentPurchase?.id) { - await setLuckmailPurchaseUsedState(currentPurchase.id, true); - await addLog(`当前 LuckMail 邮箱 ${currentPurchase.email_address} 已在本地标记为已用。`, 'ok'); - } - await clearLuckmailRuntimeState({ clearEmail: true }); - await addLog('当前 LuckMail 邮箱运行态已清空,下轮将优先复用未用邮箱或重新购买邮箱。', 'ok'); - } - const localhostPrefix = buildLocalhostCleanupPrefix(payload.localhostUrl); - if (localhostPrefix) { - await closeTabsByUrlPrefix(localhostPrefix, { - excludeUrls: [payload.localhostUrl], - excludeLocalhostCallbacks: true, - }); - } - await finalizeIcloudAliasAfterSuccessfulFlow(latestState); - break; - } default: break; } @@ -303,11 +363,15 @@ return { ok: true, error: errorMessage }; } - const completionState = message.step === 10 ? await getState() : null; + const completionStateCandidate = await getState(); + const lastStepId = typeof getLastStepIdForState === 'function' + ? getLastStepIdForState(completionStateCandidate) + : 10; + const completionState = message.step === lastStepId ? completionStateCandidate : null; await setStepStatus(message.step, 'completed'); await addLog(`步骤 ${message.step} 已完成`, 'ok'); await handleStepData(message.step, message.payload); - if (message.step === 10 && typeof appendAccountRunRecord === 'function') { + if (message.step === lastStepId && typeof appendAccountRunRecord === 'function') { await appendAccountRunRecord('success', completionState); } notifyStepComplete(message.step, message.payload); @@ -456,7 +520,8 @@ await setPersistentSettings({ emailPrefix: message.payload.emailPrefix }); await setState({ emailPrefix: message.payload.emailPrefix }); } - if (doesStepUseCompletionSignal(step)) { + const executionState = await getState(); + if (doesStepUseCompletionSignal(step, executionState)) { await executeStepViaCompletionSignal(step); } else { await executeStep(step); @@ -561,13 +626,32 @@ } case 'SAVE_SETTING': { + const currentState = await getState(); const updates = buildPersistentSettingsPayload(message.payload || {}); const sessionUpdates = buildLuckmailSessionSettingsPayload(message.payload || {}); + const modeChanged = Object.prototype.hasOwnProperty.call(updates, 'plusModeEnabled') + && Boolean(currentState?.plusModeEnabled) !== Boolean(updates.plusModeEnabled); await setPersistentSettings(updates); - await setState({ + const stateUpdates = { ...updates, ...sessionUpdates, - }); + }; + if (modeChanged && typeof getStepIdsForState === 'function') { + const nextStateForSteps = { ...currentState, ...stateUpdates }; + stateUpdates.stepStatuses = Object.fromEntries( + getStepIdsForState(nextStateForSteps).map((stepId) => [stepId, 'pending']) + ); + stateUpdates.currentStep = 0; + } + await setState(stateUpdates); + if (modeChanged) { + await addLog( + Boolean(updates.plusModeEnabled) + ? 'Plus 模式已开启,已切换为 Plus Checkout + PayPal 步骤。' + : 'Plus 模式已关闭,已恢复普通注册授权步骤。', + 'info' + ); + } return { ok: true, state: await getState() }; } diff --git a/background/steps/confirm-oauth.js b/background/steps/confirm-oauth.js index 59deab9..88607c9 100644 --- a/background/steps/confirm-oauth.js +++ b/background/steps/confirm-oauth.js @@ -33,16 +33,27 @@ setStep8TabUpdatedListener, } = deps; + function getVisibleStep(state, fallback = 9) { + const visibleStep = Math.floor(Number(state?.visibleStep) || 0); + return visibleStep > 0 ? visibleStep : fallback; + } + + function getAuthLoginStepForVisibleStep(visibleStep) { + return visibleStep >= 12 ? 10 : 7; + } + async function executeStep9(state) { + const visibleStep = getVisibleStep(state, 9); if (!state.oauthUrl) { - throw new Error('缺少登录用 OAuth 链接,请先完成步骤 7。'); + const authLoginStep = getAuthLoginStepForVisibleStep(visibleStep); + throw new Error(`缺少登录用 OAuth 链接,请先完成步骤 ${authLoginStep}。`); } - await addLog('步骤 9:正在监听 localhost 回调地址...'); + await addLog(`步骤 ${visibleStep}:正在监听 localhost 回调地址...`); const callbackTimeoutMs = typeof getOAuthFlowStepTimeoutMs === 'function' ? await getOAuthFlowStepTimeoutMs(240000, { - step: 9, + step: visibleStep, actionLabel: 'OAuth localhost 回调', }) : 240000; @@ -71,8 +82,8 @@ cleanupListener(); clearTimeout(timeout); - addLog(`步骤 9:已捕获 localhost 地址:${callbackUrl}`, 'ok').then(() => { - return completeStepFromBackground(9, { localhostUrl: callbackUrl }); + addLog(`步骤 ${visibleStep}:已捕获 localhost 地址:${callbackUrl}`, 'ok').then(() => { + return completeStepFromBackground(visibleStep, { localhostUrl: callbackUrl }); }).then(() => { resolve(); }).catch((err) => { @@ -81,7 +92,7 @@ }; const timeout = setTimeout(() => { - rejectStep9(new Error('120 秒内未捕获到 localhost 回调跳转,步骤 9 的点击可能被拦截了。')); + rejectStep9(new Error(`${Math.round(callbackTimeoutMs / 1000)} 秒内未捕获到 localhost 回调跳转,步骤 ${visibleStep} 的点击可能被拦截了。`)); }, callbackTimeoutMs); setStep8PendingReject((error) => { @@ -111,10 +122,10 @@ if (signupTabId && await isTabAlive('signup-page')) { await chrome.tabs.update(signupTabId, { active: true }); - await addLog('步骤 9:已切回认证页,正在准备调试器点击...'); + await addLog(`步骤 ${visibleStep}:已切回认证页,正在准备调试器点击...`); } else { signupTabId = await reuseOrCreateTab('signup-page', state.oauthUrl); - await addLog('步骤 9:已重新打开认证页,正在准备调试器点击...'); + await addLog(`步骤 ${visibleStep}:已重新打开认证页,正在准备调试器点击...`); } throwIfStep8SettledOrStopped(resolved); @@ -124,11 +135,11 @@ await ensureStep8SignupPageReady(signupTabId, { timeoutMs: typeof getOAuthFlowStepTimeoutMs === 'function' ? await getOAuthFlowStepTimeoutMs(15000, { - step: 9, + step: visibleStep, actionLabel: '等待 OAuth 同意页内容脚本就绪', }) : 15000, - logMessage: '步骤 9:认证页内容脚本尚未就绪,正在等待页面恢复...', + logMessage: `步骤 ${visibleStep}:认证页内容脚本尚未就绪,正在等待页面恢复...`, }); for (let round = 1; round <= STEP8_MAX_ROUNDS && !resolved; round++) { @@ -137,7 +148,7 @@ signupTabId, typeof getOAuthFlowStepTimeoutMs === 'function' ? await getOAuthFlowStepTimeoutMs(STEP8_READY_WAIT_TIMEOUT_MS, { - step: 9, + step: visibleStep, actionLabel: '等待 OAuth 同意页出现', }) : STEP8_READY_WAIT_TIMEOUT_MS @@ -149,12 +160,12 @@ const strategy = STEP8_STRATEGIES[Math.min(round - 1, STEP8_STRATEGIES.length - 1)]; - await addLog(`步骤 9:第 ${round}/${STEP8_MAX_ROUNDS} 轮尝试点击“继续”(${strategy.label})...`); + await addLog(`步骤 ${visibleStep}:第 ${round}/${STEP8_MAX_ROUNDS} 轮尝试点击“继续”(${strategy.label})...`); if (strategy.mode === 'debugger') { const clickActionTimeoutMs = typeof getOAuthFlowStepTimeoutMs === 'function' ? await getOAuthFlowStepTimeoutMs(15000, { - step: 9, + step: visibleStep, actionLabel: '定位 OAuth 同意页继续按钮', }) : 15000; @@ -167,7 +178,7 @@ } else { const clickActionTimeoutMs = typeof getOAuthFlowStepTimeoutMs === 'function' ? await getOAuthFlowStepTimeoutMs(15000, { - step: 9, + step: visibleStep, actionLabel: '点击 OAuth 同意页继续按钮', }) : 15000; @@ -186,7 +197,7 @@ pageState.url, typeof getOAuthFlowStepTimeoutMs === 'function' ? await getOAuthFlowStepTimeoutMs(15000, { - step: 9, + step: visibleStep, actionLabel: '等待 OAuth 同意页点击生效', }) : 15000 @@ -196,20 +207,20 @@ } if (effect.progressed) { - await addLog(`步骤 9:检测到本次点击已生效,${getStep8EffectLabel(effect)},继续等待 localhost 回调...`, 'info'); + await addLog(`步骤 ${visibleStep}:检测到本次点击已生效,${getStep8EffectLabel(effect)},继续等待 localhost 回调...`, 'info'); break; } if (round >= STEP8_MAX_ROUNDS) { - throw new Error(`步骤 9:连续 ${STEP8_MAX_ROUNDS} 轮点击“继续”后页面仍无反应。`); + throw new Error(`步骤 ${visibleStep}:连续 ${STEP8_MAX_ROUNDS} 轮点击“继续”后页面仍无反应。`); } - await addLog(`步骤 9:${strategy.label} 本轮点击后页面无反应,正在刷新认证页后重试(下一轮 ${round + 1}/${STEP8_MAX_ROUNDS})...`, 'warn'); + await addLog(`步骤 ${visibleStep}:${strategy.label} 本轮点击后页面无反应,正在刷新认证页后重试(下一轮 ${round + 1}/${STEP8_MAX_ROUNDS})...`, 'warn'); await reloadStep8ConsentPage( signupTabId, typeof getOAuthFlowStepTimeoutMs === 'function' ? await getOAuthFlowStepTimeoutMs(30000, { - step: 9, + step: visibleStep, actionLabel: '刷新 OAuth 同意页', }) : 30000 diff --git a/background/steps/create-plus-checkout.js b/background/steps/create-plus-checkout.js new file mode 100644 index 0000000..fb995ab --- /dev/null +++ b/background/steps/create-plus-checkout.js @@ -0,0 +1,85 @@ +(function attachBackgroundPlusCheckoutCreate(root, factory) { + root.MultiPageBackgroundPlusCheckoutCreate = factory(); +})(typeof self !== 'undefined' ? self : globalThis, function createBackgroundPlusCheckoutCreateModule() { + const PLUS_CHECKOUT_SOURCE = 'plus-checkout'; + const PLUS_CHECKOUT_ENTRY_URL = 'https://chatgpt.com/'; + const PLUS_CHECKOUT_INJECT_FILES = ['content/utils.js', 'content/plus-checkout.js']; + const PLUS_CHECKOUT_POST_CREATE_WAIT_MS = 20000; + + function createPlusCheckoutCreateExecutor(deps = {}) { + const { + addLog, + chrome, + completeStepFromBackground, + ensureContentScriptReadyOnTabUntilStopped, + reuseOrCreateTab, + sendTabMessageUntilStopped, + setState, + sleepWithStop, + waitForTabCompleteUntilStopped, + } = deps; + + async function executePlusCheckoutCreate() { + await addLog('步骤 6:正在打开 ChatGPT 会话页,准备创建 Plus Checkout...', 'info'); + const tabId = await reuseOrCreateTab(PLUS_CHECKOUT_SOURCE, PLUS_CHECKOUT_ENTRY_URL, { + inject: PLUS_CHECKOUT_INJECT_FILES, + injectSource: PLUS_CHECKOUT_SOURCE, + reloadIfSameUrl: false, + }); + + await waitForTabCompleteUntilStopped(tabId); + await sleepWithStop(1000); + await ensureContentScriptReadyOnTabUntilStopped(PLUS_CHECKOUT_SOURCE, tabId, { + inject: PLUS_CHECKOUT_INJECT_FILES, + injectSource: PLUS_CHECKOUT_SOURCE, + logMessage: '步骤 6:ChatGPT 页面仍在加载,等待 Plus Checkout 脚本就绪...', + }); + + const result = await sendTabMessageUntilStopped(tabId, PLUS_CHECKOUT_SOURCE, { + type: 'CREATE_PLUS_CHECKOUT', + source: 'background', + payload: {}, + }); + + if (result?.error) { + throw new Error(result.error); + } + if (!result?.checkoutUrl) { + throw new Error('步骤 6:Plus Checkout 创建后未返回支付链接。'); + } + + await addLog('步骤 6:Plus Checkout 已创建,正在打开支付页面...', 'ok'); + await chrome.tabs.update(tabId, { url: result.checkoutUrl, active: true }); + await waitForTabCompleteUntilStopped(tabId); + await sleepWithStop(1000); + await ensureContentScriptReadyOnTabUntilStopped(PLUS_CHECKOUT_SOURCE, tabId, { + inject: PLUS_CHECKOUT_INJECT_FILES, + injectSource: PLUS_CHECKOUT_SOURCE, + logMessage: '步骤 6:Checkout 页面仍在加载,等待页面脚本就绪...', + }); + + await setState({ + plusCheckoutTabId: tabId, + plusCheckoutUrl: result.checkoutUrl, + plusCheckoutCountry: result.country || 'DE', + plusCheckoutCurrency: result.currency || 'EUR', + }); + + await addLog('步骤 6:Plus Checkout 页面已就绪,固定等待 20 秒后继续下一步。', 'info'); + await sleepWithStop(PLUS_CHECKOUT_POST_CREATE_WAIT_MS); + + await completeStepFromBackground(6, { + plusCheckoutCountry: result.country || 'DE', + plusCheckoutCurrency: result.currency || 'EUR', + }); + } + + return { + executePlusCheckoutCreate, + }; + } + + return { + createPlusCheckoutCreateExecutor, + }; +}); diff --git a/background/steps/fetch-login-code.js b/background/steps/fetch-login-code.js index a379a77..c25b2f4 100644 --- a/background/steps/fetch-login-code.js +++ b/background/steps/fetch-login-code.js @@ -31,25 +31,34 @@ throwIfStopped, } = deps; - async function getStep8ReadyTimeoutMs(actionLabel, expectedOauthUrl = '') { + function getVisibleStep(state, fallback = 8) { + const visibleStep = Math.floor(Number(state?.visibleStep) || 0); + return visibleStep > 0 ? visibleStep : fallback; + } + + function getAuthLoginStepForVisibleStep(visibleStep) { + return visibleStep >= 11 ? 10 : 7; + } + + async function getStep8ReadyTimeoutMs(actionLabel, expectedOauthUrl = '', visibleStep = 8) { if (typeof getOAuthFlowStepTimeoutMs !== 'function') { return 15000; } return getOAuthFlowStepTimeoutMs(15000, { - step: 8, + step: visibleStep, actionLabel, oauthUrl: expectedOauthUrl, }); } - function getStep8RemainingTimeResolver(expectedOauthUrl = '') { + function getStep8RemainingTimeResolver(expectedOauthUrl = '', visibleStep = 8) { if (typeof getOAuthFlowRemainingMs !== 'function') { return undefined; } return async (details = {}) => getOAuthFlowRemainingMs({ - step: 8, + step: visibleStep, actionLabel: details.actionLabel || '登录验证码流程', oauthUrl: expectedOauthUrl, }); @@ -96,6 +105,7 @@ } async function runStep8Attempt(state) { + const visibleStep = getVisibleStep(state, 8); const mail = getMailConfig(state); if (mail.error) throw new Error(mail.error); @@ -110,14 +120,16 @@ await chrome.tabs.update(authTabId, { active: true }); } else { if (!state.oauthUrl) { - throw new Error('缺少登录用 OAuth 链接,请先完成步骤 7。'); + throw new Error(`缺少登录用 OAuth 链接,请先完成步骤 ${getAuthLoginStepForVisibleStep(visibleStep)}。`); } await reuseOrCreateTab('signup-page', state.oauthUrl); } throwIfStopped(); const pageState = await ensureStep8VerificationPageReady({ - timeoutMs: await getStep8ReadyTimeoutMs('确认登录验证码页已就绪', state?.oauthUrl || ''), + visibleStep, + authLoginStep: getAuthLoginStepForVisibleStep(visibleStep), + timeoutMs: await getStep8ReadyTimeoutMs('确认登录验证码页已就绪', state?.oauthUrl || '', visibleStep), }); const shouldCompareVerificationEmail = mail.provider !== '2925'; const displayedVerificationEmail = shouldCompareVerificationEmail @@ -131,22 +143,25 @@ step8VerificationTargetEmail: displayedVerificationEmail || '', }); - await addLog('步骤 8:登录验证码页面已就绪,开始获取验证码。', 'info'); + await addLog(`步骤 ${visibleStep}:登录验证码页面已就绪,开始获取验证码。`, 'info'); if (shouldCompareVerificationEmail && displayedVerificationEmail) { - await addLog(`步骤 8:已固定当前验证码页显示邮箱 ${displayedVerificationEmail} 作为后续匹配目标。`, 'info'); + await addLog(`步骤 ${visibleStep}:已固定当前验证码页显示邮箱 ${displayedVerificationEmail} 作为后续匹配目标。`, 'info'); } if (shouldUseCustomRegistrationEmail(state)) { - await confirmCustomVerificationStepBypass(8); + await confirmCustomVerificationStepBypass(8, { + completionStep: visibleStep, + promptStep: visibleStep, + }); return; } if (mail.source === 'icloud-mail' && typeof ensureIcloudMailSession === 'function') { - await addLog('步骤 8:正在确认 iCloud 邮箱登录态...', 'info'); + await addLog(`步骤 ${visibleStep}:正在确认 iCloud 邮箱登录态...`, 'info'); await ensureIcloudMailSession({ state, step: 8, - actionLabel: '步骤 8:确认 iCloud 邮箱登录态', + actionLabel: `步骤 ${visibleStep}:确认 iCloud 邮箱登录态`, }); } @@ -156,22 +171,22 @@ || mail.provider === LUCKMAIL_PROVIDER || mail.provider === CLOUDFLARE_TEMP_EMAIL_PROVIDER ) { - await addLog(`步骤 8:正在通过 ${mail.label} 轮询验证码...`); + await addLog(`步骤 ${visibleStep}:正在通过 ${mail.label} 轮询验证码...`); } else { - await addLog(`步骤 8:正在打开${mail.label}...`); + await addLog(`步骤 ${visibleStep}:正在打开${mail.label}...`); if (mail.provider === '2925' && typeof ensureMail2925MailboxSession === 'function') { await ensureMail2925MailboxSession({ accountId: state.currentMail2925AccountId || null, forceRelogin: false, allowLoginWhenOnLoginPage: Boolean(state?.mail2925UseAccountPool), expectedMailboxEmail: getExpectedMail2925MailboxEmail(state), - actionLabel: 'Step 8: ensure 2925 mailbox session', + actionLabel: `Step ${visibleStep}: ensure 2925 mailbox session`, }); } else { await focusOrOpenMailTab(mail); } if (mail.provider === '2925') { - await addLog(`步骤 8:将直接使用当前已登录的 ${mail.label} 轮询验证码。`, 'info'); + await addLog(`步骤 ${visibleStep}:将直接使用当前已登录的 ${mail.label} 轮询验证码。`, 'info'); } } @@ -179,10 +194,11 @@ ...state, step8VerificationTargetEmail: displayedVerificationEmail || '', }, mail, { + completionStep: visibleStep, filterAfterTimestamp: verificationFilterAfterTimestamp, sessionKey: verificationSessionKey, disableTimeBudgetCap: mail.provider === '2925', - getRemainingTimeMs: getStep8RemainingTimeResolver(state?.oauthUrl || ''), + getRemainingTimeMs: getStep8RemainingTimeResolver(state?.oauthUrl || '', visibleStep), requestFreshCodeFirst: false, targetEmail: fixedTargetEmail, resendIntervalMs: (mail.provider === HOTMAIL_PROVIDER || mail.provider === '2925') @@ -206,6 +222,8 @@ await runStep8Attempt(currentState); return; } catch (err) { + const visibleStep = getVisibleStep(currentState, 8); + const authLoginStep = getAuthLoginStepForVisibleStep(visibleStep); if (!isVerificationMailPollingError(err) && !isStep8RestartStep7Error(err)) { throw err; } @@ -218,26 +236,27 @@ mailPollingAttempt += 1; await addLog( isStep8RestartStep7Error(err) - ? `步骤 8:检测到认证页进入重试/超时报错状态,准备从步骤 7 重新开始(${mailPollingAttempt}/${STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS})...` - : `步骤 8:检测到邮箱轮询类失败,准备从步骤 7 重新开始(${mailPollingAttempt}/${STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS})...`, + ? `步骤 ${visibleStep}:检测到认证页进入重试/超时报错状态,准备从步骤 ${authLoginStep} 重新开始(${mailPollingAttempt}/${STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS})...` + : `步骤 ${visibleStep}:检测到邮箱轮询类失败,准备从步骤 ${authLoginStep} 重新开始(${mailPollingAttempt}/${STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS})...`, 'warn' ); await rerunStep7ForStep8Recovery({ logMessage: isStep8RestartStep7Error(err) - ? '步骤 8:认证页进入重试/超时报错状态,正在回到步骤 7 重新发起登录流程...' - : '步骤 8:正在回到步骤 7,重新发起登录验证码流程...', + ? `步骤 ${visibleStep}:认证页进入重试/超时报错状态,正在回到步骤 ${authLoginStep} 重新发起登录流程...` + : `步骤 ${visibleStep}:正在回到步骤 ${authLoginStep},重新发起登录验证码流程...`, }); currentState = await getState(); } } + const visibleStep = getVisibleStep(currentState, 8); if (lastMailPollingError) { throw new Error( - `步骤 8:登录验证码流程在 ${STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS} 轮邮箱轮询恢复后仍未成功。最后一次原因:${lastMailPollingError.message}` + `步骤 ${visibleStep}:登录验证码流程在 ${STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS} 轮邮箱轮询恢复后仍未成功。最后一次原因:${lastMailPollingError.message}` ); } - throw new Error('步骤 8:登录验证码流程未成功完成。'); + throw new Error(`步骤 ${visibleStep}:登录验证码流程未成功完成。`); } return { executeStep8 }; diff --git a/background/steps/fill-plus-checkout.js b/background/steps/fill-plus-checkout.js new file mode 100644 index 0000000..cec29ba --- /dev/null +++ b/background/steps/fill-plus-checkout.js @@ -0,0 +1,540 @@ +(function attachBackgroundPlusCheckoutBilling(root, factory) { + root.MultiPageBackgroundPlusCheckoutBilling = factory(); +})(typeof self !== 'undefined' ? self : globalThis, function createBackgroundPlusCheckoutBillingModule() { + const PLUS_CHECKOUT_SOURCE = 'plus-checkout'; + const PLUS_CHECKOUT_INJECT_FILES = ['content/utils.js', 'content/plus-checkout.js']; + const PLUS_CHECKOUT_URL_PATTERN = /^https:\/\/chatgpt\.com\/checkout(?:\/|$)/i; + const PLUS_CHECKOUT_FRAME_READY_DELAY_MS = 500; + const MEIGUODIZHI_ADDRESS_ENDPOINT = 'https://www.meiguodizhi.com/api/v1/dz'; + const MEIGUODIZHI_PATH_BY_COUNTRY = { + AU: '/au-address', + DE: '/de-address', + FR: '/fr-address', + US: '/', + }; + + function createPlusCheckoutBillingExecutor(deps = {}) { + const { + addLog, + chrome, + completeStepFromBackground, + ensureContentScriptReadyOnTabUntilStopped, + fetch: fetchImpl = null, + generateRandomName, + getAddressSeedForCountry, + getTabId, + isTabAlive, + setState, + sleepWithStop, + waitForTabCompleteUntilStopped, + waitForTabUrlMatchUntilStopped, + } = deps; + + function isPlusCheckoutUrl(url = '') { + return PLUS_CHECKOUT_URL_PATTERN.test(String(url || '')); + } + + function normalizeText(value = '') { + return String(value || '').replace(/\s+/g, ' ').trim(); + } + + function hasCompleteAddressFallback(seed) { + const fallback = seed?.fallback || {}; + return Boolean( + normalizeText(fallback.address1) + && normalizeText(fallback.city) + && normalizeText(fallback.postalCode) + ); + } + + function buildDirectAddressSeed(countryCode, apiAddress, fallbackSeed) { + const address1 = normalizeText(apiAddress?.Address); + const city = normalizeText(apiAddress?.City); + const region = normalizeText(apiAddress?.State || apiAddress?.State_Full); + const postalCode = normalizeText(apiAddress?.Zip_Code); + if (!address1 || !city || !postalCode) { + return null; + } + return { + ...(fallbackSeed || {}), + countryCode, + query: [address1, city].filter(Boolean).join(', '), + source: 'meiguodizhi', + skipAutocomplete: true, + fallback: { + ...(fallbackSeed?.fallback || {}), + address1, + city, + region, + postalCode, + }, + }; + } + + async function fetchMeiguodizhiAddressSeed(countryCode, fallbackSeed) { + if (typeof fetchImpl !== 'function') { + return null; + } + const path = MEIGUODIZHI_PATH_BY_COUNTRY[countryCode] || MEIGUODIZHI_PATH_BY_COUNTRY.DE; + const city = normalizeText(fallbackSeed?.fallback?.city || fallbackSeed?.query || ''); + const response = await fetchImpl(MEIGUODIZHI_ADDRESS_ENDPOINT, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + city, + path, + method: 'refresh', + }), + }); + if (!response?.ok) { + throw new Error(`HTTP ${response?.status || 0}`); + } + const data = await response.json(); + if (data?.status !== 'ok') { + throw new Error(data?.message || data?.status || 'unknown response'); + } + return buildDirectAddressSeed(countryCode, data.address || {}, fallbackSeed); + } + + async function resolveBillingAddressSeed(state = {}, countryOverride = '') { + const requestedCountry = normalizeText(countryOverride || state.plusCheckoutCountry || 'DE'); + const fallbackSeed = getAddressSeedForCountry(requestedCountry, { + fallbackCountry: 'DE', + }); + if (!fallbackSeed) { + throw new Error('步骤 7:未找到可用的本地账单地址种子。'); + } + + const countryCode = fallbackSeed.countryCode || 'DE'; + try { + const remoteSeed = await fetchMeiguodizhiAddressSeed(countryCode, fallbackSeed); + if (hasCompleteAddressFallback(remoteSeed)) { + await addLog( + `步骤 7:已从 meiguodizhi 接口获取账单地址(${remoteSeed.fallback.city} / ${remoteSeed.fallback.postalCode}),将跳过 Google 地址推荐。`, + 'info' + ); + return remoteSeed; + } + await addLog('步骤 7:meiguodizhi 接口返回的地址字段不完整,回退到本地地址种子。', 'warn'); + } catch (error) { + await addLog(`步骤 7:meiguodizhi 地址接口不可用,回退到本地地址种子:${error?.message || String(error || '')}`, 'warn'); + } + + return fallbackSeed; + } + + async function getAlivePlusCheckoutTabId(tabId) { + if (!Number.isInteger(tabId) || tabId <= 0) { + return null; + } + if (!chrome?.tabs?.get) { + return tabId; + } + const tab = await chrome.tabs.get(tabId).catch(() => null); + return tab && isPlusCheckoutUrl(tab.url) ? tabId : null; + } + + async function getCurrentPlusCheckoutTabId() { + if (!chrome?.tabs?.query) { + return null; + } + + const activeTabs = await chrome.tabs.query({ active: true, currentWindow: true }).catch(() => []); + const activeCheckoutTab = activeTabs.find((tab) => Number.isInteger(tab?.id) && isPlusCheckoutUrl(tab.url)); + if (activeCheckoutTab) { + return activeCheckoutTab.id; + } + + const checkoutTabs = await chrome.tabs.query({ url: 'https://chatgpt.com/checkout/*' }).catch(() => []); + const checkoutTab = checkoutTabs.find((tab) => Number.isInteger(tab?.id) && isPlusCheckoutUrl(tab.url)); + return checkoutTab?.id || null; + } + + async function getCheckoutFrames(tabId) { + if (!chrome?.webNavigation?.getAllFrames) { + return [{ frameId: 0, url: '' }]; + } + const frames = await chrome.webNavigation.getAllFrames({ tabId }).catch(() => null); + if (!Array.isArray(frames) || !frames.length) { + return [{ frameId: 0, url: '' }]; + } + return frames + .filter((frame) => Number.isInteger(frame?.frameId)) + .sort((left, right) => Number(left.frameId) - Number(right.frameId)); + } + + async function pingCheckoutFrame(tabId, frameId) { + try { + const pong = await chrome.tabs.sendMessage(tabId, { + type: 'PING', + source: 'background', + payload: {}, + }, { + frameId: Number.isInteger(frameId) ? frameId : 0, + }); + return Boolean(pong?.ok && (!pong.source || pong.source === PLUS_CHECKOUT_SOURCE)); + } catch { + return false; + } + } + + async function ensurePlusCheckoutFrameReady(tabId, frameId) { + if (await pingCheckoutFrame(tabId, frameId)) { + return true; + } + if (!chrome?.scripting?.executeScript) { + return false; + } + + try { + await chrome.scripting.executeScript({ + target: { tabId, frameIds: [frameId] }, + func: (injectedSource) => { + window.__MULTIPAGE_SOURCE = injectedSource; + }, + args: [PLUS_CHECKOUT_SOURCE], + }); + await chrome.scripting.executeScript({ + target: { tabId, frameIds: [frameId] }, + files: PLUS_CHECKOUT_INJECT_FILES, + }); + } catch { + // If the frame was already injected or navigated mid-injection, ping once more below. + } + + await sleepWithStop(PLUS_CHECKOUT_FRAME_READY_DELAY_MS); + return await pingCheckoutFrame(tabId, frameId); + } + + async function ensurePlusCheckoutFramesReady(tabId, frames) { + const checkedFrames = []; + for (const frame of frames) { + const ready = await ensurePlusCheckoutFrameReady(tabId, frame.frameId); + checkedFrames.push({ ...frame, ready }); + } + return checkedFrames; + } + + async function sendFrameMessage(tabId, frameId, message) { + return chrome.tabs.sendMessage(tabId, message, { + frameId: Number.isInteger(frameId) ? frameId : 0, + }); + } + + async function inspectCheckoutFrame(tabId, frame) { + try { + const result = await sendFrameMessage(tabId, frame.frameId, { + type: 'PLUS_CHECKOUT_GET_STATE', + source: 'background', + payload: {}, + }); + if (result?.error) { + return { frame, error: result.error }; + } + return { frame: { ...frame, ready: true }, result: result || {} }; + } catch (error) { + const readyError = frame.ready === false ? 'content-script-not-ready' : ''; + const message = error?.message || String(error || ''); + return { frame, error: readyError ? `${readyError}: ${message}` : message }; + } + } + + function isPaymentFrameUrl(url = '') { + return /elements-inner-payment|componentName=payment/i.test(String(url || '')); + } + + function isAddressFrameUrl(url = '') { + return /elements-inner-address|componentName=address/i.test(String(url || '')); + } + + function isAutocompleteFrameUrl(url = '') { + return /elements-inner-autocompl/i.test(String(url || '')); + } + + function buildFrameSummary(inspections) { + return inspections + .map((item) => { + const flags = []; + if (item.result?.hasPayPal) flags.push('paypal'); + if (item.result?.billingFieldsVisible) flags.push('billing'); + if (item.result?.hasSubscribeButton) flags.push('subscribe'); + if (!flags.length && item.error) flags.push(item.error); + if (!flags.length) flags.push('no-match'); + return `${item.frame.frameId}:${item.frame.url || 'about:blank'}:${flags.join(',')}`; + }) + .slice(0, 8) + .join(' | '); + } + + async function inspectCheckoutFrames(tabId, frames) { + const inspections = []; + for (const frame of frames) { + const inspection = await inspectCheckoutFrame(tabId, frame); + inspections.push(inspection); + } + return inspections; + } + + function pickPaymentFrame(inspections) { + return inspections.find((item) => item.result?.hasPayPal || item.result?.paypalCandidates?.length) + || inspections.find((item) => isPaymentFrameUrl(item.frame.url)) + || null; + } + + function pickBillingFrame(inspections) { + return inspections.find((item) => item.result?.billingFieldsVisible) + || inspections.find((item) => isAddressFrameUrl(item.frame.url)) + || null; + } + + function pickSubscribeFrame(inspections) { + return inspections.find((item) => item.result?.hasSubscribeButton) + || inspections.find((item) => item.frame.frameId === 0) + || null; + } + + async function getReadyCheckoutFrames(tabId) { + return ensurePlusCheckoutFramesReady(tabId, await getCheckoutFrames(tabId)); + } + + async function resolveOptionalFrameByUrl(tabId, predicate) { + const frames = await getCheckoutFrames(tabId); + const frame = frames.find((item) => predicate(item.url)); + if (!frame) { + return null; + } + const ready = await ensurePlusCheckoutFrameReady(tabId, frame.frameId); + return { + frame, + ready, + }; + } + + async function resolvePaymentFrame(tabId, frames) { + const inspections = await inspectCheckoutFrames(tabId, frames); + const picked = pickPaymentFrame(inspections); + if (picked) { + return { + frameId: picked.frame.frameId, + frameUrl: picked.frame.url || '', + ready: picked.frame.ready !== false, + inspections, + }; + } + + return { + frameId: null, + frameUrl: '', + inspections, + }; + } + + async function waitForBillingFrame(tabId) { + while (true) { + const frames = await getReadyCheckoutFrames(tabId); + const inspections = await inspectCheckoutFrames(tabId, frames); + const picked = pickBillingFrame(inspections); + if (picked) { + return { + frameId: picked.frame.frameId, + frameUrl: picked.frame.url || '', + countryText: picked.result?.countryText || '', + ready: picked.frame.ready !== false, + inspections, + }; + } + await sleepWithStop(250); + } + } + + async function waitForSubscribeFrame(tabId, candidateFrames) { + const frames = candidateFrames.length ? candidateFrames : [{ frameId: 0, url: '' }]; + while (true) { + const readyFrames = await ensurePlusCheckoutFramesReady(tabId, frames); + const inspections = await inspectCheckoutFrames(tabId, readyFrames); + const picked = pickSubscribeFrame(inspections); + if (picked) { + return picked.frame; + } + await sleepWithStop(250); + } + } + + async function getCheckoutTabId(state = {}) { + const registeredTabId = await getTabId(PLUS_CHECKOUT_SOURCE); + if (registeredTabId && await isTabAlive(PLUS_CHECKOUT_SOURCE)) { + const aliveRegisteredTabId = await getAlivePlusCheckoutTabId(registeredTabId); + if (aliveRegisteredTabId) { + return aliveRegisteredTabId; + } + } + const storedTabId = Number(state.plusCheckoutTabId) || 0; + if (storedTabId) { + const aliveStoredTabId = await getAlivePlusCheckoutTabId(storedTabId); + if (aliveStoredTabId) { + return aliveStoredTabId; + } + } + const currentCheckoutTabId = await getCurrentPlusCheckoutTabId(); + if (currentCheckoutTabId) { + await addLog('步骤 7:检测到当前已在 Plus Checkout 页面,直接接管当前标签页。', 'info'); + return currentCheckoutTabId; + } + throw new Error('步骤 7:未找到 Plus Checkout 标签页。请先打开 Plus Checkout 页面,或完成步骤 6。'); + } + + async function executePlusCheckoutBilling(state = {}) { + const tabId = await getCheckoutTabId(state); + await addLog('步骤 7:正在等待 Plus Checkout 页面加载完成...', 'info'); + await waitForTabCompleteUntilStopped(tabId); + await sleepWithStop(1000); + + await ensureContentScriptReadyOnTabUntilStopped(PLUS_CHECKOUT_SOURCE, tabId, { + inject: PLUS_CHECKOUT_INJECT_FILES, + injectSource: PLUS_CHECKOUT_SOURCE, + logMessage: '步骤 7:Checkout 页面仍在加载,等待账单填写脚本就绪...', + }); + const readyFrames = await getReadyCheckoutFrames(tabId); + const paymentFrame = await resolvePaymentFrame(tabId, readyFrames); + if (paymentFrame.frameId === null) { + const frameSummary = buildFrameSummary(paymentFrame.inspections); + throw new Error(`步骤 7:未在主页面或 iframe 中发现 PayPal DOM,无法自动切换付款方式。frame 摘要:${frameSummary}`); + } + if (!paymentFrame.ready) { + throw new Error(`步骤 7:已定位到 PayPal 所在 iframe(frameId=${paymentFrame.frameId}),但账单脚本无法注入该 iframe。请提供该 iframe 的控制台结构或截图。`); + } + + if (paymentFrame.frameId !== 0) { + await addLog(`步骤 7:PayPal 位于 checkout iframe(frameId=${paymentFrame.frameId}),将改为在该 frame 内操作。`, 'info'); + } + + const randomName = generateRandomName(); + const fullName = [randomName.firstName, randomName.lastName].filter(Boolean).join(' '); + + await addLog('步骤 7:正在切换 PayPal 付款方式...', 'info'); + const paymentResult = await sendFrameMessage(tabId, paymentFrame.frameId, { + type: 'PLUS_CHECKOUT_SELECT_PAYPAL', + source: 'background', + payload: {}, + }); + if (paymentResult?.error) { + throw new Error(paymentResult.error); + } + + const billingFrame = await waitForBillingFrame(tabId); + if (!billingFrame.ready) { + throw new Error(`步骤 7:已定位到账单地址 iframe(frameId=${billingFrame.frameId}),但账单脚本无法注入该 iframe。请提供该 iframe 的控制台结构或截图。`); + } + if (billingFrame.frameId !== paymentFrame.frameId) { + await addLog(`步骤 7:账单地址位于 checkout iframe(frameId=${billingFrame.frameId}),将改为在该 frame 内填写。`, 'info'); + } + + const addressSeed = await resolveBillingAddressSeed(state, billingFrame.countryText); + if (!addressSeed) { + throw new Error('步骤 7:未找到可用的本地账单地址种子。'); + } + + await addLog(`步骤 7:正在填写账单地址(${addressSeed.countryCode} / ${addressSeed.query})...`, 'info'); + const autocompleteFrame = await resolveOptionalFrameByUrl(tabId, isAutocompleteFrameUrl); + let result = null; + if (!addressSeed.skipAutocomplete && autocompleteFrame?.frame && autocompleteFrame.frame.frameId !== billingFrame.frameId) { + if (!autocompleteFrame.ready) { + throw new Error('步骤 7:发现 Google 地址推荐 iframe,但无法注入账单脚本。请提供该 iframe 的控制台结构。'); + } + await addLog(`步骤 7:Google 地址推荐位于独立 iframe(frameId=${autocompleteFrame.frame.frameId}),将拆分输入与选择动作。`, 'info'); + + const queryResult = await sendFrameMessage(tabId, billingFrame.frameId, { + type: 'PLUS_CHECKOUT_FILL_ADDRESS_QUERY', + source: 'background', + payload: { + fullName, + addressSeed, + }, + }); + if (queryResult?.error) { + throw new Error(queryResult.error); + } + + const suggestionResult = await sendFrameMessage(tabId, autocompleteFrame.frame.frameId, { + type: 'PLUS_CHECKOUT_SELECT_ADDRESS_SUGGESTION', + source: 'background', + payload: { + addressSeed, + }, + }); + if (suggestionResult?.error) { + throw new Error(suggestionResult.error); + } + + const structuredResult = await sendFrameMessage(tabId, billingFrame.frameId, { + type: 'PLUS_CHECKOUT_ENSURE_BILLING_ADDRESS', + source: 'background', + payload: { + addressSeed, + }, + }); + if (structuredResult?.error) { + throw new Error(structuredResult.error); + } + + result = { + ...structuredResult, + selectedAddressText: suggestionResult?.selectedAddressText || '', + }; + } else { + result = await sendFrameMessage(tabId, billingFrame.frameId, { + type: 'PLUS_CHECKOUT_FILL_BILLING_ADDRESS', + source: 'background', + payload: { + fullName, + addressSeed, + }, + }); + + if (result?.error) { + throw new Error(result.error); + } + } + + await addLog('步骤 7:账单地址已填写完成,正在定位订阅按钮...', 'info'); + const subscribeFrame = await waitForSubscribeFrame(tabId, [ + { frameId: 0, url: '' }, + { frameId: paymentFrame.frameId, url: paymentFrame.frameUrl || '' }, + { frameId: billingFrame.frameId, url: billingFrame.frameUrl || '' }, + ]); + const subscribeResult = await sendFrameMessage(tabId, subscribeFrame.frameId, { + type: 'PLUS_CHECKOUT_CLICK_SUBSCRIBE', + source: 'background', + payload: {}, + }); + if (subscribeResult?.error) { + throw new Error(subscribeResult.error); + } + + await setState({ + plusCheckoutTabId: tabId, + plusBillingCountryText: result?.countryText || '', + plusBillingAddress: result?.structuredAddress || null, + }); + + await addLog('步骤 7:账单地址已提交,正在等待跳转到 PayPal...', 'info'); + await waitForTabUrlMatchUntilStopped(tabId, (url) => /paypal\./i.test(url)); + await waitForTabCompleteUntilStopped(tabId); + await sleepWithStop(1000); + + await completeStepFromBackground(7, { + plusBillingCountryText: result?.countryText || '', + }); + } + + return { + executePlusCheckoutBilling, + }; + } + + return { + createPlusCheckoutBillingExecutor, + }; +}); diff --git a/background/steps/oauth-login.js b/background/steps/oauth-login.js index f3209ea..d12ca49 100644 --- a/background/steps/oauth-login.js +++ b/background/steps/oauth-login.js @@ -40,7 +40,13 @@ return /缺少|未配置|请输入|无效|错误|失败|401|认证失败|未授权|unauthorized|invalid/i.test(message); } + function getVisibleStep(state, fallback = 7) { + const visibleStep = Math.floor(Number(state?.visibleStep) || 0); + return visibleStep > 0 ? visibleStep : fallback; + } + async function executeStep7(state) { + const visibleStep = getVisibleStep(state, 7); if (!state.email) { throw new Error('缺少邮箱地址,请先完成步骤 3。'); } @@ -54,22 +60,22 @@ try { const currentState = attempt === 1 ? state : await getState(); const password = currentState.password || currentState.customPassword || ''; - const oauthUrl = await refreshOAuthUrlBeforeStep6(currentState); + const oauthUrl = await refreshOAuthUrlBeforeStep6(currentState, { visibleStep }); if (typeof startOAuthFlowTimeoutWindow === 'function') { - await startOAuthFlowTimeoutWindow({ step: 7, oauthUrl }); + await startOAuthFlowTimeoutWindow({ step: visibleStep, oauthUrl }); } const loginTimeoutMs = typeof getOAuthFlowStepTimeoutMs === 'function' ? await getOAuthFlowStepTimeoutMs(180000, { - step: 7, + step: visibleStep, actionLabel: 'OAuth 登录并进入验证码页', oauthUrl, }) : 180000; if (attempt === 1) { - await addLog('步骤 7:正在打开最新 OAuth 链接并登录...'); + await addLog(`步骤 ${visibleStep}:正在打开最新 OAuth 链接并登录...`); } else { - await addLog(`步骤 7:上一轮失败后,正在进行第 ${attempt} 次尝试(最多 ${STEP6_MAX_ATTEMPTS} 次)...`, 'warn'); + await addLog(`步骤 ${visibleStep}:上一轮失败后,正在进行第 ${attempt} 次尝试(最多 ${STEP6_MAX_ATTEMPTS} 次)...`, 'warn'); } await reuseOrCreateTab('signup-page', oauthUrl); @@ -83,13 +89,14 @@ payload: { email: currentState.email, password, + visibleStep, }, }, { timeoutMs: loginTimeoutMs, responseTimeoutMs: loginTimeoutMs, retryDelayMs: 700, - logMessage: '步骤 7:认证页正在切换,等待页面重新就绪后继续登录...', + logMessage: `步骤 ${visibleStep}:认证页正在切换,等待页面重新就绪后继续登录...`, } ); @@ -98,9 +105,16 @@ } if (isStep6SuccessResult(result)) { - await completeStepFromBackground(7, { + const completionPayload = { loginVerificationRequestedAt: result.loginVerificationRequestedAt || null, - }); + }; + if (result.skipLoginVerificationStep) { + completionPayload.skipLoginVerificationStep = true; + } + if (result.directOAuthConsentPage) { + completionPayload.directOAuthConsentPage = true; + } + await completeStepFromBackground(visibleStep, completionPayload); return; } @@ -118,7 +132,7 @@ } if (isManagementSecretConfigError(err)) { await addLog( - `步骤 7:检测到来源后台管理密钥缺失或错误,不再重试,当前流程停止。原因:${getErrorMessage(err)}`, + `步骤 ${visibleStep}:检测到来源后台管理密钥缺失或错误,不再重试,当前流程停止。原因:${getErrorMessage(err)}`, 'error' ); throw err; @@ -128,11 +142,11 @@ break; } - await addLog(`步骤 7:第 ${attempt} 次尝试失败,原因:${getErrorMessage(err)};准备重试...`, 'warn'); + await addLog(`步骤 ${visibleStep}:第 ${attempt} 次尝试失败,原因:${getErrorMessage(err)};准备重试...`, 'warn'); } } - throw new Error(`步骤 7:判断失败后已重试 ${STEP6_MAX_ATTEMPTS - 1} 次,仍未成功。最后原因:${getErrorMessage(lastError)}`); + throw new Error(`步骤 ${visibleStep}:判断失败后已重试 ${STEP6_MAX_ATTEMPTS - 1} 次,仍未成功。最后原因:${getErrorMessage(lastError)}`); } return { executeStep7 }; diff --git a/background/steps/paypal-approve.js b/background/steps/paypal-approve.js new file mode 100644 index 0000000..d69540d --- /dev/null +++ b/background/steps/paypal-approve.js @@ -0,0 +1,293 @@ +(function attachBackgroundPayPalApprove(root, factory) { + root.MultiPageBackgroundPayPalApprove = factory(); +})(typeof self !== 'undefined' ? self : globalThis, function createBackgroundPayPalApproveModule() { + const PAYPAL_SOURCE = 'paypal-flow'; + const PLUS_CHECKOUT_SOURCE = 'plus-checkout'; + const PAYPAL_INJECT_FILES = ['content/utils.js', 'content/paypal-flow.js']; + const PAYPAL_LOGIN_TRANSITION_TIMEOUT_MS = 30000; + const PAYPAL_LOGIN_TRANSITION_POLL_MS = 500; + + function createPayPalApproveExecutor(deps = {}) { + const { + addLog, + chrome, + completeStepFromBackground, + ensureContentScriptReadyOnTabUntilStopped, + getTabId, + isTabAlive, + sendTabMessageUntilStopped, + setState, + sleepWithStop, + waitForTabCompleteUntilStopped, + waitForTabUrlMatchUntilStopped, + } = deps; + + async function resolvePayPalTabId(state = {}) { + const paypalTabId = await getTabId(PAYPAL_SOURCE); + if (paypalTabId && await isTabAlive(PAYPAL_SOURCE)) { + return paypalTabId; + } + const discoveredPayPalTabId = await findOpenPayPalTabId(); + if (discoveredPayPalTabId) { + await addLog('步骤 8:已从当前浏览器标签中发现 PayPal 页面,正在接管继续执行。', 'info'); + return discoveredPayPalTabId; + } + const checkoutTabId = await getTabId(PLUS_CHECKOUT_SOURCE); + if (checkoutTabId) { + return checkoutTabId; + } + const storedTabId = Number(state.plusCheckoutTabId) || 0; + if (storedTabId) { + return storedTabId; + } + throw new Error('步骤 8:未找到 PayPal 标签页,请先完成步骤 7。'); + } + + async function findOpenPayPalTabId() { + if (!chrome?.tabs?.query) { + return 0; + } + + const tabs = await chrome.tabs.query({}).catch(() => []); + const candidates = (Array.isArray(tabs) ? tabs : []) + .filter((tab) => Number.isInteger(tab?.id) && isPayPalUrl(tab.url || '')); + if (!candidates.length) { + return 0; + } + + const match = candidates.find((tab) => tab.active && tab.currentWindow) + || candidates.find((tab) => tab.active) + || candidates[0]; + if (match?.id && chrome?.tabs?.update) { + await chrome.tabs.update(match.id, { active: true }).catch(() => {}); + } + return match?.id || 0; + } + + async function ensurePayPalReady(tabId, logMessage = '') { + await waitForTabUrlMatchUntilStopped(tabId, (url) => /paypal\./i.test(url)); + await waitForTabCompleteUntilStopped(tabId); + await sleepWithStop(1000); + await ensureContentScriptReadyOnTabUntilStopped(PAYPAL_SOURCE, tabId, { + inject: PAYPAL_INJECT_FILES, + injectSource: PAYPAL_SOURCE, + logMessage: logMessage || '步骤 8:PayPal 页面仍在加载,等待脚本就绪...', + }); + } + + async function getPayPalState(tabId) { + const result = await sendTabMessageUntilStopped(tabId, PAYPAL_SOURCE, { + type: 'PAYPAL_GET_STATE', + source: 'background', + payload: {}, + }); + if (result?.error) { + throw new Error(result.error); + } + return result || {}; + } + + async function dismissPrompts(tabId) { + const result = await sendTabMessageUntilStopped(tabId, PAYPAL_SOURCE, { + type: 'PAYPAL_DISMISS_PROMPTS', + source: 'background', + payload: {}, + }); + if (result?.error) { + throw new Error(result.error); + } + return result || {}; + } + + async function submitLogin(tabId, state = {}) { + if (!state.paypalPassword) { + throw new Error('步骤 8:未配置 PayPal 密码,请先在侧边栏填写。'); + } + await addLog('步骤 8:正在填写 PayPal 登录信息并提交...', 'info'); + const result = await sendTabMessageUntilStopped(tabId, PAYPAL_SOURCE, { + type: 'PAYPAL_SUBMIT_LOGIN', + source: 'background', + payload: { + email: state.paypalEmail || '', + password: state.paypalPassword || '', + }, + }); + if (result?.error) { + throw new Error(result.error); + } + return result || {}; + } + + function isPayPalUrl(url = '') { + return /paypal\./i.test(String(url || '')); + } + + function isPayPalPasswordState(pageState = {}) { + return Boolean(pageState.hasPasswordInput) + || pageState.loginPhase === 'password' + || pageState.loginPhase === 'login_combined'; + } + + async function waitForPayPalPostLoginDecision(tabId, actionResult = {}) { + const phase = String(actionResult?.phase || '').trim(); + const startedAt = Date.now(); + + while (Date.now() - startedAt < PAYPAL_LOGIN_TRANSITION_TIMEOUT_MS) { + const tab = await chrome.tabs.get(tabId).catch(() => null); + if (!tab) { + throw new Error('步骤 8:PayPal 标签页已关闭,无法继续识别登录后的页面。'); + } + + const currentUrl = tab.url || ''; + if (!currentUrl) { + await sleepWithStop(PAYPAL_LOGIN_TRANSITION_POLL_MS); + continue; + } + if (currentUrl && !isPayPalUrl(currentUrl)) { + return { + outcome: 'left_paypal', + url: currentUrl, + }; + } + + if (tab.status !== 'complete') { + await sleepWithStop(PAYPAL_LOGIN_TRANSITION_POLL_MS); + continue; + } + + await ensurePayPalReady( + tabId, + phase === 'email_submitted' + ? '步骤 8:PayPal 账号已提交,正在识别下一页...' + : '步骤 8:PayPal 密码已提交,正在识别跳转结果...' + ); + const pageState = await getPayPalState(tabId); + + if (pageState.hasPasskeyPrompt) { + return { + outcome: 'prompt', + pageState, + }; + } + + if (pageState.approveReady) { + return { + outcome: 'approve_ready', + pageState, + }; + } + + if (phase === 'email_submitted' && isPayPalPasswordState(pageState)) { + return { + outcome: 'password_ready', + pageState, + }; + } + + if (phase === 'password_submitted' && !pageState.needsLogin) { + return { + outcome: 'post_login_state', + pageState, + }; + } + + await sleepWithStop(PAYPAL_LOGIN_TRANSITION_POLL_MS); + } + + return { + outcome: 'timeout', + phase, + }; + } + + async function clickApprove(tabId) { + const result = await sendTabMessageUntilStopped(tabId, PAYPAL_SOURCE, { + type: 'PAYPAL_CLICK_APPROVE', + source: 'background', + payload: {}, + }); + if (result?.error) { + throw new Error(result.error); + } + return Boolean(result?.clicked); + } + + async function executePayPalApprove(state = {}) { + const tabId = await resolvePayPalTabId(state); + await ensurePayPalReady(tabId); + await setState({ plusCheckoutTabId: tabId }); + + let loggedWaiting = false; + while (true) { + const currentUrl = (await chrome.tabs.get(tabId).catch(() => null))?.url || ''; + if (currentUrl && !isPayPalUrl(currentUrl)) { + await addLog('步骤 8:PayPal 已跳转离开授权页,准备进入回跳确认。', 'ok'); + break; + } + + await ensurePayPalReady(tabId, '步骤 8:PayPal 页面正在切换,等待脚本重新就绪...'); + const pageState = await getPayPalState(tabId); + + if (pageState.needsLogin) { + const submitResult = await submitLogin(tabId, state); + const decision = await waitForPayPalPostLoginDecision(tabId, submitResult); + if (decision.outcome === 'left_paypal') { + await addLog('步骤 8:PayPal 登录后已跳转离开登录/授权页,继续进入回跳确认。', 'ok'); + break; + } + if (decision.outcome === 'password_ready') { + await addLog('步骤 8:PayPal 账号页提交后已识别到密码页,继续填写密码。', 'info'); + } else if (decision.outcome === 'approve_ready') { + await addLog('步骤 8:PayPal 登录后已识别到授权确认页,继续点击授权。', 'info'); + } else if (decision.outcome === 'prompt') { + await addLog('步骤 8:PayPal 登录后已识别到提示弹窗,继续处理弹窗。', 'info'); + } else if (decision.outcome === 'timeout') { + await addLog('步骤 8:PayPal 登录动作后暂未识别到新页面,重新检查当前页面状态。', 'warn'); + } + loggedWaiting = false; + continue; + } + + if (pageState.hasPasskeyPrompt) { + await addLog('步骤 8:检测到 PayPal 通行密钥提示,正在关闭...', 'info'); + await dismissPrompts(tabId); + await sleepWithStop(1000); + continue; + } + + const dismissed = await dismissPrompts(tabId).catch(() => ({ clicked: 0 })); + if (dismissed.clicked) { + await sleepWithStop(1000); + continue; + } + + if (pageState.approveReady) { + await addLog('步骤 8:正在点击 PayPal“同意并继续”...', 'info'); + const clicked = await clickApprove(tabId); + if (clicked) { + await setState({ plusPaypalApprovedAt: Date.now() }); + break; + } + } + + if (!loggedWaiting) { + loggedWaiting = true; + await addLog('步骤 8:等待 PayPal 授权按钮或下一步页面出现...', 'info'); + } + await sleepWithStop(500); + } + + await completeStepFromBackground(8, { + plusPaypalApprovedAt: Date.now(), + }); + } + + return { + executePayPalApprove, + }; + } + + return { + createPayPalApproveExecutor, + }; +}); diff --git a/background/steps/platform-verify.js b/background/steps/platform-verify.js index d4e01b4..b88f295 100644 --- a/background/steps/platform-verify.js +++ b/background/steps/platform-verify.js @@ -26,18 +26,31 @@ return String(value || '').trim(); } - function parseLocalhostCallback(rawUrl) { + function getVisibleStep(state, fallback = 10) { + const visibleStep = Math.floor(Number(state?.visibleStep) || 0); + return visibleStep > 0 ? visibleStep : fallback; + } + + function getConfirmStepForVisibleStep(visibleStep) { + return visibleStep >= 13 ? 12 : 9; + } + + function getAuthLoginStepForVisibleStep(visibleStep) { + return visibleStep >= 13 ? 10 : 7; + } + + function parseLocalhostCallback(rawUrl, visibleStep = 10, confirmStep = 9) { let parsed; try { parsed = new URL(rawUrl); } catch { - throw new Error('步骤 10 捕获到的 localhost OAuth 回调地址格式无效,请重新执行步骤 9。'); + throw new Error(`步骤 ${visibleStep} 捕获到的 localhost OAuth 回调地址格式无效,请重新执行步骤 ${confirmStep}。`); } const code = normalizeString(parsed.searchParams.get('code')); const state = normalizeString(parsed.searchParams.get('state')); if (!code || !state) { - throw new Error('步骤 10 捕获到的 localhost OAuth 回调地址缺少 code 或 state,请重新执行步骤 9。'); + throw new Error(`步骤 ${visibleStep} 捕获到的 localhost OAuth 回调地址缺少 code 或 state,请重新执行步骤 ${confirmStep}。`); } return { @@ -109,26 +122,28 @@ } async function executeCpaStep10(state) { + const visibleStep = getVisibleStep(state, 10); + const confirmStep = getConfirmStepForVisibleStep(visibleStep); if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) { - throw new Error('步骤 9 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 9。'); + throw new Error(`步骤 ${confirmStep} 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 ${confirmStep}。`); } if (!state.localhostUrl) { - throw new Error('缺少 localhost 回调地址,请先完成步骤 9。'); + throw new Error(`缺少 localhost 回调地址,请先完成步骤 ${confirmStep}。`); } if (!state.vpsUrl) { throw new Error('尚未填写 CPA 地址,请先在侧边栏输入。'); } if (shouldBypassStep9ForLocalCpa(state)) { - await addLog('步骤 10:检测到本地 CPA,且当前策略为“跳过第10步”,本轮不再重复提交回调地址。', 'info'); - await completeStepFromBackground(10, { + await addLog(`步骤 ${visibleStep}:检测到本地 CPA,且当前策略为“跳过第10步”,本轮不再重复提交回调地址。`, 'info'); + await completeStepFromBackground(visibleStep, { localhostUrl: state.localhostUrl, verifiedStatus: 'local-auto', }); return; } - await addLog('步骤 10:正在打开 CPA 面板...'); + await addLog(`步骤 ${visibleStep}:正在打开 CPA 面板...`); const injectFiles = ['content/activation-utils.js', 'content/utils.js', 'content/vps-panel.js']; let tabId = await getTabId('vps-panel'); @@ -149,20 +164,20 @@ inject: injectFiles, timeoutMs: 45000, retryDelayMs: 900, - logMessage: '步骤 10:CPA 面板仍在加载,正在重试连接...', + logMessage: `步骤 ${visibleStep}:CPA 面板仍在加载,正在重试连接...`, }); - await addLog('步骤 10:正在填写回调地址...'); + await addLog(`步骤 ${visibleStep}:正在填写回调地址...`); const result = await sendToContentScriptResilient('vps-panel', { type: 'EXECUTE_STEP', - step: 10, + step: visibleStep, source: 'background', - payload: { localhostUrl: state.localhostUrl, vpsPassword: state.vpsPassword }, + payload: { localhostUrl: state.localhostUrl, vpsPassword: state.vpsPassword, visibleStep }, }, { timeoutMs: 125000, responseTimeoutMs: 125000, retryDelayMs: 700, - logMessage: '步骤 10:CPA 面板通信未就绪,正在等待页面恢复...', + logMessage: `步骤 ${visibleStep}:CPA 面板通信未就绪,正在等待页面恢复...`, }); if (result?.error) { @@ -171,29 +186,31 @@ } async function executeCodex2ApiStep10(state) { + const visibleStep = getVisibleStep(state, 10); + const confirmStep = getConfirmStepForVisibleStep(visibleStep); if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) { - throw new Error('步骤 9 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 9。'); + throw new Error(`步骤 ${confirmStep} 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 ${confirmStep}。`); } if (!state.localhostUrl) { - throw new Error('缺少 localhost 回调地址,请先完成步骤 9。'); + throw new Error(`缺少 localhost 回调地址,请先完成步骤 ${confirmStep}。`); } if (!state.codex2apiSessionId) { - throw new Error('缺少 Codex2API 会话信息,请重新执行步骤 7。'); + throw new Error(`缺少 Codex2API 会话信息,请重新执行步骤 ${getAuthLoginStepForVisibleStep(visibleStep)}。`); } if (!normalizeString(state.codex2apiAdminKey)) { throw new Error('尚未配置 Codex2API 管理密钥,请先在侧边栏填写。'); } - const callback = parseLocalhostCallback(state.localhostUrl); + const callback = parseLocalhostCallback(state.localhostUrl, visibleStep, confirmStep); const expectedState = normalizeString(state.codex2apiOAuthState); if (expectedState && expectedState !== callback.state) { - throw new Error('Codex2API 回调 state 与当前授权会话不匹配,请重新执行步骤 7。'); + throw new Error(`Codex2API 回调 state 与当前授权会话不匹配,请重新执行步骤 ${getAuthLoginStepForVisibleStep(visibleStep)}。`); } const codex2apiUrl = normalizeCodex2ApiUrl(state.codex2apiUrl); const origin = new URL(codex2apiUrl).origin; - await addLog('步骤 10:正在向 Codex2API 提交回调并创建账号...'); + await addLog(`步骤 ${visibleStep}:正在向 Codex2API 提交回调并创建账号...`); const result = await fetchCodex2ApiJson(origin, '/api/admin/oauth/exchange-code', { adminKey: state.codex2apiAdminKey, method: 'POST', @@ -205,19 +222,21 @@ }); const verifiedStatus = normalizeString(result?.message) || 'Codex2API OAuth 账号添加成功'; - await addLog(`步骤 10:${verifiedStatus}`, 'ok'); - await completeStepFromBackground(10, { + await addLog(`步骤 ${visibleStep}:${verifiedStatus}`, 'ok'); + await completeStepFromBackground(visibleStep, { localhostUrl: callback.url, verifiedStatus, }); } async function executeSub2ApiStep10(state) { + const visibleStep = getVisibleStep(state, 10); + const confirmStep = getConfirmStepForVisibleStep(visibleStep); if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) { - throw new Error('步骤 9 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 9。'); + throw new Error(`步骤 ${confirmStep} 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 ${confirmStep}。`); } if (!state.localhostUrl) { - throw new Error('缺少 localhost 回调地址,请先完成步骤 9。'); + throw new Error(`缺少 localhost 回调地址,请先完成步骤 ${confirmStep}。`); } if (!state.sub2apiSessionId) { throw new Error('缺少 SUB2API 会话信息,请重新执行步骤 1。'); @@ -232,7 +251,7 @@ const sub2apiUrl = normalizeSub2ApiUrl(state.sub2apiUrl); const injectFiles = ['content/utils.js', 'content/sub2api-panel.js']; - await addLog('步骤 10:正在打开 SUB2API 后台...'); + await addLog(`步骤 ${visibleStep}:正在打开 SUB2API 后台...`); let tabId = await getTabId('sub2api-panel'); const alive = tabId && await isTabAlive('sub2api-panel'); @@ -254,12 +273,13 @@ injectSource: 'sub2api-panel', }); - await addLog('步骤 10:正在向 SUB2API 提交回调并创建账号...'); + await addLog(`步骤 ${visibleStep}:正在向 SUB2API 提交回调并创建账号...`); const result = await sendToContentScript('sub2api-panel', { type: 'EXECUTE_STEP', - step: 10, + step: visibleStep, source: 'background', payload: { + visibleStep, localhostUrl: state.localhostUrl, sub2apiUrl, sub2apiEmail: state.sub2apiEmail, diff --git a/background/steps/plus-return-confirm.js b/background/steps/plus-return-confirm.js new file mode 100644 index 0000000..c233dc6 --- /dev/null +++ b/background/steps/plus-return-confirm.js @@ -0,0 +1,64 @@ +(function attachBackgroundPlusReturnConfirm(root, factory) { + root.MultiPageBackgroundPlusReturnConfirm = factory(); +})(typeof self !== 'undefined' ? self : globalThis, function createBackgroundPlusReturnConfirmModule() { + const PAYPAL_SOURCE = 'paypal-flow'; + const PLUS_CHECKOUT_SOURCE = 'plus-checkout'; + + function createPlusReturnConfirmExecutor(deps = {}) { + const { + addLog, + completeStepFromBackground, + getTabId, + isTabAlive, + setState, + sleepWithStop, + waitForTabCompleteUntilStopped, + waitForTabUrlMatchUntilStopped, + } = deps; + + async function resolveReturnTabId(state = {}) { + const paypalTabId = await getTabId(PAYPAL_SOURCE); + if (paypalTabId && await isTabAlive(PAYPAL_SOURCE)) { + return paypalTabId; + } + const checkoutTabId = await getTabId(PLUS_CHECKOUT_SOURCE); + if (checkoutTabId) { + return checkoutTabId; + } + const storedTabId = Number(state.plusCheckoutTabId) || 0; + if (storedTabId) { + return storedTabId; + } + throw new Error('步骤 9:未找到 Plus / PayPal 标签页,无法确认订阅回跳。'); + } + + function isReturnUrl(url = '') { + return /https:\/\/(?:chatgpt\.com|chat\.openai\.com|openai\.com)\//i.test(String(url || '')) + && !/paypal\./i.test(String(url || '')); + } + + async function executePlusReturnConfirm(state = {}) { + const tabId = await resolveReturnTabId(state); + await addLog('步骤 9:正在等待 PayPal 授权后回跳到 ChatGPT / OpenAI 页面...', 'info'); + const tab = await waitForTabUrlMatchUntilStopped(tabId, isReturnUrl); + await waitForTabCompleteUntilStopped(tabId); + await sleepWithStop(1000); + + await setState({ + plusCheckoutTabId: tabId, + plusReturnUrl: tab?.url || '', + }); + await completeStepFromBackground(9, { + plusReturnUrl: tab?.url || '', + }); + } + + return { + executePlusReturnConfirm, + }; + } + + return { + createPlusReturnConfirmExecutor, + }; +}); diff --git a/background/verification-flow.js b/background/verification-flow.js index dbc9594..229bed7 100644 --- a/background/verification-flow.js +++ b/background/verification-flow.js @@ -175,25 +175,32 @@ return Math.max(0, Math.floor(Number(VERIFICATION_POLL_MAX_ROUNDS) || 1) - 1); } - async function confirmCustomVerificationStepBypass(step) { + function getCompletionStep(step, options = {}) { + const completionStep = Number(options.completionStep); + return Number.isFinite(completionStep) && completionStep > 0 ? completionStep : step; + } + + async function confirmCustomVerificationStepBypass(step, options = {}) { + const completionStep = getCompletionStep(step, options); + const promptStep = getCompletionStep(step, { completionStep: options.promptStep ?? completionStep }); const verificationLabel = getVerificationCodeLabel(step); - await addLog(`步骤 ${step}:当前为自定义邮箱模式,请手动在页面中输入${verificationLabel}验证码并进入下一页面。`, 'warn'); + await addLog(`步骤 ${completionStep}:当前为自定义邮箱模式,请手动在页面中输入${verificationLabel}验证码并进入下一页面。`, 'warn'); let response = null; try { - response = await confirmCustomVerificationStepBypassRequest(step); + response = await confirmCustomVerificationStepBypassRequest(promptStep); } catch { - throw new Error(`步骤 ${step}:无法打开确认弹窗,请先保持侧边栏打开后重试。`); + throw new Error(`步骤 ${completionStep}:无法打开确认弹窗,请先保持侧边栏打开后重试。`); } if (response?.error) { throw new Error(response.error); } if (step === 8 && response?.addPhoneDetected) { - throw new Error('步骤 8:验证码提交后页面进入手机号页面,当前流程无法继续自动授权。 URL: https://auth.openai.com/add-phone'); + throw new Error(`步骤 ${completionStep}:验证码提交后页面进入手机号页面,当前流程无法继续自动授权。 URL: https://auth.openai.com/add-phone`); } if (!response?.confirmed) { - throw new Error(`步骤 ${step}:已取消手动${verificationLabel}验证码确认。`); + throw new Error(`步骤 ${completionStep}:已取消手动${verificationLabel}验证码确认。`); } await setState({ @@ -201,8 +208,8 @@ signupVerificationRequestedAt: null, loginVerificationRequestedAt: null, }); - await deps.setStepStatus(step, 'skipped'); - await addLog(`步骤 ${step}:已确认手动完成${verificationLabel}验证码输入,当前步骤已跳过。`, 'warn'); + await deps.setStepStatus(completionStep, 'skipped'); + await addLog(`步骤 ${completionStep}:已确认手动完成${verificationLabel}验证码输入,当前步骤已跳过。`, 'warn'); } function getVerificationPollPayload(step, state, overrides = {}) { @@ -781,6 +788,7 @@ } async function resolveVerificationStep(step, state, mail, options = {}) { + const completionStep = getCompletionStep(step, options); const stateKey = getVerificationCodeStateKey(step); const rejectedCodes = new Set(); const hotmailPollConfig = mail.provider === HOTMAIL_PROVIDER @@ -918,7 +926,7 @@ [stateKey]: result.code, }); - await completeStepFromBackground(step, { + await completeStepFromBackground(completionStep, { emailTimestamp: result.emailTimestamp, code: result.code, phoneVerificationRequired: Boolean(submitResult.addPhonePage), diff --git a/content/paypal-flow.js b/content/paypal-flow.js new file mode 100644 index 0000000..9f34e51 --- /dev/null +++ b/content/paypal-flow.js @@ -0,0 +1,361 @@ +// content/paypal-flow.js — PayPal login and approval helper. + +console.log('[MultiPage:paypal-flow] Content script loaded on', location.href); + +const PAYPAL_FLOW_LISTENER_SENTINEL = 'data-multipage-paypal-flow-listener'; + +if (document.documentElement.getAttribute(PAYPAL_FLOW_LISTENER_SENTINEL) !== '1') { + document.documentElement.setAttribute(PAYPAL_FLOW_LISTENER_SENTINEL, '1'); + + chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { + if ( + message.type === 'PAYPAL_GET_STATE' + || message.type === 'PAYPAL_SUBMIT_LOGIN' + || message.type === 'PAYPAL_DISMISS_PROMPTS' + || message.type === 'PAYPAL_CLICK_APPROVE' + ) { + resetStopState(); + handlePayPalCommand(message).then((result) => { + sendResponse({ ok: true, ...(result || {}) }); + }).catch((err) => { + if (isStopError(err)) { + sendResponse({ stopped: true, error: err.message }); + return; + } + sendResponse({ error: err.message }); + }); + return true; + } + }); +} else { + console.log('[MultiPage:paypal-flow] 消息监听已存在,跳过重复注册'); +} + +async function handlePayPalCommand(message) { + switch (message.type) { + case 'PAYPAL_GET_STATE': + return inspectPayPalState(); + case 'PAYPAL_SUBMIT_LOGIN': + return submitPayPalLogin(message.payload || {}); + case 'PAYPAL_DISMISS_PROMPTS': + return dismissPayPalPrompts(); + case 'PAYPAL_CLICK_APPROVE': + return clickPayPalApprove(); + default: + throw new Error(`paypal-flow.js 不处理消息:${message.type}`); + } +} + +async function waitUntil(predicate, options = {}) { + const intervalMs = Math.max(50, Math.floor(Number(options.intervalMs) || 250)); + const timeoutMs = Math.max(0, Math.floor(Number(options.timeoutMs) || 0)); + const startedAt = Date.now(); + while (true) { + throwIfStopped(); + const value = await predicate(); + if (value) { + return value; + } + if (timeoutMs > 0 && Date.now() - startedAt >= timeoutMs) { + throw new Error(options.timeoutMessage || 'PayPal page timed out waiting for target state.'); + } + await sleep(intervalMs); + } +} + +async function waitForDocumentComplete() { + await waitUntil(() => document.readyState === 'complete', { intervalMs: 200 }); + await sleep(1000); +} + +function isVisibleElement(el) { + if (!el) return false; + let node = el; + while (node && node.nodeType === 1) { + if (node.hidden || node.getAttribute?.('aria-hidden') === 'true' || node.getAttribute?.('inert') !== null) { + return false; + } + const nodeStyle = window.getComputedStyle(node); + if ( + nodeStyle.display === 'none' + || nodeStyle.visibility === 'hidden' + || nodeStyle.visibility === 'collapse' + || Number(nodeStyle.opacity) === 0 + ) { + return false; + } + node = node.parentElement; + } + const style = window.getComputedStyle(el); + const rect = el.getBoundingClientRect(); + return style.display !== 'none' + && style.visibility !== 'hidden' + && Number(rect.width) > 0 + && Number(rect.height) > 0; +} + +function normalizeText(text = '') { + return String(text || '').replace(/\s+/g, ' ').trim(); +} + +function getActionText(el) { + return normalizeText([ + el?.textContent, + el?.value, + el?.getAttribute?.('aria-label'), + el?.getAttribute?.('title'), + el?.getAttribute?.('placeholder'), + el?.getAttribute?.('name'), + el?.id, + ].filter(Boolean).join(' ')); +} + +function getVisibleControls(selector) { + return Array.from(document.querySelectorAll(selector)).filter(isVisibleElement); +} + +function isEnabledControl(el) { + return Boolean(el) + && !el.disabled + && el.getAttribute?.('aria-disabled') !== 'true'; +} + +function findClickableByText(patterns) { + const normalizedPatterns = (Array.isArray(patterns) ? patterns : [patterns]).filter(Boolean); + const candidates = getVisibleControls('button, a, [role="button"], input[type="button"], input[type="submit"]'); + return candidates.find((el) => { + const text = getActionText(el); + return normalizedPatterns.some((pattern) => pattern.test(text)); + }) || null; +} + +function findInputByPatterns(patterns) { + const inputs = getVisibleControls('input') + .filter((input) => { + const type = String(input.getAttribute('type') || input.type || '').trim().toLowerCase(); + return isEnabledControl(input) && !['hidden', 'checkbox', 'radio', 'submit', 'button', 'file'].includes(type); + }); + return inputs.find((input) => { + const text = getActionText(input); + return patterns.some((pattern) => pattern.test(text)); + }) || null; +} + +function findEmailInput() { + return findInputByPatterns([ + /email|login|user|账号|邮箱/i, + ]) || getVisibleControls('input[type="email"]').find(isVisibleElement) || null; +} + +function findPasswordInput() { + return findInputByPatterns([ + /password|pass|密码/i, + ]) || getVisibleControls('input[type="password"]').find(isVisibleElement) || null; +} + +function findLoginNextButton() { + return findClickableByText([ + /next|continue|login|log\s*in|sign\s*in/i, + /下一步|继续|登录|登入/i, + ]); +} + +function findEmailNextButton() { + return findClickableByText([ + /next|btn\s*next|btnnext/i, + /下一页|下一步/i, + ]); +} + +function findPasswordLoginButton() { + const button = findClickableByText([ + /login|log\s*in|sign\s*in/i, + /登录|登入/i, + ]); + return button && button !== findEmailNextButton() ? button : null; +} + +function findApproveButton() { + return findClickableByText([ + /同意并继续|同意|继续|授权|确认并继续/i, + /agree\s*(?:and)?\s*continue|continue|accept|authorize|agree|pay\s*now/i, + ]); +} + +function findPasskeyPromptButtons() { + const promptPatterns = [ + /passkey|通行密钥|安全密钥|下次登录|faster|save/i, + ]; + const bodyText = normalizeText(document.body?.innerText || ''); + const likelyPrompt = promptPatterns.some((pattern) => pattern.test(bodyText)); + if (!likelyPrompt) { + return []; + } + + const cancelOrClose = getVisibleControls('button, a, [role="button"]') + .filter((el) => { + const text = getActionText(el); + return /取消|稍后|不保存|不用|关闭|cancel|not now|maybe later|skip|close|x/i.test(text) + || el.getAttribute?.('aria-label')?.match(/close|关闭/i); + }); + + const iconCloseButtons = getVisibleControls('button, [role="button"]') + .filter((el) => { + const text = getActionText(el); + const rect = el.getBoundingClientRect(); + return (/^×$|^x$/i.test(text) || /close|关闭/i.test(text)) + && rect.width <= 64 + && rect.height <= 64; + }); + + return [...cancelOrClose, ...iconCloseButtons]; +} + +function hasPasskeyPrompt() { + return findPasskeyPromptButtons().length > 0; +} + +function getPayPalLoginPhase(emailInput, passwordInput) { + const emailNextButton = findEmailNextButton(); + const passwordLoginButton = findPasswordLoginButton(); + if (emailInput && emailNextButton && isEnabledControl(emailNextButton) && (!passwordInput || !passwordLoginButton)) { + return 'email'; + } + if (emailInput && passwordInput) return 'login_combined'; + if (passwordInput) return 'password'; + if (emailInput) return 'email'; + return ''; +} + +async function submitPayPalLogin(payload = {}) { + await waitForDocumentComplete(); + + const email = normalizeText(payload.email || ''); + const password = String(payload.password || ''); + if (!password) { + throw new Error('PayPal 密码为空,请先在侧边栏配置。'); + } + + let passwordInput = findPasswordInput(); + const emailInput = findEmailInput(); + const emailNextButton = findEmailNextButton(); + + if (emailInput && emailNextButton && isEnabledControl(emailNextButton) && (!passwordInput || !findPasswordLoginButton())) { + if (normalizeText(emailInput.value || '') !== email) { + fillInput(emailInput, email); + } + simulateClick(emailNextButton); + return { + submitted: false, + phase: 'email_submitted', + awaiting: 'password_page', + }; + } + + if (!passwordInput && emailInput && email) { + if (normalizeText(emailInput.value || '') !== email) { + fillInput(emailInput, email); + } + const nextButton = await waitUntil(() => { + const button = findEmailNextButton() || findLoginNextButton(); + return button && isEnabledControl(button) ? button : null; + }, { + intervalMs: 250, + timeoutMs: 8000, + timeoutMessage: 'PayPal email page did not expose a clickable next/continue button.', + }); + simulateClick(nextButton); + return { + submitted: false, + phase: 'email_submitted', + awaiting: 'password_page', + }; + } else if (!passwordInput && emailInput && !email) { + throw new Error('PayPal 账号为空,请先在侧边栏配置。'); + } else if (emailInput && email && normalizeText(emailInput.value || '') !== email) { + fillInput(emailInput, email); + } + + passwordInput = passwordInput || await waitUntil(() => findPasswordInput(), { + intervalMs: 250, + timeoutMs: 8000, + timeoutMessage: 'PayPal password page did not expose a password input.', + }); + fillInput(passwordInput, password); + await sleep(1000); + + const loginButton = await waitUntil(() => { + const button = findClickableByText([ + /login|log\s*in|sign\s*in|continue/i, + /登录|登入|继续/i, + ]); + return button && isEnabledControl(button) ? button : null; + }, { + intervalMs: 250, + timeoutMs: 8000, + timeoutMessage: 'PayPal password page did not expose a clickable login/continue button.', + }); + + simulateClick(loginButton); + return { + submitted: true, + phase: 'password_submitted', + awaiting: 'redirect_or_approval', + }; +} + +async function dismissPayPalPrompts() { + await waitForDocumentComplete(); + const buttons = findPasskeyPromptButtons(); + let clicked = 0; + for (const button of buttons) { + if (!isVisibleElement(button) || !isEnabledControl(button)) { + continue; + } + simulateClick(button); + clicked += 1; + await sleep(500); + } + return { + clicked, + hasPromptAfterClick: hasPasskeyPrompt(), + }; +} + +async function clickPayPalApprove() { + await waitForDocumentComplete(); + await dismissPayPalPrompts().catch(() => ({ clicked: 0 })); + + const button = findApproveButton(); + if (!button || !isEnabledControl(button)) { + return { + clicked: false, + state: inspectPayPalState(), + }; + } + + simulateClick(button); + return { + clicked: true, + buttonText: getActionText(button), + }; +} + +function inspectPayPalState() { + const emailInput = findEmailInput(); + const passwordInput = findPasswordInput(); + const approveButton = findApproveButton(); + const loginPhase = getPayPalLoginPhase(emailInput, passwordInput); + return { + url: location.href, + readyState: document.readyState, + needsLogin: Boolean(loginPhase), + loginPhase, + hasEmailInput: Boolean(emailInput), + hasPasswordInput: Boolean(passwordInput), + approveReady: Boolean(approveButton && isEnabledControl(approveButton)), + approveButtonText: approveButton ? getActionText(approveButton) : '', + hasPasskeyPrompt: hasPasskeyPrompt(), + bodyTextPreview: normalizeText(document.body?.innerText || '').slice(0, 240), + }; +} diff --git a/content/plus-checkout.js b/content/plus-checkout.js new file mode 100644 index 0000000..1beca2d --- /dev/null +++ b/content/plus-checkout.js @@ -0,0 +1,972 @@ +// content/plus-checkout.js — ChatGPT Plus checkout helper. + +console.log('[MultiPage:plus-checkout] Content script loaded on', location.href); + +const PLUS_CHECKOUT_LISTENER_SENTINEL = 'data-multipage-plus-checkout-listener'; +const PLUS_CHECKOUT_PAYLOAD = { + entry_point: 'all_plans_pricing_modal', + plan_name: 'chatgptplusplan', + billing_details: { + country: 'DE', + currency: 'EUR', + }, + checkout_ui_mode: 'custom', + promo_campaign: { + promo_campaign_id: 'plus-1-month-free', + is_coupon_from_query_param: false, + }, +}; +const PAYPAL_DIAGNOSTIC_LOG_INTERVAL_MS = 5000; + +if (document.documentElement.getAttribute(PLUS_CHECKOUT_LISTENER_SENTINEL) !== '1') { + document.documentElement.setAttribute(PLUS_CHECKOUT_LISTENER_SENTINEL, '1'); + + chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { + if ( + message.type === 'CREATE_PLUS_CHECKOUT' + || message.type === 'FILL_PLUS_BILLING_AND_SUBMIT' + || message.type === 'PLUS_CHECKOUT_SELECT_PAYPAL' + || message.type === 'PLUS_CHECKOUT_FILL_BILLING_ADDRESS' + || message.type === 'PLUS_CHECKOUT_FILL_ADDRESS_QUERY' + || message.type === 'PLUS_CHECKOUT_SELECT_ADDRESS_SUGGESTION' + || message.type === 'PLUS_CHECKOUT_ENSURE_BILLING_ADDRESS' + || message.type === 'PLUS_CHECKOUT_CLICK_SUBSCRIBE' + || message.type === 'PLUS_CHECKOUT_GET_STATE' + ) { + resetStopState(); + handlePlusCheckoutCommand(message).then((result) => { + sendResponse({ ok: true, ...(result || {}) }); + }).catch((err) => { + if (isStopError(err)) { + sendResponse({ stopped: true, error: err.message }); + return; + } + sendResponse({ error: err.message }); + }); + return true; + } + }); +} else { + console.log('[MultiPage:plus-checkout] 消息监听已存在,跳过重复注册'); +} + +async function handlePlusCheckoutCommand(message) { + switch (message.type) { + case 'CREATE_PLUS_CHECKOUT': + return createPlusCheckoutSession(); + case 'FILL_PLUS_BILLING_AND_SUBMIT': + return fillPlusBillingAndSubmit(message.payload || {}); + case 'PLUS_CHECKOUT_SELECT_PAYPAL': + return selectPlusPayPalPaymentMethod(); + case 'PLUS_CHECKOUT_FILL_BILLING_ADDRESS': + return fillPlusBillingAddress(message.payload || {}); + case 'PLUS_CHECKOUT_FILL_ADDRESS_QUERY': + return fillPlusAddressQuery(message.payload || {}); + case 'PLUS_CHECKOUT_SELECT_ADDRESS_SUGGESTION': + return selectPlusAddressSuggestion(message.payload || {}); + case 'PLUS_CHECKOUT_ENSURE_BILLING_ADDRESS': + return ensurePlusStructuredBillingAddress(message.payload || {}); + case 'PLUS_CHECKOUT_CLICK_SUBSCRIBE': + return clickPlusSubscribe(); + case 'PLUS_CHECKOUT_GET_STATE': + return inspectPlusCheckoutState(); + default: + throw new Error(`plus-checkout.js 不处理消息:${message.type}`); + } +} + +async function waitUntil(predicate, options = {}) { + const intervalMs = Math.max(50, Math.floor(Number(options.intervalMs) || 250)); + const label = String(options.label || '条件').trim() || '条件'; + while (true) { + throwIfStopped(); + const value = await predicate(); + if (value) { + return value; + } + await sleep(intervalMs); + } +} + +async function waitForDocumentComplete() { + await waitUntil(() => document.readyState === 'complete', { + label: '页面加载完成', + intervalMs: 200, + }); + await sleep(1000); +} + +function isVisibleElement(el) { + if (!el) return false; + const style = window.getComputedStyle(el); + const rect = el.getBoundingClientRect(); + return style.display !== 'none' + && style.visibility !== 'hidden' + && Number(rect.width) > 0 + && Number(rect.height) > 0; +} + +function normalizeText(text = '') { + return String(text || '').replace(/\s+/g, ' ').trim(); +} + +function getActionText(el) { + return normalizeText([ + el?.textContent, + el?.value, + el?.getAttribute?.('aria-label'), + el?.getAttribute?.('title'), + el?.getAttribute?.('placeholder'), + el?.getAttribute?.('name'), + el?.id, + ].filter(Boolean).join(' ')); +} + +function getSearchText(el) { + const datasetValues = el?.dataset ? Object.values(el.dataset) : []; + return normalizeText([ + getActionText(el), + el?.getAttribute?.('alt'), + el?.getAttribute?.('role'), + el?.getAttribute?.('data-testid'), + el?.getAttribute?.('src'), + el?.getAttribute?.('href'), + el?.getAttribute?.('xlink:href'), + typeof el?.className === 'string' ? el.className : el?.getAttribute?.('class'), + ...datasetValues, + ].filter(Boolean).join(' ')); +} + +function getFieldText(el) { + const id = el?.id || ''; + const labels = []; + if (id) { + labels.push(...Array.from(document.querySelectorAll(`label[for="${CSS.escape(id)}"]`)).map((label) => label.textContent)); + } + const wrappingLabel = el?.closest?.('label'); + if (wrappingLabel) { + labels.push(wrappingLabel.textContent); + } + const container = el?.closest?.('[data-testid], [class], div, section, fieldset'); + if (container) { + labels.push(container.textContent); + } + return normalizeText([ + getActionText(el), + ...labels, + ].filter(Boolean).join(' ')); +} + +function getCombinedSearchText(el) { + return normalizeText([ + getSearchText(el), + getFieldText(el), + ].filter(Boolean).join(' ')); +} + +function getVisibleControls(selector) { + return Array.from(document.querySelectorAll(selector)).filter(isVisibleElement); +} + +function findClickableByText(patterns) { + const normalizedPatterns = (Array.isArray(patterns) ? patterns : [patterns]) + .filter(Boolean); + const candidates = getVisibleControls('button, a, [role="button"], input[type="button"], input[type="submit"], [tabindex]'); + return candidates.find((el) => { + const text = getActionText(el); + return normalizedPatterns.some((pattern) => pattern.test(text)); + }) || null; +} + +function isEnabledControl(el) { + return Boolean(el) + && !el.disabled + && el.getAttribute?.('aria-disabled') !== 'true'; +} + +function getVisibleTextInputs() { + return getVisibleControls('input, textarea') + .filter((el) => { + const type = String(el.getAttribute('type') || el.type || '').trim().toLowerCase(); + return !['hidden', 'checkbox', 'radio', 'submit', 'button', 'file'].includes(type); + }); +} + +function findInputByFieldText(patterns, options = {}) { + const inputs = getVisibleTextInputs(); + const excluded = options.exclude || (() => false); + return inputs.find((input) => { + if (excluded(input)) return false; + const text = getFieldText(input); + return patterns.some((pattern) => pattern.test(text)); + }) || null; +} + +function getDirectFieldHintText(el) { + const id = el?.id || ''; + const labels = []; + if (id) { + labels.push(...Array.from(document.querySelectorAll(`label[for="${CSS.escape(id)}"]`)).map((label) => label.textContent)); + } + const wrappingLabel = el?.closest?.('label'); + if (wrappingLabel) { + labels.push(wrappingLabel.textContent); + } + return normalizeText([ + getActionText(el), + ...labels, + ].filter(Boolean).join(' ')); +} + +function isNonAddressSearchInput(input) { + const directText = getDirectFieldHintText(input); + const type = String(input?.getAttribute?.('type') || input?.type || '').trim().toLowerCase(); + return /name|email|e-mail|phone|tel|password|coupon|promo|country|region|postal|zip|city|state|province|card|card\s*number|expiry|expiration|security|cvc|cvv|cc-/i.test(directText) + || ['email', 'tel', 'password'].includes(type); +} + +function isDocumentLevelContainer(el) { + return !el + || el === document.documentElement + || el === document.body + || ['HTML', 'BODY', 'MAIN'].includes(el.tagName); +} + +function isPaymentCardSized(el) { + if (!isVisibleElement(el) || isDocumentLevelContainer(el)) return false; + const rect = el.getBoundingClientRect(); + const maxWidth = Math.max(320, Math.min(window.innerWidth * 0.95, 900)); + const maxHeight = Math.max(140, Math.min(window.innerHeight * 0.45, 320)); + return rect.width >= 64 + && rect.height >= 28 + && rect.width <= maxWidth + && rect.height <= maxHeight; +} + +function findInteractiveAncestor(el) { + let current = el; + for (let depth = 0; current && depth < 8; depth += 1, current = current.parentElement) { + if (!isVisibleElement(current) || isDocumentLevelContainer(current)) continue; + if (current.matches?.('button, a, label, [role="button"], [role="radio"], input[type="radio"], [tabindex]')) { + return current; + } + } + return null; +} + +function findPaymentCardAncestor(el, pattern) { + let current = el; + for (let depth = 0; current && depth < 8; depth += 1, current = current.parentElement) { + if (!isVisibleElement(current)) continue; + if (isDocumentLevelContainer(current)) break; + const text = getSearchText(current); + if (pattern.test(text) && isPaymentCardSized(current)) { + return current; + } + } + return null; +} + +function getAncestorChainSummary(el, limit = 6) { + const chain = []; + let current = el; + for (let depth = 0; current && depth < limit; depth += 1, current = current.parentElement) { + if (isDocumentLevelContainer(current)) break; + const rect = current.getBoundingClientRect(); + chain.push({ + tag: String(current.tagName || '').toLowerCase(), + role: current.getAttribute?.('role') || '', + id: current.id || '', + className: typeof current.className === 'string' ? current.className.slice(0, 120) : '', + testId: current.getAttribute?.('data-testid') || '', + ariaLabel: current.getAttribute?.('aria-label') || '', + ariaChecked: current.getAttribute?.('aria-checked') || '', + ariaSelected: current.getAttribute?.('aria-selected') || '', + rect: `${Math.round(rect.width)}x${Math.round(rect.height)}`, + text: getCombinedSearchText(current).slice(0, 180), + }); + } + return chain; +} + +function getPayPalSearchCandidates() { + const selector = [ + 'button', + 'a', + 'label', + '[role="button"]', + '[role="radio"]', + 'input[type="radio"]', + '[tabindex]', + '[data-testid]', + '[aria-label]', + '[title]', + 'img', + 'svg', + 'span', + 'div', + ].join(', '); + + return getVisibleControls(selector) + .filter((el) => /paypal/i.test(getCombinedSearchText(el))) + .sort((left, right) => { + const leftRect = left.getBoundingClientRect(); + const rightRect = right.getBoundingClientRect(); + return (leftRect.width * leftRect.height) - (rightRect.width * rightRect.height); + }); +} + +function findPayPalPaymentMethodTarget() { + const paypalPattern = /paypal/i; + const directClickable = findClickableByText([paypalPattern]); + if (directClickable) { + return directClickable; + } + + const radios = getVisibleControls('input[type="radio"], [role="radio"]'); + const paypalRadio = radios.find((el) => paypalPattern.test(getCombinedSearchText(el))); + if (paypalRadio) { + return paypalRadio; + } + + const candidates = getPayPalSearchCandidates(); + for (const candidate of candidates) { + const interactive = findInteractiveAncestor(candidate); + if (interactive && paypalPattern.test(getCombinedSearchText(interactive))) { + return interactive; + } + const card = findPaymentCardAncestor(candidate, paypalPattern); + if (card) { + return card; + } + } + + return null; +} + +function summarizeElementForDebug(el) { + if (!el) return null; + const rect = el.getBoundingClientRect(); + return { + tag: String(el.tagName || '').toLowerCase(), + role: el.getAttribute?.('role') || '', + text: getSearchText(el).slice(0, 160), + rect: `${Math.round(rect.width)}x${Math.round(rect.height)}`, + chain: getAncestorChainSummary(el, 3), + }; +} + +function getPayPalCandidateSummaries(limit = 6) { + return getPayPalSearchCandidates() + .map(summarizeElementForDebug) + .filter(Boolean) + .slice(0, limit); +} + +function getPaymentTextPreview(limit = 10) { + const seen = new Set(); + const pattern = /paypal|card|payment|billing|subscribe|pay|银行卡|付款|支付|账单|订阅/i; + return getVisibleControls('button, a, label, [role="button"], [role="radio"], input[type="radio"], input[type="button"], input[type="submit"], [data-testid]') + .map((el) => getCombinedSearchText(el)) + .filter((text) => text && pattern.test(text)) + .map((text) => text.slice(0, 180)) + .filter((text) => { + if (seen.has(text)) return false; + seen.add(text); + return true; + }) + .slice(0, limit); +} + +function getPayPalDiagnostics(reason = '') { + return { + reason, + url: location.href, + readyState: document.readyState, + paypalCandidates: getPayPalCandidateSummaries(), + paymentTextPreview: getPaymentTextPreview(), + cardFieldsVisible: hasCreditCardFields(), + billingFieldsVisible: hasBillingAddressFields(), + }; +} + +function writePayPalDiagnostics(reason, level = 'info') { + const diagnostics = getPayPalDiagnostics(reason); + const writer = typeof console[level] === 'function' ? console[level] : console.info; + writer.call(console, '[MultiPage:plus-checkout] PayPal diagnostics', diagnostics); + log(`Plus Checkout:${reason}。PayPal 候选 ${diagnostics.paypalCandidates.length} 个,银行卡字段${diagnostics.cardFieldsVisible ? '仍可见' : '不可见'}。`, level === 'error' ? 'error' : 'warn'); + return diagnostics; +} + +async function createPlusCheckoutSession() { + await waitForDocumentComplete(); + log('Plus:正在读取 ChatGPT 登录会话...'); + + const sessionResponse = await fetch('/api/auth/session', { + credentials: 'include', + }); + const session = await sessionResponse.json().catch(() => ({})); + const accessToken = session?.accessToken; + if (!accessToken) { + throw new Error('请先登录 ChatGPT,当前页面未返回可用 accessToken。'); + } + + log('Plus:正在创建 checkout 会话...'); + const response = await fetch('https://chatgpt.com/backend-api/payments/checkout', { + method: 'POST', + credentials: 'include', + headers: { + Authorization: `Bearer ${accessToken}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(PLUS_CHECKOUT_PAYLOAD), + }); + + const data = await response.json().catch(() => ({})); + if (!response.ok || !data?.checkout_session_id) { + const detail = data?.detail || data?.message || `HTTP ${response.status}`; + throw new Error(`创建 Plus Checkout 失败:${detail}`); + } + + return { + checkoutUrl: `https://chatgpt.com/checkout/openai_ie/${data.checkout_session_id}`, + country: PLUS_CHECKOUT_PAYLOAD.billing_details.country, + currency: PLUS_CHECKOUT_PAYLOAD.billing_details.currency, + }; +} + +async function selectPayPalPaymentMethod() { + let lastDiagnosticsAt = 0; + const target = await waitUntil(() => { + const currentTarget = findPayPalPaymentMethodTarget(); + if (currentTarget) { + return currentTarget; + } + + const now = Date.now(); + if (!lastDiagnosticsAt || now - lastDiagnosticsAt >= PAYPAL_DIAGNOSTIC_LOG_INTERVAL_MS) { + lastDiagnosticsAt = now; + writePayPalDiagnostics('正在等待可点击的 PayPal 付款方式', 'warn'); + } + return null; + }, { + label: 'PayPal 付款方式', + intervalMs: 250, + }); + console.info('[MultiPage:plus-checkout] PayPal target selected', summarizeElementForDebug(target)); + simulateClick(target); + log('Plus Checkout:已点击 PayPal 付款方式,正在确认选中状态。'); + + if (!await waitForPayPalPaymentMethodActive()) { + const diagnostics = writePayPalDiagnostics('点击 PayPal 后页面仍未进入 PayPal 账单表单', 'error'); + throw new Error(`Plus Checkout:已尝试点击 PayPal,但页面未切换到 PayPal 表单。请提供控制台 PayPal diagnostics 结构。候选数量:${diagnostics.paypalCandidates.length},银行卡字段仍可见:${diagnostics.cardFieldsVisible ? '是' : '否'}。`); + } + + log('Plus Checkout:已确认 PayPal 付款方式生效。'); + return true; +} + +async function selectPlusPayPalPaymentMethod() { + await waitForDocumentComplete(); + await selectPayPalPaymentMethod(); + return { + paymentSelected: true, + }; +} + +async function fillFullName(fullName) { + const value = normalizeText(fullName); + if (!value) return false; + const input = findInputByFieldText([ + /full\s*name|name\s*on|cardholder|billing\s*name/i, + /姓名|全名|持卡人/i, + ]); + if (!input) { + return false; + } + fillInput(input, value); + await sleep(300); + return true; +} + +function readCountryText() { + const countryInput = findInputByFieldText([ + /country|region/i, + /国家|地区/i, + ]); + if (countryInput?.value) { + return countryInput.value; + } + const countrySelect = getVisibleControls('select').find((select) => /country|region|国家|地区/i.test(getFieldText(select))); + if (countrySelect) { + const option = countrySelect.selectedOptions?.[0]; + return option?.textContent || countrySelect.value || ''; + } + return ''; +} + +function isLikelyAddressSearchInput(input) { + const text = getFieldText(input); + if (isNonAddressSearchInput(input)) { + return false; + } + if (/name|email|e-mail|phone|tel|password|coupon|promo|country|region|postal|zip|city|state|province|card|card\s*number|expiry|expiration|security|cvc|cvv|cc-|全名|姓名|邮箱|电话|密码|国家|地区|邮编|城市|省|州|银行卡|卡号|有效期|安全码/i.test(text)) { + return false; + } + if (/address|street|billing|search|line\s*1|地址|街道|账单/i.test(text)) { + return true; + } + return false; +} + +function hasCreditCardFields() { + return getVisibleTextInputs().some((input) => { + const text = getFieldText(input); + return /card\s*number|card|expiry|expiration|security\s*code|cvc|cvv|银行卡|卡号|有效期|安全码/i.test(text); + }); +} + +function hasBillingAddressFields() { + return getVisibleTextInputs().some((input) => { + const text = getFieldText(input); + return /address|street|billing|line\s*1|地址|街道|账单/i.test(text) + && !/card\s*number|card|expiry|expiration|security|cvc|cvv|银行卡|卡号|有效期|安全码/i.test(text); + }); +} + +function hasSelectedPayPalControl() { + const paypalPattern = /paypal/i; + const candidates = getPayPalSearchCandidates(); + return candidates.some((candidate) => { + let current = candidate; + for (let depth = 0; current && depth < 6; depth += 1, current = current.parentElement) { + if (isDocumentLevelContainer(current)) break; + if (!paypalPattern.test(getCombinedSearchText(current))) continue; + const className = typeof current.className === 'string' ? current.className : current.getAttribute?.('class') || ''; + if ( + current.checked === true + || current.getAttribute?.('aria-checked') === 'true' + || current.getAttribute?.('aria-selected') === 'true' + || current.getAttribute?.('data-state') === 'checked' + || current.getAttribute?.('data-selected') === 'true' + || /\b(selected|checked|active)\b/i.test(className) + ) { + return true; + } + } + return false; + }); +} + +function isPayPalPaymentMethodActive() { + return hasSelectedPayPalControl(); +} + +async function waitForPayPalPaymentMethodActive(timeoutMs = 5000) { + const startedAt = Date.now(); + while (Date.now() - startedAt < timeoutMs) { + throwIfStopped(); + if (isPayPalPaymentMethodActive()) { + return true; + } + await sleep(250); + } + return false; +} + +async function findAddressSearchInput() { + return waitUntil(() => { + const direct = findInputByFieldText([ + /address|street|billing|search|line\s*1/i, + /地址|街道|账单/i, + ], { + exclude: (input) => /city|state|province|postal|zip|country|城市|省|州|邮编|国家|地区/i.test(getFieldText(input)), + }); + if (direct && !isNonAddressSearchInput(direct)) return direct; + const candidates = getVisibleTextInputs().filter(isLikelyAddressSearchInput); + return candidates[0] || null; + }, { + label: '地址搜索输入框', + intervalMs: 250, + }); +} + +function getAddressSuggestions() { + const selectors = [ + '[role="listbox"] [role="option"]', + '[role="option"]', + '.pac-container .pac-item', + '[data-testid*="address" i] [role="option"]', + 'li', + ]; + const seen = new Set(); + const results = []; + for (const selector of selectors) { + for (const el of Array.from(document.querySelectorAll(selector))) { + if (!isVisibleElement(el)) continue; + const text = normalizeText(el.textContent || el.getAttribute?.('aria-label') || ''); + if (!text || text.length < 3) continue; + const key = `${selector}:${text}`; + if (seen.has(key)) continue; + seen.add(key); + results.push(el); + } + } + return results; +} + +async function selectAddressSuggestion(seed) { + await fillAddressQuery(seed); + return clickAddressSuggestion(seed); +} + +async function clickAddressSuggestion(seed = {}) { + const suggestions = await waitUntil(() => { + const options = getAddressSuggestions(); + return options.length ? options : null; + }, { + label: '地址推荐列表', + intervalMs: 250, + }); + + const suggestionIndex = Math.max(0, Math.min( + suggestions.length - 1, + Math.floor(Number(seed.suggestionIndex) || 0) + )); + const target = suggestions[suggestionIndex] || suggestions[0]; + simulateClick(target); + await sleep(1200); + return { + selectedText: normalizeText(target.textContent || ''), + suggestionIndex, + }; +} + +async function fillAddressQuery(seed = {}) { + const addressInput = await findAddressSearchInput(); + fillInput(addressInput, seed.query || 'Berlin Mitte'); + await sleep(800); + return { + filled: true, + }; +} + +function getRegionCandidates(value) { + const raw = normalizeText(value); + if (!raw) return []; + const aliases = { + act: 'Australian Capital Territory', + nsw: 'New South Wales', + nt: 'Northern Territory', + qld: 'Queensland', + sa: 'South Australia', + tas: 'Tasmania', + vic: 'Victoria', + wa: 'Western Australia', + }; + const compact = raw.toLowerCase().replace(/[^a-z0-9]/g, ''); + const candidates = [raw]; + if (aliases[compact]) { + candidates.push(aliases[compact]); + } + for (const [abbr, name] of Object.entries(aliases)) { + const compactName = name.toLowerCase().replace(/[^a-z0-9]/g, ''); + if (compact === compactName) { + candidates.push(abbr.toUpperCase()); + } + } + return Array.from(new Set(candidates.filter(Boolean))); +} + +function matchesRegionOption(text, desiredValue) { + const normalizedText = normalizeText(text).toLowerCase(); + const compactText = normalizedText.replace(/[^a-z0-9]/g, ''); + if (!compactText) return false; + return getRegionCandidates(desiredValue).some((candidate) => { + const normalizedCandidate = normalizeText(candidate).toLowerCase(); + const compactCandidate = normalizedCandidate.replace(/[^a-z0-9]/g, ''); + if (!compactCandidate) return false; + return normalizedText === normalizedCandidate + || compactText === compactCandidate + || (compactCandidate.length > 3 && compactText.includes(compactCandidate)); + }); +} + +function findRegionDropdown() { + const controls = getVisibleControls('select, button, [role="button"], [role="combobox"], [aria-haspopup="listbox"]'); + return controls.find((control) => { + if (!isEnabledControl(control) || isDocumentLevelContainer(control)) return false; + const text = getFieldText(control); + if (/country/i.test(text) || /\u56fd\u5bb6|\u5730\u533a/.test(text)) return false; + return /state|province|county/i.test(text) + || /(?:^|\s)region(?:\s|$)/i.test(text) + || /\u5dde|\u7701/.test(text); + }) || null; +} + +function getRegionDropdownValue(control) { + if (!control) return ''; + if (String(control.tagName || '').toUpperCase() === 'SELECT') { + const selected = control.selectedOptions?.[0]; + return normalizeText(selected?.textContent || control.value || ''); + } + return normalizeText( + control.getAttribute?.('aria-valuetext') + || control.getAttribute?.('aria-label') + || control.getAttribute?.('data-value') + || control.textContent + || '' + ); +} + +function getVisibleRegionOptions() { + const selectors = [ + '[role="listbox"] [role="option"]', + '[role="option"]', + 'li', + ]; + const seen = new Set(); + const options = []; + for (const selector of selectors) { + for (const option of Array.from(document.querySelectorAll(selector))) { + if (!isVisibleElement(option)) continue; + const text = normalizeText(getActionText(option) || option.textContent || ''); + if (!text || seen.has(text)) continue; + seen.add(text); + options.push(option); + } + } + return options; +} + +async function selectRegionDropdown(regionDropdown, value) { + if (!regionDropdown || !value) return false; + if (matchesRegionOption(getRegionDropdownValue(regionDropdown), value)) { + return false; + } + + if (String(regionDropdown.tagName || '').toUpperCase() === 'SELECT') { + const option = Array.from(regionDropdown.options || []).find((item) => ( + matchesRegionOption(item.textContent || '', value) + || matchesRegionOption(item.value || '', value) + )); + if (!option) { + throw new Error(`Plus Checkout: state dropdown option "${value}" was not found.`); + } + regionDropdown.value = option.value; + option.selected = true; + regionDropdown.dispatchEvent(new Event('input', { bubbles: true })); + regionDropdown.dispatchEvent(new Event('change', { bubbles: true })); + return true; + } + + simulateClick(regionDropdown); + await sleep(250); + const startedAt = Date.now(); + let option = null; + while (Date.now() - startedAt < 2500) { + throwIfStopped(); + option = getVisibleRegionOptions().find((item) => ( + matchesRegionOption(getActionText(item) || item.textContent || '', value) + )); + if (option) break; + await sleep(100); + } + if (!option) { + const visibleOptions = getVisibleRegionOptions() + .map((item) => normalizeText(getActionText(item) || item.textContent || '')) + .filter(Boolean) + .slice(0, 12) + .join(' | '); + throw new Error(`Plus Checkout: state dropdown option "${value}" was not found. Visible options: ${visibleOptions || 'none'}.`); + } + simulateClick(option); + await sleep(500); + return true; +} + +function getStructuredAddressFields() { + const address1 = findInputByFieldText([ + /address\s*(?:line)?\s*1|street/i, + /地址\s*1|街道|详细地址/i, + ]); + const address2 = findInputByFieldText([ + /address\s*(?:line)?\s*2|apt|suite|unit/i, + /地址\s*2|公寓|单元|门牌/i, + ]); + const city = findInputByFieldText([ + /city|town|suburb/i, + /城市|市区/i, + ]); + const region = findInputByFieldText([ + /state|province|region|county/i, + /省|州|地区/i, + ]); + const postalCode = findInputByFieldText([ + /postal|zip|postcode/i, + /邮编|邮政/i, + ]); + return { address1, address2, city, region, postalCode }; +} + +function fillIfEmpty(input, value) { + if (!input || !value) return false; + if (String(input.value || '').trim()) return false; + fillInput(input, value); + return true; +} + +async function ensureStructuredAddress(seed) { + const fallback = seed?.fallback || {}; + const fields = await waitUntil(() => { + const currentFields = getStructuredAddressFields(); + if (currentFields.address1 || currentFields.city || currentFields.postalCode) { + return currentFields; + } + return null; + }, { + label: '结构化账单地址字段', + intervalMs: 250, + }); + + fillIfEmpty(fields.address1, fallback.address1); + fillIfEmpty(fields.city, fallback.city); + await selectRegionDropdown(findRegionDropdown(), fallback.region); + fillIfEmpty(fields.postalCode, fallback.postalCode); + await sleep(500); + + const latest = getStructuredAddressFields(); + const missing = []; + if (!String(latest.address1?.value || '').trim()) missing.push('地址1'); + if (!String(latest.city?.value || '').trim()) missing.push('城市'); + if (!String(latest.postalCode?.value || '').trim()) missing.push('邮编'); + if (missing.length) { + throw new Error(`Plus Checkout:账单地址字段未填写完整:${missing.join('、')}。`); + } + + return { + address1: latest.address1?.value || '', + city: latest.city?.value || '', + region: getRegionDropdownValue(findRegionDropdown()) || latest.region?.value || '', + postalCode: latest.postalCode?.value || '', + }; +} + +function findSubscribeButton() { + return findClickableByText([ + /订阅|继续|确认|支付/i, + /subscribe|continue|confirm|pay|start\s*subscription|place\s*order/i, + ]); +} + +async function fillPlusBillingAndSubmit(payload = {}) { + await waitForDocumentComplete(); + await selectPayPalPaymentMethod(); + const billingResult = await fillPlusBillingAddress(payload); + + if (payload.skipSubmit) { + return { + ...billingResult, + submitted: false, + }; + } + + await clickPlusSubscribe(); + return { + ...billingResult, + submitted: true, + }; +} + +async function fillPlusBillingAddress(payload = {}) { + await waitForDocumentComplete(); + await fillFullName(payload.fullName || ''); + + const countryText = readCountryText(); + const seed = payload.addressSeed || { + query: 'Berlin Mitte', + suggestionIndex: 1, + fallback: { + address1: 'Unter den Linden', + city: 'Berlin', + region: 'Berlin', + postalCode: '10117', + }, + }; + let selected = { selectedText: '' }; + if (!seed.skipAutocomplete) { + selected = await selectAddressSuggestion(seed); + } + const structuredAddress = await ensureStructuredAddress(seed); + + return { + countryText, + selectedAddressText: selected.selectedText, + structuredAddress, + }; +} + +async function fillPlusAddressQuery(payload = {}) { + await waitForDocumentComplete(); + await fillFullName(payload.fullName || ''); + const seed = payload.addressSeed || {}; + await fillAddressQuery(seed); + return { + countryText: readCountryText(), + queryFilled: true, + }; +} + +async function selectPlusAddressSuggestion(payload = {}) { + await waitForDocumentComplete(); + const selected = await clickAddressSuggestion(payload.addressSeed || {}); + return { + selectedAddressText: selected.selectedText, + suggestionIndex: selected.suggestionIndex, + }; +} + +async function ensurePlusStructuredBillingAddress(payload = {}) { + await waitForDocumentComplete(); + const structuredAddress = await ensureStructuredAddress(payload.addressSeed || {}); + return { + countryText: readCountryText(), + structuredAddress, + }; +} + +async function clickPlusSubscribe() { + const subscribeButton = await waitUntil(() => { + const button = findSubscribeButton(); + return button && isEnabledControl(button) ? button : null; + }, { + label: '订阅按钮', + intervalMs: 250, + }); + + simulateClick(subscribeButton); + return { + clicked: true, + }; +} + +function inspectPlusCheckoutState() { + const structuredAddress = getStructuredAddressFields(); + return { + url: location.href, + readyState: document.readyState, + countryText: readCountryText(), + hasPayPal: Boolean(findPayPalPaymentMethodTarget()), + paypalCandidates: getPayPalCandidateSummaries(), + paymentTextPreview: getPaymentTextPreview(), + cardFieldsVisible: hasCreditCardFields(), + billingFieldsVisible: hasBillingAddressFields(), + hasSubscribeButton: Boolean(findSubscribeButton()), + addressFieldValues: { + address1: structuredAddress.address1?.value || '', + city: structuredAddress.city?.value || '', + region: getRegionDropdownValue(findRegionDropdown()) || structuredAddress.region?.value || '', + postalCode: structuredAddress.postalCode?.value || '', + }, + }; +} diff --git a/content/signup-page.js b/content/signup-page.js index 74311df..9c6caf6 100644 --- a/content/signup-page.js +++ b/content/signup-page.js @@ -32,9 +32,10 @@ if (document.documentElement.getAttribute(SIGNUP_PAGE_LISTENER_SENTINEL) !== '1' handleCommand(message).then((result) => { sendResponse({ ok: true, ...(result || {}) }); }).catch(err => { + const reportedStep = Number(message.payload?.visibleStep) || message.step; if (isStopError(err)) { - if (message.step) { - log(`步骤 ${message.step || 8}:已被用户停止。`, 'warn'); + if (reportedStep) { + log(`步骤 ${reportedStep || 8}:已被用户停止。`, 'warn'); } sendResponse({ stopped: true, error: err.message }); return; @@ -46,8 +47,8 @@ if (document.documentElement.getAttribute(SIGNUP_PAGE_LISTENER_SENTINEL) !== '1' return; } - if (message.step) { - reportError(message.step, err.message); + if (reportedStep) { + reportError(reportedStep, err.message); } sendResponse({ error: err.message }); }); @@ -1802,6 +1803,13 @@ function inspectLoginAuthState() { }; } + if (consentReady) { + return { + ...baseState, + state: 'oauth_consent_page', + }; + } + return baseState; } @@ -1829,7 +1837,7 @@ function serializeLoginAuthState(snapshot) { } function getLoginAuthStateLabel(snapshot) { - const state = snapshot?.state === 'oauth_consent_page' ? 'unknown' : snapshot?.state; + const state = snapshot?.state; switch (state) { case 'verification_page': return '登录验证码页'; @@ -1886,13 +1894,32 @@ async function waitForLoginVerificationPageReady(timeout = 10000) { } function createStep6SuccessResult(snapshot, options = {}) { - return { + const result = { step6Outcome: 'success', state: snapshot?.state || 'verification_page', url: snapshot?.url || location.href, via: options.via || '', loginVerificationRequestedAt: options.loginVerificationRequestedAt || null, }; + + if (options.skipLoginVerificationStep) { + result.skipLoginVerificationStep = true; + } + if (options.directOAuthConsentPage) { + result.directOAuthConsentPage = true; + } + + return result; +} + +function createStep6OAuthConsentSuccessResult(snapshot, options = {}) { + return createStep6SuccessResult(snapshot, { + ...options, + via: options.via || 'oauth_consent_page', + loginVerificationRequestedAt: null, + skipLoginVerificationStep: true, + directOAuthConsentPage: true, + }); } function createStep6RecoverableResult(reason, snapshot, options = {}) { @@ -1947,6 +1974,15 @@ async function createStep6LoginTimeoutRecoveryTransition(reason, snapshot, messa }; } + if (resolvedSnapshot.state === 'oauth_consent_page') { + return { + action: 'done', + result: createStep6OAuthConsentSuccessResult(resolvedSnapshot, { + via, + }), + }; + } + if (resolvedSnapshot.state === 'password_page') { log('步骤 7:登录超时报错页恢复后已进入密码页,继续当前登录流程。', 'warn'); return { action: 'password', snapshot: resolvedSnapshot }; @@ -2006,6 +2042,13 @@ async function finalizeStep6VerificationReady(options = {}) { }); } + if (snapshot.state === 'oauth_consent_page') { + log(`${logLabel}:认证页已直接进入 OAuth 授权页,跳过登录验证码步骤。`, 'ok'); + return createStep6OAuthConsentSuccessResult(snapshot, { + via: `${via}_oauth_consent`, + }); + } + if (snapshot.state === 'login_timeout_error_page') { log(`${logLabel}:页面进入登录超时报错页,准备自动恢复后重试步骤 7。`, 'warn'); return createStep6LoginTimeoutRecoverableResult( @@ -2036,6 +2079,12 @@ async function finalizeStep6VerificationReady(options = {}) { loginVerificationRequestedAt, }); } + if (snapshot.state === 'oauth_consent_page') { + log(`${logLabel}:认证页已直接进入 OAuth 授权页,跳过登录验证码步骤。`, 'ok'); + return createStep6OAuthConsentSuccessResult(snapshot, { + via: `${via}_oauth_consent`, + }); + } if (snapshot.state === 'login_timeout_error_page') { log(`${logLabel}:页面进入登录超时报错页,准备自动恢复后重试步骤 7。`, 'warn'); return createStep6LoginTimeoutRecoverableResult( @@ -2058,21 +2107,14 @@ async function finalizeStep6VerificationReady(options = {}) { } function normalizeStep6Snapshot(snapshot) { - if (snapshot?.state !== 'oauth_consent_page') { - return snapshot; - } - - return { - ...snapshot, - state: 'unknown', - }; + return snapshot; } function throwForStep6FatalState(snapshot) { snapshot = normalizeStep6Snapshot(snapshot); switch (snapshot?.state) { case 'oauth_consent_page': - throw new Error(`当前页面已进入 OAuth 授权页,未经过登录验证码页,无法完成步骤 7。URL: ${snapshot.url}`); + return; case 'add_phone_page': throw new Error(`当前页面已进入手机号页面,未经过登录验证码页,无法完成步骤 7。URL: ${snapshot.url}`); case 'unknown': @@ -2594,88 +2636,55 @@ async function fillVerificationCode(step, payload) { // Step 7: Login with registered account (on OAuth auth page) // ============================================================ -async function waitForStep6EmailSubmitTransition(emailSubmittedAt, timeout = 12000) { - const start = Date.now(); - let snapshot = normalizeStep6Snapshot(inspectLoginAuthState()); +function getStep6OptionMessage(value, snapshot) { + return typeof value === 'function' ? value(snapshot) : String(value || ''); +} - while (Date.now() - start < timeout) { - throwIfStopped(); - snapshot = normalizeStep6Snapshot(inspectLoginAuthState()); +async function resolveStep6PostSubmitSnapshot(snapshot, options = {}) { + const normalizedSnapshot = normalizeStep6Snapshot(snapshot || inspectLoginAuthState()); + const { + via = 'post_submit', + loginVerificationRequestedAt = null, + oauthConsentVia = `${via}_oauth_consent`, + timeoutRecoveryReason = 'login_timeout_error_page', + timeoutRecoveryMessage = '登录提交后进入登录超时报错页。', + timeoutRecoveryVia = `${via}_timeout_recovered`, + allowPasswordAction = false, + allowEmailAction = false, + allowFinalPasswordAction = false, + allowFinalEmailAction = false, + allowFinalSwitchAction = false, + final = false, + addPhoneMessage, + } = options; - if (snapshot.state === 'verification_page') { - return { - action: 'done', - result: createStep6SuccessResult(snapshot, { - via: 'email_submit', - loginVerificationRequestedAt: emailSubmittedAt, - }), - }; - } - - if (snapshot.state === 'password_page') { - return { action: 'password', snapshot }; - } - - if (snapshot.state === 'login_timeout_error_page') { - const transition = await createStep6LoginTimeoutRecoveryTransition( - 'login_timeout_error_page', - snapshot, - '提交邮箱后进入登录超时报错页。', - { - loginVerificationRequestedAt: emailSubmittedAt, - via: 'email_submit_timeout_recovered', - } - ); - if (transition.action === 'done') { - return { - action: 'done', - result: transition.result, - }; - } - if (transition.action === 'password') { - return { action: 'password', snapshot: transition.snapshot }; - } - if (transition.action === 'email') { - return { action: 'email', snapshot: transition.snapshot }; - } - return { - action: 'recoverable', - result: transition.result, - }; - } - - if (snapshot.state === 'oauth_consent_page') { - throw new Error(`提交邮箱后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`); - } - - if (snapshot.state === 'add_phone_page') { - throw new Error(`提交邮箱后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`); - } - - await sleep(250); - } - - snapshot = normalizeStep6Snapshot(inspectLoginAuthState()); - if (snapshot.state === 'verification_page') { + if (normalizedSnapshot.state === 'verification_page') { return { action: 'done', - result: createStep6SuccessResult(snapshot, { - via: 'email_submit', - loginVerificationRequestedAt: emailSubmittedAt, + result: createStep6SuccessResult(normalizedSnapshot, { + via, + loginVerificationRequestedAt, }), }; } - if (snapshot.state === 'password_page') { - return { action: 'password', snapshot }; + + if (normalizedSnapshot.state === 'oauth_consent_page') { + return { + action: 'done', + result: createStep6OAuthConsentSuccessResult(normalizedSnapshot, { + via: oauthConsentVia, + }), + }; } - if (snapshot.state === 'login_timeout_error_page') { + + if (normalizedSnapshot.state === 'login_timeout_error_page') { const transition = await createStep6LoginTimeoutRecoveryTransition( - 'login_timeout_error_page', - snapshot, - '提交邮箱后进入登录超时报错页。', + timeoutRecoveryReason, + normalizedSnapshot, + timeoutRecoveryMessage, { - loginVerificationRequestedAt: emailSubmittedAt, - via: 'email_submit_timeout_recovered', + loginVerificationRequestedAt, + via: timeoutRecoveryVia, } ); if (transition.action === 'done') { @@ -2695,213 +2704,116 @@ async function waitForStep6EmailSubmitTransition(emailSubmittedAt, timeout = 120 result: transition.result, }; } - if (snapshot.state === 'oauth_consent_page') { - throw new Error(`提交邮箱后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`); + + if (normalizedSnapshot.state === 'password_page') { + if (allowPasswordAction || (final && allowFinalPasswordAction)) { + return { action: 'password', snapshot: normalizedSnapshot }; + } + if (final && allowFinalSwitchAction && normalizedSnapshot.switchTrigger) { + return { action: 'switch', snapshot: normalizedSnapshot }; + } } - if (snapshot.state === 'add_phone_page') { - throw new Error(`提交邮箱后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`); + + if (normalizedSnapshot.state === 'email_page' && (allowEmailAction || (final && allowFinalEmailAction))) { + return { action: 'email', snapshot: normalizedSnapshot }; + } + + if (normalizedSnapshot.state === 'add_phone_page') { + const message = getStep6OptionMessage(addPhoneMessage, normalizedSnapshot) + || `登录提交后页面进入手机号页面。URL: ${normalizedSnapshot.url || location.href}`; + throw new Error(message); + } + + return null; +} + +async function waitForStep6PostSubmitTransition(options = {}) { + const { + timeout = 10000, + stalledReason = 'post_submit_stalled', + stalledMessage = '登录提交后未进入可识别的下一页。', + } = options; + const start = Date.now(); + let snapshot = normalizeStep6Snapshot(inspectLoginAuthState()); + + while (Date.now() - start < timeout) { + throwIfStopped(); + snapshot = normalizeStep6Snapshot(inspectLoginAuthState()); + const transition = await resolveStep6PostSubmitSnapshot(snapshot, { + ...options, + final: false, + }); + if (transition) { + return transition; + } + await sleep(250); + } + + snapshot = normalizeStep6Snapshot(inspectLoginAuthState()); + const transition = await resolveStep6PostSubmitSnapshot(snapshot, { + ...options, + final: true, + }); + if (transition) { + return transition; } return { action: 'recoverable', - result: createStep6RecoverableResult('email_submit_stalled', snapshot, { - message: '提交邮箱后长时间未进入密码页或登录验证码页。', + result: createStep6RecoverableResult(stalledReason, snapshot, { + message: stalledMessage, + loginVerificationRequestedAt: options.loginVerificationRequestedAt || null, }), }; } +async function waitForStep6EmailSubmitTransition(emailSubmittedAt, timeout = 12000) { + return waitForStep6PostSubmitTransition({ + timeout, + via: 'email_submit', + oauthConsentVia: 'email_submit_oauth_consent', + loginVerificationRequestedAt: emailSubmittedAt, + timeoutRecoveryMessage: '提交邮箱后进入登录超时报错页。', + timeoutRecoveryVia: 'email_submit_timeout_recovered', + allowPasswordAction: true, + stalledReason: 'email_submit_stalled', + stalledMessage: '提交邮箱后长时间未进入密码页或登录验证码页。', + addPhoneMessage: (snapshot) => `提交邮箱后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`, + }); +} + async function waitForStep6PasswordSubmitTransition(passwordSubmittedAt, timeout = 10000) { - const start = Date.now(); - let snapshot = normalizeStep6Snapshot(inspectLoginAuthState()); - - while (Date.now() - start < timeout) { - throwIfStopped(); - snapshot = normalizeStep6Snapshot(inspectLoginAuthState()); - - if (snapshot.state === 'verification_page') { - return { - action: 'done', - result: createStep6SuccessResult(snapshot, { - via: 'password_submit', - loginVerificationRequestedAt: passwordSubmittedAt, - }), - }; - } - - if (snapshot.state === 'login_timeout_error_page') { - const transition = await createStep6LoginTimeoutRecoveryTransition( - 'login_timeout_error_page', - snapshot, - '提交密码后进入登录超时报错页。', - { - loginVerificationRequestedAt: passwordSubmittedAt, - via: 'password_submit_timeout_recovered', - } - ); - if (transition.action === 'done') { - return { - action: 'done', - result: transition.result, - }; - } - if (transition.action === 'password') { - return { action: 'password', snapshot: transition.snapshot }; - } - if (transition.action === 'email') { - return { action: 'email', snapshot: transition.snapshot }; - } - return { - action: 'recoverable', - result: transition.result, - }; - } - - if (snapshot.state === 'oauth_consent_page') { - throw new Error(`提交密码后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`); - } - - if (snapshot.state === 'add_phone_page') { - throw new Error(`提交密码后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`); - } - - await sleep(250); - } - - snapshot = normalizeStep6Snapshot(inspectLoginAuthState()); - if (snapshot.state === 'verification_page') { - return { - action: 'done', - result: createStep6SuccessResult(snapshot, { - via: 'password_submit', - loginVerificationRequestedAt: passwordSubmittedAt, - }), - }; - } - if (snapshot.state === 'login_timeout_error_page') { - const transition = await createStep6LoginTimeoutRecoveryTransition( - 'login_timeout_error_page', - snapshot, - '提交密码后进入登录超时报错页。', - { - loginVerificationRequestedAt: passwordSubmittedAt, - via: 'password_submit_timeout_recovered', - } - ); - if (transition.action === 'done') { - return { - action: 'done', - result: transition.result, - }; - } - if (transition.action === 'password') { - return { action: 'password', snapshot: transition.snapshot }; - } - if (transition.action === 'email') { - return { action: 'email', snapshot: transition.snapshot }; - } - return { - action: 'recoverable', - result: transition.result, - }; - } - if (snapshot.state === 'oauth_consent_page') { - throw new Error(`提交密码后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`); - } - if (snapshot.state === 'add_phone_page') { - throw new Error(`提交密码后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`); - } - if (snapshot.state === 'password_page' && snapshot.switchTrigger) { - return { action: 'switch', snapshot }; - } - - return { - action: 'recoverable', - result: createStep6RecoverableResult('password_submit_stalled', snapshot, { - message: '提交密码后仍未进入登录验证码页。', - }), - }; + return waitForStep6PostSubmitTransition({ + timeout, + via: 'password_submit', + oauthConsentVia: 'password_submit_oauth_consent', + loginVerificationRequestedAt: passwordSubmittedAt, + timeoutRecoveryMessage: '提交密码后进入登录超时报错页。', + timeoutRecoveryVia: 'password_submit_timeout_recovered', + allowFinalSwitchAction: true, + stalledReason: 'password_submit_stalled', + stalledMessage: '提交密码后仍未进入登录验证码页。', + addPhoneMessage: (snapshot) => `提交密码后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`, + }); } async function waitForStep6SwitchTransition(loginVerificationRequestedAt, timeout = 10000) { - const start = Date.now(); - let snapshot = normalizeStep6Snapshot(inspectLoginAuthState()); + const transition = await waitForStep6PostSubmitTransition({ + timeout, + via: 'switch_to_one_time_code_login', + oauthConsentVia: 'switch_to_one_time_code_oauth_consent', + loginVerificationRequestedAt, + timeoutRecoveryMessage: '切换到一次性验证码登录后进入登录超时报错页。', + timeoutRecoveryVia: 'switch_to_one_time_code_timeout_recovered', + stalledReason: 'one_time_code_switch_stalled', + stalledMessage: '点击一次性验证码登录后仍未进入登录验证码页。', + addPhoneMessage: (snapshot) => `切换到一次性验证码登录后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`, + }); - while (Date.now() - start < timeout) { - throwIfStopped(); - snapshot = normalizeStep6Snapshot(inspectLoginAuthState()); - - if (snapshot.state === 'verification_page') { - return createStep6SuccessResult(snapshot, { - via: 'switch_to_one_time_code_login', - loginVerificationRequestedAt, - }); - } - - if (snapshot.state === 'login_timeout_error_page') { - const transition = await createStep6LoginTimeoutRecoveryTransition( - 'login_timeout_error_page', - snapshot, - '切换到一次性验证码登录后进入登录超时报错页。', - { - loginVerificationRequestedAt, - via: 'switch_to_one_time_code_timeout_recovered', - } - ); - if (transition.action === 'done') { - return transition.result; - } - if (transition.action === 'password' || transition.action === 'email') { - return transition; - } - return transition.result; - } - - if (snapshot.state === 'oauth_consent_page') { - throw new Error(`切换到一次性验证码登录后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`); - } - - if (snapshot.state === 'add_phone_page') { - throw new Error(`切换到一次性验证码登录后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`); - } - - await sleep(250); - } - - snapshot = normalizeStep6Snapshot(inspectLoginAuthState()); - if (snapshot.state === 'verification_page') { - return createStep6SuccessResult(snapshot, { - via: 'switch_to_one_time_code_login', - loginVerificationRequestedAt, - }); - } - if (snapshot.state === 'login_timeout_error_page') { - const transition = await createStep6LoginTimeoutRecoveryTransition( - 'login_timeout_error_page', - snapshot, - '切换到一次性验证码登录后进入登录超时报错页。', - { - loginVerificationRequestedAt, - via: 'switch_to_one_time_code_timeout_recovered', - } - ); - if (transition.action === 'done') { - return transition.result; - } - if (transition.action === 'password' || transition.action === 'email') { - return transition; - } + if (transition.action === 'done' || transition.action === 'recoverable') { return transition.result; } - if (snapshot.state === 'oauth_consent_page') { - throw new Error(`切换到一次性验证码登录后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`); - } - if (snapshot.state === 'add_phone_page') { - throw new Error(`切换到一次性验证码登录后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`); - } - - return createStep6RecoverableResult('one_time_code_switch_stalled', snapshot, { - message: '点击一次性验证码登录后仍未进入登录验证码页。', - }); + return transition; } async function step6SwitchToOneTimeCodeLogin(payload, snapshot) { @@ -2920,6 +2832,9 @@ async function step6SwitchToOneTimeCodeLogin(payload, snapshot) { await sleep(1200); const result = await waitForStep6SwitchTransition(loginVerificationRequestedAt); if (result?.step6Outcome === 'success') { + if (result.skipLoginVerificationStep) { + return result; + } return finalizeStep6VerificationReady({ logLabel: '步骤 7 收尾', loginVerificationRequestedAt: result.loginVerificationRequestedAt || loginVerificationRequestedAt, @@ -2963,6 +2878,9 @@ async function step6LoginFromPasswordPage(payload, snapshot) { const transition = await waitForStep6PasswordSubmitTransition(passwordSubmittedAt); if (transition.action === 'done') { + if (transition.result?.skipLoginVerificationStep) { + return transition.result; + } return finalizeStep6VerificationReady({ logLabel: '步骤 7 收尾', loginVerificationRequestedAt: transition.result.loginVerificationRequestedAt || passwordSubmittedAt, @@ -3019,6 +2937,9 @@ async function step6LoginFromEmailPage(payload, snapshot) { const transition = await waitForStep6EmailSubmitTransition(emailSubmittedAt); if (transition.action === 'done') { + if (transition.result?.skipLoginVerificationStep) { + return transition.result; + } return finalizeStep6VerificationReady({ logLabel: '步骤 7 收尾', loginVerificationRequestedAt: transition.result.loginVerificationRequestedAt || emailSubmittedAt, @@ -3056,6 +2977,13 @@ async function step6_login(payload) { }); } + if (snapshot.state === 'oauth_consent_page') { + log('步骤 7:认证页已直接进入 OAuth 授权页,跳过登录验证码步骤。', 'ok'); + return createStep6OAuthConsentSuccessResult(snapshot, { + via: 'already_on_oauth_consent_page', + }); + } + if (snapshot.state === 'login_timeout_error_page') { log('步骤 7:检测到登录超时报错页,先尝试恢复当前页面。', 'warn'); const transition = await createStep6LoginTimeoutRecoveryTransition( @@ -3068,6 +2996,9 @@ async function step6_login(payload) { } ); if (transition.action === 'done') { + if (transition.result?.skipLoginVerificationStep) { + return transition.result; + } return finalizeStep6VerificationReady({ logLabel: '步骤 7 收尾', loginVerificationRequestedAt: transition.result.loginVerificationRequestedAt || null, diff --git a/content/sub2api-panel.js b/content/sub2api-panel.js index 0cdd8c7..c078202 100644 --- a/content/sub2api-panel.js +++ b/content/sub2api-panel.js @@ -68,7 +68,8 @@ async function handleStep(step, payload = {}) { case 1: return step1_generateOpenAiAuthUrl(payload); case 10: - return step9_submitOpenAiCallback(payload); + case 12: + return step9_submitOpenAiCallback({ ...(payload || {}), visibleStep: step }); default: throw new Error(`sub2api-panel.js 不处理步骤 ${step}`); } @@ -501,6 +502,7 @@ async function step1_generateOpenAiAuthUrl(payload = {}, options = {}) { } async function step9_submitOpenAiCallback(payload = {}) { + const visibleStep = Number(payload?.visibleStep) || 10; const callback = parseLocalhostCallback(payload.localhostUrl || ''); const backgroundState = await getBackgroundState(); const flowEmail = String(backgroundState.email || '').trim(); @@ -574,7 +576,7 @@ async function step9_submitOpenAiCallback(payload = {}) { createPayload.extra = extra; } - log(`步骤 10:授权码交换成功,正在创建 SUB2API 账号(名称:${accountName})...`); + log(`步骤 ${visibleStep}:授权码交换成功,正在创建 SUB2API 账号(名称:${accountName})...`); const createdAccount = await requestJson(origin, '/api/v1/admin/accounts', { method: 'POST', token, @@ -582,8 +584,8 @@ async function step9_submitOpenAiCallback(payload = {}) { }); const verifiedStatus = `SUB2API 已创建账号 #${createdAccount?.id || 'unknown'}`; - log(`步骤 10:${verifiedStatus}`, 'ok'); - reportComplete(10, { + log(`步骤 ${visibleStep}:${verifiedStatus}`, 'ok'); + reportComplete(visibleStep, { localhostUrl: callback.url, verifiedStatus, }); diff --git a/content/utils.js b/content/utils.js index 7eab2e4..a38143d 100644 --- a/content/utils.js +++ b/content/utils.js @@ -421,9 +421,20 @@ async function humanPause(min = 250, max = 850) { await sleep(duration); } -// Auto-report ready on load -// Skip ready signal from child iframes of mail pages to avoid overwriting the top frame's registration -const _isMailChildFrame = (SCRIPT_SOURCE === 'qq-mail' || SCRIPT_SOURCE === 'mail-163' || SCRIPT_SOURCE === 'gmail-mail' || SCRIPT_SOURCE === 'mail-2925' || SCRIPT_SOURCE === 'inbucket-mail') && window !== window.top; -if (!_isMailChildFrame) { +function shouldReportReadyForFrame(source, isChildFrame) { + if (!isChildFrame) return true; + return ![ + 'qq-mail', + 'mail-163', + 'gmail-mail', + 'mail-2925', + 'inbucket-mail', + 'plus-checkout', + ].includes(source); +} + +// Auto-report ready on load. Child frames are probed explicitly by frameId, so +// they should not overwrite the tab-level registration or spam the side panel. +if (shouldReportReadyForFrame(SCRIPT_SOURCE, window !== window.top)) { reportReady(); } diff --git a/content/vps-panel.js b/content/vps-panel.js index 63af31c..0a590ee 100644 --- a/content/vps-panel.js +++ b/content/vps-panel.js @@ -86,7 +86,9 @@ if (document.documentElement.getAttribute(VPS_PANEL_LISTENER_SENTINEL) !== '1') async function handleStep(step, payload) { switch (step) { case 1: return await step1_getOAuthLink(payload); - case 10: return await step9_vpsVerify(payload); + case 10: + case 12: + return await step9_vpsVerify({ ...(payload || {}), visibleStep: step }); default: throw new Error(`vps-panel.js 不处理步骤 ${step}`); } @@ -1009,27 +1011,29 @@ async function step1_getOAuthLink(payload, options = {}) { // ============================================================ async function step9_vpsVerify(payload) { - await ensureOAuthManagementPage(payload?.vpsPassword, 9); + const visibleStep = Number(payload?.visibleStep) || 10; + const confirmStep = visibleStep >= 13 ? 12 : 9; + await ensureOAuthManagementPage(payload?.vpsPassword, confirmStep); // 优先从 payload 读取 localhostUrl;没有时再回退到全局状态 let localhostUrl = payload?.localhostUrl; if (localhostUrl && !isLocalhostOAuthCallbackUrl(localhostUrl)) { - throw new Error('步骤 10 只接受真实的 localhost OAuth 回调地址,请重新执行步骤 9。'); + throw new Error(`步骤 ${visibleStep} 只接受真实的 localhost OAuth 回调地址,请重新执行步骤 ${confirmStep}。`); } if (!localhostUrl) { - log('步骤 10:payload 中没有 localhostUrl,正在从状态中读取...'); + log(`步骤 ${visibleStep}:payload 中没有 localhostUrl,正在从状态中读取...`); const state = await chrome.runtime.sendMessage({ type: 'GET_STATE' }); localhostUrl = state.localhostUrl; if (localhostUrl && !isLocalhostOAuthCallbackUrl(localhostUrl)) { - throw new Error('步骤 10 只接受真实的 localhost OAuth 回调地址,请重新执行步骤 9。'); + throw new Error(`步骤 ${visibleStep} 只接受真实的 localhost OAuth 回调地址,请重新执行步骤 ${confirmStep}。`); } } if (!localhostUrl) { - throw new Error('未找到 localhost 回调地址,请先完成步骤 8。'); + throw new Error(`未找到 localhost 回调地址,请先完成步骤 ${confirmStep}。`); } - log(`步骤 10:已获取 localhostUrl:${localhostUrl.slice(0, 60)}...`); + log(`步骤 ${visibleStep}:已获取 localhostUrl:${localhostUrl.slice(0, 60)}...`); - log('步骤 10:正在查找回调地址输入框...'); + log(`步骤 ${visibleStep}:正在查找回调地址输入框...`); // Find the callback URL input // Actual DOM: @@ -1046,7 +1050,7 @@ async function step9_vpsVerify(payload) { await humanPause(600, 1500); fillInput(urlInput, localhostUrl); - log(`步骤 10:已填写回调地址:${localhostUrl.slice(0, 80)}...`); + log(`步骤 ${visibleStep}:已填写回调地址:${localhostUrl.slice(0, 80)}...`); // Find and click the callback submit button in supported UI languages. const callbackSubmitPattern = /提交回调\s*URL|Submit\s+Callback\s+URL|Отправить\s+Callback\s+URL/i; @@ -1067,9 +1071,9 @@ async function step9_vpsVerify(payload) { await humanPause(450, 1200); simulateClick(submitBtn); - log('步骤 10:已点击回调提交按钮,正在等待认证结果...'); + log(`步骤 ${visibleStep}:已点击回调提交按钮,正在等待认证结果...`); const verifiedStatus = await waitForExactSuccessBadge(); - log(`步骤 10:${verifiedStatus}`, 'ok'); - reportComplete(10, { localhostUrl, verifiedStatus }); + log(`步骤 ${visibleStep}:${verifiedStatus}`, 'ok'); + reportComplete(visibleStep, { localhostUrl, verifiedStatus }); } diff --git a/data/address-sources.js b/data/address-sources.js new file mode 100644 index 0000000..df56c85 --- /dev/null +++ b/data/address-sources.js @@ -0,0 +1,129 @@ +(function attachAddressSources(root, factory) { + root.MultiPageAddressSources = factory(); +})(typeof self !== 'undefined' ? self : globalThis, function createAddressSourcesModule() { + const COUNTRY_ALIASES = { + AU: ['au', 'aus', 'australia', '澳大利亚'], + DE: ['de', 'deu', 'germany', 'deutschland', '德国'], + FR: ['fr', 'fra', 'france', '法国'], + US: ['us', 'usa', 'united states', 'united states of america', 'america', '美国'], + }; + + const ADDRESS_SEEDS = { + AU: [ + { + query: 'New South Wales', + suggestionIndex: 1, + fallback: { + address1: 'Thyne Reid Drive', + city: 'Thredbo', + region: 'New South Wales', + postalCode: '2625', + }, + }, + { + query: 'Sydney NSW', + suggestionIndex: 1, + fallback: { + address1: 'George Street', + city: 'Sydney', + region: 'New South Wales', + postalCode: '2000', + }, + }, + ], + DE: [ + { + query: 'Berlin Mitte', + suggestionIndex: 1, + fallback: { + address1: 'Unter den Linden', + city: 'Berlin', + region: 'Berlin', + postalCode: '10117', + }, + }, + { + query: 'Munich Altstadt', + suggestionIndex: 1, + fallback: { + address1: 'Marienplatz', + city: 'Munich', + region: 'Bavaria', + postalCode: '80331', + }, + }, + ], + FR: [ + { + query: 'Paris France', + suggestionIndex: 1, + fallback: { + address1: 'Rue de Rivoli', + city: 'Paris', + region: 'Ile-de-France', + postalCode: '75001', + }, + }, + { + query: 'Lyon France', + suggestionIndex: 1, + fallback: { + address1: 'Rue de la Republique', + city: 'Lyon', + region: 'Auvergne-Rhone-Alpes', + postalCode: '69002', + }, + }, + ], + US: [ + { + query: 'New York NY', + suggestionIndex: 1, + fallback: { + address1: 'Broadway', + city: 'New York', + region: 'New York', + postalCode: '10007', + }, + }, + ], + }; + + function normalizeCountryCode(value = '') { + const normalized = String(value || '').trim().toLowerCase(); + if (!normalized) { + return ''; + } + + for (const [code, aliases] of Object.entries(COUNTRY_ALIASES)) { + if (aliases.some((alias) => normalized === alias || normalized.includes(alias))) { + return code; + } + } + + const compact = normalized.replace(/[^a-z]/g, '').toUpperCase(); + return ADDRESS_SEEDS[compact] ? compact : ''; + } + + function getAddressSeedForCountry(countryValue = '', options = {}) { + const fallbackCountry = normalizeCountryCode(options.fallbackCountry || 'DE') || 'DE'; + const countryCode = normalizeCountryCode(countryValue) || fallbackCountry; + const candidates = ADDRESS_SEEDS[countryCode] || ADDRESS_SEEDS[fallbackCountry] || []; + const seed = candidates[0] || null; + if (!seed) { + return null; + } + return { + countryCode, + query: seed.query, + suggestionIndex: Math.max(0, Math.floor(Number(seed.suggestionIndex) || 0)), + fallback: { ...(seed.fallback || {}) }, + }; + } + + return { + ADDRESS_SEEDS, + getAddressSeedForCountry, + normalizeCountryCode, + }; +}); diff --git a/data/step-definitions.js b/data/step-definitions.js index 5dd6b3a..3852332 100644 --- a/data/step-definitions.js +++ b/data/step-definitions.js @@ -1,7 +1,7 @@ (function attachStepDefinitions(root, factory) { root.MultiPageStepDefinitions = factory(); })(typeof self !== 'undefined' ? self : globalThis, function createStepDefinitionsModule() { - const STEP_DEFINITIONS = [ + const NORMAL_STEP_DEFINITIONS = [ { id: 1, order: 10, key: 'open-chatgpt', title: '打开 ChatGPT 官网' }, { id: 2, order: 20, key: 'submit-signup-email', title: '注册并输入邮箱' }, { id: 3, order: 30, key: 'fill-password', title: '填写密码并继续' }, @@ -14,19 +14,78 @@ { id: 10, order: 100, key: 'platform-verify', title: '平台回调验证' }, ]; - function getSteps() { - return STEP_DEFINITIONS.map((step) => ({ ...step })); + const PLUS_STEP_DEFINITIONS = [ + { id: 1, order: 10, key: 'open-chatgpt', title: '打开 ChatGPT 官网' }, + { id: 2, order: 20, key: 'submit-signup-email', title: '注册并输入邮箱' }, + { id: 3, order: 30, key: 'fill-password', title: '填写密码并继续' }, + { id: 4, order: 40, key: 'fetch-signup-code', title: '获取注册验证码' }, + { id: 5, order: 50, key: 'fill-profile', title: '填写姓名和生日' }, + { id: 6, order: 60, key: 'plus-checkout-create', title: '创建 Plus Checkout' }, + { id: 7, order: 70, key: 'plus-checkout-billing', title: '填写账单并提交订阅' }, + { id: 8, order: 80, key: 'paypal-approve', title: 'PayPal 登录与授权' }, + { id: 9, order: 90, key: 'plus-checkout-return', title: '订阅回跳确认' }, + { id: 10, order: 100, key: 'oauth-login', title: '刷新 OAuth 并登录' }, + { id: 11, order: 110, key: 'fetch-login-code', title: '获取登录验证码' }, + { id: 12, order: 120, key: 'confirm-oauth', title: '自动确认 OAuth' }, + { id: 13, order: 130, key: 'platform-verify', title: '平台回调验证' }, + ]; + + function isPlusModeEnabled(options = {}) { + return Boolean(options?.plusModeEnabled || options?.plusMode); } - function getStepById(id) { + function getModeStepDefinitions(options = {}) { + return isPlusModeEnabled(options) ? PLUS_STEP_DEFINITIONS : NORMAL_STEP_DEFINITIONS; + } + + function cloneSteps(steps = []) { + return steps.map((step) => ({ ...step })); + } + + function getSteps(options = {}) { + return cloneSteps(getModeStepDefinitions(options)); + } + + function getAllSteps() { + const keyed = new Map(); + for (const step of [...NORMAL_STEP_DEFINITIONS, ...PLUS_STEP_DEFINITIONS]) { + keyed.set(`${step.id}:${step.key}`, step); + } + return cloneSteps(Array.from(keyed.values()).sort((left, right) => { + const leftOrder = Number.isFinite(left.order) ? left.order : left.id; + const rightOrder = Number.isFinite(right.order) ? right.order : right.id; + if (leftOrder !== rightOrder) return leftOrder - rightOrder; + return left.id - right.id; + })); + } + + function getStepIds(options = {}) { + return getModeStepDefinitions(options) + .map((step) => Number(step.id)) + .filter(Number.isFinite) + .sort((left, right) => left - right); + } + + function getLastStepId(options = {}) { + const ids = getStepIds(options); + return ids[ids.length - 1] || 0; + } + + function getStepById(id, options = {}) { const numericId = Number(id); - const match = STEP_DEFINITIONS.find((step) => step.id === numericId); + const match = getModeStepDefinitions(options).find((step) => step.id === numericId); return match ? { ...match } : null; } return { - STEP_DEFINITIONS, + STEP_DEFINITIONS: NORMAL_STEP_DEFINITIONS, + NORMAL_STEP_DEFINITIONS, + PLUS_STEP_DEFINITIONS, + getAllSteps, + getLastStepId, getStepById, + getStepIds, getSteps, + isPlusModeEnabled, }; }); diff --git a/docs/使用教程.md b/docs/使用教程.md index d419c53..2b2e1c1 100644 --- a/docs/使用教程.md +++ b/docs/使用教程.md @@ -1,4 +1,6 @@ -本教程用于说明相关项目地址、扩展更新方式、`QQ 邮箱`切换邮箱的使用方法,以及 `Clash Verge` 的 `🔁 非港轮询` 配置方法。 +# Codex 注册扩展相关项目、更新、邮箱切换、PayPal 与 Clash Verge 配置教程 + +本教程用于说明相关项目地址、扩展更新方式、`Cloudflare Temp Email` 与 `QQ 邮箱` 的使用方法、`PayPal` 注册绑卡流程,以及 [Clash Verge](https://github.com/clash-verge-rev/clash-verge-rev) 的 `🔁 非港轮询` 配置方法。 ## 适用场景 @@ -6,6 +8,7 @@ - 已经安装本扩展,想更新到最新版本 - 需要把 `Cloudflare Temp Email` 用作 `邮箱生成` 或 `邮箱服务` - 需要临时切换 `QQ 邮箱` 地址继续使用 +- 需要注册并使用 `PayPal` 个人账户 - 需要在 `Clash Verge` 中启用 `🔁 非港轮询` ## 准备内容 @@ -15,16 +18,18 @@ - 可以打开浏览器的 `扩展程序管理` 页面 - 已准备好 `Cloudflare Temp Email` 后端地址;如需随机子域,域名解析也已配置完成 - 一个可正常登录的 `QQ 邮箱` +- 一个可正常接收短信的手机号 +- 一张可在线支付的借记卡或信用卡 - 如需部署 `cpa`,部署环境必须可以访问 `OpenAI` -- 已安装 `Clash Verge`,并已导入可用订阅 +- 已安装 [Clash Verge](https://github.com/clash-verge-rev/clash-verge-rev),并已导入可用订阅 ## 操作步骤 ### 第一部分:相关项目地址与部署说明 1. 查看项目地址 - `cpa` 项目地址:`https://github.com/router-for-me/CLIProxyAPI` - `sub2api` 项目地址:`https://github.com/Wei-Shaw/sub2api` + `cpa` 项目地址:[https://github.com/router-for-me/CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) + `sub2api` 项目地址:[https://github.com/Wei-Shaw/sub2api](https://github.com/Wei-Shaw/sub2api) 2. 拉取项目到本地 先将你需要的项目拉取到本地目录。 @@ -67,7 +72,7 @@ 如果两边都选择了它,就需要把两套配置都填完整。 2. 填写 `Temp API` - 这里填写 `Cloudflare Temp Email` 后端地址,例如 `https://your-worker-domain`。 + 这里填写 `Cloudflare Temp Email` 后端地址,例如 [https://your-worker-domain](https://your-worker-domain)。 不论你是拿它来生成邮箱,还是接收转发邮件,这一项都需要先配好。 3. 作为 `邮箱生成` 使用时填写 `Admin Auth` @@ -101,7 +106,7 @@ 先登录你当前正在使用的 `QQ 邮箱` 账号。 2. 进入 `账号与安全` 页面 - 打开 `账号与安全` 页面:`https://wx.mail.qq.com/account/index?sid=zdd4Voy7S04uZjBnAKhFZQAA#/` + 打开 `账号与安全` 页面:[https://wx.mail.qq.com/account/index?sid=zdd4Voy7S04uZjBnAKhFZQAA#/](https://wx.mail.qq.com/account/index?sid=zdd4Voy7S04uZjBnAKhFZQAA#/) 3. 进入 `账号管理` 在 `账号与安全` 页面中找到 `账号管理`。 @@ -114,11 +119,218 @@ 这两个邮箱地址使用完成后,可以直接删除。 删除后再次创建新的英文邮箱和 `Foxmail` 邮箱,即可重复注册使用。 -### 第五部分:配置 `Clash Verge` 的 `🔁 非港轮询` +### 第五部分:`PayPal` 注册与绑卡使用教程 + +1. 打开注册页面 + 打开 [https://www.paypal.com/signin](https://www.paypal.com/signin)。 + 然后点击 `注册`。 + +2. 选择账户类型 + 选择 `个人账户`。 + 如果页面显示英文,通常对应 `Individual Account`。 + +3. 选择国家或地区 + 在 `国家/地区` 中直接选择 `中国`。 + 后续会绑定手机号,按中国手机号流程继续即可。 + +4. 输入手机号并继续 + 按页面提示输入手机号。 + 如果页面要求短信验证,就先完成短信验证再继续下一步。 + +5. 填写登录信息和个人信息 + 按页面提示继续填写邮箱、密码,以及姓名、出生日期、地址和联系方式。 + `PayPal` 官方说明,中国大陆居民注册时必须使用身份证上的中文姓名,不能使用拼音。 + 填完后勾选协议并完成注册。 + +6. 完成邮箱确认 + 注册成功后,按页面或邮箱提示确认邮箱地址。 + 如页面继续提示验证手机号,也一并完成。 + +7. 进入 `钱包` 或主页绑卡 + 注册成功后,进入主页。 + 然后在页面中找到 `关联卡或银行账户`,也可以直接进入 `钱包` 页面操作。 + +8. 选择关联借记卡或信用卡 + 点击 `关联借记卡或信用卡`。 + 如果你要先完成最基础的付款配置,优先把卡先绑上。 + +9. 填写银行卡信息 + 按页面提示输入银行卡号、有效期、安全代码和账单地址。 + 有效期一般在卡正面,通常写成 `10/45` 这种格式,表示 `2045 年 10 月` 到期。 + 安全代码一般在卡背面,输入三位数的那个。 + 如果卡背面分成两段数字,一段四位、一段三位,选择三位数的那段。 + 账单地址如果页面默认信息正确,保持默认即可。 + +10. 完成绑卡并检查结果 + 点击 `关联卡`。 + 有时候页面会报错,但你仍然可以去 `钱包` 页面重新看一下,因为卡有可能已经绑定成功。 + +11. 检查右上角通知并完成认证 + 绑卡成功后,记得查看右上角的通知图标。 + 如果通知图标标红,或者页面提示账户需要认证,请按提示补交资料。 + 常见情况是上传身份证件。 + `PayPal` 官方帮助中心说明,通常会在 `2 个工作日` 内审核,但某些情况可能更久。 + +### 第六部分:0元试用 ChatGPT Plus 教程 + +本部分说明如何在已登录 ChatGPT 的状态下,通过脚本快速生成 Plus 支付链接,然后选择 PayPal 支付完成0元试用订阅。 + +#### 准备工作 + +1. 已有一个登录状态的 ChatGPT 账户。 +2. 一个可用的 PayPal 账户(参考第五部分进行注册和绑卡)。 +3. 能够接收生成的账单地址的真实地址或虚拟地址。 +4. Chrome 浏览器(推荐使用地址补全功能)。 + +#### 执行步骤 + +1. **进入 ChatGPT 并打开开发者工具** + 在已登录 ChatGPT 的页面上,按 `F12` 打开浏览器开发者工具。 + 点击 `Console`(控制台)标签进入命令行界面。 + +2. **允许粘贴脚本** + 在控制台输入 `allow pasting` 并回车。 + 浏览器将允许你粘贴多行脚本代码。 + +3. **粘贴并执行脚本** + 复制下方脚本代码,粘贴到控制台,然后回车执行。 + +```javascript +(async function(){ + try { + const t = await (await fetch("/api/auth/session")).json(); + if(!t.accessToken){ + alert("请先登录 ChatGPT!"); + return; + } + + // 核心1:强制使用触发 PayPal 的欧洲区参数 (DE 德国 / EUR 欧元) + const payload = { + entry_point: "all_plans_pricing_modal", + plan_name: "chatgptplusplan", // Plus 的套餐名 + billing_details: { + country: "DE", // 必须是 DE 或 FR 才能在后续页面使用 PayPal + currency: "EUR" + }, + checkout_ui_mode: "custom", + promo_campaign: { + promo_campaign_id: "plus-1-month-free", // Plus 对应优惠码 + is_coupon_from_query_param: false + } + }; + + const response = await fetch("https://chatgpt.com/backend-api/payments/checkout", { + method: "POST", + headers: { + "Authorization": "Bearer " + t.accessToken, + "Content-Type": "application/json" + }, + body: JSON.stringify(payload) + }); + + const data = await response.json(); + + if(data.checkout_session_id) { + // 核心2:拼接 Plus 的专属支付短链 + // 如果 openai_ie 报错,可以直接把 /openai_ie 删掉,变成 "https://chatgpt.com/checkout/" + data.checkout_session_id + const shortLink = "https://chatgpt.com/checkout/openai_ie/" + data.checkout_session_id; + + // 弹窗让你复制这个带有 PayPal 的短链 + prompt("提取成功!这是你的 Plus 支付短链(复制保留):", shortLink); + + // 自动跳转到该短链 + window.location.href = shortLink; + } else { + console.error(data); + alert("提取失败:" + (data.detail || JSON.stringify(data))); + } + } catch(e) { + alert("发生异常:" + e); + } +})(); +``` + +4. **复制支付短链** + 脚本执行后会弹出一个对话框,显示你的 Plus 支付短链。 + 点击"确定"按钮,页面会自动跳转到支付页面。 + (可以复制这个链接备用,以防需要重新进入。) + +5. **选择 PayPal 支付** + 页面加载完成后,你会看到 ChatGPT Plus 的 checkout 页面,标题通常为"开始免费试用 Plus"。 + 在左侧付款方式中选择 `PayPal`。 + +6. **填写账单信息 - 选择国家** + 页面右侧会显示账单地址表单。 + "国家或地区" 字段会根据你当前的地址预填(通常是德国或法国)。 + 如果页面显示的不是你期望的国家,可以点击下拉框更改(建议保持德国或法国,以确保支付流程顺利)。 + +7. **填写账单信息 - 输入完整名字** + 在 "全名" 字段中输入完整的英文名字(例如 `John Smith`)。 + +8. **生成和填写地址** + 在 "地址第 1 行" 字段中开始输入。 + 输入城市名、州名或街道名(例如输入 `Berlin` 或 `New York`)。 + 页面会弹出 Google 地址推荐列表。 + 从推荐列表中选择一个地址项(建议选择第二项)。 + 页面会自动回填"城市"、"州"、"邮编"等字段。 + +9. **使用虚拟地址生成工具(可选)** + 如果地址推荐没有出现或推荐的地址不满足需求,可以使用 [https://www.meiguodizhi.com/](https://www.meiguodizhi.com/) 生成虚拟地址。 + 在该网站输入城市名或随机字母获取推荐地址,复制完整地址后粘贴到表单对应字段。 + +10. **完成地址填写并点击订阅** + 确认所有必填字段已填完(全名、地址、城市、州、邮编)。 + 在右侧点击 "订阅" 按钮。 + 页面会跳转到 PayPal 登录界面。 + +11. **PayPal 登录** + 在 PayPal 登录页输入 PayPal 账户邮箱。 + 输入 PayPal 账户密码。 + 点击 "登录" 按钮。 + +12. **处理浏览器通行密钥提示(如果出现)** + 如果出现 "要在无痕模式以外保存此通行密钥吗?" 的弹窗,点击 "取消"。 + +13. **关闭 PayPal 引导弹窗(如果出现)** + 如果出现 "下次登录更快捷" 或其他 PayPal 通行密钥引导弹窗,点击右上角的关闭图标。 + +14. **同意并继续** + 页面显示 "只需一次设置,结账更快捷。" 以及向 `OpenAI Ireland Limited` 付款的摘要。 + 点击 "同意并继续" 按钮。 + 等待页面跳转并加载完成。 + +15. **订阅成功** + 页面会回跳到 ChatGPT 或 OpenAI 的订阅确认页面。 + 此时 Plus 的0元试用订阅已成功完成。 + 你现在可以使用 ChatGPT Plus 的所有功能,试用期结束后会自动按月续订。 + +#### 常见问题处理 + +- **脚本执行报错 "请先登录 ChatGPT!"** + 请确认你当前已登录 ChatGPT 账户。退出重新登录后再尝试。 + +- **脚本执行返回错误信息** + 检查网络连接是否正常。如果多次尝试仍然失败,可能是当前账户不符合0元试用条件,请稍后再试。 + +- **/openai_ie 部分出现404错误** + 如果短链中的 `/openai_ie/` 无法访问,手动修改短链为: + `https://chatgpt.com/checkout/{checkout_session_id}` (删除 `/openai_ie/`) + 然后在浏览器地址栏中重新访问。 + +- **支付页面没有显示 PayPal 选项** + 这可能是因为脚本中的 `country` 参数不是 `DE` 或 `FR`。重新运行脚本,确保国家参数为德国 (DE) 或法国 (FR)。 + +- **地址推荐没有出现** + 稍等 1-2 秒,输入框下方应该会出现地址推荐列表。如果仍未出现,尝试清空后重新输入,或直接使用虚拟地址生成网站的地址。 + +- **PayPal 登录后页面无法继续跳转** + 稍等片刻让页面加载完毕。如果长时间未响应,检查浏览器是否有弹窗被隐藏,或尝试刷新页面。 + +### 第七部分:配置 [Clash Verge](https://github.com/clash-verge-rev/clash-verge-rev) 的 `🔁 非港轮询` #### 第一步:添加扩展脚本 -1. 打开 `Clash Verge`,进入左侧的 `订阅`(`Profiles`)界面。 +1. 打开 [Clash Verge](https://github.com/clash-verge-rev/clash-verge-rev),进入左侧的 `订阅`(`Profiles`)界面。 2. 在右上角或对应位置找到并双击打开 `全局扩展脚本`。  3. 将里面的内容全部清空,替换为下方脚本代码。 @@ -236,6 +448,18 @@ function main(config, profileName) { 可以。你在 `账号管理` 中创建英文邮箱和 `Foxmail` 邮箱,使用后直接删除,再重复创建即可继续使用。 +### `PayPal` 绑卡时报错怎么办? + +先去 `钱包` 页面再看一眼,有时虽然页面提示报错,但实际上已经绑定成功。 +如果还没有成功,优先检查账单地址是否与银行卡账单地址一致。 +`PayPal` 官方还说明,绑定新卡时会向发卡行发送最高 `1 USD` 或等值货币的临时授权验证,如果这一步被银行拒绝,绑卡也会失败。 + +### `PayPal` 右上角通知标红怎么办? + +先点开通知查看具体要求。 +如果页面要求 `Confirm your Identity` 或账户认证,就按提示上传身份证件或其他所需材料。 +`PayPal` 官方说明,资料通常会在 `2 个工作日` 内审核,但某些情况可能更久。 + ### 为什么没有看到 `🔁 非港轮询`? 请先确认脚本已经完整粘贴并保存,然后回到 `代理` 页面重新查看。若仍未出现,请继续确认当前订阅可用、`代理模式` 为 `规则模式`,并且 `系统代理` 已开启。 @@ -247,6 +471,9 @@ function main(config, profileName) { - 开启 `随机子域` 前,请先确认后端已经配置 `RANDOM_SUBDOMAIN_DOMAINS`,并且 Cloudflare DNS 已完成 `MX *` 设置。 - 如需部署 `cpa`,请先确认部署环境可以访问 `OpenAI`,否则可能出现第十步认证成功但没有认证文件的问题。 - `QQ 邮箱`切换邮箱时,建议在使用完成后及时删除,再重新创建,避免混淆当前正在使用的邮箱地址。 +- 中国大陆居民注册 `PayPal` 个人账户时,姓名请按身份证上的中文姓名填写,不要使用拼音。 +- `PayPal` 官方说明,绑定新卡时可能会向发卡行发送最高 `1 USD` 或等值货币的临时授权验证,所以完全没有余额的卡也可能因为授权失败而无法绑定。 +- 为了控制风险,更稳妥的做法是使用单独管理、余额较低的借记卡,并在绑卡后及时检查 `钱包` 页面和右上角通知。 - 使用 `git pull` 更新扩展是最方便、最推荐的方式。 - 在 `Clash Verge` 中粘贴脚本时,请先清空旧内容,再完整粘贴新代码并保存。 diff --git a/sidepanel/sidepanel.html b/sidepanel/sidepanel.html index ff8faa3..1cf6c96 100644 --- a/sidepanel/sidepanel.html +++ b/sidepanel/sidepanel.html @@ -212,6 +212,28 @@ +