diff --git a/background.js b/background.js
index 7dd50f4..7abad4f 100644
--- a/background.js
+++ b/background.js
@@ -26,7 +26,6 @@ const PERSISTED_SETTING_DEFAULTS = {
sub2apiEmail: '', // SUB2API 登录邮箱。
sub2apiPassword: '', // SUB2API 登录密码。
sub2apiGroupName: DEFAULT_SUB2API_GROUP_NAME, // SUB2API 创建账号时绑定的分组名。
- sub2apiRedirectUri: DEFAULT_SUB2API_REDIRECT_URI, // SUB2API OpenAI Auth 回调地址。
customPassword: '', // 自定义账号密码;留空时由程序自动生成随机密码。
autoRunSkipFailures: false, // 自动运行遇到失败步骤后,是否继续执行后续流程。
mailProvider: '163', // 验证码邮箱来源,当前支持 163 / inbucket。
@@ -243,19 +242,6 @@ function normalizeSub2ApiUrl(rawUrl) {
return parsed.toString();
}
-function normalizeSub2ApiRedirectUri(rawUrl) {
- const input = (rawUrl || '').trim() || DEFAULT_SUB2API_REDIRECT_URI;
- const withProtocol = /^https?:\/\//i.test(input) ? input : `http://${input}`;
- const parsed = new URL(withProtocol);
- if (!parsed.pathname || parsed.pathname === '/') {
- parsed.pathname = '/auth/callback';
- }
- if (parsed.pathname !== '/auth/callback') {
- throw new Error('SUB2API 回调地址必须是 /auth/callback,例如 http://localhost:1455/auth/callback');
- }
- return parsed.toString();
-}
-
function getPanelMode(state = {}) {
return state.panelMode === 'sub2api' ? 'sub2api' : 'cpa';
}
@@ -280,18 +266,22 @@ function isLocalhostOAuthCallbackUrl(rawUrl) {
if (!parsed) return false;
if (!['http:', 'https:'].includes(parsed.protocol)) return false;
if (!['localhost', '127.0.0.1'].includes(parsed.hostname)) return false;
- if (parsed.pathname !== '/auth/callback') return false;
+ if (!['/auth/callback', '/codex/callback'].includes(parsed.pathname)) return false;
const code = (parsed.searchParams.get('code') || '').trim();
const state = (parsed.searchParams.get('state') || '').trim();
return Boolean(code && state);
}
-function buildLocalhostCleanupPrefix(rawUrl) {
- if (!isLocalhostOAuthCallbackUrl(rawUrl)) return '';
-
+function isLocalCpaUrl(rawUrl) {
const parsed = parseUrlSafely(rawUrl);
- return parsed ? `${parsed.origin}/auth` : '';
+ if (!parsed) return false;
+ if (!['http:', 'https:'].includes(parsed.protocol)) return false;
+ return ['localhost', '127.0.0.1'].includes(parsed.hostname);
+}
+
+function shouldBypassStep9ForLocalCpa(state) {
+ return Boolean(state?.localhostUrl) && isLocalCpaUrl(state?.vpsUrl);
}
function matchesSourceUrlFamily(source, candidateUrl, referenceUrl) {
@@ -366,21 +356,43 @@ async function closeConflictingTabsForSource(source, currentUrl, options = {}) {
await addLog(`已关闭 ${matchedIds.length} 个旧的${getSourceLabel(source)}标签页。`, 'info');
}
-async function closeTabsByUrlPrefix(prefix, options = {}) {
- if (!prefix) return 0;
+function isLocalhostOAuthCallbackTabMatch(callbackUrl, candidateUrl) {
+ if (!isLocalhostOAuthCallbackUrl(callbackUrl) || !isLocalhostOAuthCallbackUrl(candidateUrl)) {
+ return false;
+ }
+
+ const callback = parseUrlSafely(callbackUrl);
+ const candidate = parseUrlSafely(candidateUrl);
+ if (!callback || !candidate) return false;
+
+ return callback.origin === candidate.origin
+ && callback.pathname === candidate.pathname
+ && callback.searchParams.get('code') === candidate.searchParams.get('code')
+ && callback.searchParams.get('state') === candidate.searchParams.get('state');
+}
+
+async function closeLocalhostCallbackTabs(callbackUrl, options = {}) {
+ if (!isLocalhostOAuthCallbackUrl(callbackUrl)) return 0;
const { excludeTabIds = [] } = options;
const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
const tabs = await chrome.tabs.query({});
const matchedIds = tabs
.filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
- .filter((tab) => typeof tab.url === 'string' && tab.url.startsWith(prefix))
+ .filter((tab) => isLocalhostOAuthCallbackTabMatch(callbackUrl, tab.url))
.map((tab) => tab.id);
if (!matchedIds.length) return 0;
await chrome.tabs.remove(matchedIds).catch(() => { });
- await addLog(`已关闭 ${matchedIds.length} 个匹配 ${prefix} 的 localhost 残留标签页。`, 'info');
+
+ const registry = await getTabRegistry();
+ if (registry['signup-page']?.tabId && matchedIds.includes(registry['signup-page'].tabId)) {
+ registry['signup-page'] = null;
+ await setState({ tabRegistry: registry });
+ }
+
+ await addLog(`已关闭 ${matchedIds.length} 个匹配当前 OAuth callback 的 localhost 残留标签页。`, 'info');
return matchedIds.length;
}
@@ -925,6 +937,26 @@ async function addLog(message, level = 'info') {
chrome.runtime.sendMessage({ type: 'LOG_ENTRY', payload: entry }).catch(() => { });
}
+function getStep8CallbackUrlFromNavigation(details, signupTabId) {
+ if (!Number.isInteger(signupTabId) || !details) return '';
+ if (details.tabId !== signupTabId) return '';
+ if (details.frameId !== 0) return '';
+ return isLocalhostOAuthCallbackUrl(details.url) ? details.url : '';
+}
+
+function getStep8CallbackUrlFromTabUpdate(tabId, changeInfo, tab, signupTabId) {
+ if (!Number.isInteger(signupTabId) || tabId !== signupTabId) return '';
+
+ const candidates = [changeInfo?.url, tab?.url];
+ for (const candidate of candidates) {
+ if (isLocalhostOAuthCallbackUrl(candidate)) {
+ return candidate;
+ }
+ }
+
+ return '';
+}
+
function getSourceLabel(source) {
const labels = {
'sidepanel': '侧边栏',
@@ -1387,7 +1419,6 @@ async function handleMessage(message, sender) {
if (message.payload.sub2apiEmail !== undefined) updates.sub2apiEmail = message.payload.sub2apiEmail;
if (message.payload.sub2apiPassword !== undefined) updates.sub2apiPassword = message.payload.sub2apiPassword;
if (message.payload.sub2apiGroupName !== undefined) updates.sub2apiGroupName = message.payload.sub2apiGroupName;
- if (message.payload.sub2apiRedirectUri !== undefined) updates.sub2apiRedirectUri = message.payload.sub2apiRedirectUri;
if (message.payload.customPassword !== undefined) updates.customPassword = message.payload.customPassword;
if (message.payload.autoRunSkipFailures !== undefined) updates.autoRunSkipFailures = Boolean(message.payload.autoRunSkipFailures);
if (message.payload.mailProvider !== undefined) updates.mailProvider = message.payload.mailProvider;
@@ -1468,9 +1499,8 @@ async function handleStepData(step, payload) {
}
break;
case 9: {
- const localhostPrefix = buildLocalhostCleanupPrefix(payload.localhostUrl);
- if (localhostPrefix) {
- await closeTabsByUrlPrefix(localhostPrefix);
+ if (payload.localhostUrl) {
+ await closeLocalhostCallbackTabs(payload.localhostUrl);
}
break;
}
@@ -1549,10 +1579,8 @@ async function requestStop(options = {}) {
stopRequested = true;
cancelPendingCommands();
- if (webNavListener) {
- chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
- webNavListener = null;
- }
+ cleanupStep8NavigationListeners();
+ rejectPendingStep8(new Error(STOP_ERROR_MESSAGE));
await addLog(logMessage, 'warn');
await broadcastStopToContentScripts();
@@ -2123,7 +2151,6 @@ async function executeCpaStep1(state) {
async function executeSub2ApiStep1(state) {
const sub2apiUrl = normalizeSub2ApiUrl(state.sub2apiUrl);
- const sub2apiRedirectUri = normalizeSub2ApiRedirectUri(state.sub2apiRedirectUri);
const groupName = (state.sub2apiGroupName || DEFAULT_SUB2API_GROUP_NAME).trim() || DEFAULT_SUB2API_GROUP_NAME;
if (!state.sub2apiEmail) {
@@ -2169,7 +2196,6 @@ async function executeSub2ApiStep1(state) {
sub2apiEmail: state.sub2apiEmail,
sub2apiPassword: state.sub2apiPassword,
sub2apiGroupName: groupName,
- sub2apiRedirectUri,
},
}, {
timeoutMs: 40000,
@@ -2696,6 +2722,9 @@ async function executeStep7(state) {
// ============================================================
let webNavListener = null;
+let webNavCommittedListener = null;
+let step8TabUpdatedListener = null;
+let step8PendingReject = null;
const STEP8_CLICK_EFFECT_TIMEOUT_MS = 3500;
const STEP8_CLICK_RETRY_DELAY_MS = 500;
const STEP8_READY_WAIT_TIMEOUT_MS = 30000;
@@ -2707,6 +2736,34 @@ const STEP8_STRATEGIES = [
{ mode: 'debugger', label: 'debugger click retry' },
];
+function cleanupStep8NavigationListeners() {
+ if (webNavListener) {
+ chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
+ webNavListener = null;
+ }
+ if (webNavCommittedListener) {
+ chrome.webNavigation.onCommitted.removeListener(webNavCommittedListener);
+ webNavCommittedListener = null;
+ }
+ if (step8TabUpdatedListener) {
+ chrome.tabs.onUpdated.removeListener(step8TabUpdatedListener);
+ step8TabUpdatedListener = null;
+ }
+}
+
+function rejectPendingStep8(error) {
+ if (!step8PendingReject) return;
+ const reject = step8PendingReject;
+ step8PendingReject = null;
+ reject(error);
+}
+
+function throwIfStep8SettledOrStopped(isSettled = false) {
+ if (isSettled || stopRequested) {
+ throw new Error(STOP_ERROR_MESSAGE);
+ }
+}
+
async function getStep8PageState(tabId, responseTimeoutMs = 1500) {
try {
const result = await sendTabMessageWithTimeout(tabId, 'signup-page', {
@@ -2841,13 +2898,11 @@ async function executeStep8(state) {
let signupTabId = null;
const cleanupListener = () => {
- if (webNavListener) {
- chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
- webNavListener = null;
- }
+ cleanupStep8NavigationListeners();
+ step8PendingReject = null;
};
- const failStep8 = (error) => {
+ const rejectStep8 = (error) => {
if (resolved) return;
resolved = true;
clearTimeout(timeout);
@@ -2855,44 +2910,67 @@ async function executeStep8(state) {
reject(error);
};
+ const finalizeStep8Callback = (callbackUrl) => {
+ if (resolved || !callbackUrl) return;
+
+ resolved = true;
+ cleanupListener();
+ clearTimeout(timeout);
+
+ addLog(`步骤 8:已捕获 localhost 地址:${callbackUrl}`, 'ok').then(() => {
+ return completeStepFromBackground(8, { localhostUrl: callbackUrl });
+ }).then(() => {
+ resolve();
+ }).catch((err) => {
+ reject(err);
+ });
+ };
+
const timeout = setTimeout(() => {
- failStep8(new Error('120 秒内未捕获到 localhost 回调跳转,步骤 8 已持续重试点击“继续”但页面仍未完成授权。'));
+ rejectStep8(new Error('120 秒内未捕获到 localhost 回调跳转,步骤 8 的点击可能被拦截了。'));
}, 120000);
+ step8PendingReject = (error) => {
+ rejectStep8(error);
+ };
+
webNavListener = (details) => {
- if (resolved || !signupTabId) return;
- if (details.tabId !== signupTabId) return;
- if (details.frameId !== 0) return;
- if (isLocalhostOAuthCallbackUrl(details.url)) {
- console.log(LOG_PREFIX, `已捕获 localhost OAuth 回调:${details.url}`);
- resolved = true;
- cleanupListener();
- clearTimeout(timeout);
- addLog(`步骤 8:已捕获 localhost 地址:${details.url}`, 'ok').then(() => {
- return completeStepFromBackground(8, { localhostUrl: details.url });
- }).then(() => {
- resolve();
- }).catch((err) => {
- reject(err);
- });
- }
+ const callbackUrl = getStep8CallbackUrlFromNavigation(details, signupTabId);
+ finalizeStep8Callback(callbackUrl);
+ };
+
+ webNavCommittedListener = (details) => {
+ const callbackUrl = getStep8CallbackUrlFromNavigation(details, signupTabId);
+ finalizeStep8Callback(callbackUrl);
+ };
+
+ step8TabUpdatedListener = (tabId, changeInfo, tab) => {
+ const callbackUrl = getStep8CallbackUrlFromTabUpdate(tabId, changeInfo, tab, signupTabId);
+ finalizeStep8Callback(callbackUrl);
};
(async () => {
try {
+ throwIfStep8SettledOrStopped(resolved);
signupTabId = await getTabId('signup-page');
- if (signupTabId) {
+ throwIfStep8SettledOrStopped(resolved);
+
+ if (signupTabId && await isTabAlive('signup-page')) {
await chrome.tabs.update(signupTabId, { active: true });
- await addLog('步骤 8:已切回认证页,准备循环确认“继续”按钮直到页面真正跳转...');
+ await addLog('步骤 8:已切回认证页,正在准备调试器点击...');
} else {
signupTabId = await reuseOrCreateTab('signup-page', state.oauthUrl);
- await addLog('步骤 8:已重新打开认证页,准备循环确认“继续”按钮直到页面真正跳转...');
+ await addLog('步骤 8:已重新打开认证页,正在准备调试器点击...');
}
+ throwIfStep8SettledOrStopped(resolved);
chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
+ chrome.webNavigation.onCommitted.addListener(webNavCommittedListener);
+ chrome.tabs.onUpdated.addListener(step8TabUpdatedListener);
let attempt = 0;
while (!resolved) {
+ throwIfStep8SettledOrStopped(resolved);
const pageState = await waitForStep8Ready(signupTabId);
if (!pageState?.consentReady) {
await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
@@ -2907,9 +2985,8 @@ async function executeStep8(state) {
if (strategy.mode === 'debugger') {
const clickTarget = await prepareStep8DebuggerClick();
- if (!resolved) {
- await clickWithDebugger(signupTabId, clickTarget?.rect);
- }
+ throwIfStep8SettledOrStopped(resolved);
+ await clickWithDebugger(signupTabId, clickTarget?.rect);
} else {
await triggerStep8ContentStrategy(strategy.strategy);
}
@@ -2932,7 +3009,7 @@ async function executeStep8(state) {
await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
}
} catch (err) {
- failStep8(err);
+ rejectStep8(err);
}
})();
});
@@ -2960,6 +3037,15 @@ async function executeCpaStep9(state) {
throw new Error('尚未填写 CPA 地址,请先在侧边栏输入。');
}
+ if (shouldBypassStep9ForLocalCpa(state)) {
+ await addLog('步骤 9:检测到本地 CPA,步骤 8 完成后已自动添加,无需重复提交回调地址。', 'info');
+ await completeStepFromBackground(9, {
+ localhostUrl: state.localhostUrl,
+ verifiedStatus: 'local-auto',
+ });
+ return;
+ }
+
await addLog('步骤 9:正在打开 CPA 面板...');
const injectFiles = ['content/utils.js', 'content/vps-panel.js'];
diff --git a/content/sub2api-panel.js b/content/sub2api-panel.js
index 2196f7d..a38b082 100644
--- a/content/sub2api-panel.js
+++ b/content/sub2api-panel.js
@@ -42,8 +42,8 @@ function getSub2ApiOrigin(payload = {}) {
}
}
-function normalizeRedirectUri(rawUrl) {
- const input = (rawUrl || '').trim() || SUB2API_DEFAULT_REDIRECT_URI;
+function normalizeRedirectUri() {
+ const input = SUB2API_DEFAULT_REDIRECT_URI;
const withProtocol = /^https?:\/\//i.test(input) ? input : `http://${input}`;
const parsed = new URL(withProtocol);
if (!parsed.pathname || parsed.pathname === '/') {
@@ -288,7 +288,7 @@ function openAccountsPageSoon(origin) {
}
async function step1_generateOpenAiAuthUrl(payload = {}) {
- const redirectUri = normalizeRedirectUri(payload.sub2apiRedirectUri);
+ const redirectUri = normalizeRedirectUri();
const groupName = (payload.sub2apiGroupName || SUB2API_DEFAULT_GROUP_NAME).trim() || SUB2API_DEFAULT_GROUP_NAME;
const { origin, token } = await loginSub2Api(payload);
diff --git a/content/vps-panel.js b/content/vps-panel.js
index 0b7ca49..7f5a2e5 100644
--- a/content/vps-panel.js
+++ b/content/vps-panel.js
@@ -169,7 +169,7 @@ function isLocalhostOAuthCallbackUrl(rawUrl) {
if (!parsed) return false;
if (!['http:', 'https:'].includes(parsed.protocol)) return false;
if (!['localhost', '127.0.0.1'].includes(parsed.hostname)) return false;
- if (parsed.pathname !== '/auth/callback') return false;
+ if (!['/auth/callback', '/codex/callback'].includes(parsed.pathname)) return false;
const code = (parsed.searchParams.get('code') || '').trim();
const state = (parsed.searchParams.get('state') || '').trim();
diff --git a/sidepanel/sidepanel.html b/sidepanel/sidepanel.html
index cf196e6..d127f0f 100644
--- a/sidepanel/sidepanel.html
+++ b/sidepanel/sidepanel.html
@@ -78,10 +78,6 @@
分组
-
- 回调
-
-
邮箱服务