import GuJumpgate snapshot from GitHub

This commit is contained in:
2026-05-20 20:33:51 +08:00
commit f8903dcd14
335 changed files with 179790 additions and 0 deletions
+452
View File
@@ -0,0 +1,452 @@
(function attachMultiPageFlowCapabilities(root, factory) {
root.MultiPageFlowCapabilities = factory();
})(typeof self !== 'undefined' ? self : globalThis, function createFlowCapabilitiesModule() {
const DEFAULT_FLOW_ID = 'openai';
const DEFAULT_PANEL_MODE = 'local-cpa-json';
const LOCAL_CPA_JSON_NO_RT_PANEL_MODE = 'local-cpa-json-no-rt';
const SIGNUP_METHOD_EMAIL = 'email';
const SIGNUP_METHOD_PHONE = 'phone';
const VALID_PANEL_MODES = Object.freeze(['local-cpa-json', LOCAL_CPA_JSON_NO_RT_PANEL_MODE, 'cpa', 'sub2api', 'codex2api']);
const DEFAULT_FLOW_CAPABILITIES = Object.freeze({
supportsEmailSignup: true,
supportsPhoneSignup: false,
supportsPhoneVerificationSettings: false,
supportsPlusMode: false,
supportsContributionMode: false,
supportsPlatformBinding: [],
supportsLuckmail: false,
supportsOauthTimeoutBudget: false,
canSwitchFlow: false,
stepDefinitionMode: 'default',
});
const FLOW_CAPABILITIES = Object.freeze({
openai: Object.freeze({
...DEFAULT_FLOW_CAPABILITIES,
supportsPhoneSignup: true,
supportsPhoneVerificationSettings: true,
supportsPlusMode: true,
supportsContributionMode: true,
supportsPlatformBinding: ['local-cpa-json', LOCAL_CPA_JSON_NO_RT_PANEL_MODE, 'cpa', 'sub2api', 'codex2api'],
supportsLuckmail: true,
supportsOauthTimeoutBudget: true,
stepDefinitionMode: 'openai-dynamic',
}),
});
const DEFAULT_PANEL_CAPABILITIES = Object.freeze({
supportsPhoneSignup: true,
requiresPhoneSignupWarning: false,
});
const MODE_SWITCH_RELEVANT_KEYS = Object.freeze([
'activeFlowId',
'contributionMode',
'panelMode',
'phoneVerificationEnabled',
'plusModeEnabled',
'signupMethod',
]);
const PANEL_CAPABILITIES = Object.freeze({
cpa: Object.freeze({
supportsPhoneSignup: true,
requiresPhoneSignupWarning: true,
}),
'local-cpa-json': Object.freeze({
supportsPhoneSignup: true,
requiresPhoneSignupWarning: false,
}),
[LOCAL_CPA_JSON_NO_RT_PANEL_MODE]: Object.freeze({
supportsPhoneSignup: true,
requiresPhoneSignupWarning: false,
}),
sub2api: Object.freeze({
supportsPhoneSignup: true,
requiresPhoneSignupWarning: false,
}),
codex2api: Object.freeze({
supportsPhoneSignup: true,
requiresPhoneSignupWarning: false,
}),
});
function normalizeFlowId(value = '', fallback = DEFAULT_FLOW_ID) {
const normalized = String(value || '').trim().toLowerCase();
if (normalized) {
return normalized;
}
const fallbackValue = String(fallback || '').trim().toLowerCase();
return fallbackValue || DEFAULT_FLOW_ID;
}
function normalizePanelMode(value = '', fallback = DEFAULT_PANEL_MODE) {
const normalized = String(value || '').trim().toLowerCase();
if (VALID_PANEL_MODES.includes(normalized)) {
return normalized;
}
const fallbackValue = String(fallback || '').trim().toLowerCase();
return VALID_PANEL_MODES.includes(fallbackValue) ? fallbackValue : DEFAULT_PANEL_MODE;
}
function normalizeSignupMethod(value = '') {
return String(value || '').trim().toLowerCase() === SIGNUP_METHOD_PHONE
? SIGNUP_METHOD_PHONE
: SIGNUP_METHOD_EMAIL;
}
function normalizePanelModeList(values = []) {
if (!Array.isArray(values)) {
return [];
}
const seen = new Set();
const normalized = [];
values.forEach((value) => {
const mode = normalizePanelMode(value, '');
if (!mode || seen.has(mode)) {
return;
}
seen.add(mode);
normalized.push(mode);
});
return normalized;
}
function getPanelModeLabel(panelMode = '') {
const normalized = normalizePanelMode(panelMode);
if (normalized === 'local-cpa-json') {
return '本地CPA JSON 有RT';
}
if (normalized === LOCAL_CPA_JSON_NO_RT_PANEL_MODE) {
return '本地CPA JSON 无RT';
}
if (normalized === 'sub2api') {
return 'SUB2API';
}
if (normalized === 'codex2api') {
return 'Codex2API';
}
return 'CPA';
}
function createFlowCapabilityRegistry(deps = {}) {
const {
defaultFlowCapabilities = DEFAULT_FLOW_CAPABILITIES,
defaultFlowId = DEFAULT_FLOW_ID,
defaultPanelCapabilities = DEFAULT_PANEL_CAPABILITIES,
flowCapabilities = FLOW_CAPABILITIES,
panelCapabilities = PANEL_CAPABILITIES,
} = deps;
function getFlowCapabilities(flowId) {
const normalizedFlowId = normalizeFlowId(flowId, defaultFlowId);
const entry = flowCapabilities[normalizedFlowId] || null;
return {
...defaultFlowCapabilities,
...(entry || {}),
supportsPlatformBinding: normalizePanelModeList(entry?.supportsPlatformBinding || defaultFlowCapabilities.supportsPlatformBinding),
};
}
function getPanelCapabilities(panelMode) {
const normalizedPanelMode = normalizePanelMode(panelMode);
return {
...defaultPanelCapabilities,
...(panelCapabilities[normalizedPanelMode] || {}),
};
}
function normalizeChangedKeys(values = []) {
const list = Array.isArray(values) ? values : [];
const seen = new Set();
const normalized = [];
list.forEach((value) => {
const key = String(value || '').trim();
if (!key || seen.has(key)) {
return;
}
seen.add(key);
normalized.push(key);
});
return normalized;
}
function resolveSidepanelCapabilities(options = {}) {
const state = options?.state || {};
const activeFlowId = normalizeFlowId(
options?.activeFlowId ?? state?.activeFlowId,
defaultFlowId
);
const flowState = getFlowCapabilities(activeFlowId);
const requestedPanelMode = normalizePanelMode(
options?.panelMode ?? state?.panelMode,
DEFAULT_PANEL_MODE
);
const supportedPanelModes = normalizePanelModeList(flowState.supportsPlatformBinding);
const panelModeSupported = supportedPanelModes.length === 0
? true
: supportedPanelModes.includes(requestedPanelMode);
const effectivePanelMode = panelModeSupported
? requestedPanelMode
: supportedPanelModes[0];
const panelState = getPanelCapabilities(effectivePanelMode);
const runtimeLocks = {
autoRunLocked: Boolean(options?.autoRunLocked ?? state?.autoRunLocked),
contributionMode: flowState.supportsContributionMode && Boolean(state?.contributionMode),
phoneVerificationEnabled: flowState.supportsPhoneVerificationSettings && Boolean(state?.phoneVerificationEnabled),
plusModeEnabled: flowState.supportsPlusMode && Boolean(state?.plusModeEnabled),
settingsMenuLocked: Boolean(options?.settingsMenuLocked ?? state?.settingsMenuLocked),
};
const effectiveSignupMethods = [];
if (flowState.supportsEmailSignup !== false) {
effectiveSignupMethods.push(SIGNUP_METHOD_EMAIL);
}
const canSelectPhoneSignup = Boolean(flowState.supportsPhoneSignup)
&& Boolean(panelState.supportsPhoneSignup)
&& runtimeLocks.phoneVerificationEnabled
&& !runtimeLocks.plusModeEnabled
&& !runtimeLocks.contributionMode;
if (canSelectPhoneSignup) {
effectiveSignupMethods.push(SIGNUP_METHOD_PHONE);
}
if (!effectiveSignupMethods.length) {
effectiveSignupMethods.push(SIGNUP_METHOD_EMAIL);
}
const requestedSignupMethod = normalizeSignupMethod(
options?.signupMethod ?? state?.signupMethod
);
const effectiveSignupMethod = requestedSignupMethod === SIGNUP_METHOD_PHONE && canSelectPhoneSignup
? SIGNUP_METHOD_PHONE
: (effectiveSignupMethods.includes(SIGNUP_METHOD_EMAIL)
? SIGNUP_METHOD_EMAIL
: effectiveSignupMethods[0]);
return {
activeFlowId,
canShowContributionMode: Boolean(flowState.supportsContributionMode),
canShowLuckmail: Boolean(flowState.supportsLuckmail),
canShowPhoneSettings: Boolean(flowState.supportsPhoneVerificationSettings),
canShowPlusSettings: Boolean(flowState.supportsPlusMode),
canSwitchFlow: Boolean(flowState.canSwitchFlow),
canUsePhoneSignup: canSelectPhoneSignup,
canUseSelectedPanelMode: panelModeSupported,
effectivePanelMode,
effectiveSignupMethod,
effectiveSignupMethods,
flowCapabilities: flowState,
panelCapabilities: panelState,
panelMode: effectivePanelMode,
requestedPanelMode,
requestedSignupMethod,
runtimeLocks,
shouldWarnCpaPhoneSignup: effectiveSignupMethod === SIGNUP_METHOD_PHONE
&& Boolean(panelState.requiresPhoneSignupWarning),
stepDefinitionOptions: {
activeFlowId,
panelMode: effectivePanelMode,
plusModeEnabled: runtimeLocks.plusModeEnabled,
signupMethod: effectiveSignupMethod,
},
supportedPanelModes,
};
}
function buildPhoneSignupValidationError(capabilityState = {}) {
const flowState = capabilityState.flowCapabilities || {};
const panelState = capabilityState.panelCapabilities || {};
const runtimeLocks = capabilityState.runtimeLocks || {};
if (!flowState.supportsPhoneSignup) {
return {
code: 'phone_signup_flow_unsupported',
message: '当前 flow 不支持手机号注册。',
};
}
if (!panelState.supportsPhoneSignup) {
return {
code: 'phone_signup_panel_unsupported',
message: `当前面板模式 ${getPanelModeLabel(capabilityState.requestedPanelMode)} 不支持手机号注册。`,
};
}
if (!runtimeLocks.phoneVerificationEnabled) {
return {
code: 'phone_signup_phone_verification_disabled',
message: '请先开启接码功能后再使用手机号注册。',
};
}
if (runtimeLocks.plusModeEnabled) {
return {
code: 'phone_signup_plus_mode_locked',
message: 'Plus 模式开启时不能使用手机号注册。',
};
}
if (runtimeLocks.contributionMode) {
return {
code: 'phone_signup_contribution_mode_locked',
message: '贡献模式开启时不能使用手机号注册。',
};
}
return {
code: 'phone_signup_unavailable',
message: '当前设置暂不支持手机号注册。',
};
}
function validateAutoRunStart(options = {}) {
const state = options?.state || {};
const capabilityState = resolveSidepanelCapabilities(options);
const errors = [];
if (
Array.isArray(capabilityState.supportedPanelModes)
&& capabilityState.supportedPanelModes.length > 0
&& capabilityState.canUseSelectedPanelMode === false
) {
errors.push({
code: 'panel_mode_unsupported',
message: `当前 flow 不支持 ${getPanelModeLabel(capabilityState.requestedPanelMode)} 面板模式。`,
});
}
if (Boolean(state?.plusModeEnabled) && !capabilityState.flowCapabilities?.supportsPlusMode) {
errors.push({
code: 'plus_mode_unsupported',
message: '当前 flow 不支持 Plus 模式。',
});
}
if (Boolean(state?.contributionMode) && !capabilityState.flowCapabilities?.supportsContributionMode) {
errors.push({
code: 'contribution_mode_unsupported',
message: '当前 flow 不支持贡献模式。',
});
}
if (
capabilityState.requestedSignupMethod === SIGNUP_METHOD_PHONE
&& capabilityState.effectiveSignupMethod !== SIGNUP_METHOD_PHONE
) {
errors.push(buildPhoneSignupValidationError(capabilityState));
}
return {
ok: errors.length === 0,
errors,
capabilityState,
};
}
function validateModeSwitch(options = {}) {
const state = options?.state || {};
const changedKeys = normalizeChangedKeys(
options?.changedKeys !== undefined
? options.changedKeys
: Object.keys(state || {})
);
const changedKeySet = new Set(changedKeys);
const capabilityState = resolveSidepanelCapabilities(options);
const errors = [];
const normalizedUpdates = {};
const flowState = capabilityState.flowCapabilities || {};
const requestedPhoneSignup = capabilityState.requestedSignupMethod === SIGNUP_METHOD_PHONE;
const shouldReconcileSignupMethod = MODE_SWITCH_RELEVANT_KEYS.some((key) => changedKeySet.has(key));
if (
changedKeySet.has('panelMode')
&& Array.isArray(capabilityState.supportedPanelModes)
&& capabilityState.supportedPanelModes.length > 0
&& capabilityState.canUseSelectedPanelMode === false
) {
normalizedUpdates.panelMode = capabilityState.effectivePanelMode;
errors.push({
code: 'panel_mode_unsupported',
message: `当前 flow 不支持 ${getPanelModeLabel(capabilityState.requestedPanelMode)} 面板模式。`,
});
}
if (changedKeySet.has('plusModeEnabled') && Boolean(state?.plusModeEnabled) && !flowState.supportsPlusMode) {
normalizedUpdates.plusModeEnabled = false;
errors.push({
code: 'plus_mode_unsupported',
message: '当前 flow 不支持 Plus 模式。',
});
}
if (changedKeySet.has('contributionMode') && Boolean(state?.contributionMode) && !flowState.supportsContributionMode) {
normalizedUpdates.contributionMode = false;
errors.push({
code: 'contribution_mode_unsupported',
message: '当前 flow 不支持贡献模式。',
});
}
if (
changedKeySet.has('phoneVerificationEnabled')
&& Boolean(state?.phoneVerificationEnabled)
&& !flowState.supportsPhoneVerificationSettings
) {
normalizedUpdates.phoneVerificationEnabled = false;
errors.push({
code: 'phone_verification_unsupported',
message: '当前 flow 不支持接码配置。',
});
}
if (
shouldReconcileSignupMethod
&& requestedPhoneSignup
&& capabilityState.effectiveSignupMethod !== SIGNUP_METHOD_PHONE
) {
normalizedUpdates.signupMethod = capabilityState.effectiveSignupMethod;
errors.push(buildPhoneSignupValidationError(capabilityState));
}
return {
ok: errors.length === 0,
changedKeys,
capabilityState,
errors,
normalizedUpdates,
};
}
function canUsePhoneSignup(state = {}) {
return resolveSidepanelCapabilities({ state }).canUsePhoneSignup;
}
function resolveSignupMethod(state = {}, signupMethod = undefined) {
return resolveSidepanelCapabilities({
signupMethod,
state,
}).effectiveSignupMethod;
}
return {
canUsePhoneSignup,
getFlowCapabilities,
getPanelCapabilities,
normalizeFlowId,
normalizePanelMode,
normalizeSignupMethod,
resolveSidepanelCapabilities,
resolveSignupMethod,
validateAutoRunStart,
validateModeSwitch,
};
}
return {
createFlowCapabilityRegistry,
DEFAULT_FLOW_CAPABILITIES,
DEFAULT_FLOW_ID,
DEFAULT_PANEL_CAPABILITIES,
DEFAULT_PANEL_MODE,
FLOW_CAPABILITIES,
PANEL_CAPABILITIES,
SIGNUP_METHOD_EMAIL,
SIGNUP_METHOD_PHONE,
normalizeFlowId,
normalizePanelMode,
normalizeSignupMethod,
};
});
+292
View File
@@ -0,0 +1,292 @@
(function attachSessionToJsonConverter(root, factory) {
root.MultiPageSessionToJsonConverter = factory();
})(typeof self !== 'undefined' ? self : globalThis, function createSessionToJsonConverterModule() {
function isPlainObject(value) {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}
function firstNonEmpty(...values) {
for (const value of values) {
if (typeof value === 'string' && value.trim() !== '') {
return value.trim();
}
}
return undefined;
}
function decodeBase64Url(value) {
const normalized = String(value || '').replace(/-/g, '+').replace(/_/g, '/');
const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=');
if (typeof Buffer !== 'undefined') {
return Buffer.from(padded, 'base64').toString('utf8');
}
const binary = atob(padded);
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
return new TextDecoder().decode(bytes);
}
function bytesToBase64Url(bytes) {
if (typeof Buffer !== 'undefined') {
return Buffer.from(bytes).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
}
let binary = '';
for (let index = 0; index < bytes.length; index += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
}
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
}
function encodeBase64UrlJson(value) {
const json = JSON.stringify(value);
if (typeof Buffer !== 'undefined') {
return Buffer.from(json, 'utf8').toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
}
return bytesToBase64Url(new TextEncoder().encode(json));
}
function parseJwtPayload(token) {
if (typeof token !== 'string' || token.trim() === '') {
return undefined;
}
const segments = token.split('.');
if (segments.length < 2) {
return undefined;
}
try {
return JSON.parse(decodeBase64Url(segments[1]));
} catch {
return undefined;
}
}
function getOpenAIAuthSection(payload) {
if (!isPlainObject(payload)) {
return {};
}
const auth = payload['https://api.openai.com/auth'];
return isPlainObject(auth) ? auth : {};
}
function getOpenAIProfileSection(payload) {
if (!isPlainObject(payload)) {
return {};
}
const profile = payload['https://api.openai.com/profile'];
return isPlainObject(profile) ? profile : {};
}
function normalizeTimestamp(value) {
if (value instanceof Date && !Number.isNaN(value.getTime())) {
return value.toISOString();
}
if (typeof value === 'number' && Number.isFinite(value)) {
const milliseconds = value > 1e11 ? value : value * 1000;
const date = new Date(milliseconds);
return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
}
if (typeof value !== 'string' || value.trim() === '') {
return undefined;
}
const date = new Date(value);
return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
}
function timestampFromUnixSeconds(value) {
const numeric = Number(value);
if (!Number.isFinite(numeric)) {
return undefined;
}
const date = new Date(numeric * 1000);
return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
}
function epochSecondsFromValue(value) {
if (value === undefined || value === null || value === '') {
return 0;
}
const numeric = Number(value);
if (Number.isFinite(numeric)) {
return Math.trunc(numeric > 1e11 ? numeric / 1000 : numeric);
}
const parsed = Date.parse(String(value));
return Number.isFinite(parsed) ? Math.trunc(parsed / 1000) : 0;
}
function buildSyntheticCodexIdToken(email, accountId, planType, userId, expiresAt) {
if (!accountId) {
return undefined;
}
const now = Math.trunc(Date.now() / 1000);
const authInfo = { chatgpt_account_id: accountId };
const expires = epochSecondsFromValue(expiresAt) || now + 90 * 24 * 60 * 60;
if (planType) {
authInfo.chatgpt_plan_type = planType;
}
if (userId) {
authInfo.chatgpt_user_id = userId;
authInfo.user_id = userId;
}
const payload = {
iat: now,
exp: expires,
'https://api.openai.com/auth': authInfo,
};
if (email) {
payload.email = email;
}
return `${encodeBase64UrlJson({ alg: 'none', typ: 'JWT', cpa_synthetic: true })}.${encodeBase64UrlJson(payload)}.`;
}
function convertSessionJson(record, options = {}) {
if (!isPlainObject(record)) {
throw new Error('session 不是 JSON 对象');
}
const accessToken = firstNonEmpty(
record.accessToken,
record.access_token,
record.token?.accessToken,
record.token?.access_token,
record.credentials?.accessToken,
record.credentials?.access_token
);
if (!accessToken) {
throw new Error('缺少 accessToken');
}
const sessionToken = firstNonEmpty(
record.sessionToken,
record.session_token,
record.token?.sessionToken,
record.token?.session_token,
record.credentials?.session_token
);
const refreshToken = firstNonEmpty(
record.refreshToken,
record.refresh_token,
record.token?.refreshToken,
record.token?.refresh_token,
record.credentials?.refresh_token
);
const inputIdToken = firstNonEmpty(
record.idToken,
record.id_token,
record.token?.idToken,
record.token?.id_token,
record.credentials?.id_token
);
const payload = parseJwtPayload(accessToken);
const idPayload = parseJwtPayload(inputIdToken);
const auth = getOpenAIAuthSection(payload);
const idAuth = getOpenAIAuthSection(idPayload);
const profile = getOpenAIProfileSection(payload);
const expiresAt = firstNonEmpty(
payload ? timestampFromUnixSeconds(payload.exp) : undefined,
normalizeTimestamp(record.expires),
normalizeTimestamp(record.expiresAt),
normalizeTimestamp(record.expired),
normalizeTimestamp(record.expires_at)
);
const email = firstNonEmpty(
record.user?.email,
record.email,
record.credentials?.email,
record.providerSpecificData?.email,
profile.email,
idPayload?.email,
payload?.email
);
const accountId = firstNonEmpty(
record.account?.id,
record.account_id,
record.chatgptAccountId,
record.providerSpecificData?.chatgptAccountId,
record.providerSpecificData?.chatgpt_account_id,
record.credentials?.chatgpt_account_id,
auth.chatgpt_account_id,
idAuth.chatgpt_account_id,
record.provider === 'codex' ? record.id : undefined
);
const userId = firstNonEmpty(
record.user?.id,
record.user_id,
record.chatgptUserId,
record.providerSpecificData?.chatgptUserId,
record.providerSpecificData?.chatgpt_user_id,
auth.chatgpt_user_id,
auth.user_id,
idAuth.chatgpt_user_id,
idAuth.user_id
);
const planType = firstNonEmpty(
record.account?.planType,
record.account?.plan_type,
record.planType,
record.plan_type,
record.providerSpecificData?.chatgptPlanType,
record.providerSpecificData?.chatgpt_plan_type,
record.credentials?.plan_type,
auth.chatgpt_plan_type,
idAuth.chatgpt_plan_type
);
const exportedAt = Object.prototype.hasOwnProperty.call(options, 'lastRefresh')
? String(options.lastRefresh ?? '')
: normalizeTimestamp(options.now || new Date());
const name = firstNonEmpty(email, options.sourceName, 'ChatGPT Account');
const syntheticIdToken = !inputIdToken
? buildSyntheticCodexIdToken(email, accountId, planType, userId, expiresAt)
: undefined;
const idToken = firstNonEmpty(inputIdToken, syntheticIdToken);
const output = Object.fromEntries(
Object.entries({
type: 'codex',
account_id: accountId,
chatgpt_account_id: accountId,
email,
name,
plan_type: planType,
chatgpt_plan_type: planType,
id_token: idToken,
id_token_synthetic: Boolean(syntheticIdToken) || undefined,
access_token: accessToken,
refresh_token: refreshToken || '',
session_token: sessionToken,
last_refresh: exportedAt,
expired: expiresAt,
disabled: Boolean(record.disabled) || undefined,
}).filter(([, value]) => value !== undefined && value !== null)
);
const warnings = [];
if (!inputIdToken && syntheticIdToken) {
warnings.push('Missing real id_token; generated synthetic CPA-compatible id_token.');
}
if (!refreshToken) {
warnings.push('Missing refresh_token; imported account cannot refresh automatically after access token expiry.');
}
return { output, warnings };
}
return {
convertSessionJson,
};
});
+461
View File
@@ -0,0 +1,461 @@
(function attachMultiPageSourceRegistry(root, factory) {
root.MultiPageSourceRegistry = factory();
})(typeof self !== 'undefined' ? self : globalThis, function createSourceRegistryModule() {
const SOURCE_ALIASES = Object.freeze({
'signup-page': 'openai-auth',
});
const SOURCE_DEFINITIONS = Object.freeze({
'openai-auth': {
flowId: 'openai',
kind: 'flow-page',
label: '认证页',
readyPolicy: 'allow-child-frame',
family: 'openai-auth-family',
driverId: 'content/signup-page',
cleanupScopes: ['oauth-localhost-callback'],
},
chatgpt: {
flowId: 'openai',
kind: 'flow-entry',
label: 'ChatGPT 首页',
readyPolicy: 'allow-child-frame',
family: 'chatgpt-entry-family',
driverId: null,
cleanupScopes: [],
},
'qq-mail': {
flowId: null,
kind: 'mail-provider',
label: 'QQ 邮箱',
readyPolicy: 'top-frame-only',
family: 'qq-mail-family',
driverId: 'content/qq-mail',
cleanupScopes: [],
},
'mail-163': {
flowId: null,
kind: 'mail-provider',
label: '163 邮箱',
readyPolicy: 'top-frame-only',
family: 'mail-163-family',
driverId: 'content/mail-163',
cleanupScopes: [],
},
'gmail-mail': {
flowId: null,
kind: 'mail-provider',
label: 'Gmail 邮箱',
readyPolicy: 'top-frame-only',
family: 'gmail-mail-family',
driverId: 'content/gmail-mail',
cleanupScopes: [],
},
'icloud-mail': {
flowId: null,
kind: 'mail-provider',
label: 'iCloud 邮箱',
readyPolicy: 'allow-child-frame',
family: 'icloud-mail-family',
driverId: 'content/icloud-mail',
cleanupScopes: [],
},
'inbucket-mail': {
flowId: null,
kind: 'mail-provider',
label: 'Inbucket 邮箱',
readyPolicy: 'top-frame-only',
family: 'inbucket-mail-family',
driverId: 'content/inbucket-mail',
cleanupScopes: [],
},
'mail-2925': {
flowId: null,
kind: 'mail-provider',
label: '2925 邮箱',
readyPolicy: 'top-frame-only',
family: 'mail-2925-family',
driverId: 'content/mail-2925',
cleanupScopes: [],
},
'duck-mail': {
flowId: null,
kind: 'mail-provider',
label: 'Duck 邮箱',
readyPolicy: 'allow-child-frame',
family: 'duck-mail-family',
driverId: 'content/duck-mail',
cleanupScopes: [],
},
'vps-panel': {
flowId: 'openai',
kind: 'panel-page',
label: 'CPA 面板',
readyPolicy: 'allow-child-frame',
family: 'vps-panel-family',
driverId: 'content/vps-panel',
cleanupScopes: [],
},
'platform-panel': {
flowId: 'openai',
kind: 'virtual-page',
label: '平台回调面板',
readyPolicy: 'disabled',
family: 'platform-panel-family',
driverId: 'content/platform-panel',
cleanupScopes: [],
},
'sub2api-panel': {
flowId: 'openai',
kind: 'panel-page',
label: 'SUB2API 后台',
readyPolicy: 'allow-child-frame',
family: 'sub2api-panel-family',
driverId: 'content/sub2api-panel',
cleanupScopes: [],
},
'codex2api-panel': {
flowId: 'openai',
kind: 'panel-page',
label: 'Codex2API 后台',
readyPolicy: 'allow-child-frame',
family: 'codex2api-panel-family',
driverId: 'content/sub2api-panel',
cleanupScopes: [],
},
'plus-checkout': {
flowId: 'openai',
kind: 'flow-page',
label: 'Plus Checkout',
readyPolicy: 'top-frame-only',
family: 'plus-checkout-family',
driverId: 'content/plus-checkout',
cleanupScopes: [],
},
'paypal-flow': {
flowId: 'openai',
kind: 'flow-page',
label: 'PayPal 授权页',
readyPolicy: 'allow-child-frame',
family: 'paypal-flow-family',
driverId: 'content/paypal-flow',
cleanupScopes: [],
},
'gopay-flow': {
flowId: 'openai',
kind: 'flow-page',
label: 'GoPay 授权页',
readyPolicy: 'allow-child-frame',
family: 'gopay-flow-family',
driverId: 'content/gopay-flow',
cleanupScopes: [],
},
'unknown-source': {
flowId: null,
kind: 'unknown',
label: '未知来源',
readyPolicy: 'disabled',
family: 'unknown-family',
driverId: null,
cleanupScopes: [],
},
});
const DRIVER_DEFINITIONS = Object.freeze({
'content/signup-page': {
sourceId: 'openai-auth',
commands: [
'submit-signup-email',
'fill-password',
'fill-profile',
'oauth-login',
'submit-verification-code',
'post-login-phone-verification',
'bind-email',
'fetch-bind-email-code',
'confirm-oauth',
'detect-auth-state',
],
},
'content/qq-mail': {
sourceId: 'qq-mail',
commands: ['POLL_EMAIL'],
},
'content/mail-163': {
sourceId: 'mail-163',
commands: ['POLL_EMAIL'],
},
'content/gmail-mail': {
sourceId: 'gmail-mail',
commands: ['POLL_EMAIL'],
},
'content/icloud-mail': {
sourceId: 'icloud-mail',
commands: ['POLL_EMAIL'],
},
'content/mail-2925': {
sourceId: 'mail-2925',
commands: ['POLL_EMAIL'],
},
'content/duck-mail': {
sourceId: 'duck-mail',
commands: ['FETCH_ALIAS_EMAIL'],
},
'content/sub2api-panel': {
sourceId: 'sub2api-panel',
commands: ['open-panel', 'fetch-oauth-url', 'platform-verify'],
},
'content/vps-panel': {
sourceId: 'vps-panel',
commands: ['open-panel', 'fetch-oauth-url', 'platform-verify'],
},
'content/platform-panel': {
sourceId: 'platform-panel',
commands: ['platform-verify', 'fetch-oauth-url'],
},
'content/plus-checkout': {
sourceId: 'plus-checkout',
commands: ['plus-checkout-create', 'plus-checkout-billing', 'plus-checkout-return'],
},
'content/paypal-flow': {
sourceId: 'paypal-flow',
commands: ['paypal-approve'],
},
'content/gopay-flow': {
sourceId: 'gopay-flow',
commands: ['gopay-subscription-confirm'],
},
});
const CLEANUP_SCOPE_OWNERS = Object.freeze({
'oauth-localhost-callback': 'openai-auth',
});
const AUTH_PAGE_HOSTS = new Set(['auth0.openai.com', 'auth.openai.com', 'accounts.openai.com']);
const ENTRY_PAGE_HOSTS = new Set(['chatgpt.com', 'www.chatgpt.com', 'chat.openai.com']);
const CHILD_FRAME_BLOCKED_SOURCES = new Set([
'qq-mail',
'mail-163',
'gmail-mail',
'mail-2925',
'inbucket-mail',
'plus-checkout',
]);
function createSourceRegistry() {
function parseUrlSafely(rawUrl) {
if (!rawUrl) return null;
try {
return new URL(rawUrl);
} catch {
return null;
}
}
function normalizeSourceId(source) {
return String(source || '').trim();
}
function resolveCanonicalSource(source) {
const normalized = normalizeSourceId(source);
if (!normalized) return '';
return SOURCE_ALIASES[normalized] || normalized;
}
function getAliasKeysForCanonicalSource(source) {
const canonical = resolveCanonicalSource(source);
return Object.keys(SOURCE_ALIASES).filter((alias) => SOURCE_ALIASES[alias] === canonical);
}
function getSourceKeys(source) {
const normalized = normalizeSourceId(source);
const canonical = resolveCanonicalSource(normalized);
return Array.from(new Set([
canonical,
...getAliasKeysForCanonicalSource(canonical),
normalized,
].filter(Boolean)));
}
function getSourceMeta(source) {
const canonical = resolveCanonicalSource(source);
const definition = SOURCE_DEFINITIONS[canonical];
if (!definition) {
return null;
}
return {
id: canonical,
aliases: getAliasKeysForCanonicalSource(canonical),
...definition,
};
}
function getSourceLabel(source) {
return getSourceMeta(source)?.label || normalizeSourceId(source) || '未知来源';
}
function getDriverIdForSource(source) {
return getSourceMeta(source)?.driverId || null;
}
function getDriverMeta(sourceOrDriverId) {
const directDriverId = normalizeSourceId(sourceOrDriverId);
const driverId = Object.prototype.hasOwnProperty.call(DRIVER_DEFINITIONS, directDriverId)
? directDriverId
: getDriverIdForSource(sourceOrDriverId);
if (!driverId || !Object.prototype.hasOwnProperty.call(DRIVER_DEFINITIONS, driverId)) {
return null;
}
return {
id: driverId,
...DRIVER_DEFINITIONS[driverId],
};
}
function driverAcceptsCommand(sourceOrDriverId, command) {
const normalizedCommand = normalizeSourceId(command);
if (!normalizedCommand) {
return false;
}
const driver = getDriverMeta(sourceOrDriverId);
return Array.isArray(driver?.commands) && driver.commands.includes(normalizedCommand);
}
function isSignupPageHost(hostname = '') {
return AUTH_PAGE_HOSTS.has(String(hostname || '').toLowerCase());
}
function isSignupEntryHost(hostname = '') {
return ENTRY_PAGE_HOSTS.has(String(hostname || '').toLowerCase());
}
function is163MailHost(hostname = '') {
const normalized = String(hostname || '').toLowerCase();
return normalized === 'mail.163.com'
|| normalized.endsWith('.mail.163.com')
|| normalized === 'mail.126.com'
|| normalized.endsWith('.mail.126.com')
|| normalized === 'webmail.vip.163.com';
}
function matchesSourceUrlFamily(source, candidateUrl, referenceUrl) {
const candidate = parseUrlSafely(candidateUrl);
if (!candidate) return false;
const canonical = resolveCanonicalSource(source);
const reference = parseUrlSafely(referenceUrl);
switch (canonical) {
case 'openai-auth':
return isSignupPageHost(candidate.hostname) || isSignupEntryHost(candidate.hostname);
case 'chatgpt':
return isSignupEntryHost(candidate.hostname);
case 'duck-mail':
return candidate.hostname === 'duckduckgo.com' && candidate.pathname.startsWith('/email/');
case 'qq-mail':
return candidate.hostname === 'mail.qq.com' || candidate.hostname === 'wx.mail.qq.com';
case 'mail-163':
return is163MailHost(candidate.hostname);
case 'gmail-mail':
return candidate.hostname === 'mail.google.com';
case 'icloud-mail':
return candidate.hostname === 'www.icloud.com'
|| candidate.hostname === 'www.icloud.com.cn';
case 'inbucket-mail':
return Boolean(reference)
&& candidate.origin === reference.origin
&& candidate.pathname.startsWith('/m/');
case 'mail-2925':
return candidate.hostname === '2925.com' || candidate.hostname === 'www.2925.com';
case 'vps-panel':
return Boolean(reference)
&& candidate.origin === reference.origin
&& candidate.pathname === reference.pathname;
case 'sub2api-panel':
return Boolean(reference)
&& candidate.origin === reference.origin
&& (
candidate.pathname.startsWith('/admin/accounts')
|| 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 === '/'
);
case 'plus-checkout':
return candidate.hostname === 'chatgpt.com'
&& candidate.pathname.startsWith('/checkout/');
case 'paypal-flow':
return candidate.hostname.endsWith('paypal.com');
case 'gopay-flow':
return /gopay|gojek/i.test(candidate.hostname);
default:
return false;
}
}
function detectSourceFromLocation({
injectedSource,
url = '',
hostname = '',
} = {}) {
if (injectedSource) return resolveCanonicalSource(injectedSource);
const normalizedHostname = String(hostname || '').toLowerCase();
const normalizedUrl = String(url || '');
if (isSignupPageHost(normalizedHostname)) return 'openai-auth';
if (normalizedHostname === 'mail.qq.com' || normalizedHostname === 'wx.mail.qq.com') return 'qq-mail';
if (is163MailHost(normalizedHostname)) return 'mail-163';
if (normalizedHostname === 'mail.google.com') return 'gmail-mail';
if (normalizedHostname === 'www.icloud.com' || normalizedHostname === 'www.icloud.com.cn') return 'icloud-mail';
if (normalizedUrl.includes('duckduckgo.com/email/settings/autofill')) return 'duck-mail';
if (normalizedUrl.includes('2925.com')) return 'mail-2925';
if (normalizedHostname === 'pay.openai.com' || normalizedHostname === 'checkout.stripe.com') return 'plus-checkout';
if (normalizedHostname === 'www.paypal.com' || normalizedHostname === 'paypal.com') return 'paypal-flow';
if (isSignupEntryHost(normalizedHostname)) return 'chatgpt';
return 'unknown-source';
}
function shouldReportReadyForFrame(source, isChildFrame) {
const canonical = resolveCanonicalSource(source);
const readyPolicy = getSourceMeta(canonical)?.readyPolicy || 'allow-child-frame';
if (readyPolicy === 'disabled') return false;
if (!isChildFrame) return true;
if (readyPolicy === 'top-frame-only') return false;
if (CHILD_FRAME_BLOCKED_SOURCES.has(canonical)) return false;
return true;
}
function getCleanupOwnerSource(cleanupScope) {
return resolveCanonicalSource(CLEANUP_SCOPE_OWNERS[String(cleanupScope || '').trim()] || '');
}
return {
detectSourceFromLocation,
getCleanupOwnerSource,
getDriverIdForSource,
getDriverMeta,
driverAcceptsCommand,
getSourceKeys,
getSourceLabel,
getSourceMeta,
is163MailHost,
isSignupEntryHost,
isSignupPageHost,
matchesSourceUrlFamily,
parseUrlSafely,
resolveCanonicalSource,
shouldReportReadyForFrame,
};
}
return {
createSourceRegistry,
};
});