Security
Relevant source files
The following files were used as context for generating this wiki page:
- apps/desktop/src/main/const/store.ts
- src/libs/oidc-provider/config.ts
- src/middleware/rate-limit.ts
- sentry.server.config.ts
- packages/utils/src/client/sanitize.ts
- apps/desktop/README.md
- src/tools/local-system/systemRole.ts
- CLERK_AUTH_FIX_SUMMARY.md
- FILE_UPLOAD_COMPREHENSIVE_ANALYSIS.md
- src/tools/artifacts/systemRole.ts
LobeChat incorporates a multi-layered security strategy to protect user data, secure communications, and ensure application integrity. The security measures span across authentication, data handling, API access, and platform-specific features for the desktop application. This includes secure authentication flows like OAuth 2.0, encrypted storage for sensitive data, rate-limiting to prevent abuse, and careful handling of file uploads and local system interactions.
The desktop application, built with Electron, has a particular focus on security, leveraging native OS capabilities for encrypted storage and implementing secure protocols for inter-process communication and updates. The overall architecture aims to provide a secure and reliable user experience by default.
Authentication and Authorization
The application employs robust authentication mechanisms to secure user accounts and sessions. This includes integration with third-party providers like Clerk and a configurable OIDC provider.
Sources: apps/desktop/README.md, CLERK_AUTH_FIX_SUMMARY.md, src/libs/oidc-provider/config.ts
OAuth 2.0 with PKCE
For the desktop application, a secure OAuth 2.0 flow with Proof Key for Code Exchange (PKCE) is used. This flow prevents authorization code interception attacks and ensures that only the legitimate application can exchange the authorization code for an access token.
Key features of this flow include:
- State Parameter Validation: To prevent Cross-Site Request Forgery (CSRF) attacks.
- Encrypted Token Storage: Utilizes the operating system's native secure storage where available.
- Custom Protocol Handler: For securely handling OAuth callback URLs.
Sources: apps/desktop/README.md:200-203
The following diagram illustrates the OAuth 2.0 PKCE flow as implemented in the desktop application.
Sources: apps/desktop/README.md:198-203
Clerk Authentication
The web application uses Clerk for authentication. A critical part of the configuration is defining public routes and redirect URLs to ensure users are correctly routed after signing in or signing up. The middleware is configured to distinguish between public routes (like /login, /signup, /sso-callback) and protected routes.
Sources: CLERK_AUTH_FIX_SUMMARY.md:19-25
OIDC Provider Configuration
The application can be configured to use a generic OpenID Connect (OIDC) provider. The configuration allows specifying various security-related parameters.
| Parameter | Type | Description |
|---|---|---|
OIDC_CLIENT_ID | string | The client ID for the OIDC application. |
OIDC_CLIENT_SECRET | string | The client secret for the OIDC application. |
OIDC_ISSUER | string | The issuer URL of the OIDC provider. |
OIDC_TOKEN_ENDPOINT | string | The token endpoint URL. |
OIDC_USERINFO_ENDPOINT | string | The user info endpoint URL. |
OIDC_AUTHORIZATION_SCOPE | string | The scopes to request during authorization. Defaults to openid profile email. |
OIDC_LOGOUT_ENDPOINT_SUPPORTED | boolean | Indicates if the provider supports a logout endpoint. |
Sources: src/libs/oidc-provider/config.ts:4-24
Desktop Application Security
The Electron-based desktop application includes several platform-specific security features to enhance data protection and application integrity.
Sources: apps/desktop/README.md, apps/desktop/src/main/const/store.ts
Encrypted Storage
Sensitive information, such as authentication tokens, is stored using Electron's safeStorage API when available. This encrypts data at rest using native OS-level encryption. For the desktop application, specific configuration keys are designated for encryption.
The following keys are explicitly marked for encryption:
settings.passwordsettings.languageModel.openrouter.apiKeysettings.languageModel.bedrock.accessKeyIdsettings.languageModel.bedrock.secretAccessKeysettings.languageModel.google.apiKeysettings.languageModel.perplexity.apiKeysettings.languageModel.anthropic.apiKeysettings.languageModel.mistral.apiKeysettings.languageModel.openai.apiKeysettings.languageModel.moonshot.apiKeysettings.languageModel.groq.apiKeysettings.languageModel.deepseek.apiKeysettings.languageModel.zhipu.apiKey
Sources: apps/desktop/src/main/const/store.ts:3-17, apps/desktop/README.md:223-225
The diagram below shows how the StoreManager handles encrypted keys.
Other Desktop Security Features
| Feature | Description |
|---|---|
| Code Signing | The macOS application is notarized to enhance security and assure users of its origin. |
| Sandboxing | Electron's sandboxing is used to provide controlled access to system resources. |
| CSP Controls | Content Security Policy is managed to mitigate injection attacks. |
| Request Filtering | Security controls are in place for external web requests and links. |
| Path Validation | File system access is controlled with secure path validation. |
Sources: apps/desktop/README.md:214-221
API and Network Security
Rate Limiting
To prevent abuse and ensure service availability, the application implements rate limiting for API endpoints. This is handled by a middleware that uses the @upstash/ratelimit library with Redis (ioredis).
The middleware identifies users by their IP address or, if available, their userId from the authentication context.
Sources: [src/middleware/rate-limit.ts]
The rate-limiting logic is as follows:
Sources: src/middleware/rate-limit.ts:13-33
S3 CORS Policy
For file uploads, the application generates pre-signed URLs for direct client-side uploads to an S3 bucket. To make this work securely, the S3 bucket must have a Cross-Origin Resource Sharing (CORS) policy configured. This policy explicitly allows PUT requests from the application's domain (https://pho.chat) and development environments. Without this, browsers would block the cross-origin requests as a security precaution.
The required CORS configuration specifies:
AllowedOrigins: e.g.,https://pho.chat,http://localhost:3000AllowedMethods:GET,PUT,POST,DELETE,HEADAllowedHeaders:*ExposeHeaders:ETag,x-amz-version-id
Sources: FILE_UPLOAD_COMPREHENSIVE_ANALYSIS.md:73-87
Data and Tool Security
Input Sanitization
To prevent Cross-Site Scripting (XSS) attacks, user-provided content is sanitized. The application uses the dompurify library to clean HTML strings, removing potentially malicious scripts or tags.
// packages/utils/src/client/sanitize.ts:4-10
import DOMPurify from 'dompurify';
export const sanitize = (dirty: string) => {
// Check if running in a browser environment
if (typeof window === 'undefined') return dirty;
return DOMPurify.sanitize(dirty);
};
This function ensures that any string rendered as HTML is safe. It runs only in the browser environment.
Sources: packages/utils/src/client/sanitize.ts:4-10
Local File System Tool
The application provides a tool for interacting with the user's local file system. To mitigate risks, strict security considerations are defined:
- User Confirmation: Always confirm with the user before performing write operations (e.g.,
writeFile) or moving files. - Path Handling: File paths must be handled carefully to avoid unintended access.
- Scoped Access: The tool should not access files outside the user's designated workspace unless explicitly permitted.
- Formatted Output: All file paths in responses must be wrapped in a
<localFile />tag to ensure they are handled correctly by the client and not interpreted as raw text.
Sources: src/tools/local-system/systemRole.ts:44-52, 55-63
Artifact Generation
When generating artifacts (like code, documents, or diagrams), the assistant is instructed to avoid producing content that would be "highly hazardous to human health or wellbeing if misused." This serves as a content-level security check to prevent the generation of malicious or dangerous artifacts.
Sources: src/tools/artifacts/systemRole.ts:199-201
Error Monitoring
The application is configured to use Sentry for error monitoring. This helps developers quickly identify and respond to security-related issues and other bugs in production. The Sentry SDK is initialized in sentry.server.config.ts, capturing unhandled exceptions and performance data. The configuration includes a tracesSampleRate to control the volume of performance data sent.
Sources: sentry.server.config.ts:3-17