Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🔒 security: replace KEY_VAULTS_SECRET with JWT signing for async router auth

YuTengjing7a532eee92ff
diff --git a/docs/self-hosting/advanced/desktop.mdx b/docs/self-hosting/advanced/desktop.mdx
index cb99898f807..f05b8bc23bd 100644
--- a/docs/self-hosting/advanced/desktop.mdx
+++ b/docs/self-hosting/advanced/desktop.mdx
@@ -44,12 +44,14 @@ Before connecting the desktop to your self-hosted instance, ensure that your sel
#### OIDC Environment Variable Configuration
-You need to add the following two environment variables, `ENABLE_OIDC` and `OIDC_JWKS_KEY`, to your self-hosted instance. You can click the button below to generate them with one click:
+You need to add the following two environment variables, `ENABLE_OIDC` and `JWKS_KEY`, to your self-hosted instance. You can click the button below to generate them with one click:
<OIDCJWKs />
Add the generated JWK key to your environment variables.
+<Callout>If you have already configured `OIDC_JWKS_KEY`, no changes are needed. The system will automatically fall back to `OIDC_JWKS_KEY` for backward compatibility.</Callout>
+
If you are deploying LobeChat using one-click deployment methods (such as Vercel, Railway, etc.), you need to:
1. Add the above environment variables to the environment variable configuration of your deployment platform.
@@ -71,8 +73,8 @@ If you are deploying LobeChat using one-click deployment methods (such as Vercel
**Solution:**
-- Confirm that you have correctly set the `ENABLE_OIDC=1` and `OIDC_JWKS_KEY` environment variables.
-- Ensure that `OIDC_JWKS_KEY` is in valid JSON format without extra single quotes.
+- Confirm that you have correctly set the `ENABLE_OIDC=1` and `JWKS_KEY` environment variables.
+- Ensure that `JWKS_KEY` is in valid JSON format without extra single quotes.
- Check your server logs for specific error messages.
If you are using Nginx as a reverse proxy, the issue may be due to oversized request headers. You can try adding the following settings to your Nginx configuration:
diff --git a/docs/self-hosting/advanced/desktop.zh-CN.mdx b/docs/self-hosting/advanced/desktop.zh-CN.mdx
index 5028b492e9b..34aa3c62474 100644
--- a/docs/self-hosting/advanced/desktop.zh-CN.mdx
+++ b/docs/self-hosting/advanced/desktop.zh-CN.mdx
@@ -42,12 +42,14 @@ LobeChat 桌面端可以与您自托管的 LobeChat 实例连接,以便您可
#### OIDC 环境变量配置
-您需要在自托管实例中添加以下`ENABLE_OIDC` 和 `OIDC_JWKS_KEY` 这两个环境变量,你可以点击下方按钮一键生成:
+您需要在自托管实例中添加以下`ENABLE_OIDC` 和 `JWKS_KEY` 这两个环境变量,你可以点击下方按钮一键生成:
<OIDCJWKs />
将生成的 JWK 密钥添加到您的环境变量中。
+<Callout>如果您之前已配置 `OIDC_JWKS_KEY`,无需修改。系统会自动回退使用 `OIDC_JWKS_KEY`(向后兼容)。</Callout>
+
如果您使用一键部署方式(如 Vercel、Railway 等平台)部署 LobeChat,您需要:
1. 将上述环境变量添加到部署平台的环境变量配置中
@@ -69,8 +71,8 @@ LobeChat 桌面端可以与您自托管的 LobeChat 实例连接,以便您可
**解决方案:**
-- 确认您已经正确设置了 `ENABLE_OIDC=1` 和 `OIDC_JWKS_KEY` 环境变量
-- 确保 `OIDC_JWKS_KEY` 是有效的 JSON 格式,没有额外的单引号
+- 确认您已经正确设置了 `ENABLE_OIDC=1` 和 `JWKS_KEY` 环境变量
+- 确保 `JWKS_KEY` 是有效的 JSON 格式,没有额外的单引号
- 检查您的服务端日志,查看具体错误信息
如果您使用 Nginx 作为反向代理,可能是请求头太大导致的问题。可以尝试在 Nginx 配置中添加以下设置:
diff --git a/docs/self-hosting/environment-variables/auth.mdx b/docs/self-hosting/environment-variables/auth.mdx
index 1267e66322a..c5fa2ea0718 100644
--- a/docs/self-hosting/environment-variables/auth.mdx
+++ b/docs/self-hosting/environment-variables/auth.mdx
@@ -55,6 +55,14 @@ LobeChat provides a complete authentication service capability when deployed. Th
- Default: `-`
- Example: `google,github,microsoft,cognito`
+#### `JWKS_KEY`
+
+- Type: Required
+- Description: Generic JWKS (JSON Web Key Set) key for signing and verifying JWTs. Used for internal service authentication and other cryptographic operations. Must be a JWKS JSON string containing an RS256 RSA key pair. Falls back to `OIDC_JWKS_KEY` if not set (for backward compatibility).
+- Default: `-`
+
+<OIDCJWKs />
+
### Email Service (SMTP)
These settings are required for email verification and password reset features.
diff --git a/docs/self-hosting/environment-variables/auth.zh-CN.mdx b/docs/self-hosting/environment-variables/auth.zh-CN.mdx
index a0918726b66..822a28abf14 100644
--- a/docs/self-hosting/environment-variables/auth.zh-CN.mdx
+++ b/docs/self-hosting/environment-variables/auth.zh-CN.mdx
@@ -53,6 +53,14 @@ LobeChat 在部署时提供了完善的身份验证服务能力,以下是相
- 默认值:`-`
- 示例:`google,github,microsoft,cognito`
+#### `JWKS_KEY`
+
+- 类型:必选
+- 描述:用于签名和验证 JWT 的通用 JWKS(JSON Web Key Set)密钥。用于内部服务认证和其他加密操作。必须是包含 RS256 RSA 密钥对的 JWKS JSON 字符串。如果未设置,将回退到 `OIDC_JWKS_KEY`(向后兼容)。
+- 默认值:`-`
+
+<OIDCJWKs />
+
### 邮件服务(SMTP)
启用邮箱验证和密码重置功能需要配置以下设置。
diff --git a/src/envs/auth.ts b/src/envs/auth.ts
index 1745b3cd1e1..80651b6ba7b 100644
--- a/src/envs/auth.ts
+++ b/src/envs/auth.ts
@@ -149,6 +149,15 @@ declare global {
ZITADEL_CLIENT_ID?: string;
ZITADEL_CLIENT_SECRET?: string;
ZITADEL_ISSUER?: string;
+
+ // ===== JWKS Key ===== //
+ /**
+ * Generic JWKS key for signing/verifying JWTs.
+ * Used for internal service authentication and other cryptographic operations.
+ * Must be a JWKS JSON string containing an RS256 RSA key pair.
+ * Can be generated using `node scripts/generate-oidc-jwk.mjs`.
+ */
+ JWKS_KEY?: string;
}
}
}
@@ -272,6 +281,9 @@ export const getAuthConfig = () => {
// Casdoor
CASDOOR_WEBHOOK_SECRET: z.string().optional(),
+
+ // Generic JWKS key for signing/verifying JWTs
+ JWKS_KEY: z.string().optional(),
},
runtimeEnv: {
@@ -392,6 +404,9 @@ export const getAuthConfig = () => {
// Casdoor
CASDOOR_WEBHOOK_SECRET: process.env.CASDOOR_WEBHOOK_SECRET,
+
+ // Generic JWKS key (fallback to OIDC_JWKS_KEY for backward compatibility)
+ JWKS_KEY: process.env.JWKS_KEY || process.env.OIDC_JWKS_KEY,
},
});
};
diff --git a/src/libs/oidc-provider/jwt.ts b/src/libs/oidc-provider/jwt.ts
index 7a62ef94dbc..e96628e25cf 100644
--- a/src/libs/oidc-provider/jwt.ts
+++ b/src/libs/oidc-provider/jwt.ts
@@ -1,21 +1,29 @@
import { TRPCError } from '@trpc/server';
import debug from 'debug';
-import { oidcEnv } from '@/envs/oidc';
+import { authEnv } from '@/envs/auth';
const log = debug('oidc-jwt');
+/**
+ * Get JWKS key string from environment
+ * Uses JWKS_KEY which already has fallback to OIDC_JWKS_KEY in authEnv
+ */
+const getJwksKeyString = () => {
+ return authEnv.JWKS_KEY;
+};
+
/**
* 从环境变量中获取 JWKS
* 该 JWKS 是一个包含 RS256 私钥的 JSON 对象
*/
export const getJWKS = (): object => {
try {
- const jwksString = oidcEnv.OIDC_JWKS_KEY;
+ const jwksString = getJwksKeyString();
if (!jwksString) {
throw new Error(
- 'OIDC_JWKS_KEY 环境变量是必需的。请使用 scripts/generate-oidc-jwk.mjs 生成 JWKS。',
+ 'JWKS_KEY 环境变量是必需的。请使用 scripts/generate-oidc-jwk.mjs 生成 JWKS。',
);
}
@@ -36,16 +44,16 @@ export const getJWKS = (): object => {
return jwks;
} catch (error) {
console.error('解析 JWKS 失败:', error);
- throw new Error(`OIDC_JWKS_KEY 解析错误: ${(error as Error).message}`);
+ throw new Error(`JWKS_KEY 解析错误: ${(error as Error).message}`);
}
};
const getVerificationKey = async () => {
try {
- const jwksString = oidcEnv.OIDC_JWKS_KEY;
+ const jwksString = getJwksKeyString();
if (!jwksString) {
- throw new Error('OIDC_JWKS_KEY 环境变量未设置');
+ throw new Error('JWKS_KEY 环境变量未设置');
}
const jwks = JSON.parse(jwksString);
@@ -81,7 +89,7 @@ const getVerificationKey = async () => {
return await importJWK(publicKeyJwk, 'RS256');
} catch (error) {
log('获取 JWKS 公钥失败: %O', error);
- throw new Error(`JWKS 公key获取失败: ${(error as Error).message}`);
+ throw new Error(`JWKS_KEY 公钥获取失败: ${(error as Error).message}`);
}
};
diff --git a/src/libs/trpc/async/asyncAuth.ts b/src/libs/trpc/async/asyncAuth.ts
index e6e325c0e52..ff33456c040 100644
--- a/src/libs/trpc/async/asyncAuth.ts
+++ b/src/libs/trpc/async/asyncAuth.ts
@@ -2,7 +2,6 @@ import { type LobeChatDatabase } from '@lobechat/database';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
-import { serverDBEnv } from '@/config/db';
import { UserModel } from '@/database/models/user';
import { asyncTrpc } from './init';
@@ -13,11 +12,9 @@ export const asyncAuth = asyncTrpc.middleware(async (opts) => {
const { ctx } = opts;
log('Async auth middleware called for userId: %s', ctx.userId);
- log('Secret validation: %s', ctx.secret === serverDBEnv.KEY_VAULTS_SECRET);
- if (ctx.secret !== serverDBEnv.KEY_VAULTS_SECRET || !ctx.userId) {
- log('Async auth failed - invalid secret or missing userId');
- log('Has secret: %s, Has userId: %s', !!ctx.secret, !!ctx.userId);
+ if (!ctx.userId) {
+ log('Async auth failed - missing userId');
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
diff --git a/src/libs/trpc/async/context.ts b/src/libs/trpc/async/context.ts
index 317c4a01d29..6f9d846c10d 100644
--- a/src/libs/trpc/async/context.ts
+++ b/src/libs/trpc/async/context.ts
@@ -4,13 +4,13 @@ import debug from 'debug';
import { type NextRequest } from 'next/server';
import { LOBE_CHAT_AUTH_HEADER } from '@/const/auth';
+import { validateInternalJWT } from '@/libs/trpc/utils/internalJwt';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
const log = debug('lobe-async:context');
export interface AsyncAuthContext {
jwtPayload: ClientSecretPayload;
- secret: string;
serverDB?: LobeChatDatabase;
userId?: string | null;
}
@@ -21,11 +21,9 @@ export interface AsyncAuthContext {
*/
export const createAsyncContextInner = async (params?: {
jwtPayload?: ClientSecretPayload;
- secret?: string;
userId?: string | null;
}): Promise<AsyncAuthContext> => ({
jwtPayload: params?.jwtPayload || {},
- secret: params?.secret || '',
userId: params?.userId,
});
@@ -52,8 +50,14 @@ export const createAsyncRouteContext = async (request: NextRequest): Promise<Asy
throw new Error('No LobeChat authorization header found');
}
- const secret = authorization?.split(' ')[1];
- log('Secret extracted from authorization header: %s', !!secret);
+ // Validate JWT token to verify request is from lambda
+ log('Validating internal JWT token');
+ const isValid = await validateInternalJWT(authorization);
+ if (!isValid) {
+ log('JWT validation failed');
+ throw new Error('Invalid JWT token');
+ }
+ log('JWT validation successful');
try {
log('Initializing KeyVaultsGateKeeper');
@@ -71,7 +75,7 @@ export const createAsyncRouteContext = async (request: NextRequest): Promise<Asy
Object.keys(payload || {}),
);
- return createAsyncContextInner({ jwtPayload: payload, secret, userId });
+ return createAsyncContextInner({ jwtPayload: payload, userId });
} catch (error) {
log('Error creating async route context: %O', error);
throw error;
diff --git a/src/libs/trpc/utils/internalJwt.ts b/src/libs/trpc/utils/internalJwt.ts
new file mode 100644
index 00000000000..c562f52923d
--- /dev/null
+++ b/src/libs/trpc/utils/internalJwt.ts
@@ -0,0 +1,108 @@
+import debug from 'debug';
+import { SignJWT, importJWK, jwtVerify } from 'jose';
+
+import { authEnv } from '@/envs/auth';
+
+const log = debug('lobe-internal-jwt');
+
+const INTERNAL_JWT_PURPOSE = 'lobe-internal-call';
+
+/**
+ * Get RSA key pair from JWKS_KEY environment variable
+ */
+const getJwksKey = () => {
+ const jwksString = authEnv.JWKS_KEY;
+
+ if (!jwksString) {
+ throw new Error('JWKS_KEY environment variable is not set');
+ }
+
+ const jwks = JSON.parse(jwksString);
+ const rsaKey = jwks.keys.find((key: any) => key.alg === 'RS256' && key.kty === 'RSA');
+
+ if (!rsaKey) {
+ throw new Error('No RS256 RSA key found in JWKS');
+ }
+
+ return rsaKey;
+};
+
+/**
+ * Get RSA private key for signing
+ */
+const getSigningKey = async () => {
+ const rsaKey = getJwksKey();
+
+ return {
+ key: await importJWK(rsaKey, 'RS256'),
+ kid: rsaKey.kid as string,
+ };
+};
+
+/**
+ * Get RSA public key for verification
+ */
+const getVerificationKey = async () => {
+ const privateRsaKey = getJwksKey();
+
+ // Create a "clean" JWK object containing only public key components
+ // The essential fields for RSA public key are: kty, n, e
+ const publicKeyJwk = {
+ alg: privateRsaKey.alg,
+ e: privateRsaKey.e,
+ kid: privateRsaKey.kid,
+ kty: privateRsaKey.kty,
+ n: privateRsaKey.n,
+ use: privateRsaKey.use,
+ };
+
+ // Remove any undefined fields to keep the object clean
+ Object.keys(publicKeyJwk).forEach(
+ (key) => (publicKeyJwk as any)[key] === undefined && delete (publicKeyJwk as any)[key],
+ );
+
+ return await importJWK(publicKeyJwk, 'RS256');
+};
+
+/**
+ * Sign JWT for internal lambda → async calls
+ * Uses JWKS private key with short expiration (3s)
+ * The JWT only proves the request is from lambda, payload is sent via LOBE_CHAT_AUTH_HEADER
+ */
+export const signInternalJWT = async (): Promise<string> => {
+ const { key, kid } = await getSigningKey();
+
+ return new SignJWT({ purpose: INTERNAL_JWT_PURPOSE })
+ .setProtectedHeader({ alg: 'RS256', kid })
+ .setIssuedAt()
+ .setExpirationTime('3s')
+ .sign(key);
+};
+
+/**
+ * Validate internal JWT from lambda → async calls
+ * Returns true if valid, false otherwise
+ */
+export const validateInternalJWT = async (token: string): Promise<boolean> => {
+ try {
+ log('Validating internal JWT token');
+
+ const publicKey = await getVerificationKey();
+
+ const { payload } = await jwtVerify(token, publicKey, {
+ algorithms: ['RS256'],
+ });
+
+ // Verify this is an internal call token, not a user's OIDC token
+ if (payload.purpose !== INTERNAL_JWT_PURPOSE) {
+ log('JWT purpose mismatch: expected %s, got %s', INTERNAL_JWT_PURPOSE, payload.purpose);
+ return false;
+ }
+
+ log('Internal JWT validation successful');
+ return true;
+ } catch (error) {
+ log('Internal JWT validation failed: %O', error);
+ return false;
+ }
+};
diff --git a/src/server/routers/async/caller.ts b/src/server/routers/async/caller.ts
index f3012c0c484..9efe98c9481 100644
--- a/src/server/routers/async/caller.ts
+++ b/src/server/routers/async/caller.ts
@@ -3,19 +3,20 @@ import { createTRPCClient, httpLink } from '@trpc/client';
import superjson from 'superjson';
import urlJoin from 'url-join';
-import { serverDBEnv } from '@/config/db';
import { LOBE_CHAT_AUTH_HEADER } from '@/const/auth';
import { appEnv } from '@/envs/app';
import { createAsyncCallerFactory } from '@/libs/trpc/async';
+import { signInternalJWT } from '@/libs/trpc/utils/internalJwt';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import { asyncRouter } from './index';
import type { AsyncRouter } from './index';
export const createAsyncServerClient = async (userId: string, payload: ClientSecretPayload) => {
+ const token = await signInternalJWT();
const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
const headers: Record<string, string> = {
- Authorization: `Bearer ${serverDBEnv.KEY_VAULTS_SECRET}`,
+ Authorization: token,
[LOBE_CHAT_AUTH_HEADER]: await gateKeeper.encrypt(JSON.stringify({ payload, userId })),
};