LibreChat/api/server/routes/config.js
Danny Avila 0abbf3313d
🔐 fix: Apply Base Config Overrides Before Sign-In and Refuse Script Policy Links (#17351)
* 🔐 fix: Apply Base Config Overrides Before Sign-In and Refuse Script Policy Links

Sign-in decisions made before the user is known now read librechat.yaml plus the `__base__`
override of the request's tenant, or of the deployment outside a tenant, and fail closed
(`resolvePreAuthAppConfig`). Registration, the first phase of password reset and the first
email-domain check of the LDAP, OpenID, SAML and social strategies use it. The second check
applies the account's role overrides with or without a tenant, and a new account is checked
against the role it will be created with before anything is inserted. OpenID checks again when
the admin claim or role sync changes the role. Password reset issues no link when the
account's config cannot be read.

The signed-out `GET /api/config` serves Base `registration.socialLogins` and the pre-login
interface fields (`resolvePreLoginAppConfig`), falling back to librechat.yaml when overrides
cannot be read. `turnstile` becomes a base-only section, so Turnstile comes only from
librechat.yaml.

Config reads that merge documents stay in one tenant partition (`tenantPartition`, Mongoose
binding `tenantPartitionFilter`): the active tenant's documents, or the tenantless ones outside
a tenant. The config store's Mongoose binding reads, writes, lists and restores role documents,
`__base__` included, in that partition, and its `listActive` draws every document from it;
group and user documents stay addressed by id. Only a `list` with `acrossTenants` reads every
partition, which `listConfigTombstones` uses so the startup MCP tombstone report still names
each tenant's documents. The tenant-isolation conformance suite gains single-partition cases.

Privacy policy and terms of service `externalUrl` must be http(s), `mailto:`, `tel:`, relative
or blank (`isSafeLinkUrl`). Admin writes of another scheme are refused, a librechat.yaml link is
dropped with a warning at load, a stored one is dropped at merge, and every payload and the
client remove one that reaches them. The admin config meta reports
`features.preAuthBaseOverrides: true`.

* 🧪 test: Layer a Required-Field Override Through interface.currency Instead of Turnstile

Turnstile is set in librechat.yaml only now, so profile overrides of it are skipped and the
layering scenario could no longer see a role's Turnstile options completed by a user's site key.
The scenario now layers `interface.currency`, whose `code` and `rate` are both required: the role
stores only the rate, the user only the code, and /api/config serves both.

* 🛂 fix: Admit a First OpenID Login Under Its Claimed Role Before Creating the Account

The admin-role claim and role sync are now decided before a first-login OpenID account is created, and createUserOnce admits the email under that role's config, read in parallel with the USER role's, before inserting anything. A login the claimed role refuses creates no account and no start balance. Admitted logins are unchanged: the account is still created as USER (now explicitly), moved into the claimed role, re-checked and audited as before, with the claims decided once. An account a concurrent first login created gets the claims decided again for its own role and tenant.
2026-10-22 22:49:54 +02:00

395 lines
14 KiB
JavaScript

const express = require('express');
const {
isEnabled,
resolveEmailChangeSettings,
checkEmailConfig,
isLangfuseConnectionAvailable,
isLangfuseFanoutEnabled,
getBalanceConfig,
getCloudFrontConfig,
getAppConfigOptionsFromUser,
resolveBuildInfo,
resolveTitleTiming,
getConversationTitleCapabilities,
sanitizeModelSpecs,
excludeHiddenModelSpecs,
isFileSnapshotEnabled,
getEndpointsDropParamsMap,
resolveCodeEnvironmentDecisionVersion,
isPasskeyEnabled,
buildPreLoginInterface,
resolveMaxPasskeysPerUser,
resolveCodeEnvironmentMoveCapabilities,
resolveCodeWorkspaceInheritanceCapability,
resolveCodeEnvironmentTransitionVersion,
loadConversationListLimits,
resolvePullRequestCapabilities,
resolvePreLoginAppConfig,
withSafePolicyLinks,
} = require('@librechat/api');
const {
DEFAULT_MCP_APP_CSP_LIMITS,
EModelEndpoint,
defaultSocialLogins,
resolveMCPAppsPolicy,
} = require('librechat-data-provider');
const { logger, SystemCapabilities } = require('@librechat/data-schemas');
const { hasCapability, hasConfigCapability } = require('~/server/middleware/roles/capabilities');
const { getLdapConfig } = require('~/server/services/Config/ldap');
const { getRumConfig } = require('~/server/services/Config/rum');
const { getAppConfig } = require('~/server/services/Config/app');
const router = express.Router();
const emailLoginEnabled =
process.env.ALLOW_EMAIL_LOGIN === undefined || isEnabled(process.env.ALLOW_EMAIL_LOGIN);
const passwordResetEnabled = isEnabled(process.env.ALLOW_PASSWORD_RESET);
const sharedLinksEnabled =
process.env.ALLOW_SHARED_LINKS === undefined || isEnabled(process.env.ALLOW_SHARED_LINKS);
const publicSharedLinksEnabled =
sharedLinksEnabled && isEnabled(process.env.ALLOW_SHARED_LINKS_PUBLIC);
const sharePointFilePickerEnabled = isEnabled(process.env.ENABLE_SHAREPOINT_FILEPICKER);
const openidReuseTokens = isEnabled(process.env.OPENID_REUSE_TOKENS);
/**
* Resolve build metadata eagerly at module load so the first `/api/config`
* request does not pay the cost of `execFileSync('git', ...)` on the hot path.
* The resolver caches its result after the first call.
*/
resolveBuildInfo();
function isBirthday() {
const today = new Date();
return today.getMonth() === 1 && today.getDate() === 11;
}
/**
* Pre-login fields rendered by the unauthenticated login, registration, password-reset,
* and email-verification pages. Any field added here is readable by anonymous callers
* of `GET /api/config`, so keep this set strictly to what those pages need.
*
* See client consumers under `client/src/components/Auth/` and `client/src/routes/Layouts/Startup.tsx`.
*/
function buildPreLoginPayload() {
const isOpenIdEnabled =
!!process.env.OPENID_CLIENT_ID &&
(isEnabled(process.env.OPENID_USE_PKCE) || !!process.env.OPENID_CLIENT_SECRET?.trim()) &&
!!process.env.OPENID_ISSUER &&
!!process.env.OPENID_SESSION_SECRET;
const isSamlEnabled =
!!process.env.SAML_ENTRY_POINT &&
!!process.env.SAML_ISSUER &&
!!process.env.SAML_CERT &&
!!process.env.SAML_SESSION_SECRET;
const ldap = getLdapConfig();
/** @type {Partial<TStartupConfig>} */
const payload = {
appTitle: process.env.APP_TITLE || 'LibreChat',
discordLoginEnabled: !!process.env.DISCORD_CLIENT_ID && !!process.env.DISCORD_CLIENT_SECRET,
facebookLoginEnabled: !!process.env.FACEBOOK_CLIENT_ID && !!process.env.FACEBOOK_CLIENT_SECRET,
githubLoginEnabled: !!process.env.GITHUB_CLIENT_ID && !!process.env.GITHUB_CLIENT_SECRET,
googleLoginEnabled: !!process.env.GOOGLE_CLIENT_ID && !!process.env.GOOGLE_CLIENT_SECRET,
appleLoginEnabled:
!!process.env.APPLE_CLIENT_ID &&
!!process.env.APPLE_TEAM_ID &&
!!process.env.APPLE_KEY_ID &&
!!process.env.APPLE_PRIVATE_KEY_PATH,
passkeyLoginEnabled: isPasskeyEnabled(),
openidLoginEnabled: isOpenIdEnabled,
openidLabel: process.env.OPENID_BUTTON_LABEL || 'Continue with OpenID',
openidImageUrl: process.env.OPENID_IMAGE_URL,
openidAutoRedirect: isEnabled(process.env.OPENID_AUTO_REDIRECT),
samlLoginEnabled: !isOpenIdEnabled && isSamlEnabled,
samlLabel: process.env.SAML_BUTTON_LABEL,
samlImageUrl: process.env.SAML_IMAGE_URL,
serverDomain: process.env.DOMAIN_SERVER || 'http://localhost:3080',
emailLoginEnabled,
registrationEnabled: !ldap?.enabled && isEnabled(process.env.ALLOW_REGISTRATION),
socialLoginEnabled: isEnabled(process.env.ALLOW_SOCIAL_LOGIN),
emailEnabled: checkEmailConfig(),
passwordResetEnabled,
twoFactorAuthenticationRequired: isEnabled(process.env.ENFORCE_TWO_FACTOR_AUTHENTICATION),
};
const minPasswordLength = parseInt(process.env.MIN_PASSWORD_LENGTH, 10);
if (minPasswordLength && !isNaN(minPasswordLength)) {
payload.minPasswordLength = minPasswordLength;
}
if (ldap) {
payload.ldap = ldap;
}
return payload;
}
/**
* Fields shared by authenticated chat and share-view config. Anonymous share
* views receive these through `/api/share/:shareId/config` after share access
* checks, not through the generic startup config endpoint.
*/
function buildPublicSharePayload() {
/** @type {Partial<TStartupConfig>} */
const payload = {
analyticsGtmId: process.env.ANALYTICS_GTM_ID,
};
if (typeof process.env.CUSTOM_FOOTER === 'string') {
payload.customFooter = process.env.CUSTOM_FOOTER;
}
return payload;
}
/**
* Post-login fields appended only when `req.user` is present. These describe the
* authenticated UX (account-settings links, share-link feature flags, birthday icon,
* openid token-reuse marker) and are not needed on the pre-login screens, so they
* are not exposed to unauthenticated callers.
*/
function buildPostLoginPayload(appConfig) {
/** @type {Partial<TStartupConfig>} */
const payload = {
showBirthdayIcon:
isBirthday() ||
isEnabled(process.env.SHOW_BIRTHDAY_ICON) ||
process.env.SHOW_BIRTHDAY_ICON === '',
helpAndFaqURL: process.env.HELP_AND_FAQ_URL || 'https://librechat.ai',
sharedLinksEnabled,
publicSharedLinksEnabled,
openidReuseTokens,
ragEnabled: Boolean(process.env.RAG_API_URL?.trim()),
/** Read inline (not module-level) for per-request evaluation and test isolation */
allowAccountDeletion:
process.env.ALLOW_ACCOUNT_DELETION === undefined ||
isEnabled(process.env.ALLOW_ACCOUNT_DELETION),
allowEmailChange: resolveEmailChangeSettings(appConfig?.emailChange).enabled,
maxPasskeysPerUser: resolveMaxPasskeysPerUser(appConfig?.passkeys),
};
return payload;
}
function buildBuildInfoPayload(interfaceConfig) {
if (interfaceConfig?.buildInfo === false) {
return undefined;
}
const info = resolveBuildInfo();
if (!info.commit && !info.branch && !info.buildDate) {
return undefined;
}
return {
commit: info.commit,
commitShort: info.commitShort,
branch: info.branch,
buildDate: info.buildDate,
};
}
function buildWebSearchConfig(appConfig) {
const ws = appConfig?.webSearch;
if (!ws) {
return undefined;
}
const { searchProvider, scraperProvider, rerankerType } = ws;
if (!searchProvider && !scraperProvider && !rerankerType) {
return undefined;
}
return {
...(searchProvider && { searchProvider }),
...(scraperProvider && { scraperProvider }),
...(rerankerType && { rerankerType }),
};
}
function buildCloudFrontStartupConfig() {
const config = getCloudFrontConfig();
if (
config?.imageSigning !== 'cookies' ||
!config.domain ||
!config.cookieDomain ||
!config.privateKey ||
!config.keyPairId
) {
return undefined;
}
return {
cookieRefresh: {
endpoint: '/api/auth/cloudfront/refresh',
domain: config.domain,
},
};
}
router.get('/', async function (req, res) {
try {
const preLoginPayload = buildPreLoginPayload();
const publicSharePayload = buildPublicSharePayload();
if (!req.user) {
const baseConfig = await resolvePreLoginAppConfig(getAppConfig);
/** @type {Partial<TStartupConfig>} */
const payload = {
...preLoginPayload,
socialLogins: baseConfig?.registration?.socialLogins ?? defaultSocialLogins,
turnstile: baseConfig?.turnstileConfig,
rum: getRumConfig(baseConfig?.config?.telemetry),
};
const interfaceConfig = baseConfig?.interfaceConfig;
const preLoginInterface = buildPreLoginInterface(interfaceConfig);
if (preLoginInterface) {
payload.interface = preLoginInterface;
}
const unauthBuildInfo = buildBuildInfoPayload(interfaceConfig);
if (unauthBuildInfo) {
payload.buildInfo = unauthBuildInfo;
}
return res.status(200).send(payload);
}
const [appConfig, conversationListLimits] = await Promise.all([
getAppConfig({
...getAppConfigOptionsFromUser(req.user),
failClosed: true,
}),
loadConversationListLimits(getAppConfig),
]);
const codeEnvironmentDecisionVersion = resolveCodeEnvironmentDecisionVersion(
process.env.CODE_ENVIRONMENT_DECISION_VERSION,
);
const codeEnvironmentMoveCapabilities = resolveCodeEnvironmentMoveCapabilities(appConfig);
const codeEnvironmentTransitionVersion = resolveCodeEnvironmentTransitionVersion(appConfig);
const endpointsDropParamsMap = getEndpointsDropParamsMap(appConfig?.endpoints);
const balanceConfig = getBalanceConfig(appConfig);
const cloudFront = buildCloudFrontStartupConfig();
const langfuseFanoutEnabled = isLangfuseFanoutEnabled();
const langfuseConnectionAvailable = isLangfuseConnectionAvailable();
let langfuseConnectionAccess = false;
if (langfuseConnectionAvailable) {
try {
const userId = req.user.id ?? req.user._id?.toString();
if (userId) {
const capabilityUser = {
id: userId,
role: req.user.role ?? '',
tenantId: req.user.tenantId,
idOnTheSource: req.user.idOnTheSource ?? null,
};
const hasAdminAccess = await hasCapability(
capabilityUser,
SystemCapabilities.ACCESS_ADMIN,
);
if (hasAdminAccess) {
langfuseConnectionAccess = await hasConfigCapability(capabilityUser, 'langfuse');
}
}
} catch (err) {
logger.warn(`[config] Langfuse capability check failed: ${err.message}`);
}
}
/** @type {TStartupConfig} */
const payload = {
...preLoginPayload,
...publicSharePayload,
...buildPostLoginPayload(appConfig),
...getConversationTitleCapabilities(appConfig?.interfaceConfig),
conversationListLimits,
sharedLinksSnapshotFilesEnabled: sharedLinksEnabled && isFileSnapshotEnabled(appConfig),
socialLogins: appConfig?.registration?.socialLogins ?? defaultSocialLogins,
projects: appConfig?.projects,
interface: withSafePolicyLinks(appConfig?.interfaceConfig),
titleGenerationTiming: resolveTitleTiming({
appConfig,
endpoint: EModelEndpoint.agents,
}),
turnstile: appConfig?.turnstileConfig,
modelSpecs: sanitizeModelSpecs(excludeHiddenModelSpecs(appConfig?.modelSpecs)),
balance: balanceConfig,
bundlerURL: process.env.SANDPACK_BUNDLER_URL,
staticBundlerURL: process.env.SANDPACK_STATIC_BUNDLER_URL,
sharePointFilePickerEnabled,
sharePointBaseUrl: process.env.SHAREPOINT_BASE_URL,
sharePointPickerGraphScope: process.env.SHAREPOINT_PICKER_GRAPH_SCOPE,
sharePointPickerSharePointScope: process.env.SHAREPOINT_PICKER_SHAREPOINT_SCOPE,
conversationImportMaxFileSize: process.env.CONVERSATION_IMPORT_MAX_FILE_SIZE_BYTES
? parseInt(process.env.CONVERSATION_IMPORT_MAX_FILE_SIZE_BYTES, 10)
: 0,
langfuseFanoutEnabled,
langfuseConnectionAccess,
insightsEnabled: isEnabled(process.env.ENABLE_INSIGHTS),
/** Lets the client skip the pull request lookup entirely when the feature is off. */
...resolvePullRequestCapabilities(appConfig, process.env),
compactionEnabled: appConfig?.summarization?.enabled !== false,
...(codeEnvironmentDecisionVersion != null ? { codeEnvironmentDecisionVersion } : {}),
mcpApps: resolveMCPAppsPolicy(
appConfig?.mcpSettings?.apps,
appConfig?.mcpAppSandbox ?? DEFAULT_MCP_APP_CSP_LIMITS,
appConfig?.mcpAppSandbox?.maxPersistedAppBytes,
appConfig?.mcpAppSandbox?.maxAdmissionRequestsPerMinute,
appConfig?.mcpAppSandbox?.url,
appConfig?.mcpAppSandbox?.maxActiveViews,
appConfig?.mcpAppSandbox?.maxActionPreviewChars,
appConfig?.mcpAppSandbox?.operationLimits,
),
...codeEnvironmentMoveCapabilities,
...resolveCodeWorkspaceInheritanceCapability(process.env.CODE_ENVIRONMENT_DECISION_VERSION),
...(codeEnvironmentTransitionVersion != null ? { codeEnvironmentTransitionVersion } : {}),
...(cloudFront ? { cloudFront } : {}),
rum: getRumConfig(appConfig?.config?.telemetry),
fileUploadSseEnabled: isEnabled(process.env.FILE_UPLOAD_SSE_ENABLED),
endpointsDropParamsMap: endpointsDropParamsMap,
};
const webSearch = buildWebSearchConfig(appConfig);
if (webSearch) {
payload.webSearch = webSearch;
}
const buildInfo = buildBuildInfoPayload(appConfig?.interfaceConfig);
if (buildInfo) {
payload.buildInfo = buildInfo;
}
const adminPanelURL = process.env.ADMIN_PANEL_URL;
if (adminPanelURL || !payload.allowAccountDeletion) {
try {
const userId = req.user.id ?? req.user._id?.toString();
if (userId) {
const hasAdminAccess = await hasCapability(
{ id: userId, role: req.user.role ?? '', tenantId: req.user.tenantId },
SystemCapabilities.ACCESS_ADMIN,
);
if (hasAdminAccess && adminPanelURL) {
payload.adminPanelURL = adminPanelURL;
}
if (hasAdminAccess && !payload.allowAccountDeletion) {
payload.allowAccountDeletion = true;
}
}
} catch (err) {
logger.warn(`[config] ACCESS_ADMIN capability check failed: ${err.message}`);
}
}
return res.status(200).send(payload);
} catch (err) {
logger.error('Error in startup config', err);
return res.status(500).send({ error: 'Failed to load startup config' });
}
});
module.exports = router;