feat: continue OAuth flow through HeroSMS phone verification
- 合并 dev 最新主线改动:同步当前认证页恢复、来源配置和侧栏能力的现有基线 - 本地补充修复:补齐 HeroSMS 手机验证与 sidepanel 初始化冲突,修正 Step 9 等待逻辑里的未声明变量,并同步结构/链路文档与回归测试 - 影响范围:OAuth 步骤 8/9、HeroSMS 配置、认证页内容脚本、侧栏初始化、项目文档与测试
This commit is contained in:
@@ -96,6 +96,12 @@
|
||||
.join(';');
|
||||
}
|
||||
|
||||
function shouldKeepCustomMailProviderPoolEmail(state = {}) {
|
||||
return String(state?.mailProvider || '').trim().toLowerCase() === 'custom'
|
||||
&& Array.isArray(state?.customMailProviderPool)
|
||||
&& state.customMailProviderPool.length > 0;
|
||||
}
|
||||
|
||||
async function logAutoRunFinalSummary(totalRuns, roundSummaries = []) {
|
||||
const summaries = buildAutoRunRoundSummaries(totalRuns, roundSummaries);
|
||||
const successRounds = summaries.filter((item) => item.status === 'success');
|
||||
@@ -328,8 +334,10 @@
|
||||
const resumingCurrentRound = continueCurrentOnFirstAttempt && targetRun === resumeCurrentRun;
|
||||
let attemptRun = resumingCurrentRound ? resumeAttemptRun : 1;
|
||||
let reuseExistingProgress = resumingCurrentRound;
|
||||
const currentRoundState = await getState();
|
||||
const keepSameEmailUntilAddPhone = autoRunSkipFailures && shouldKeepCustomMailProviderPoolEmail(currentRoundState);
|
||||
const maxAttemptsForRound = autoRunSkipFailures
|
||||
? AUTO_RUN_MAX_RETRIES_PER_ROUND + 1
|
||||
? (keepSameEmailUntilAddPhone ? Number.MAX_SAFE_INTEGER : AUTO_RUN_MAX_RETRIES_PER_ROUND + 1)
|
||||
: Math.max(1, attemptRun);
|
||||
|
||||
while (attemptRun <= maxAttemptsForRound) {
|
||||
@@ -461,6 +469,7 @@
|
||||
roundSummary.failureReasons.push(reason);
|
||||
const blockedByAddPhone = typeof isAddPhoneAuthFailure === 'function' && isAddPhoneAuthFailure(err);
|
||||
const blockedBySignupUserAlreadyExists = typeof isSignupUserAlreadyExistsFailure === 'function'
|
||||
&& !keepSameEmailUntilAddPhone
|
||||
&& isSignupUserAlreadyExistsFailure(err);
|
||||
const canRetry = !blockedByAddPhone && !blockedBySignupUserAlreadyExists && autoRunSkipFailures && attemptRun < maxAttemptsForRound;
|
||||
|
||||
@@ -555,7 +564,9 @@
|
||||
});
|
||||
forceFreshTabsNextRun = true;
|
||||
await addLog(
|
||||
`自动重试:${Math.round(AUTO_RUN_RETRY_DELAY_MS / 1000)} 秒后开始第 ${targetRun}/${totalRuns} 轮第 ${attemptRun + 1} 次尝试(第 ${retryIndex}/${AUTO_RUN_MAX_RETRIES_PER_ROUND} 次重试)。`,
|
||||
keepSameEmailUntilAddPhone
|
||||
? `自动重试:${Math.round(AUTO_RUN_RETRY_DELAY_MS / 1000)} 秒后继续使用当前邮箱,开始第 ${targetRun}/${totalRuns} 轮第 ${attemptRun + 1} 次尝试。`
|
||||
: `自动重试:${Math.round(AUTO_RUN_RETRY_DELAY_MS / 1000)} 秒后开始第 ${targetRun}/${totalRuns} 轮第 ${attemptRun + 1} 次尝试(第 ${retryIndex}/${AUTO_RUN_MAX_RETRIES_PER_ROUND} 次重试)。`,
|
||||
'warn'
|
||||
);
|
||||
try {
|
||||
|
||||
@@ -599,6 +599,7 @@
|
||||
body: {
|
||||
nickname: buildNickname(currentState, options.nickname),
|
||||
qq: buildContributionQq(currentState, options.qq),
|
||||
email: normalizeString(currentState.email),
|
||||
source: 'cpa',
|
||||
channel: 'codex-extension',
|
||||
},
|
||||
|
||||
@@ -7,11 +7,13 @@
|
||||
buildGeneratedAliasEmail,
|
||||
buildCloudflareTempEmailHeaders,
|
||||
CLOUDFLARE_TEMP_EMAIL_GENERATOR,
|
||||
CUSTOM_EMAIL_POOL_GENERATOR,
|
||||
DUCK_AUTOFILL_URL,
|
||||
fetch,
|
||||
fetchIcloudHideMyEmail,
|
||||
getCloudflareTempEmailAddressFromResponse,
|
||||
getCloudflareTempEmailConfig,
|
||||
getCustomEmailPoolEmail,
|
||||
getState,
|
||||
ensureMail2925AccountForFlow,
|
||||
joinCloudflareTempEmailUrl,
|
||||
@@ -146,6 +148,7 @@
|
||||
const requestedName = String(options.localPart || options.name || '').trim().toLowerCase() || generateCloudflareAliasLocalPart();
|
||||
const payload = {
|
||||
enablePrefix: true,
|
||||
enableRandomSubdomain: Boolean(config.useRandomSubdomain),
|
||||
name: requestedName,
|
||||
domain: config.domain,
|
||||
};
|
||||
@@ -188,6 +191,24 @@
|
||||
return result.email;
|
||||
}
|
||||
|
||||
async function fetchCustomEmailPoolEmail(state, options = {}) {
|
||||
throwIfStopped();
|
||||
const latestState = state || await getState();
|
||||
const requestedIndex = Math.max(0, Math.floor(Number(options.poolIndex) || 0));
|
||||
const email = String(getCustomEmailPoolEmail?.(latestState, requestedIndex + 1) || '').trim().toLowerCase();
|
||||
if (!email) {
|
||||
throw new Error(
|
||||
requestedIndex > 0
|
||||
? `自定义邮箱池第 ${requestedIndex + 1} 个邮箱不存在,请检查邮箱池配置。`
|
||||
: '自定义邮箱池为空,请先至少填写 1 个邮箱。'
|
||||
);
|
||||
}
|
||||
|
||||
await setEmailState(email);
|
||||
await addLog(`自定义邮箱池:已取用 ${email}`, 'ok');
|
||||
return email;
|
||||
}
|
||||
|
||||
async function fetchManagedAliasEmail(state, options = {}) {
|
||||
throwIfStopped();
|
||||
const provider = String(options.mailProvider || state?.mailProvider || '').trim().toLowerCase();
|
||||
@@ -233,21 +254,45 @@
|
||||
const mail2925Mode = options.mail2925Mode !== undefined
|
||||
? options.mail2925Mode
|
||||
: currentState.mail2925Mode;
|
||||
if (isGeneratedAliasProvider?.(provider, mail2925Mode)) {
|
||||
return fetchManagedAliasEmail(currentState, options);
|
||||
}
|
||||
const generator = normalizeEmailGenerator(options.generator ?? currentState.emailGenerator);
|
||||
const mergedState = {
|
||||
...currentState,
|
||||
mailProvider: provider || currentState.mailProvider,
|
||||
mail2925Mode,
|
||||
emailGenerator: generator,
|
||||
};
|
||||
if (options.gmailBaseEmail !== undefined) {
|
||||
mergedState.gmailBaseEmail = String(options.gmailBaseEmail || '').trim();
|
||||
}
|
||||
if (options.mail2925BaseEmail !== undefined) {
|
||||
mergedState.mail2925BaseEmail = String(options.mail2925BaseEmail || '').trim();
|
||||
}
|
||||
if (options.customEmailPool !== undefined) {
|
||||
mergedState.customEmailPool = options.customEmailPool;
|
||||
}
|
||||
if (generator === 'custom') {
|
||||
throw new Error('当前邮箱生成方式为自定义邮箱,请直接填写注册邮箱。');
|
||||
}
|
||||
if (generator === CUSTOM_EMAIL_POOL_GENERATOR) {
|
||||
return fetchCustomEmailPoolEmail(mergedState, options);
|
||||
}
|
||||
const shouldUseManagedAlias = typeof isGeneratedAliasProvider === 'function'
|
||||
? isGeneratedAliasProvider(mergedState, mail2925Mode)
|
||||
: false;
|
||||
if (shouldUseManagedAlias) {
|
||||
return fetchManagedAliasEmail(mergedState, options);
|
||||
}
|
||||
if (generator === 'icloud') {
|
||||
return fetchIcloudHideMyEmail();
|
||||
const stateFetchMode = String(mergedState.icloudFetchMode || '').trim().toLowerCase();
|
||||
return fetchIcloudHideMyEmail({
|
||||
generateNew: Boolean(options.generateNew) || stateFetchMode === 'always_new',
|
||||
});
|
||||
}
|
||||
if (generator === 'cloudflare') {
|
||||
return fetchCloudflareEmail(currentState, options);
|
||||
return fetchCloudflareEmail(mergedState, options);
|
||||
}
|
||||
if (generator === CLOUDFLARE_TEMP_EMAIL_GENERATOR) {
|
||||
return fetchCloudflareTempEmailAddress(currentState, options);
|
||||
return fetchCloudflareTempEmailAddress(mergedState, options);
|
||||
}
|
||||
return fetchDuckEmail(options);
|
||||
}
|
||||
@@ -255,6 +300,7 @@
|
||||
return {
|
||||
ensureCloudflareTempEmailConfig,
|
||||
fetchCloudflareEmail,
|
||||
fetchCustomEmailPoolEmail,
|
||||
fetchCloudflareTempEmailAddress,
|
||||
fetchDuckEmail,
|
||||
fetchGeneratedEmail,
|
||||
|
||||
+126
-15
@@ -25,6 +25,7 @@
|
||||
sleepWithStop,
|
||||
throwIfStopped,
|
||||
upsertMail2925AccountInList,
|
||||
waitForTabComplete,
|
||||
waitForTabUrlMatch,
|
||||
} = deps;
|
||||
|
||||
@@ -45,6 +46,9 @@
|
||||
];
|
||||
const MAIL2925_LIMIT_ERROR_PREFIX = 'MAIL2925_LIMIT_REACHED::';
|
||||
const MAIL2925_THREAD_TERMINATED_ERROR_PREFIX = 'MAIL2925_THREAD_TERMINATED::';
|
||||
const MAIL2925_LOGIN_MESSAGE_RETRY_WINDOW_MS = 15000;
|
||||
const MAIL2925_LOGIN_RESPONSE_TIMEOUT_MS = 120000;
|
||||
const MAIL2925_LOGIN_PAGE_RECOVERY_TIMEOUT_MS = 120000;
|
||||
|
||||
function getMail2925MailConfig() {
|
||||
return {
|
||||
@@ -95,6 +99,14 @@
|
||||
return getErrorMessage(error).startsWith(MAIL2925_THREAD_TERMINATED_ERROR_PREFIX);
|
||||
}
|
||||
|
||||
function isRetryableMail2925TransportError(error) {
|
||||
const message = getErrorMessage(error).toLowerCase();
|
||||
return message.includes('receiving end does not exist')
|
||||
|| message.includes('message port closed')
|
||||
|| message.includes('content script on')
|
||||
|| message.includes('did not respond');
|
||||
}
|
||||
|
||||
async function syncMail2925Accounts(accounts) {
|
||||
const normalized = normalizeMail2925Accounts(accounts);
|
||||
await setPersistentSettings({ mail2925Accounts: normalized });
|
||||
@@ -168,6 +180,10 @@
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeMailboxEmail(value = '') {
|
||||
return String(value || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
async function setCurrentMail2925Account(accountId, options = {}) {
|
||||
const { logMessage = '', updateLastUsedAt = false } = options;
|
||||
const state = await getState();
|
||||
@@ -186,6 +202,7 @@
|
||||
await syncMail2925Accounts(accounts.map((item) => (item.id === account.id ? nextAccount : item)));
|
||||
}
|
||||
|
||||
await setPersistentSettings({ currentMail2925AccountId: nextAccount.id });
|
||||
await setState({ currentMail2925AccountId: nextAccount.id });
|
||||
broadcastDataUpdate({ currentMail2925AccountId: nextAccount.id });
|
||||
if (logMessage) {
|
||||
@@ -210,6 +227,7 @@
|
||||
await syncMail2925Accounts(accounts.map((item) => (item.id === account.id ? nextAccount : item)));
|
||||
|
||||
if (state.currentMail2925AccountId === account.id && nextAccount.enabled === false) {
|
||||
await setPersistentSettings({ currentMail2925AccountId: '' });
|
||||
await setState({ currentMail2925AccountId: null });
|
||||
broadcastDataUpdate({ currentMail2925AccountId: null });
|
||||
}
|
||||
@@ -224,6 +242,7 @@
|
||||
await syncMail2925Accounts(nextAccounts);
|
||||
|
||||
if (state.currentMail2925AccountId === accountId) {
|
||||
await setPersistentSettings({ currentMail2925AccountId: '' });
|
||||
await setState({ currentMail2925AccountId: null });
|
||||
broadcastDataUpdate({ currentMail2925AccountId: null });
|
||||
}
|
||||
@@ -239,6 +258,7 @@
|
||||
await syncMail2925Accounts(nextAccounts);
|
||||
|
||||
if (state.currentMail2925AccountId && !findMail2925Account(nextAccounts, state.currentMail2925AccountId)) {
|
||||
await setPersistentSettings({ currentMail2925AccountId: '' });
|
||||
await setState({ currentMail2925AccountId: null });
|
||||
broadcastDataUpdate({ currentMail2925AccountId: null });
|
||||
}
|
||||
@@ -391,16 +411,56 @@
|
||||
return removedCount;
|
||||
}
|
||||
|
||||
async function recoverMail2925LoginPageAfterTransportError(tabId) {
|
||||
const numericTabId = Number(tabId);
|
||||
if (!Number.isInteger(numericTabId) || numericTabId <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentUrl = (await getMail2925TabUrlById(numericTabId)) || await getMail2925CurrentTabUrl();
|
||||
await addLog(
|
||||
`2925:登录提交后页面发生跳转或重载,正在等待当前标签页恢复后继续确认登录态。当前地址:${currentUrl || 'unknown'}`,
|
||||
'warn'
|
||||
);
|
||||
|
||||
if (typeof waitForTabComplete === 'function') {
|
||||
const completedTab = await waitForTabComplete(numericTabId, {
|
||||
timeoutMs: MAIL2925_LOGIN_PAGE_RECOVERY_TIMEOUT_MS,
|
||||
retryDelayMs: 300,
|
||||
});
|
||||
await addLog(
|
||||
`2925:登录跳转等待结束,当前标签地址:${String(completedTab?.url || '').trim() || 'unknown'}`,
|
||||
completedTab?.url ? 'info' : 'warn'
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof ensureContentScriptReadyOnTab === 'function') {
|
||||
await ensureContentScriptReadyOnTab(MAIL2925_SOURCE, numericTabId, {
|
||||
inject: MAIL2925_INJECT,
|
||||
injectSource: MAIL2925_INJECT_SOURCE,
|
||||
timeoutMs: MAIL2925_LOGIN_PAGE_RECOVERY_TIMEOUT_MS,
|
||||
retryDelayMs: 800,
|
||||
logMessage: '步骤 0:2925 登录后页面仍在跳转,正在等待邮箱页重新就绪...',
|
||||
});
|
||||
}
|
||||
|
||||
const recoveredUrl = (await getMail2925TabUrlById(numericTabId)) || await getMail2925CurrentTabUrl();
|
||||
await addLog(`2925:登录跳转恢复后当前标签地址:${recoveredUrl || 'unknown'}`, 'info');
|
||||
}
|
||||
|
||||
async function ensureMail2925MailboxSession(options = {}) {
|
||||
const {
|
||||
accountId = null,
|
||||
forceRelogin = false,
|
||||
actionLabel = '确保 2925 邮箱登录态',
|
||||
allowLoginWhenOnLoginPage = true,
|
||||
expectedMailboxEmail = '',
|
||||
} = options;
|
||||
|
||||
const normalizedExpectedMailboxEmail = normalizeMailboxEmail(expectedMailboxEmail);
|
||||
|
||||
let account = null;
|
||||
if (forceRelogin) {
|
||||
if (forceRelogin || (allowLoginWhenOnLoginPage && normalizedExpectedMailboxEmail)) {
|
||||
account = await ensureMail2925AccountForFlow({
|
||||
allowAllocate: true,
|
||||
preferredAccountId: accountId,
|
||||
@@ -477,16 +537,16 @@
|
||||
}
|
||||
}
|
||||
|
||||
if (!forceRelogin && !isMail2925LoginUrl(openedUrl)) {
|
||||
if (!forceRelogin && !isMail2925LoginUrl(openedUrl) && !normalizedExpectedMailboxEmail) {
|
||||
await addLog('2925:当前邮箱页未跳转到登录页,将直接复用已登录会话。', 'info');
|
||||
return buildSuccessPayload();
|
||||
}
|
||||
|
||||
if (!forceRelogin && !allowLoginWhenOnLoginPage) {
|
||||
if (!forceRelogin && isMail2925LoginUrl(openedUrl) && !allowLoginWhenOnLoginPage) {
|
||||
await failMailboxSession(`2925:${actionLabel}失败,当前页面已跳转到登录页,且当前未启用 2925 账号池,不执行自动登录。`);
|
||||
}
|
||||
|
||||
if (!account) {
|
||||
if (!account && (forceRelogin || allowLoginWhenOnLoginPage)) {
|
||||
account = await ensureMail2925AccountForFlow({
|
||||
allowAllocate: true,
|
||||
preferredAccountId: accountId,
|
||||
@@ -509,35 +569,51 @@
|
||||
}
|
||||
|
||||
let result;
|
||||
try {
|
||||
const sendEnsureSessionRequest = async () => {
|
||||
const beforeSendUrl = (await getMail2925TabUrlById(tabId)) || await getMail2925CurrentTabUrl();
|
||||
await addLog(`2925:发送 ENSURE_MAIL2925_SESSION 前当前地址:${beforeSendUrl || 'unknown'}`, 'info');
|
||||
result = await sendLoginMessage(
|
||||
return sendLoginMessage(
|
||||
MAIL2925_SOURCE,
|
||||
{
|
||||
type: 'ENSURE_MAIL2925_SESSION',
|
||||
step: 0,
|
||||
source: 'background',
|
||||
payload: {
|
||||
email: account.email,
|
||||
password: account.password,
|
||||
email: account?.email || '',
|
||||
password: account?.password || '',
|
||||
forceLogin: forceRelogin,
|
||||
allowLoginWhenOnLoginPage,
|
||||
},
|
||||
},
|
||||
{
|
||||
timeoutMs: 50000,
|
||||
timeoutMs: MAIL2925_LOGIN_MESSAGE_RETRY_WINDOW_MS,
|
||||
retryDelayMs: 800,
|
||||
responseTimeoutMs: 50000,
|
||||
responseTimeoutMs: MAIL2925_LOGIN_RESPONSE_TIMEOUT_MS,
|
||||
logMessage: '步骤 0:2925 登录页通信异常,正在等待页面恢复...',
|
||||
}
|
||||
);
|
||||
};
|
||||
try {
|
||||
result = await sendEnsureSessionRequest();
|
||||
} catch (err) {
|
||||
const message = `2925:${actionLabel}失败(${getErrorMessage(err) || '40 秒内未进入收件箱'})。`;
|
||||
const stopped = await stopAutoRunForMail2925LoginFailure(`${message}已按手动停止逻辑暂停自动流程。`);
|
||||
if (stopped) {
|
||||
throw new Error('流程已被用户停止。');
|
||||
if (isRetryableMail2925TransportError(err)) {
|
||||
try {
|
||||
await recoverMail2925LoginPageAfterTransportError(tabId);
|
||||
await addLog('2925:页面恢复完成,正在重新确认登录态...', 'info');
|
||||
result = await sendEnsureSessionRequest();
|
||||
} catch (recoveryErr) {
|
||||
err = recoveryErr;
|
||||
}
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
const message = `2925:${actionLabel}失败(${getErrorMessage(err) || '登录结果确认超时'})。`;
|
||||
const stopped = await stopAutoRunForMail2925LoginFailure(`${message}已按手动停止逻辑暂停自动流程。`);
|
||||
if (stopped) {
|
||||
throw new Error('流程已被用户停止。');
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (result?.error) {
|
||||
@@ -546,10 +622,44 @@
|
||||
if (result?.limitReached) {
|
||||
throw new Error(`${MAIL2925_LIMIT_ERROR_PREFIX}${result.limitMessage || '子邮箱已达上限邮箱'}`);
|
||||
}
|
||||
const actualMailboxEmail = normalizeMailboxEmail(result?.mailboxEmail || '');
|
||||
if (normalizedExpectedMailboxEmail && actualMailboxEmail && actualMailboxEmail !== normalizedExpectedMailboxEmail) {
|
||||
if (allowLoginWhenOnLoginPage) {
|
||||
await addLog(
|
||||
`2925:当前邮箱页显示账号 ${actualMailboxEmail},与目标账号 ${normalizedExpectedMailboxEmail} 不一致,准备登出当前账号并登录目标账号。`,
|
||||
'warn'
|
||||
);
|
||||
return ensureMail2925MailboxSession({
|
||||
accountId: account?.id || accountId || null,
|
||||
forceRelogin: true,
|
||||
allowLoginWhenOnLoginPage: true,
|
||||
expectedMailboxEmail: normalizedExpectedMailboxEmail,
|
||||
actionLabel,
|
||||
});
|
||||
}
|
||||
await failMailboxSession(
|
||||
`2925:${actionLabel}失败,当前邮箱页显示账号 ${actualMailboxEmail},与目标账号 ${normalizedExpectedMailboxEmail} 不一致,且当前未启用 2925 账号池。`
|
||||
);
|
||||
}
|
||||
if (normalizedExpectedMailboxEmail && !actualMailboxEmail && result?.currentView === 'mailbox') {
|
||||
await addLog('2925:未能识别当前邮箱页顶部邮箱地址,已跳过邮箱一致性校验。', 'warn');
|
||||
}
|
||||
if (!result?.loggedIn) {
|
||||
await failMailboxSession(`2925:${actionLabel}失败,登录后仍未进入收件箱。`);
|
||||
}
|
||||
|
||||
if (!account) {
|
||||
await addLog('2925:未触发自动登录,继续复用当前已登录会话。', 'info');
|
||||
return {
|
||||
account: null,
|
||||
mail: getMail2925MailConfig(),
|
||||
result: {
|
||||
...result,
|
||||
usedExistingSession: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
await patchMail2925Account(account.id, {
|
||||
lastLoginAt: Date.now(),
|
||||
lastError: '',
|
||||
@@ -613,6 +723,7 @@
|
||||
});
|
||||
|
||||
if (!nextAccount) {
|
||||
await setPersistentSettings({ currentMail2925AccountId: '' });
|
||||
await setState({ currentMail2925AccountId: null });
|
||||
broadcastDataUpdate({ currentMail2925AccountId: null });
|
||||
if (typeof requestStop === 'function') {
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
getPendingAutoRunTimerPlan,
|
||||
getSourceLabel,
|
||||
getState,
|
||||
getTabId,
|
||||
getStopRequested,
|
||||
handleAutoRunLoopUnhandledError,
|
||||
importSettingsBundle,
|
||||
@@ -50,6 +51,7 @@
|
||||
isLocalhostOAuthCallbackUrl,
|
||||
isLuckmailProvider,
|
||||
isStopError,
|
||||
isTabAlive,
|
||||
launchAutoRunTimerPlan,
|
||||
listIcloudAliases,
|
||||
listLuckmailPurchasesForManagement,
|
||||
@@ -108,6 +110,23 @@
|
||||
return appendAccountRunRecord(status, state, reason);
|
||||
}
|
||||
|
||||
async function ensureManualStepPrerequisites(step) {
|
||||
if (step !== 4) {
|
||||
return;
|
||||
}
|
||||
|
||||
const signupTabId = typeof getTabId === 'function'
|
||||
? await getTabId('signup-page')
|
||||
: null;
|
||||
const signupTabAlive = signupTabId && typeof isTabAlive === 'function'
|
||||
? await isTabAlive('signup-page')
|
||||
: Boolean(signupTabId);
|
||||
|
||||
if (!signupTabId || !signupTabAlive) {
|
||||
throw new Error('手动执行步骤 4 前,请先执行步骤 1 或步骤 2,确保认证页仍然打开并停留在验证码页。');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleStepData(step, payload) {
|
||||
switch (step) {
|
||||
case 1: {
|
||||
@@ -121,6 +140,8 @@
|
||||
if (payload.sub2apiGroupId !== undefined) updates.sub2apiGroupId = payload.sub2apiGroupId || null;
|
||||
if (payload.sub2apiDraftName !== undefined) updates.sub2apiDraftName = payload.sub2apiDraftName || null;
|
||||
if (payload.sub2apiProxyId !== undefined) updates.sub2apiProxyId = payload.sub2apiProxyId || null;
|
||||
if (payload.codex2apiSessionId !== undefined) updates.codex2apiSessionId = payload.codex2apiSessionId || null;
|
||||
if (payload.codex2apiOAuthState !== undefined) updates.codex2apiOAuthState = payload.codex2apiOAuthState || null;
|
||||
if (Object.keys(updates).length) {
|
||||
await setState(updates);
|
||||
}
|
||||
@@ -130,6 +151,18 @@
|
||||
if (payload.email) {
|
||||
await setEmailState(payload.email);
|
||||
}
|
||||
if (payload.skipRegistrationFlow) {
|
||||
const latestState = await getState();
|
||||
for (const skipStep of [3, 4, 5]) {
|
||||
const status = latestState.stepStatuses?.[skipStep];
|
||||
if (status === 'running' || status === 'completed' || status === 'manual_completed') {
|
||||
continue;
|
||||
}
|
||||
await setStepStatus(skipStep, 'skipped');
|
||||
}
|
||||
await addLog('步骤 2:检测到当前已登录会话,已自动跳过步骤 3/4/5,流程将直接进入步骤 6。', 'warn');
|
||||
break;
|
||||
}
|
||||
if (payload.skippedPasswordStep) {
|
||||
const latestState = await getState();
|
||||
const step3Status = latestState.stepStatuses?.[3];
|
||||
@@ -158,6 +191,14 @@
|
||||
lastEmailTimestamp: payload.emailTimestamp || null,
|
||||
signupVerificationRequestedAt: null,
|
||||
});
|
||||
if (payload.skipProfileStep) {
|
||||
const latestState = await getState();
|
||||
const step5Status = latestState.stepStatuses?.[5];
|
||||
if (step5Status !== 'running' && step5Status !== 'completed' && step5Status !== 'manual_completed') {
|
||||
await setStepStatus(5, 'skipped');
|
||||
await addLog('步骤 4:检测到账号已直接进入已登录态,已自动跳过步骤 5。', 'warn');
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 8:
|
||||
await setState({
|
||||
@@ -402,6 +443,9 @@
|
||||
await ensureManualInteractionAllowed('手动执行步骤');
|
||||
}
|
||||
const step = message.payload.step;
|
||||
if (message.source === 'sidepanel') {
|
||||
await ensureManualStepPrerequisites(step);
|
||||
}
|
||||
if (message.source === 'sidepanel') {
|
||||
await invalidateDownstreamAfterStepRestart(step, { logLabel: `步骤 ${step} 重新执行` });
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
})(typeof self !== 'undefined' ? self : globalThis, function createBackgroundNavigationUtilsModule() {
|
||||
function createNavigationUtils(deps = {}) {
|
||||
const {
|
||||
DEFAULT_CODEX2API_URL,
|
||||
DEFAULT_SUB2API_URL,
|
||||
normalizeLocalCpaStep9Mode,
|
||||
} = deps;
|
||||
@@ -27,13 +28,36 @@
|
||||
return parsed.toString();
|
||||
}
|
||||
|
||||
function normalizeCodex2ApiUrl(rawUrl) {
|
||||
const input = (rawUrl || '').trim() || DEFAULT_CODEX2API_URL;
|
||||
const withProtocol = /^https?:\/\//i.test(input) ? input : `http://${input}`;
|
||||
const parsed = new URL(withProtocol);
|
||||
if (!parsed.pathname || parsed.pathname === '/' || parsed.pathname === '/admin') {
|
||||
parsed.pathname = '/admin/accounts';
|
||||
}
|
||||
parsed.hash = '';
|
||||
return parsed.toString();
|
||||
}
|
||||
|
||||
function getPanelMode(state = {}) {
|
||||
return state.panelMode === 'sub2api' ? 'sub2api' : 'cpa';
|
||||
if (state.panelMode === 'sub2api') {
|
||||
return 'sub2api';
|
||||
}
|
||||
if (state.panelMode === 'codex2api') {
|
||||
return 'codex2api';
|
||||
}
|
||||
return 'cpa';
|
||||
}
|
||||
|
||||
function getPanelModeLabel(modeOrState) {
|
||||
const mode = typeof modeOrState === 'string' ? modeOrState : getPanelMode(modeOrState);
|
||||
return mode === 'sub2api' ? 'SUB2API' : 'CPA';
|
||||
if (mode === 'sub2api') {
|
||||
return 'SUB2API';
|
||||
}
|
||||
if (mode === 'codex2api') {
|
||||
return 'Codex2API';
|
||||
}
|
||||
return 'CPA';
|
||||
}
|
||||
|
||||
function isSignupPageHost(hostname = '') {
|
||||
@@ -124,6 +148,14 @@
|
||||
|| candidate.pathname.startsWith('/login')
|
||||
|| candidate.pathname === '/'
|
||||
);
|
||||
case 'codex2api-panel':
|
||||
return Boolean(reference)
|
||||
&& candidate.origin === reference.origin
|
||||
&& (
|
||||
candidate.pathname.startsWith('/admin/accounts')
|
||||
|| candidate.pathname === '/admin'
|
||||
|| candidate.pathname === '/'
|
||||
);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
@@ -160,6 +192,7 @@
|
||||
isSignupPageHost,
|
||||
isSignupPasswordPageUrl,
|
||||
matchesSourceUrlFamily,
|
||||
normalizeCodex2ApiUrl,
|
||||
normalizeSub2ApiUrl,
|
||||
parseUrlSafely,
|
||||
shouldBypassStep9ForLocalCpa,
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
closeConflictingTabsForSource,
|
||||
ensureContentScriptReadyOnTab,
|
||||
getPanelMode,
|
||||
normalizeCodex2ApiUrl,
|
||||
normalizeSub2ApiUrl,
|
||||
rememberSourceLastUrl,
|
||||
sendToContentScript,
|
||||
@@ -17,7 +18,74 @@
|
||||
SUB2API_STEP1_RESPONSE_TIMEOUT_MS,
|
||||
} = deps;
|
||||
|
||||
function normalizeAdminKey(value = '') {
|
||||
return String(value || '').trim();
|
||||
}
|
||||
|
||||
function extractStateFromAuthUrl(authUrl = '') {
|
||||
try {
|
||||
return new URL(authUrl).searchParams.get('state') || '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function getCodex2ApiErrorMessage(payload, responseStatus = 500) {
|
||||
const candidates = [
|
||||
payload?.error,
|
||||
payload?.message,
|
||||
payload?.detail,
|
||||
payload?.reason,
|
||||
];
|
||||
const message = candidates
|
||||
.map((value) => String(value || '').trim())
|
||||
.find(Boolean);
|
||||
return message || `Codex2API 请求失败(HTTP ${responseStatus})。`;
|
||||
}
|
||||
|
||||
async function fetchCodex2ApiJson(origin, path, options = {}) {
|
||||
const timeoutMs = Math.max(1000, Math.floor(Number(options.timeoutMs) || 30000));
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${origin}${path}`, {
|
||||
method: options.method || 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-Admin-Key': normalizeAdminKey(options.adminKey),
|
||||
},
|
||||
body: options.body === undefined ? undefined : JSON.stringify(options.body),
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
let payload = {};
|
||||
try {
|
||||
payload = await response.json();
|
||||
} catch {
|
||||
payload = {};
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(getCodex2ApiErrorMessage(payload, response.status));
|
||||
}
|
||||
|
||||
return payload;
|
||||
} catch (error) {
|
||||
if (error?.name === 'AbortError') {
|
||||
throw new Error('Codex2API 请求超时,请稍后重试。');
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
async function requestOAuthUrlFromPanel(state, options = {}) {
|
||||
if (getPanelMode(state) === 'codex2api') {
|
||||
return requestCodex2ApiOAuthUrl(state, options);
|
||||
}
|
||||
if (getPanelMode(state) === 'sub2api') {
|
||||
return requestSub2ApiOAuthUrl(state, options);
|
||||
}
|
||||
@@ -74,6 +142,39 @@
|
||||
return result || {};
|
||||
}
|
||||
|
||||
async function requestCodex2ApiOAuthUrl(state, options = {}) {
|
||||
const { logLabel = 'OAuth 刷新' } = options;
|
||||
const codex2apiUrl = normalizeCodex2ApiUrl(state.codex2apiUrl);
|
||||
const adminKey = normalizeAdminKey(state.codex2apiAdminKey);
|
||||
|
||||
if (!adminKey) {
|
||||
throw new Error('尚未配置 Codex2API 管理密钥,请先在侧边栏填写。');
|
||||
}
|
||||
|
||||
const origin = new URL(codex2apiUrl).origin;
|
||||
await addLog(`${logLabel}:正在通过 Codex2API 协议生成 OAuth 授权链接...`);
|
||||
|
||||
const result = await fetchCodex2ApiJson(origin, '/api/admin/oauth/generate-auth-url', {
|
||||
adminKey,
|
||||
method: 'POST',
|
||||
body: {},
|
||||
});
|
||||
|
||||
const oauthUrl = String(result?.auth_url || result?.authUrl || '').trim();
|
||||
const sessionId = String(result?.session_id || result?.sessionId || '').trim();
|
||||
const oauthState = extractStateFromAuthUrl(oauthUrl);
|
||||
|
||||
if (!oauthUrl || !sessionId) {
|
||||
throw new Error('Codex2API 未返回有效的 auth_url 或 session_id。');
|
||||
}
|
||||
|
||||
return {
|
||||
oauthUrl,
|
||||
codex2apiSessionId: sessionId,
|
||||
codex2apiOAuthState: oauthState || null,
|
||||
};
|
||||
}
|
||||
|
||||
async function requestSub2ApiOAuthUrl(state, options = {}) {
|
||||
const { logLabel = 'OAuth 刷新' } = options;
|
||||
const sub2apiUrl = normalizeSub2ApiUrl(state.sub2apiUrl);
|
||||
@@ -135,6 +236,7 @@
|
||||
|
||||
return {
|
||||
requestOAuthUrlFromPanel,
|
||||
requestCodex2ApiOAuthUrl,
|
||||
requestCpaOAuthUrl,
|
||||
requestSub2ApiOAuthUrl,
|
||||
};
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
})(typeof self !== 'undefined' ? self : globalThis, function createSignupFlowHelpersModule() {
|
||||
function createSignupFlowHelpers(deps = {}) {
|
||||
const {
|
||||
addLog,
|
||||
buildGeneratedAliasEmail,
|
||||
chrome,
|
||||
ensureContentScriptReadyOnTab,
|
||||
@@ -12,6 +13,7 @@
|
||||
isGeneratedAliasProvider,
|
||||
isReusableGeneratedAliasEmail,
|
||||
isHotmailProvider,
|
||||
isRetryableContentScriptTransportError = () => false,
|
||||
isLuckmailProvider,
|
||||
isSignupEmailVerificationPageUrl,
|
||||
isSignupPasswordPageUrl,
|
||||
@@ -164,20 +166,32 @@
|
||||
logMessage: `步骤 ${step}:认证页仍在切换,正在等待页面恢复后继续确认提交流程...`,
|
||||
});
|
||||
|
||||
const result = await sendToContentScriptResilient('signup-page', {
|
||||
type: 'PREPARE_SIGNUP_VERIFICATION',
|
||||
step,
|
||||
source: 'background',
|
||||
payload: {
|
||||
password: password || '',
|
||||
prepareSource: 'step3_finalize',
|
||||
prepareLogLabel: '步骤 3 收尾',
|
||||
},
|
||||
}, {
|
||||
timeoutMs: 30000,
|
||||
retryDelayMs: 700,
|
||||
logMessage: `步骤 ${step}:密码已提交,正在确认是否进入下一页面,必要时自动恢复重试页...`,
|
||||
});
|
||||
let result;
|
||||
try {
|
||||
result = await sendToContentScriptResilient('signup-page', {
|
||||
type: 'PREPARE_SIGNUP_VERIFICATION',
|
||||
step,
|
||||
source: 'background',
|
||||
payload: {
|
||||
password: password || '',
|
||||
prepareSource: 'step3_finalize',
|
||||
prepareLogLabel: '步骤 3 收尾',
|
||||
},
|
||||
}, {
|
||||
timeoutMs: 30000,
|
||||
retryDelayMs: 700,
|
||||
logMessage: `步骤 ${step}:密码已提交,正在确认是否进入下一页面,必要时自动恢复重试页...`,
|
||||
});
|
||||
} catch (error) {
|
||||
if (isRetryableContentScriptTransportError(error)) {
|
||||
const message = `步骤 ${step}:认证页在提交后切换过程中页面通信超时,未能重新就绪,暂时无法确认是否进入下一页面。请重试当前轮。`;
|
||||
if (typeof addLog === 'function') {
|
||||
await addLog(message, 'warn');
|
||||
}
|
||||
throw new Error(message);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (result?.error) {
|
||||
throw new Error(result.error);
|
||||
|
||||
@@ -200,12 +200,6 @@
|
||||
break;
|
||||
}
|
||||
|
||||
if (effect.restartCurrentStep) {
|
||||
await addLog(`步骤 9:${getStep8EffectLabel(effect)},准备重新定位“继续”按钮并重试...`, 'warn');
|
||||
await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (round >= STEP8_MAX_ROUNDS) {
|
||||
throw new Error(`步骤 9:连续 ${STEP8_MAX_ROUNDS} 轮点击“继续”后页面仍无反应。`);
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
chrome,
|
||||
CLOUDFLARE_TEMP_EMAIL_PROVIDER,
|
||||
confirmCustomVerificationStepBypass,
|
||||
ensureMail2925MailboxSession,
|
||||
ensureIcloudMailSession,
|
||||
ensureStep8VerificationPageReady,
|
||||
getOAuthFlowRemainingMs,
|
||||
getOAuthFlowStepTimeoutMs,
|
||||
@@ -57,6 +59,20 @@
|
||||
return String(value || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function getExpectedMail2925MailboxEmail(state = {}) {
|
||||
if (Boolean(state?.mail2925UseAccountPool)) {
|
||||
const currentAccountId = String(state?.currentMail2925AccountId || '').trim();
|
||||
const accounts = Array.isArray(state?.mail2925Accounts) ? state.mail2925Accounts : [];
|
||||
const currentAccount = accounts.find((account) => String(account?.id || '') === currentAccountId) || null;
|
||||
const accountEmail = String(currentAccount?.email || '').trim().toLowerCase();
|
||||
if (accountEmail) {
|
||||
return accountEmail;
|
||||
}
|
||||
}
|
||||
|
||||
return String(state?.mail2925BaseEmail || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
async function focusOrOpenMailTab(mail) {
|
||||
const alive = await isTabAlive(mail.source);
|
||||
if (alive) {
|
||||
@@ -125,6 +141,15 @@
|
||||
return;
|
||||
}
|
||||
|
||||
if (mail.source === 'icloud-mail' && typeof ensureIcloudMailSession === 'function') {
|
||||
await addLog('步骤 8:正在确认 iCloud 邮箱登录态...', 'info');
|
||||
await ensureIcloudMailSession({
|
||||
state,
|
||||
step: 8,
|
||||
actionLabel: '步骤 8:确认 iCloud 邮箱登录态',
|
||||
});
|
||||
}
|
||||
|
||||
throwIfStopped();
|
||||
if (
|
||||
mail.provider === HOTMAIL_PROVIDER
|
||||
@@ -134,7 +159,17 @@
|
||||
await addLog(`步骤 8:正在通过 ${mail.label} 轮询验证码...`);
|
||||
} else {
|
||||
await addLog(`步骤 8:正在打开${mail.label}...`);
|
||||
await focusOrOpenMailTab(mail);
|
||||
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',
|
||||
});
|
||||
} else {
|
||||
await focusOrOpenMailTab(mail);
|
||||
}
|
||||
if (mail.provider === '2925') {
|
||||
await addLog(`步骤 8:将直接使用当前已登录的 ${mail.label} 轮询验证码。`, 'info');
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
completeStepFromBackground,
|
||||
confirmCustomVerificationStepBypass,
|
||||
ensureMail2925MailboxSession,
|
||||
ensureIcloudMailSession,
|
||||
getMailConfig,
|
||||
getTabId,
|
||||
HOTMAIL_PROVIDER,
|
||||
@@ -24,6 +25,20 @@
|
||||
throwIfStopped,
|
||||
} = deps;
|
||||
|
||||
function getExpectedMail2925MailboxEmail(state = {}) {
|
||||
if (Boolean(state?.mail2925UseAccountPool)) {
|
||||
const currentAccountId = String(state?.currentMail2925AccountId || '').trim();
|
||||
const accounts = Array.isArray(state?.mail2925Accounts) ? state.mail2925Accounts : [];
|
||||
const currentAccount = accounts.find((account) => String(account?.id || '') === currentAccountId) || null;
|
||||
const accountEmail = String(currentAccount?.email || '').trim().toLowerCase();
|
||||
if (accountEmail) {
|
||||
return accountEmail;
|
||||
}
|
||||
}
|
||||
|
||||
return String(state?.mail2925BaseEmail || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
async function focusOrOpenMailTab(mail) {
|
||||
const alive = await isTabAlive(mail.source);
|
||||
if (alive) {
|
||||
@@ -58,7 +73,7 @@
|
||||
const signupTabId = await getTabId('signup-page');
|
||||
|
||||
if (!signupTabId) {
|
||||
throw new Error('认证页面标签页已关闭,无法继续步骤 4。');
|
||||
throw new Error('认证页面标签页已关闭,无法继续步骤 4。请先执行步骤 1 或步骤 2,重新打开认证页后再试。');
|
||||
}
|
||||
|
||||
await chrome.tabs.update(signupTabId, { active: true });
|
||||
@@ -97,6 +112,15 @@
|
||||
return;
|
||||
}
|
||||
|
||||
if (mail.source === 'icloud-mail' && typeof ensureIcloudMailSession === 'function') {
|
||||
await addLog('步骤 4:正在确认 iCloud 邮箱登录态...', 'info');
|
||||
await ensureIcloudMailSession({
|
||||
state,
|
||||
step: 4,
|
||||
actionLabel: '步骤 4:确认 iCloud 邮箱登录态',
|
||||
});
|
||||
}
|
||||
|
||||
throwIfStopped();
|
||||
if (
|
||||
mail.provider === HOTMAIL_PROVIDER
|
||||
@@ -111,6 +135,7 @@
|
||||
accountId: state.currentMail2925AccountId || null,
|
||||
forceRelogin: false,
|
||||
allowLoginWhenOnLoginPage: Boolean(state?.mail2925UseAccountPool),
|
||||
expectedMailboxEmail: getExpectedMail2925MailboxEmail(state),
|
||||
actionLabel: '步骤 4:确认 2925 邮箱登录态',
|
||||
});
|
||||
} else {
|
||||
|
||||
@@ -23,6 +23,20 @@
|
||||
throwIfStopped,
|
||||
} = deps;
|
||||
|
||||
function isManagementSecretConfigError(error) {
|
||||
const message = String(typeof error === 'string' ? error : error?.message || '').trim();
|
||||
if (!message) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const mentionsSecret = /管理密钥|Admin Secret|X-Admin-Key|CPA Key/i.test(message);
|
||||
if (!mentionsSecret) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return /缺少|未配置|请输入|无效|错误|失败|401|认证失败|未授权|unauthorized|invalid/i.test(message);
|
||||
}
|
||||
|
||||
async function executeStep7(state) {
|
||||
if (!state.email) {
|
||||
throw new Error('缺少邮箱地址,请先完成步骤 3。');
|
||||
@@ -99,6 +113,13 @@
|
||||
if (isAddPhoneAuthFailure(err)) {
|
||||
throw err;
|
||||
}
|
||||
if (isManagementSecretConfigError(err)) {
|
||||
await addLog(
|
||||
`步骤 7:检测到来源后台管理密钥缺失或错误,不再重试,当前流程停止。原因:${getErrorMessage(err)}`,
|
||||
'error'
|
||||
);
|
||||
throw err;
|
||||
}
|
||||
lastError = err;
|
||||
if (attempt >= STEP6_MAX_ATTEMPTS) {
|
||||
break;
|
||||
|
||||
@@ -1,14 +1,142 @@
|
||||
(function attachBackgroundStep1(root, factory) {
|
||||
root.MultiPageBackgroundStep1 = factory();
|
||||
})(typeof self !== 'undefined' ? self : globalThis, function createBackgroundStep1Module() {
|
||||
const STEP1_COOKIE_CLEAR_DOMAINS = [
|
||||
'chatgpt.com',
|
||||
'chat.openai.com',
|
||||
'openai.com',
|
||||
'auth.openai.com',
|
||||
'auth0.openai.com',
|
||||
'accounts.openai.com',
|
||||
];
|
||||
const STEP1_COOKIE_CLEAR_ORIGINS = [
|
||||
'https://chatgpt.com',
|
||||
'https://chat.openai.com',
|
||||
'https://auth.openai.com',
|
||||
'https://auth0.openai.com',
|
||||
'https://accounts.openai.com',
|
||||
'https://openai.com',
|
||||
];
|
||||
|
||||
function normalizeCookieDomainForStep1(domain) {
|
||||
return String(domain || '').trim().replace(/^\.+/, '').toLowerCase();
|
||||
}
|
||||
|
||||
function shouldClearStep1Cookie(cookie) {
|
||||
const domain = normalizeCookieDomainForStep1(cookie?.domain);
|
||||
if (!domain) return false;
|
||||
return STEP1_COOKIE_CLEAR_DOMAINS.some((target) => (
|
||||
domain === target || domain.endsWith(`.${target}`)
|
||||
));
|
||||
}
|
||||
|
||||
function buildStep1CookieRemovalUrl(cookie) {
|
||||
const host = normalizeCookieDomainForStep1(cookie?.domain);
|
||||
const rawPath = String(cookie?.path || '/');
|
||||
const path = rawPath.startsWith('/') ? rawPath : `/${rawPath}`;
|
||||
return `https://${host}${path}`;
|
||||
}
|
||||
|
||||
function getStep1ErrorMessage(error) {
|
||||
return error?.message || String(error || '未知错误');
|
||||
}
|
||||
|
||||
async function collectStep1Cookies(chromeApi) {
|
||||
if (!chromeApi.cookies?.getAll) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const stores = chromeApi.cookies.getAllCookieStores
|
||||
? await chromeApi.cookies.getAllCookieStores()
|
||||
: [{ id: undefined }];
|
||||
const cookies = [];
|
||||
const seen = new Set();
|
||||
|
||||
for (const store of stores) {
|
||||
const storeId = store?.id;
|
||||
const batch = await chromeApi.cookies.getAll(storeId ? { storeId } : {});
|
||||
for (const cookie of batch || []) {
|
||||
if (!shouldClearStep1Cookie(cookie)) continue;
|
||||
const key = [
|
||||
cookie.storeId || storeId || '',
|
||||
cookie.domain || '',
|
||||
cookie.path || '',
|
||||
cookie.name || '',
|
||||
cookie.partitionKey ? JSON.stringify(cookie.partitionKey) : '',
|
||||
].join('|');
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
cookies.push(cookie);
|
||||
}
|
||||
}
|
||||
|
||||
return cookies;
|
||||
}
|
||||
|
||||
async function removeStep1Cookie(chromeApi, cookie) {
|
||||
const details = {
|
||||
url: buildStep1CookieRemovalUrl(cookie),
|
||||
name: cookie.name,
|
||||
};
|
||||
if (cookie.storeId) {
|
||||
details.storeId = cookie.storeId;
|
||||
}
|
||||
if (cookie.partitionKey) {
|
||||
details.partitionKey = cookie.partitionKey;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await chromeApi.cookies.remove(details);
|
||||
return Boolean(result);
|
||||
} catch (error) {
|
||||
console.warn('[MultiPage:step1] remove cookie failed', {
|
||||
domain: cookie?.domain,
|
||||
name: cookie?.name,
|
||||
message: getStep1ErrorMessage(error),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function createStep1Executor(deps = {}) {
|
||||
const {
|
||||
addLog,
|
||||
chrome: chromeApi = globalThis.chrome,
|
||||
completeStepFromBackground,
|
||||
openSignupEntryTab,
|
||||
} = deps;
|
||||
|
||||
async function clearOpenAiCookiesBeforeStep1() {
|
||||
if (!chromeApi?.cookies?.getAll || !chromeApi.cookies?.remove) {
|
||||
await addLog('步骤 1:当前浏览器不支持 cookies API,跳过打开官网前 cookie 清理。', 'warn');
|
||||
return;
|
||||
}
|
||||
|
||||
await addLog('步骤 1:打开 ChatGPT 官网前清理 ChatGPT / OpenAI cookies...', 'info');
|
||||
const cookies = await collectStep1Cookies(chromeApi);
|
||||
let removedCount = 0;
|
||||
for (const cookie of cookies) {
|
||||
if (await removeStep1Cookie(chromeApi, cookie)) {
|
||||
removedCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (chromeApi.browsingData?.removeCookies) {
|
||||
try {
|
||||
await chromeApi.browsingData.removeCookies({
|
||||
since: 0,
|
||||
origins: STEP1_COOKIE_CLEAR_ORIGINS,
|
||||
});
|
||||
} catch (error) {
|
||||
await addLog(`步骤 1:browsingData 补扫 cookies 失败:${getStep1ErrorMessage(error)}`, 'warn');
|
||||
}
|
||||
}
|
||||
|
||||
await addLog(`步骤 1:已清理 ${removedCount} 个 ChatGPT / OpenAI cookies。`, 'ok');
|
||||
}
|
||||
|
||||
async function executeStep1() {
|
||||
await clearOpenAiCookiesBeforeStep1();
|
||||
await addLog('步骤 1:正在打开 ChatGPT 官网...');
|
||||
await openSignupEntryTab(1);
|
||||
await completeStepFromBackground(1, {});
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
getTabId,
|
||||
isLocalhostOAuthCallbackUrl,
|
||||
isTabAlive,
|
||||
normalizeCodex2ApiUrl,
|
||||
normalizeSub2ApiUrl,
|
||||
rememberSourceLastUrl,
|
||||
reuseOrCreateTab,
|
||||
@@ -21,7 +22,86 @@
|
||||
SUB2API_STEP9_RESPONSE_TIMEOUT_MS,
|
||||
} = deps;
|
||||
|
||||
function normalizeString(value = '') {
|
||||
return String(value || '').trim();
|
||||
}
|
||||
|
||||
function parseLocalhostCallback(rawUrl) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(rawUrl);
|
||||
} catch {
|
||||
throw new Error('步骤 10 捕获到的 localhost OAuth 回调地址格式无效,请重新执行步骤 9。');
|
||||
}
|
||||
|
||||
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。');
|
||||
}
|
||||
|
||||
return {
|
||||
url: parsed.toString(),
|
||||
code,
|
||||
state,
|
||||
};
|
||||
}
|
||||
|
||||
function getCodex2ApiErrorMessage(payload, responseStatus = 500) {
|
||||
const details = [
|
||||
payload?.error,
|
||||
payload?.message,
|
||||
payload?.detail,
|
||||
payload?.reason,
|
||||
]
|
||||
.map((value) => normalizeString(value))
|
||||
.find(Boolean);
|
||||
return details || `Codex2API 请求失败(HTTP ${responseStatus})。`;
|
||||
}
|
||||
|
||||
async function fetchCodex2ApiJson(origin, path, options = {}) {
|
||||
const controller = new AbortController();
|
||||
const timeoutMs = Math.max(1000, Math.floor(Number(options.timeoutMs) || 30000));
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${origin}${path}`, {
|
||||
method: options.method || 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-Admin-Key': normalizeString(options.adminKey),
|
||||
},
|
||||
body: options.body === undefined ? undefined : JSON.stringify(options.body),
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
let payload = {};
|
||||
try {
|
||||
payload = await response.json();
|
||||
} catch {
|
||||
payload = {};
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(getCodex2ApiErrorMessage(payload, response.status));
|
||||
}
|
||||
|
||||
return payload;
|
||||
} catch (error) {
|
||||
if (error?.name === 'AbortError') {
|
||||
throw new Error('Codex2API 请求超时,请稍后重试。');
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
async function executeStep10(state) {
|
||||
if (getPanelMode(state) === 'codex2api') {
|
||||
return executeCodex2ApiStep10(state);
|
||||
}
|
||||
if (getPanelMode(state) === 'sub2api') {
|
||||
return executeSub2ApiStep10(state);
|
||||
}
|
||||
@@ -79,7 +159,8 @@
|
||||
source: 'background',
|
||||
payload: { localhostUrl: state.localhostUrl, vpsPassword: state.vpsPassword },
|
||||
}, {
|
||||
timeoutMs: 30000,
|
||||
timeoutMs: 125000,
|
||||
responseTimeoutMs: 125000,
|
||||
retryDelayMs: 700,
|
||||
logMessage: '步骤 10:CPA 面板通信未就绪,正在等待页面恢复...',
|
||||
});
|
||||
@@ -89,6 +170,48 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function executeCodex2ApiStep10(state) {
|
||||
if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) {
|
||||
throw new Error('步骤 9 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 9。');
|
||||
}
|
||||
if (!state.localhostUrl) {
|
||||
throw new Error('缺少 localhost 回调地址,请先完成步骤 9。');
|
||||
}
|
||||
if (!state.codex2apiSessionId) {
|
||||
throw new Error('缺少 Codex2API 会话信息,请重新执行步骤 7。');
|
||||
}
|
||||
if (!normalizeString(state.codex2apiAdminKey)) {
|
||||
throw new Error('尚未配置 Codex2API 管理密钥,请先在侧边栏填写。');
|
||||
}
|
||||
|
||||
const callback = parseLocalhostCallback(state.localhostUrl);
|
||||
const expectedState = normalizeString(state.codex2apiOAuthState);
|
||||
if (expectedState && expectedState !== callback.state) {
|
||||
throw new Error('Codex2API 回调 state 与当前授权会话不匹配,请重新执行步骤 7。');
|
||||
}
|
||||
|
||||
const codex2apiUrl = normalizeCodex2ApiUrl(state.codex2apiUrl);
|
||||
const origin = new URL(codex2apiUrl).origin;
|
||||
|
||||
await addLog('步骤 10:正在向 Codex2API 提交回调并创建账号...');
|
||||
const result = await fetchCodex2ApiJson(origin, '/api/admin/oauth/exchange-code', {
|
||||
adminKey: state.codex2apiAdminKey,
|
||||
method: 'POST',
|
||||
body: {
|
||||
session_id: state.codex2apiSessionId,
|
||||
code: callback.code,
|
||||
state: callback.state,
|
||||
},
|
||||
});
|
||||
|
||||
const verifiedStatus = normalizeString(result?.message) || 'Codex2API OAuth 账号添加成功';
|
||||
await addLog(`步骤 10:${verifiedStatus}`, 'ok');
|
||||
await completeStepFromBackground(10, {
|
||||
localhostUrl: callback.url,
|
||||
verifiedStatus,
|
||||
});
|
||||
}
|
||||
|
||||
async function executeSub2ApiStep10(state) {
|
||||
if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) {
|
||||
throw new Error('步骤 9 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 9。');
|
||||
@@ -160,6 +283,7 @@
|
||||
|
||||
return {
|
||||
executeCpaStep10,
|
||||
executeCodex2ApiStep10,
|
||||
executeStep10,
|
||||
executeSub2ApiStep10,
|
||||
};
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
chrome,
|
||||
completeStepFromBackground,
|
||||
ensureContentScriptReadyOnTab,
|
||||
ensureSignupAuthEntryPageReady,
|
||||
ensureSignupEntryPageReady,
|
||||
ensureSignupPostEmailPageReadyInTab,
|
||||
getTabId,
|
||||
@@ -16,6 +17,107 @@
|
||||
SIGNUP_PAGE_INJECT_FILES,
|
||||
} = deps;
|
||||
|
||||
function getErrorMessage(error) {
|
||||
return String(typeof error === 'string' ? error : error?.message || '');
|
||||
}
|
||||
|
||||
function isSignupEntryUnavailableErrorMessage(errorLike) {
|
||||
const message = getErrorMessage(errorLike);
|
||||
return /未找到可用的邮箱输入入口|当前页面没有可用的注册入口,也不在邮箱\/密码页/.test(message);
|
||||
}
|
||||
|
||||
function isRetryableStep2TransportErrorMessage(errorLike) {
|
||||
const message = getErrorMessage(errorLike);
|
||||
return /Content script on signup-page did not respond in \d+s|Receiving end does not exist|message channel closed|A listener indicated an asynchronous response|port closed before a response was received|did not respond in \d+s/i.test(message);
|
||||
}
|
||||
|
||||
function isLikelyLoggedInChatgptHomeUrl(rawUrl) {
|
||||
const url = String(rawUrl || '').trim();
|
||||
if (!url) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
const host = String(parsed.hostname || '').toLowerCase();
|
||||
if (!['chatgpt.com', 'www.chatgpt.com'].includes(host)) {
|
||||
return false;
|
||||
}
|
||||
const path = String(parsed.pathname || '');
|
||||
if (/^\/(?:auth\/|create-account\/|email-verification|log-in|add-phone)(?:[/?#]|$)/i.test(path)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function shouldForceAuthEntryRetry(tabId) {
|
||||
if (!Number.isInteger(tabId) || typeof chrome?.tabs?.get !== 'function') {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const tab = await chrome.tabs.get(tabId);
|
||||
const currentUrl = String(tab?.url || '');
|
||||
return isLikelyLoggedInChatgptHomeUrl(currentUrl);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function getTabUrl(tabId) {
|
||||
if (!Number.isInteger(tabId) || typeof chrome?.tabs?.get !== 'function') {
|
||||
return '';
|
||||
}
|
||||
try {
|
||||
const tab = await chrome.tabs.get(tabId);
|
||||
return String(tab?.url || '');
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
async function completeStep2AsLoggedInSession(tabId, resolvedEmail, reasonMessage = '') {
|
||||
const currentUrl = await getTabUrl(tabId);
|
||||
if (!isLikelyLoggedInChatgptHomeUrl(currentUrl)) {
|
||||
return false;
|
||||
}
|
||||
const reasonText = getErrorMessage(reasonMessage);
|
||||
const reasonSuffix = reasonText ? `(触发原因:${reasonText})` : '';
|
||||
await addLog(`步骤 2:检测到当前会话已登录 ChatGPT,已跳过注册链路(步骤 3/4/5),将直接进入步骤 6。${reasonSuffix}`, 'warn');
|
||||
await completeStepFromBackground(2, {
|
||||
email: resolvedEmail,
|
||||
nextSignupState: 'already_logged_in_home',
|
||||
nextSignupUrl: currentUrl || 'https://chatgpt.com/',
|
||||
skippedPasswordStep: true,
|
||||
skipRegistrationFlow: true,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
async function submitSignupEmail(resolvedEmail, options = {}) {
|
||||
const {
|
||||
timeoutMs = 35000,
|
||||
retryDelayMs = 700,
|
||||
logMessage = '步骤 2:官网注册入口正在切换,等待页面恢复后继续输入邮箱...',
|
||||
} = options;
|
||||
|
||||
try {
|
||||
return await sendToContentScriptResilient('signup-page', {
|
||||
type: 'EXECUTE_STEP',
|
||||
step: 2,
|
||||
source: 'background',
|
||||
payload: { email: resolvedEmail },
|
||||
}, {
|
||||
timeoutMs,
|
||||
retryDelayMs,
|
||||
logMessage,
|
||||
});
|
||||
} catch (error) {
|
||||
return { error: getErrorMessage(error) };
|
||||
}
|
||||
}
|
||||
|
||||
async function executeStep2(state) {
|
||||
const resolvedEmail = await resolveSignupEmailForFlow(state);
|
||||
|
||||
@@ -34,19 +136,73 @@
|
||||
});
|
||||
}
|
||||
|
||||
const step2Result = await sendToContentScriptResilient('signup-page', {
|
||||
type: 'EXECUTE_STEP',
|
||||
step: 2,
|
||||
source: 'background',
|
||||
payload: { email: resolvedEmail },
|
||||
}, {
|
||||
timeoutMs: 20000,
|
||||
if (await shouldForceAuthEntryRetry(signupTabId)) {
|
||||
await addLog('步骤 2:检测到当前位于已登录 ChatGPT 首页,先切换认证入口页再提交邮箱。', 'warn');
|
||||
try {
|
||||
signupTabId = (await ensureSignupAuthEntryPageReady(2)).tabId;
|
||||
} catch (entryError) {
|
||||
const entryErrorMessage = getErrorMessage(entryError);
|
||||
if (await completeStep2AsLoggedInSession(signupTabId, resolvedEmail, entryErrorMessage)) {
|
||||
return;
|
||||
}
|
||||
await addLog('步骤 2:切换认证入口失败,正在重新打开官网入口并重试提交邮箱...', 'warn');
|
||||
signupTabId = (await ensureSignupEntryPageReady(2)).tabId;
|
||||
}
|
||||
}
|
||||
|
||||
let step2Result = await submitSignupEmail(resolvedEmail, {
|
||||
timeoutMs: 35000,
|
||||
retryDelayMs: 700,
|
||||
logMessage: '步骤 2:官网注册入口正在切换,等待页面恢复后继续输入邮箱...',
|
||||
});
|
||||
|
||||
if (step2Result?.error) {
|
||||
throw new Error(step2Result.error);
|
||||
const errorMessage = getErrorMessage(step2Result.error);
|
||||
if (isSignupEntryUnavailableErrorMessage(errorMessage)) {
|
||||
await addLog('步骤 2:未找到邮箱输入入口,正在切换认证入口页后重试一次...', 'warn');
|
||||
signupTabId = (await ensureSignupAuthEntryPageReady(2)).tabId;
|
||||
step2Result = await submitSignupEmail(resolvedEmail, {
|
||||
timeoutMs: 35000,
|
||||
retryDelayMs: 700,
|
||||
logMessage: '步骤 2:认证入口页已打开,正在重新提交邮箱...',
|
||||
});
|
||||
|
||||
if (step2Result?.error) {
|
||||
const retryErrorMessage = getErrorMessage(step2Result.error);
|
||||
if (isSignupEntryUnavailableErrorMessage(retryErrorMessage)) {
|
||||
if (await completeStep2AsLoggedInSession(signupTabId, resolvedEmail, retryErrorMessage)) {
|
||||
return;
|
||||
}
|
||||
await addLog('步骤 2:认证入口仍不可用,正在重新进入官网注册入口再重试一次...', 'warn');
|
||||
signupTabId = (await ensureSignupEntryPageReady(2)).tabId;
|
||||
step2Result = await submitSignupEmail(resolvedEmail, {
|
||||
timeoutMs: 35000,
|
||||
retryDelayMs: 700,
|
||||
logMessage: '步骤 2:重试官网注册入口后正在重新提交邮箱...',
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if (isRetryableStep2TransportErrorMessage(errorMessage)) {
|
||||
await addLog('步骤 2:注册入口页通信超时,正在切换认证入口页并重试提交邮箱...', 'warn');
|
||||
signupTabId = (await ensureSignupAuthEntryPageReady(2)).tabId;
|
||||
step2Result = await submitSignupEmail(resolvedEmail, {
|
||||
timeoutMs: 45000,
|
||||
retryDelayMs: 700,
|
||||
logMessage: '步骤 2:认证入口页已打开,正在重新提交邮箱...',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (step2Result?.error) {
|
||||
const finalErrorMessage = getErrorMessage(step2Result.error);
|
||||
if (
|
||||
(isSignupEntryUnavailableErrorMessage(finalErrorMessage)
|
||||
|| isRetryableStep2TransportErrorMessage(finalErrorMessage))
|
||||
&& await completeStep2AsLoggedInSession(signupTabId, resolvedEmail, finalErrorMessage)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
throw new Error(finalErrorMessage);
|
||||
}
|
||||
|
||||
if (!step2Result?.alreadyOnPasswordPage) {
|
||||
|
||||
@@ -376,6 +376,17 @@
|
||||
return 30000;
|
||||
}
|
||||
|
||||
function resolveResponseTimeoutMs(message, requestedResponseTimeoutMs, remainingTimeoutMs = null) {
|
||||
const fallbackTimeoutMs = getContentScriptResponseTimeoutMs(message);
|
||||
const requestedTimeoutMs = Number.isFinite(Number(requestedResponseTimeoutMs))
|
||||
? Math.max(1, Math.floor(Number(requestedResponseTimeoutMs)))
|
||||
: fallbackTimeoutMs;
|
||||
if (!Number.isFinite(Number(remainingTimeoutMs))) {
|
||||
return requestedTimeoutMs;
|
||||
}
|
||||
return Math.max(1, Math.min(requestedTimeoutMs, Math.floor(Number(remainingTimeoutMs))));
|
||||
}
|
||||
|
||||
function getMessageDebugLabel(source, message, tabId = null) {
|
||||
const parts = [source || 'unknown', message?.type || 'UNKNOWN'];
|
||||
if (Number.isInteger(message?.step)) parts.push(`step=${message.step}`);
|
||||
@@ -439,7 +450,13 @@
|
||||
pendingCommands.delete(source);
|
||||
reject(new Error(`Content script on ${source} did not respond in ${timeout / 1000}s. Try refreshing the tab and retry.`));
|
||||
}, timeout);
|
||||
pendingCommands.set(source, { message, resolve, reject, timer });
|
||||
pendingCommands.set(source, {
|
||||
message,
|
||||
resolve,
|
||||
reject,
|
||||
timer,
|
||||
responseTimeoutMs: timeout,
|
||||
});
|
||||
console.log(LOG_PREFIX, `Command queued for ${source} (waiting for ready)`);
|
||||
});
|
||||
}
|
||||
@@ -449,7 +466,7 @@
|
||||
if (pending) {
|
||||
clearTimeout(pending.timer);
|
||||
pendingCommands.delete(source);
|
||||
sendTabMessageWithTimeout(tabId, source, pending.message).then(pending.resolve).catch(pending.reject);
|
||||
sendTabMessageWithTimeout(tabId, source, pending.message, pending.responseTimeoutMs).then(pending.resolve).catch(pending.reject);
|
||||
console.log(LOG_PREFIX, `Flushed queued command to ${source} (tab ${tabId})`);
|
||||
}
|
||||
}
|
||||
@@ -564,13 +581,13 @@
|
||||
|
||||
if (!entry || !entry.ready) {
|
||||
throwIfStopped();
|
||||
return queueCommand(source, message);
|
||||
return queueCommand(source, message, responseTimeoutMs);
|
||||
}
|
||||
|
||||
const alive = await isTabAlive(source);
|
||||
throwIfStopped();
|
||||
if (!alive) {
|
||||
return queueCommand(source, message);
|
||||
return queueCommand(source, message, responseTimeoutMs);
|
||||
}
|
||||
|
||||
throwIfStopped();
|
||||
@@ -592,12 +609,18 @@
|
||||
while (Date.now() - start < timeoutMs) {
|
||||
throwIfStopped();
|
||||
attempt += 1;
|
||||
const remainingTimeoutMs = Math.max(1, timeoutMs - (Date.now() - start));
|
||||
const effectiveResponseTimeoutMs = resolveResponseTimeoutMs(
|
||||
message,
|
||||
responseTimeoutMs,
|
||||
remainingTimeoutMs
|
||||
);
|
||||
|
||||
try {
|
||||
return await sendToContentScript(
|
||||
source,
|
||||
message,
|
||||
responseTimeoutMs !== undefined ? { responseTimeoutMs } : {}
|
||||
{ responseTimeoutMs: effectiveResponseTimeoutMs }
|
||||
);
|
||||
} catch (err) {
|
||||
const retryable = isRetryableContentScriptTransportError(err);
|
||||
@@ -631,12 +654,18 @@
|
||||
|
||||
while (Date.now() - start < timeoutMs) {
|
||||
throwIfStopped();
|
||||
const remainingTimeoutMs = Math.max(1, timeoutMs - (Date.now() - start));
|
||||
const effectiveResponseTimeoutMs = resolveResponseTimeoutMs(
|
||||
message,
|
||||
responseTimeoutMs,
|
||||
remainingTimeoutMs
|
||||
);
|
||||
|
||||
try {
|
||||
return await sendToContentScript(
|
||||
mail.source,
|
||||
message,
|
||||
responseTimeoutMs !== undefined ? { responseTimeoutMs } : {}
|
||||
{ responseTimeoutMs: effectiveResponseTimeoutMs }
|
||||
);
|
||||
} catch (err) {
|
||||
if (!isRetryableContentScriptTransportError(err)) {
|
||||
@@ -684,6 +713,7 @@
|
||||
queueCommand,
|
||||
registerTab,
|
||||
rememberSourceLastUrl,
|
||||
resolveResponseTimeoutMs,
|
||||
reuseOrCreateTab,
|
||||
sendTabMessageWithTimeout,
|
||||
sendToContentScript,
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
pollHotmailVerificationCode,
|
||||
pollLuckmailVerificationCode,
|
||||
sendToContentScript,
|
||||
sendToContentScriptResilient,
|
||||
sendToMailContentScriptResilient,
|
||||
setState,
|
||||
sleepWithStop,
|
||||
@@ -30,6 +31,12 @@
|
||||
VERIFICATION_POLL_MAX_ROUNDS,
|
||||
} = deps;
|
||||
|
||||
const isRetryableVerificationTransportError = typeof deps.isRetryableContentScriptTransportError === 'function'
|
||||
? deps.isRetryableContentScriptTransportError
|
||||
: ((error) => /back\/forward cache|message channel is closed|Receiving end does not exist|port closed before a response was received|A listener indicated an asynchronous response|did not respond in \d+s/i.test(
|
||||
String(typeof error === 'string' ? error : error?.message || '')
|
||||
));
|
||||
|
||||
function getVerificationCodeStateKey(step) {
|
||||
return step === 4 ? 'lastSignupCode' : 'lastLoginCode';
|
||||
}
|
||||
@@ -38,6 +45,89 @@
|
||||
return step === 4 ? '注册' : '登录';
|
||||
}
|
||||
|
||||
function isLikelyLoggedInChatgptHomeUrl(rawUrl) {
|
||||
const url = String(rawUrl || '').trim();
|
||||
if (!url) return false;
|
||||
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
const host = String(parsed.hostname || '').toLowerCase();
|
||||
if (!['chatgpt.com', 'www.chatgpt.com'].includes(host)) {
|
||||
return false;
|
||||
}
|
||||
const path = String(parsed.pathname || '');
|
||||
if (/^\/(?:auth\/|create-account\/|email-verification|log-in|add-phone)(?:[/?#]|$)/i.test(path)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isSignupProfilePageUrl(rawUrl) {
|
||||
const url = String(rawUrl || '').trim();
|
||||
if (!url) return false;
|
||||
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
const host = String(parsed.hostname || '').toLowerCase();
|
||||
if (!['auth.openai.com', 'auth0.openai.com', 'accounts.openai.com'].includes(host)) {
|
||||
return false;
|
||||
}
|
||||
return /\/create-account\/profile(?:[/?#]|$)/i.test(String(parsed.pathname || ''));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function detectStep4PostSubmitFallback(tabId, options = {}) {
|
||||
const timeoutMs = Math.max(1000, Number(options.timeoutMs) || 8000);
|
||||
const pollIntervalMs = Math.max(100, Number(options.pollIntervalMs) || 250);
|
||||
const startedAt = Date.now();
|
||||
let lastUrl = '';
|
||||
|
||||
while (Date.now() - startedAt < timeoutMs) {
|
||||
throwIfStopped();
|
||||
try {
|
||||
const tab = await chrome.tabs.get(tabId);
|
||||
const currentUrl = String(tab?.url || '').trim();
|
||||
if (currentUrl) {
|
||||
lastUrl = currentUrl;
|
||||
}
|
||||
|
||||
if (isLikelyLoggedInChatgptHomeUrl(currentUrl)) {
|
||||
return {
|
||||
success: true,
|
||||
reason: 'chatgpt_home',
|
||||
skipProfileStep: true,
|
||||
url: currentUrl,
|
||||
};
|
||||
}
|
||||
|
||||
if (isSignupProfilePageUrl(currentUrl)) {
|
||||
return {
|
||||
success: true,
|
||||
reason: 'signup_profile',
|
||||
skipProfileStep: false,
|
||||
url: currentUrl,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// Keep polling until timeout; tab may be mid-navigation.
|
||||
}
|
||||
|
||||
await sleepWithStop(pollIntervalMs);
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
reason: 'unknown',
|
||||
skipProfileStep: false,
|
||||
url: lastUrl,
|
||||
};
|
||||
}
|
||||
|
||||
function getVerificationResendStateKey() {
|
||||
return 'verificationResendCount';
|
||||
}
|
||||
@@ -98,6 +188,9 @@
|
||||
if (response?.error) {
|
||||
throw new Error(response.error);
|
||||
}
|
||||
if (step === 8 && response?.addPhoneDetected) {
|
||||
throw new Error('步骤 8:验证码提交后页面进入手机号页面,当前流程无法继续自动授权。 URL: https://auth.openai.com/add-phone');
|
||||
}
|
||||
if (!response?.confirmed) {
|
||||
throw new Error(`步骤 ${step}:已取消手动${verificationLabel}验证码确认。`);
|
||||
}
|
||||
@@ -445,6 +538,17 @@
|
||||
`步骤 ${step}:距离下次重新发送验证码还差 ${Math.ceil(remainingBeforeResendMs / 1000)} 秒,继续刷新邮箱(第 ${round}/${maxRounds} 轮)...`,
|
||||
'info'
|
||||
);
|
||||
const configuredIntervalMs = Math.max(
|
||||
1,
|
||||
Number(payloadOverrides.intervalMs)
|
||||
|| Number(pollOverrides.intervalMs)
|
||||
|| 3000
|
||||
);
|
||||
const cooldownSleepMs = Math.min(
|
||||
remainingBeforeResendMs,
|
||||
Math.max(1000, Math.min(configuredIntervalMs, 3000))
|
||||
);
|
||||
await sleepWithStop(cooldownSleepMs);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -594,19 +698,54 @@
|
||||
}
|
||||
|
||||
await chrome.tabs.update(signupTabId, { active: true });
|
||||
const result = await sendToContentScript('signup-page', {
|
||||
const baseResponseTimeoutMs = await getResponseTimeoutMsForStep(
|
||||
step,
|
||||
options,
|
||||
step === 7 ? 45000 : 30000,
|
||||
`填写${getVerificationCodeLabel(step)}验证码`
|
||||
);
|
||||
const message = {
|
||||
type: 'FILL_CODE',
|
||||
step,
|
||||
source: 'background',
|
||||
payload: { code },
|
||||
}, {
|
||||
responseTimeoutMs: await getResponseTimeoutMsForStep(
|
||||
step,
|
||||
options,
|
||||
step === 7 ? 45000 : 30000,
|
||||
`填写${getVerificationCodeLabel(step)}验证码`
|
||||
),
|
||||
});
|
||||
};
|
||||
let result;
|
||||
if (typeof sendToContentScriptResilient === 'function') {
|
||||
try {
|
||||
result = await sendToContentScriptResilient('signup-page', message, {
|
||||
timeoutMs: Math.max(baseResponseTimeoutMs + 15000, 30000),
|
||||
retryDelayMs: 700,
|
||||
responseTimeoutMs: baseResponseTimeoutMs,
|
||||
logMessage: `步骤 ${step}:认证页正在切换,等待页面重新就绪后继续确认验证码提交结果...`,
|
||||
});
|
||||
} catch (err) {
|
||||
if (step === 4 && isRetryableVerificationTransportError(err)) {
|
||||
const fallback = await detectStep4PostSubmitFallback(signupTabId, {
|
||||
timeoutMs: 9000,
|
||||
pollIntervalMs: 300,
|
||||
});
|
||||
if (fallback.success) {
|
||||
const fallbackLabel = fallback.reason === 'chatgpt_home'
|
||||
? 'ChatGPT 已登录首页'
|
||||
: '注册资料页';
|
||||
await addLog(`步骤 4:验证码提交后页面已切换到${fallbackLabel},按提交成功继续。`, 'warn');
|
||||
return {
|
||||
success: true,
|
||||
assumed: true,
|
||||
transportRecovered: true,
|
||||
skipProfileStep: Boolean(fallback.skipProfileStep),
|
||||
url: fallback.url,
|
||||
};
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
} else {
|
||||
result = await sendToContentScript('signup-page', message, {
|
||||
responseTimeoutMs: baseResponseTimeoutMs,
|
||||
});
|
||||
}
|
||||
|
||||
if (result && result.error) {
|
||||
throw new Error(result.error);
|
||||
@@ -732,6 +871,7 @@
|
||||
`步骤 ${step}:提交失败后距离下次重新发送验证码还差 ${Math.ceil(remainingBeforeResendMs / 1000)} 秒,先继续刷新邮箱(${attempt + 1}/${maxSubmitAttempts})...`,
|
||||
'warn'
|
||||
);
|
||||
await sleepWithStop(Math.min(remainingBeforeResendMs, 2000));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -756,6 +896,7 @@
|
||||
emailTimestamp: result.emailTimestamp,
|
||||
code: result.code,
|
||||
phoneVerificationRequired: Boolean(submitResult.addPhonePage),
|
||||
...(step === 4 && submitResult?.skipProfileStep ? { skipProfileStep: true } : {}),
|
||||
});
|
||||
triggerPostSuccessMailboxCleanup(step, mail);
|
||||
return {
|
||||
|
||||
Reference in New Issue
Block a user