修复设置自动保存与标签清理边界

This commit is contained in:
QLHazyCoder
2026-05-20 05:15:56 +08:00
119 changed files with 24116 additions and 3966 deletions
+276
View File
@@ -0,0 +1,276 @@
(function attachBackgroundCpaSessionImport(root, factory) {
root.MultiPageBackgroundCpaSessionImport = factory();
})(typeof self !== 'undefined' ? self : globalThis, function createBackgroundCpaSessionImportModule() {
const PLUS_CHECKOUT_SOURCE = 'plus-checkout';
const PLUS_CHECKOUT_INJECT_FILES = ['content/utils.js', 'content/operation-delay.js', 'content/plus-checkout.js'];
function createCpaSessionImportExecutor(deps = {}) {
const {
addLog: rawAddLog = async () => {},
chrome,
completeNodeFromBackground,
ensureContentScriptReadyOnTabUntilStopped,
getTabId,
isTabAlive,
registerTab,
sendTabMessageUntilStopped,
sleepWithStop = async () => {},
throwIfStopped = () => {},
waitForTabCompleteUntilStopped = async () => {},
} = deps;
let cpaApi = null;
function addStepLog(step, message, level = 'info') {
return rawAddLog(message, level, {
step,
stepKey: 'cpa-session-import',
});
}
function getCpaApi() {
if (cpaApi) {
return cpaApi;
}
const factory = deps.createCpaApi
|| self.MultiPageBackgroundCpaApi?.createCpaApi;
if (typeof factory !== 'function') {
throw new Error('CPA 接口模块未加载,无法导入当前 ChatGPT 会话。');
}
cpaApi = factory({
addLog: rawAddLog,
});
return cpaApi;
}
function normalizeString(value = '') {
return String(value || '').trim();
}
function resolveVisibleStep(state = {}) {
const visibleStep = Math.floor(Number(state?.visibleStep) || 0);
return visibleStep > 0 ? visibleStep : 10;
}
function isSupportedChatGptSessionUrl(url = '') {
try {
const parsed = new URL(String(url || ''));
if (!/^https?:$/i.test(parsed.protocol)) {
return false;
}
const hostname = String(parsed.hostname || '').trim().toLowerCase();
return /(^|\.)chatgpt\.com$/.test(hostname)
|| hostname === 'chat.openai.com'
|| /(^|\.)openai\.com$/.test(hostname);
} catch {
return false;
}
}
function getSessionTabHostPriority(url = '') {
try {
const hostname = String(new URL(String(url || '')).hostname || '').trim().toLowerCase();
if (/(^|\.)chatgpt\.com$/.test(hostname)) {
return 0;
}
if (hostname === 'chat.openai.com') {
return 1;
}
if (/(^|\.)openai\.com$/.test(hostname)) {
return 2;
}
} catch {
return Number.POSITIVE_INFINITY;
}
return Number.POSITIVE_INFINITY;
}
function getSessionTabActivityPriority(tab = {}) {
if (tab?.active && tab?.currentWindow) {
return 0;
}
if (tab?.active) {
return 1;
}
return 2;
}
function pickPreferredSessionTab(tabs = []) {
const candidates = (Array.isArray(tabs) ? tabs : [])
.filter((tab) => Number.isInteger(tab?.id) && isSupportedChatGptSessionUrl(tab.url));
if (!candidates.length) {
return null;
}
return candidates.reduce((best, candidate) => {
if (!best) {
return candidate;
}
const candidateHostPriority = getSessionTabHostPriority(candidate.url);
const bestHostPriority = getSessionTabHostPriority(best.url);
if (candidateHostPriority !== bestHostPriority) {
return candidateHostPriority < bestHostPriority ? candidate : best;
}
const candidateActivityPriority = getSessionTabActivityPriority(candidate);
const bestActivityPriority = getSessionTabActivityPriority(best);
if (candidateActivityPriority !== bestActivityPriority) {
return candidateActivityPriority < bestActivityPriority ? candidate : best;
}
const candidateLastAccessed = Number(candidate?.lastAccessed) || 0;
const bestLastAccessed = Number(best?.lastAccessed) || 0;
if (candidateLastAccessed !== bestLastAccessed) {
return candidateLastAccessed > bestLastAccessed ? candidate : best;
}
return Number(candidate.id) < Number(best.id) ? candidate : best;
}, null);
}
async function readSupportedSessionTab(tabId) {
const numericTabId = Number(tabId) || 0;
if (!numericTabId || !chrome?.tabs?.get) {
return null;
}
const tab = await chrome.tabs.get(numericTabId).catch(() => null);
return tab?.id && isSupportedChatGptSessionUrl(tab.url)
? tab
: null;
}
async function findFallbackSessionTab() {
if (!chrome?.tabs?.query) {
return null;
}
const activeTabs = await chrome.tabs.query({ active: true, currentWindow: true }).catch(() => []);
const activeMatch = pickPreferredSessionTab(activeTabs);
const allTabs = await chrome.tabs.query({}).catch(() => []);
const globalMatch = pickPreferredSessionTab(allTabs);
return pickPreferredSessionTab([activeMatch, globalMatch]);
}
async function resolveSessionTabId(state = {}) {
const registeredTabId = typeof getTabId === 'function'
? await getTabId(PLUS_CHECKOUT_SOURCE)
: null;
if (registeredTabId && typeof isTabAlive === 'function' && await isTabAlive(PLUS_CHECKOUT_SOURCE)) {
const registeredTab = await readSupportedSessionTab(registeredTabId);
if (registeredTab?.id) {
return registeredTab.id;
}
}
const storedTabId = Number(state?.plusCheckoutTabId) || 0;
const storedTab = await readSupportedSessionTab(storedTabId);
if (storedTab?.id) {
if (typeof registerTab === 'function') {
await registerTab(PLUS_CHECKOUT_SOURCE, storedTab.id);
}
return storedTab.id;
}
const fallbackTab = await findFallbackSessionTab();
if (fallbackTab?.id) {
if (typeof registerTab === 'function') {
await registerTab(PLUS_CHECKOUT_SOURCE, fallbackTab.id);
}
return fallbackTab.id;
}
throw new Error('未找到可读取 ChatGPT 会话的标签页,请先打开一个已登录的 ChatGPT / OpenAI 页面,或完成当前 Plus 支付链路。');
}
async function getResolvedSessionTab(tabId, visibleStep) {
const tab = await chrome?.tabs?.get?.(tabId).catch(() => null);
if (!tab?.id) {
throw new Error(`步骤 ${visibleStep}:ChatGPT 会话标签页不存在或已关闭,无法继续导入 CPA。`);
}
if (!isSupportedChatGptSessionUrl(tab.url)) {
throw new Error(`步骤 ${visibleStep}:当前标签页不在 ChatGPT / OpenAI 页面,无法读取当前登录会话。`);
}
return tab;
}
async function readCurrentChatGptSession(tabId, visibleStep) {
await waitForTabCompleteUntilStopped(tabId);
await sleepWithStop(1000);
await ensureContentScriptReadyOnTabUntilStopped(PLUS_CHECKOUT_SOURCE, tabId, {
inject: PLUS_CHECKOUT_INJECT_FILES,
injectSource: PLUS_CHECKOUT_SOURCE,
logMessage: `步骤 ${visibleStep}:正在等待 ChatGPT 会话页完成加载,再继续读取当前登录会话...`,
});
const sessionResult = await sendTabMessageUntilStopped(tabId, PLUS_CHECKOUT_SOURCE, {
type: 'PLUS_CHECKOUT_GET_STATE',
source: 'background',
payload: {
includeSession: true,
includeAccessToken: true,
},
});
if (sessionResult?.error) {
throw new Error(sessionResult.error);
}
const session = sessionResult?.session && typeof sessionResult.session === 'object' && !Array.isArray(sessionResult.session)
? sessionResult.session
: null;
const accessToken = normalizeString(
sessionResult?.accessToken
|| session?.accessToken
);
if (!session && !accessToken) {
throw new Error(`步骤 ${visibleStep}:未读取到有效的 ChatGPT 会话或 accessToken,请确认当前标签页仍处于已登录状态。`);
}
return {
session,
accessToken,
};
}
async function executeCpaSessionImport(state = {}) {
throwIfStopped();
const visibleStep = resolveVisibleStep(state);
const api = getCpaApi();
await addStepLog(visibleStep, '正在定位当前 ChatGPT 会话页并准备导入 CPA...', 'info');
const tabId = await resolveSessionTabId(state);
const tab = await getResolvedSessionTab(tabId, visibleStep);
if (chrome?.tabs?.update) {
await chrome.tabs.update(tab.id, { active: true }).catch(() => {});
}
await addStepLog(visibleStep, '正在读取当前 ChatGPT 登录会话...', 'info');
const sessionState = await readCurrentChatGptSession(tab.id, visibleStep);
throwIfStopped();
const result = await api.importCurrentChatGptSession({
...state,
session: sessionState.session,
accessToken: sessionState.accessToken,
}, {
visibleStep,
logLabel: `步骤 ${visibleStep}`,
logOptions: { step: visibleStep, stepKey: 'cpa-session-import' },
timeoutMs: 120000,
importTimeoutMs: 120000,
});
await completeNodeFromBackground(state?.nodeId || 'cpa-session-import', result);
}
return {
executeCpaSessionImport,
isSupportedChatGptSessionUrl,
};
}
return {
createCpaSessionImportExecutor,
};
});
+4 -1
View File
@@ -212,7 +212,10 @@
{
type: 'SUBMIT_ADD_EMAIL',
source: 'background',
payload: { email: resolvedEmail },
payload: {
email: resolvedEmail,
nodeId: state?.nodeId || activeFetchLoginCodeStepKey || 'fetch-login-code',
},
},
{
timeoutMs,
+64 -5
View File
@@ -2,8 +2,61 @@
root.MultiPageBackgroundGoPayManualConfirm = factory();
})(typeof self !== 'undefined' ? self : globalThis, function createBackgroundGoPayManualConfirmModule() {
const PLUS_CHECKOUT_SOURCE = 'plus-checkout';
const GOPAY_CONFIRM_NODE_ID = 'gopay-subscription-confirm';
const SUB2API_SESSION_IMPORT_NODE_ID = 'sub2api-session-import';
const CPA_SESSION_IMPORT_NODE_ID = 'cpa-session-import';
const DEFAULT_CONFIRM_TITLE = 'GoPay 订阅确认';
const DEFAULT_CONFIRM_MESSAGE = 'GoPay 订阅页已打开。请先手动完成订阅,完成后确认继续 OAuth 登录';
const OAUTH_CONTINUATION_LABEL = 'OAuth 登录';
const SUB2API_SESSION_CONTINUATION_LABEL = '导入当前 ChatGPT 会话到 SUB2API';
const CPA_SESSION_CONTINUATION_LABEL = '导入当前 ChatGPT 会话到 CPA';
function normalizeString(value = '') {
return String(value || '').trim();
}
function getContinuationActionLabelForNodeId(nodeId = '') {
const normalizedNodeId = normalizeString(nodeId);
if (normalizedNodeId === SUB2API_SESSION_IMPORT_NODE_ID) {
return SUB2API_SESSION_CONTINUATION_LABEL;
}
if (normalizedNodeId === CPA_SESSION_IMPORT_NODE_ID) {
return CPA_SESSION_CONTINUATION_LABEL;
}
return OAUTH_CONTINUATION_LABEL;
}
function getContinuationActionLabel(state = {}, options = {}) {
const { getNodeIdsForState = null } = options;
if (typeof getNodeIdsForState === 'function') {
const nodeIds = getNodeIdsForState(state)
.map((nodeId) => normalizeString(nodeId))
.filter(Boolean);
const currentNodeId = normalizeString(state?.nodeId || GOPAY_CONFIRM_NODE_ID) || GOPAY_CONFIRM_NODE_ID;
const currentNodeIndex = nodeIds.indexOf(currentNodeId);
const nextNodeId = currentNodeIndex >= 0
? normalizeString(nodeIds[currentNodeIndex + 1])
: '';
if (nextNodeId) {
return getContinuationActionLabelForNodeId(nextNodeId);
}
if (currentNodeIndex < 0) {
if (nodeIds.includes(SUB2API_SESSION_IMPORT_NODE_ID)) {
return SUB2API_SESSION_CONTINUATION_LABEL;
}
if (nodeIds.includes(CPA_SESSION_IMPORT_NODE_ID)) {
return CPA_SESSION_CONTINUATION_LABEL;
}
}
}
return OAUTH_CONTINUATION_LABEL;
}
function buildDefaultConfirmMessage(state = {}, options = {}) {
const continuationActionLabel = getContinuationActionLabel(state, options);
return `GoPay 订阅页已打开。请先手动完成订阅,完成后确认继续${continuationActionLabel}`;
}
function createGoPayManualConfirmExecutor(deps = {}) {
const {
@@ -12,6 +65,7 @@
chrome,
createAutomationTab = null,
getTabId,
getNodeIdsForState = null,
isTabAlive,
registerTab,
setState,
@@ -40,7 +94,7 @@
}
}
const checkoutUrl = String(state?.plusCheckoutUrl || '').trim();
const checkoutUrl = normalizeString(state?.plusCheckoutUrl);
if (!checkoutUrl) {
throw new Error('步骤 7:未检测到 GoPay 订阅页,请先执行步骤 6。');
}
@@ -63,19 +117,21 @@
}
async function executeGoPayManualConfirm(state = {}) {
const visibleStep = Number(state?.visibleStep) || 7;
const tabId = await resolveCheckoutTabId(state);
if (chrome?.tabs?.update && tabId) {
await chrome.tabs.update(tabId, { active: true }).catch(() => {});
}
const continuationActionLabel = getContinuationActionLabel(state, { getNodeIdsForState });
const payload = {
plusCheckoutTabId: tabId,
plusManualConfirmationPending: true,
plusManualConfirmationRequestId: buildRequestId(),
plusManualConfirmationStep: 7,
plusManualConfirmationStep: visibleStep,
plusManualConfirmationMethod: 'gopay',
plusManualConfirmationTitle: DEFAULT_CONFIRM_TITLE,
plusManualConfirmationMessage: DEFAULT_CONFIRM_MESSAGE,
plusManualConfirmationMessage: buildDefaultConfirmMessage(state, { getNodeIdsForState }),
};
await setState(payload);
@@ -83,7 +139,10 @@
broadcastDataUpdate(payload);
}
await addLog('步骤 7:正在等待手动完成 GoPay 订阅,确认后继续 OAuth 登录。', 'info');
await addLog(
`步骤 ${visibleStep}:正在等待手动完成 GoPay 订阅,确认后继续${continuationActionLabel}`,
'info'
);
}
return {
+2 -2
View File
@@ -59,7 +59,7 @@
return normalizeStep7SignupMethod(state?.signupMethod) === 'phone'
&& Boolean(state?.phoneVerificationEnabled)
&& !Boolean(state?.plusModeEnabled)
&& !Boolean(state?.contributionMode);
&& !Boolean(state?.accountContributionEnabled);
}
function hasStep7PhoneSignupIdentity(state = {}) {
@@ -307,7 +307,7 @@
'signup-page',
{
type: 'EXECUTE_NODE',
nodeId: 'oauth-login',
nodeId: state?.nodeId || 'oauth-login',
step: 7,
source: 'background',
payload: {
+36 -15
View File
@@ -10,6 +10,7 @@
ensureContentScriptReadyOnTab,
getPanelMode,
getTabId,
getStepIdByKeyForState,
isLocalhostOAuthCallbackUrl,
isTabAlive,
normalizeCodex2ApiUrl,
@@ -51,11 +52,31 @@
return visibleStep >= 10 ? visibleStep : 10;
}
function resolveConfirmOauthStep(platformVerifyStep = 10) {
return Number(platformVerifyStep) >= 13 ? 12 : 9;
function resolveStepIdByKey(state = {}, stepKey = '') {
if (typeof getStepIdByKeyForState !== 'function') {
return null;
}
const step = Number(getStepIdByKeyForState(stepKey, state));
return Number.isInteger(step) && step > 0 ? step : null;
}
function resolveAuthLoginStep(platformVerifyStep = 10) {
function resolveConfirmOauthStep(platformVerifyStep = 10, state = {}) {
const dynamicStep = resolveStepIdByKey(state, 'confirm-oauth');
if (dynamicStep && dynamicStep < Number(platformVerifyStep)) {
return dynamicStep;
}
return Math.max(1, Number(platformVerifyStep) - 1);
}
function resolveAuthLoginStep(platformVerifyStep = 10, state = {}) {
const reloginStep = resolveStepIdByKey(state, 'relogin-bound-email');
if (reloginStep && reloginStep < Number(platformVerifyStep)) {
return reloginStep;
}
const oauthLoginStep = resolveStepIdByKey(state, 'oauth-login');
if (oauthLoginStep && oauthLoginStep < Number(platformVerifyStep)) {
return oauthLoginStep;
}
return Number(platformVerifyStep) >= 13 ? 10 : 7;
}
@@ -63,8 +84,8 @@
return addLog(message, level, { step, stepKey: 'platform-verify' });
}
function parseLocalhostCallback(rawUrl, platformVerifyStep = 10) {
const confirmOauthStep = resolveConfirmOauthStep(platformVerifyStep);
function parseLocalhostCallback(rawUrl, platformVerifyStep = 10, state = {}) {
const confirmOauthStep = resolveConfirmOauthStep(platformVerifyStep, state);
let parsed;
try {
parsed = new URL(rawUrl);
@@ -73,15 +94,15 @@
}
const code = normalizeString(parsed.searchParams.get('code'));
const state = normalizeString(parsed.searchParams.get('state'));
if (!code || !state) {
const oauthState = normalizeString(parsed.searchParams.get('state'));
if (!code || !oauthState) {
throw new Error(`步骤 ${platformVerifyStep} 捕获到的 localhost OAuth 回调地址缺少 code 或 state,请重新执行步骤 ${confirmOauthStep}`);
}
return {
url: parsed.toString(),
code,
state,
state: oauthState,
};
}
@@ -239,8 +260,8 @@
async function executeCpaStep10(state) {
const platformVerifyStep = resolvePlatformVerifyStep(state);
const confirmOauthStep = resolveConfirmOauthStep(platformVerifyStep);
const authLoginStep = resolveAuthLoginStep(platformVerifyStep);
const confirmOauthStep = resolveConfirmOauthStep(platformVerifyStep, state);
const authLoginStep = resolveAuthLoginStep(platformVerifyStep, state);
if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) {
throw new Error(`步骤 ${confirmOauthStep} 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 ${confirmOauthStep}`);
}
@@ -260,7 +281,7 @@
return;
}
const callback = parseLocalhostCallback(state.localhostUrl, platformVerifyStep);
const callback = parseLocalhostCallback(state.localhostUrl, platformVerifyStep, state);
const expectedState = normalizeString(state.cpaOAuthState);
if (expectedState && expectedState !== callback.state) {
throw new Error(`CPA 回调 state 与当前授权会话不匹配,请重新执行步骤 ${authLoginStep}`);
@@ -299,8 +320,8 @@
async function executeCodex2ApiStep10(state) {
const platformVerifyStep = resolvePlatformVerifyStep(state);
const confirmOauthStep = resolveConfirmOauthStep(platformVerifyStep);
const authLoginStep = resolveAuthLoginStep(platformVerifyStep);
const confirmOauthStep = resolveConfirmOauthStep(platformVerifyStep, state);
const authLoginStep = resolveAuthLoginStep(platformVerifyStep, state);
if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) {
throw new Error(`步骤 ${confirmOauthStep} 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 ${confirmOauthStep}`);
}
@@ -314,7 +335,7 @@
throw new Error('尚未配置 Codex2API 管理密钥,请先在侧边栏填写。');
}
const callback = parseLocalhostCallback(state.localhostUrl, platformVerifyStep);
const callback = parseLocalhostCallback(state.localhostUrl, platformVerifyStep, state);
const expectedState = normalizeString(state.codex2apiOAuthState);
if (expectedState && expectedState !== callback.state) {
throw new Error(`Codex2API 回调 state 与当前授权会话不匹配,请重新执行步骤 ${authLoginStep}`);
@@ -345,7 +366,7 @@
async function executeSub2ApiStep10(state) {
const platformVerifyStep = resolvePlatformVerifyStep(state);
const visibleStep = platformVerifyStep;
const confirmOauthStep = resolveConfirmOauthStep(visibleStep);
const confirmOauthStep = resolveConfirmOauthStep(visibleStep, state);
if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) {
throw new Error(`步骤 ${confirmOauthStep} 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 ${confirmOauthStep}`);
}
+7 -3
View File
@@ -4,13 +4,14 @@
function createNodeRegistry(definitions = []) {
const ordered = (Array.isArray(definitions) ? definitions : [])
.map((definition) => ({
flowId: String(definition?.flowId || '').trim(),
nodeId: String(definition?.nodeId || definition?.key || '').trim(),
displayOrder: Number(definition?.displayOrder ?? definition?.order),
displayOrder: Number(definition?.displayOrder ?? definition?.order ?? definition?.id),
executeKey: String(definition?.executeKey || definition?.key || definition?.nodeId || '').trim(),
title: String(definition?.title || '').trim(),
execute: definition?.execute,
}))
.filter((definition) => definition.nodeId && typeof definition.execute === 'function')
.filter((definition) => definition.nodeId)
.sort((left, right) => {
const leftOrder = Number.isFinite(left.displayOrder) ? left.displayOrder : 0;
const rightOrder = Number.isFinite(right.displayOrder) ? right.displayOrder : 0;
@@ -31,7 +32,10 @@
function executeNode(nodeId, state) {
const definition = getNodeDefinition(nodeId);
if (!definition) {
throw new Error(`未知节点:${nodeId}`);
throw new Error(`Unknown node: ${nodeId}`);
}
if (typeof definition.execute !== 'function') {
throw new Error(`Missing node executor: ${definition.executeKey || definition.nodeId}`);
}
return definition.execute(state);
}
+280
View File
@@ -0,0 +1,280 @@
(function attachBackgroundSub2ApiSessionImport(root, factory) {
root.MultiPageBackgroundSub2ApiSessionImport = factory();
})(typeof self !== 'undefined' ? self : globalThis, function createBackgroundSub2ApiSessionImportModule() {
const PLUS_CHECKOUT_SOURCE = 'plus-checkout';
const PLUS_CHECKOUT_INJECT_FILES = ['content/utils.js', 'content/operation-delay.js', 'content/plus-checkout.js'];
function createSub2ApiSessionImportExecutor(deps = {}) {
const {
addLog: rawAddLog = async () => {},
chrome,
completeNodeFromBackground,
ensureContentScriptReadyOnTabUntilStopped,
getTabId,
isTabAlive,
normalizeSub2ApiUrl = (value) => value,
registerTab,
sendTabMessageUntilStopped,
sleepWithStop = async () => {},
throwIfStopped = () => {},
waitForTabCompleteUntilStopped = async () => {},
DEFAULT_SUB2API_GROUP_NAME = 'codex',
} = deps;
let sub2ApiApi = null;
function addStepLog(step, message, level = 'info') {
return rawAddLog(message, level, {
step,
stepKey: 'sub2api-session-import',
});
}
function getSub2ApiApi() {
if (sub2ApiApi) {
return sub2ApiApi;
}
const factory = deps.createSub2ApiApi
|| self.MultiPageBackgroundSub2ApiApi?.createSub2ApiApi;
if (typeof factory !== 'function') {
throw new Error('SUB2API 接口模块未加载,无法导入当前 ChatGPT 会话。');
}
sub2ApiApi = factory({
addLog: rawAddLog,
normalizeSub2ApiUrl,
DEFAULT_SUB2API_GROUP_NAME,
});
return sub2ApiApi;
}
function normalizeString(value = '') {
return String(value || '').trim();
}
function resolveVisibleStep(state = {}) {
const visibleStep = Math.floor(Number(state?.visibleStep) || 0);
return visibleStep > 0 ? visibleStep : 10;
}
function isSupportedChatGptSessionUrl(url = '') {
try {
const parsed = new URL(String(url || ''));
if (!/^https?:$/i.test(parsed.protocol)) {
return false;
}
const hostname = String(parsed.hostname || '').trim().toLowerCase();
return /(^|\.)chatgpt\.com$/.test(hostname)
|| hostname === 'chat.openai.com'
|| /(^|\.)openai\.com$/.test(hostname);
} catch {
return false;
}
}
function getSessionTabHostPriority(url = '') {
try {
const hostname = String(new URL(String(url || '')).hostname || '').trim().toLowerCase();
if (/(^|\.)chatgpt\.com$/.test(hostname)) {
return 0;
}
if (hostname === 'chat.openai.com') {
return 1;
}
if (/(^|\.)openai\.com$/.test(hostname)) {
return 2;
}
} catch {
return Number.POSITIVE_INFINITY;
}
return Number.POSITIVE_INFINITY;
}
function getSessionTabActivityPriority(tab = {}) {
if (tab?.active && tab?.currentWindow) {
return 0;
}
if (tab?.active) {
return 1;
}
return 2;
}
function pickPreferredSessionTab(tabs = []) {
const candidates = (Array.isArray(tabs) ? tabs : [])
.filter((tab) => Number.isInteger(tab?.id) && isSupportedChatGptSessionUrl(tab.url));
if (!candidates.length) {
return null;
}
return candidates.reduce((best, candidate) => {
if (!best) {
return candidate;
}
const candidateHostPriority = getSessionTabHostPriority(candidate.url);
const bestHostPriority = getSessionTabHostPriority(best.url);
if (candidateHostPriority !== bestHostPriority) {
return candidateHostPriority < bestHostPriority ? candidate : best;
}
const candidateActivityPriority = getSessionTabActivityPriority(candidate);
const bestActivityPriority = getSessionTabActivityPriority(best);
if (candidateActivityPriority !== bestActivityPriority) {
return candidateActivityPriority < bestActivityPriority ? candidate : best;
}
const candidateLastAccessed = Number(candidate?.lastAccessed) || 0;
const bestLastAccessed = Number(best?.lastAccessed) || 0;
if (candidateLastAccessed !== bestLastAccessed) {
return candidateLastAccessed > bestLastAccessed ? candidate : best;
}
return Number(candidate.id) < Number(best.id) ? candidate : best;
}, null);
}
async function readSupportedSessionTab(tabId) {
const numericTabId = Number(tabId) || 0;
if (!numericTabId || !chrome?.tabs?.get) {
return null;
}
const tab = await chrome.tabs.get(numericTabId).catch(() => null);
return tab?.id && isSupportedChatGptSessionUrl(tab.url)
? tab
: null;
}
async function findFallbackSessionTab() {
if (!chrome?.tabs?.query) {
return null;
}
const activeTabs = await chrome.tabs.query({ active: true, currentWindow: true }).catch(() => []);
const activeMatch = pickPreferredSessionTab(activeTabs);
const allTabs = await chrome.tabs.query({}).catch(() => []);
const globalMatch = pickPreferredSessionTab(allTabs);
return pickPreferredSessionTab([activeMatch, globalMatch]);
}
async function resolveSessionTabId(state = {}) {
const registeredTabId = typeof getTabId === 'function'
? await getTabId(PLUS_CHECKOUT_SOURCE)
: null;
if (registeredTabId && typeof isTabAlive === 'function' && await isTabAlive(PLUS_CHECKOUT_SOURCE)) {
const registeredTab = await readSupportedSessionTab(registeredTabId);
if (registeredTab?.id) {
return registeredTab.id;
}
}
const storedTabId = Number(state?.plusCheckoutTabId) || 0;
const storedTab = await readSupportedSessionTab(storedTabId);
if (storedTab?.id) {
if (typeof registerTab === 'function') {
await registerTab(PLUS_CHECKOUT_SOURCE, storedTab.id);
}
return storedTab.id;
}
const fallbackTab = await findFallbackSessionTab();
if (fallbackTab?.id) {
if (typeof registerTab === 'function') {
await registerTab(PLUS_CHECKOUT_SOURCE, fallbackTab.id);
}
return fallbackTab.id;
}
throw new Error('未找到可读取 ChatGPT 会话的标签页,请先打开一个已登录的 ChatGPT / OpenAI 页面,或完成当前 Plus 支付链路。');
}
async function getResolvedSessionTab(tabId, visibleStep) {
const tab = await chrome?.tabs?.get?.(tabId).catch(() => null);
if (!tab?.id) {
throw new Error(`步骤 ${visibleStep}:ChatGPT 会话标签页不存在或已关闭,无法继续导入 SUB2API。`);
}
if (!isSupportedChatGptSessionUrl(tab.url)) {
throw new Error(`步骤 ${visibleStep}:当前标签页不在 ChatGPT / OpenAI 页面,无法读取当前登录会话。`);
}
return tab;
}
async function readCurrentChatGptSession(tabId, visibleStep) {
await waitForTabCompleteUntilStopped(tabId);
await sleepWithStop(1000);
await ensureContentScriptReadyOnTabUntilStopped(PLUS_CHECKOUT_SOURCE, tabId, {
inject: PLUS_CHECKOUT_INJECT_FILES,
injectSource: PLUS_CHECKOUT_SOURCE,
logMessage: `步骤 ${visibleStep}:正在等待 ChatGPT 会话页完成加载,再继续读取当前登录会话...`,
});
const sessionResult = await sendTabMessageUntilStopped(tabId, PLUS_CHECKOUT_SOURCE, {
type: 'PLUS_CHECKOUT_GET_STATE',
source: 'background',
payload: {
includeSession: true,
includeAccessToken: true,
},
});
if (sessionResult?.error) {
throw new Error(sessionResult.error);
}
const session = sessionResult?.session && typeof sessionResult.session === 'object' && !Array.isArray(sessionResult.session)
? sessionResult.session
: null;
const accessToken = normalizeString(
sessionResult?.accessToken
|| session?.accessToken
);
if (!session && !accessToken) {
throw new Error(`步骤 ${visibleStep}:未读取到有效的 ChatGPT 会话或 accessToken,请确认当前标签页仍处于已登录状态。`);
}
return {
session,
accessToken,
};
}
async function executeSub2ApiSessionImport(state = {}) {
throwIfStopped();
const visibleStep = resolveVisibleStep(state);
const api = getSub2ApiApi();
await addStepLog(visibleStep, '正在定位当前 ChatGPT 会话页并准备导入 SUB2API...', 'info');
const tabId = await resolveSessionTabId(state);
const tab = await getResolvedSessionTab(tabId, visibleStep);
if (chrome?.tabs?.update) {
await chrome.tabs.update(tab.id, { active: true }).catch(() => {});
}
await addStepLog(visibleStep, '正在读取当前 ChatGPT 登录会话...', 'info');
const sessionState = await readCurrentChatGptSession(tab.id, visibleStep);
throwIfStopped();
const result = await api.importCurrentChatGptSession({
...state,
session: sessionState.session,
accessToken: sessionState.accessToken,
}, {
visibleStep,
logLabel: `步骤 ${visibleStep}`,
logOptions: { step: visibleStep, stepKey: 'sub2api-session-import' },
timeoutMs: 120000,
importTimeoutMs: 120000,
});
await completeNodeFromBackground(state?.nodeId || 'sub2api-session-import', result);
}
return {
executeSub2ApiSessionImport,
isSupportedChatGptSessionUrl,
};
}
return {
createSub2ApiSessionImportExecutor,
};
});