LibreChat/packages/api/src/utils/identity.ts
Marco Beretta d0e253043a
🙈 fix: Mask Emails and Drop Personal Identifiers From Logs (#17048)
* fix: Mask Email Addresses and Drop Personal Identifiers from Logs

* fix: Log User IDs in OpenID Admin Role and LDAP Domain Block Messages

* fix: Mask Unicode Email Addresses in Log Redaction

* test: Add Log Email Masking Scenarios

* fix: Bound the Email Redaction Matcher and Handle Quoted Local Parts

* fix: Mask Quoted and Special-Character Email Local Parts

* fix: Redact Whole Email Tokens, Top-Level Log Fields and Metadata Keys

* fix: Redact Top-Level Metadata Keys and Escaped Quotes in Email Local Parts

* fix: Redact Truncated Emails, Address Literals and Request Paths in Logs

* fix: Redact the Full Log String Before Truncating

* fix: Preserve Colliding and Object Keys When Redacting Log Metadata

* fix: Bound Log Redaction to a Window Past the Truncation Limit

* fix: Redact the Truncation Window Without a Whitespace Cut

* fix: Redact Serialized Quoted Addresses and Keep Key Collisions Linear

* fix: Bound Every Log Redaction Path and the URL Credential Pattern

* fix: Keep Long-Scheme Credential Redaction and Serialized Escaped Quotes

* test: Cover Every Secret Shape Across the Log Truncation Cap

* fix: Drop Unfinished Window Tokens, Mask Short TLDs and Redact Direct Error Stacks

* fix: Treat Input End as a Token Boundary and Mask Parenthesized Identifiers

* fix: Remove the Quoted Local Part Length Cap Without Quadratic Scans

* fix: Drop an Unfinished Quoted Address at the Window Edge

* fix: Check Quoted Locals Before Accepting a Window Delimiter

* fix: Count Only Opening Quotes When Trimming the Window

* fix: Track Unmatched Quoted Locals Instead of Counting Closing Quotes

* fix: Lift Residual Email Caps, Keep Punctuated Credential URIs Masked and Move OBO Log Id to the API Package

* fix: Mask Empty Quoted Locals and Tolerate Read-Only Log Fields

* fix: Return a Sanitized Copy When a Log Field Cannot Be Replaced

* fix: Treat a Failed Key Removal as a Failed Replacement and Guard Stack Writes

* fix: Skip Heavy Error Graphs and Accept Escaped Backslashes in Serialized Locals

* fix: Accept Lone Escaped Backslashes in Serialized Locals Without Rescans

* fix: Compact Axios Request Info Before Redaction and Skip Heavy Splat Error Graphs

* fix: Redact Address Keys on Nested Error Objects

* fix: Materialize and Redact Enumerable Getters on Nested Errors

* fix: Guard Throwing Top-Level Getters and Skip Heavy Fields Only on Error Records

* fix: Skip Serialized Quotes When Trimming an Unfinished Address

* fix: Bound Redaction With a Per-Record Node Budget and Accept JSON Control Escapes

* fix: Match Credential URIs From the Separator So Scheme Length Is Unbounded

* fix: Count Strings Against the Redaction Budget and Guard Nested Getters

* fix: Rebuild the Log Record When a Top-Level Accessor Ignores Writes

* fix: Rebuild the Log Record When a Stack Accessor Ignores Writes

* fix: Guard the Initial Stack Read on Direct Error Logs

* fix: Accept Escaped Solidus and Preserve the Outer Budget on Reentrant Logging

* fix: Guard the Axios Marker and Error-Like Probes Against Throwing Getters

* fix: Guard the Axios Marker on Nested Errors

* fix: Replace Skipped Heavy Fields Up Front, Budget Top-Level Fields and Mask Encoded Emails

* fix: Mask Encoded Address Keys and Guard Nested Axios Config Compaction

* fix: Redact URL Objects in Compact Request Info

* fix: Remove Encoded Email Caps and Strip Serializer Hooks From Clones

* fix: Strip Serializer Hooks From Error Clones and Top-Level Records

* fix: Neutralize Inherited Serializer Hooks on Log Records

* fix: Guard the Serializer Hook Probe

* fix: Replace Function Values in Log Records

* fix: Mask Percent-Encoded Domain Separators in Logged URLs

* fix: Bound the Encoded Email Domain at URL Delimiters

* fix: Shadow Throwing Serializer Getters on Nested Errors

* fix: Rebuild Accessor Messages and Mask Doubly Encoded Addresses

* fix: Redact Multiply Encoded Address Keys

* feat: Make the Log Redaction Node Budget Configurable

* fix: Guard Message and Serializer Property Reads

* fix: Contain Proxy Failures and Redact the Compact Request Method
2026-10-15 15:54:27 +02:00

296 lines
7.7 KiB
TypeScript

import { normalizeOpenIdIssuer } from '~/auth/openid';
/**
* Auth-boundary identity helpers for token/cache scoping.
* Do not use these as a blanket replacement for app ownership checks, and keep
* tenant/issuer data out of placeholder-visible safe user fields.
*/
type StringableId = string | number | { toString(): string };
export type AuthIdentitySource = {
id?: string | null;
_id?: StringableId | null;
openidId?: string | null;
openidIssuer?: string | null;
tenantId?: string | null;
};
export type AuthIdentityContext = {
appUserId?: string;
openidSubject?: string;
tenantId?: string;
openidIssuer?: string;
};
export type AuthIdentityTuple = {
tenantId: string;
openidIssuer: string;
subject: string;
};
export type RefreshTokenBridgeIdentity = {
userId: string;
tenantId?: string;
openidIssuer?: string;
};
export type OpenIDSessionIdentitySource = {
appUserId?: string | null;
openidSubject?: string | null;
tenantId?: string | null;
openidIssuer?: string | null;
};
const NO_TENANT = 'no-tenant';
const NO_ISSUER = 'no-issuer';
const IDENTITY_PART_SEPARATOR = '\x1f';
function normalizeIdentityValue(value: string | null | undefined): string | undefined {
const normalized = value?.trim();
return normalized ? normalized : undefined;
}
function stringifyId(value: StringableId | null | undefined): string | undefined {
if (value == null) {
return undefined;
}
const id =
typeof value === 'string' || typeof value === 'number' ? String(value) : value.toString();
return normalizeIdentityValue(id);
}
export function resolveAppUserId(
...sources: Array<AuthIdentitySource | null | undefined>
): string | undefined {
for (const source of sources) {
const id = stringifyId(source?._id) ?? normalizeIdentityValue(source?.id);
if (id) {
return id;
}
}
return undefined;
}
export function resolveOpenIDSubject(
source: AuthIdentitySource | null | undefined,
): string | undefined {
return normalizeIdentityValue(source?.openidId);
}
export function resolveRefreshSubject(
...sources: Array<AuthIdentitySource | null | undefined>
): string | undefined {
for (const source of sources) {
const subject = resolveOpenIDSubject(source) ?? resolveAppUserId(source);
if (subject) {
return subject;
}
}
return undefined;
}
export function resolveTenantId({
tenantId,
user,
requestUser,
}: {
tenantId?: string | null;
user?: AuthIdentitySource | null;
requestUser?: AuthIdentitySource | null;
}): string | undefined {
return (
normalizeIdentityValue(tenantId) ??
normalizeIdentityValue(user?.tenantId) ??
normalizeIdentityValue(requestUser?.tenantId)
);
}
export function resolveAuthOpenIDIssuer({
openidIssuer,
user,
requestUser,
}: {
openidIssuer?: string | null;
user?: AuthIdentitySource | null;
requestUser?: AuthIdentitySource | null;
}): string | undefined {
return (
normalizeOpenIdIssuer(openidIssuer ?? undefined) ??
normalizeOpenIdIssuer(user?.openidIssuer ?? undefined) ??
normalizeOpenIdIssuer(requestUser?.openidIssuer ?? undefined)
);
}
export function createAuthIdentityContext({
user,
requestUser,
tenantId,
openidIssuer,
}: {
user?: AuthIdentitySource | null;
requestUser?: AuthIdentitySource | null;
tenantId?: string | null;
openidIssuer?: string | null;
}): AuthIdentityContext {
return {
appUserId: resolveAppUserId(user, requestUser),
openidSubject: resolveOpenIDSubject(user) ?? resolveOpenIDSubject(requestUser),
tenantId: resolveTenantId({ tenantId, user, requestUser }),
openidIssuer: resolveAuthOpenIDIssuer({ openidIssuer, user, requestUser }),
};
}
export function createOpenIDSessionIdentity({
user,
requestUser,
userId,
openidSubject,
tenantId,
openidIssuer,
}: {
user?: AuthIdentitySource | null;
requestUser?: AuthIdentitySource | null;
userId?: string | null;
openidSubject?: string | null;
tenantId?: string | null;
openidIssuer?: string | null;
}): AuthIdentityContext {
return createAuthIdentityContext({
user: {
id: userId,
openidId: openidSubject,
tenantId,
openidIssuer,
},
requestUser: user ?? requestUser,
tenantId,
openidIssuer,
});
}
function normalizeOpenIDSessionIdentity(
identity: OpenIDSessionIdentitySource | null | undefined,
): AuthIdentityContext | null {
const appUserId = normalizeIdentityValue(identity?.appUserId);
const openidSubject = normalizeIdentityValue(identity?.openidSubject);
if (!appUserId || !openidSubject) {
return null;
}
return {
appUserId,
openidSubject,
tenantId: normalizeIdentityValue(identity?.tenantId),
openidIssuer: normalizeOpenIdIssuer(identity?.openidIssuer ?? undefined),
};
}
export function isOpenIDSessionIdentityMatch(
sessionIdentity: OpenIDSessionIdentitySource | null | undefined,
expectedIdentity: OpenIDSessionIdentitySource | null | undefined,
): boolean {
const session = normalizeOpenIDSessionIdentity(sessionIdentity);
const expected = normalizeOpenIDSessionIdentity(expectedIdentity);
return (
session != null &&
expected != null &&
session.appUserId === expected.appUserId &&
session.openidSubject === expected.openidSubject &&
session.tenantId === expected.tenantId &&
session.openidIssuer === expected.openidIssuer
);
}
export function createRefreshTokenBridgeIdentity({
user,
requestUser,
userId,
tenantId,
openidIssuer,
}: {
user?: AuthIdentitySource | null;
requestUser?: AuthIdentitySource | null;
userId?: string | null;
tenantId?: string | null;
openidIssuer?: string | null;
}): RefreshTokenBridgeIdentity | null {
const appUserId = normalizeIdentityValue(userId) ?? resolveAppUserId(user, requestUser);
if (!appUserId) {
return null;
}
return {
userId: appUserId,
tenantId: resolveTenantId({ tenantId, user, requestUser }),
openidIssuer: resolveAuthOpenIDIssuer({ openidIssuer, user, requestUser }),
};
}
export function createOpenIDRefreshIdentityTuple({
user,
requestUser,
tenantId,
openidIssuer,
}: {
user?: AuthIdentitySource | null;
requestUser?: AuthIdentitySource | null;
tenantId?: string | null;
openidIssuer?: string | null;
}): AuthIdentityTuple | null {
const subject = resolveRefreshSubject(user, requestUser);
if (!subject) {
return null;
}
return {
subject,
tenantId: resolveTenantId({ tenantId, user, requestUser }) ?? NO_TENANT,
openidIssuer: resolveAuthOpenIDIssuer({ openidIssuer, user, requestUser }) ?? NO_ISSUER,
};
}
export function createOpenIDOboIdentityTuple({
user,
identityContext,
tenantId,
openidIssuer,
}: {
user?: AuthIdentitySource | null;
identityContext?: AuthIdentityContext | null;
tenantId?: string | null;
openidIssuer?: string | null;
}): AuthIdentityTuple | null {
const subject =
normalizeIdentityValue(identityContext?.openidSubject) ?? resolveOpenIDSubject(user);
if (!subject) {
return null;
}
return {
subject,
tenantId:
normalizeIdentityValue(tenantId) ??
normalizeIdentityValue(identityContext?.tenantId) ??
normalizeIdentityValue(user?.tenantId) ??
NO_TENANT,
openidIssuer:
normalizeOpenIdIssuer(openidIssuer ?? undefined) ??
normalizeOpenIdIssuer(identityContext?.openidIssuer) ??
normalizeOpenIdIssuer(user?.openidIssuer ?? undefined) ??
NO_ISSUER,
};
}
export function serializeAuthIdentityTuple(tuple: AuthIdentityTuple): string {
return [tuple.tenantId, tuple.openidIssuer, tuple.subject].join(IDENTITY_PART_SEPARATOR);
}
/** Internal user id for log lines, never an email, name or provider subject. */
export function getUserLogId(user?: Pick<AuthIdentitySource, 'id' | '_id'> | null): string {
const id = user?._id ?? user?.id;
return id == null ? 'unknown' : String(id);
}