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.

🌐 chore: translate non-English comments to English in src/libs/oidc-provider (#12383)

LobeHub Bote32a2fbad4b0
diff --git a/src/libs/oidc-provider/http-adapter.ts b/src/libs/oidc-provider/http-adapter.ts
index a5e0d15bce0..c89dd00cdec 100644
--- a/src/libs/oidc-provider/http-adapter.ts
+++ b/src/libs/oidc-provider/http-adapter.ts
@@ -10,7 +10,7 @@ import { appEnv } from '@/envs/app';
const log = debug('lobe-oidc:http-adapter');
/**
- * 将 Next.js 请求头转换为标准 Node.js HTTP 头格式
+ * Convert Next.js request headers to standard Node.js HTTP header format
*/
export const convertHeadersToNodeHeaders = (nextHeaders: Headers): Record<string, string> => {
const headers: Record<string, string> = {};
@@ -21,17 +21,17 @@ export const convertHeadersToNodeHeaders = (nextHeaders: Headers): Record<string
};
/**
- * 创建用于 OIDC Provider 的 Node.js HTTP 请求对象
- * @param req Next.js 请求对象
+ * Create a Node.js HTTP request object for OIDC Provider
+ * @param req Next.js request object
*/
export const createNodeRequest = async (req: NextRequest): Promise<IncomingMessage> => {
- // 构建 URL 对象
+ // Build URL object
const url = new URL(req.url);
- // 计算相对于前缀的路径
+ // Compute path relative to prefix
let providerPath = url.pathname;
- // 确保路径始终以/开头
+ // Ensure path always starts with /
if (!providerPath.startsWith('/')) {
providerPath = '/' + providerPath;
}
@@ -81,11 +81,11 @@ export const createNodeRequest = async (req: NextRequest): Promise<IncomingMessa
}
}
const nodeRequest = {
- // 基本属性
+ // Basic properties
headers: convertHeadersToNodeHeaders(req.headers),
method: req.method,
- // 模拟可读流行为 (oidc-provider might not rely on this if body is pre-parsed)
+ // Simulate readable stream behavior (oidc-provider might not rely on this if body is pre-parsed)
// eslint-disable-next-line @typescript-eslint/ban-types
on: (event: string, handler: Function) => {
if (event === 'end') {
@@ -93,7 +93,7 @@ export const createNodeRequest = async (req: NextRequest): Promise<IncomingMessa
handler();
}
},
- // 添加 Node.js 服务器所期望的额外属性
+ // Add extra properties expected by the Node.js server
socket: {
remoteAddress: req.headers.get('x-forwarded-for') || '127.0.0.1',
},
@@ -110,7 +110,7 @@ export const createNodeRequest = async (req: NextRequest): Promise<IncomingMessa
};
/**
- * 响应收集器接口,用于捕获 OIDC Provider 的响应
+ * Response collector interface for capturing OIDC Provider responses
*/
export interface ResponseCollector {
nodeResponse: ServerResponse;
@@ -120,13 +120,13 @@ export interface ResponseCollector {
}
/**
- * 创建用于 OIDC Provider 的 Node.js HTTP 响应对象
- * @param resolvePromise 当响应完成时调用的解析函数
+ * Create a Node.js HTTP response object for OIDC Provider
+ * @param resolvePromise Resolution function called when the response completes
*/
export const createNodeResponse = (resolvePromise: () => void): ResponseCollector => {
log('Creating Node.js response collector');
- // 存储响应状态的对象
+ // Object to store response state
const state = {
responseBody: '' as string | Buffer,
responseHeaders: {} as Record<string, string | string[]>,
@@ -226,8 +226,8 @@ export const createNodeResponse = (resolvePromise: () => void): ResponseCollecto
};
/**
- * 创建用于调用 provider.interactionDetails 的上下文 (req, res)
- * @param uid 交互 ID
+ * Create context (req, res) for calling provider.interactionDetails
+ * @param uid Interaction ID
*/
export const createContextForInteractionDetails = async (
uid: string,
@@ -236,12 +236,12 @@ export const createContextForInteractionDetails = async (
const baseUrl = appEnv.APP_URL!;
log('Using base URL: %s', baseUrl);
- // 从baseUrl提取主机名和协议用于headers
+ // Extract hostname and protocol from baseUrl for headers
const parsedUrl = new URL(baseUrl);
const hostName = parsedUrl.host;
const protocol = parsedUrl.protocol.replace(':', '');
- // 1. 获取真实的 Cookies
+ // 1. Get real cookies
const cookieStore = await cookies();
const realCookies: Record<string, string> = {};
cookieStore.getAll().forEach((cookie) => {
@@ -249,7 +249,7 @@ export const createContextForInteractionDetails = async (
});
log('Real cookies found: %o', Object.keys(realCookies));
- // 特别检查交互会话cookie
+ // Specifically check for interaction session cookie
const interactionCookieName = `_interaction_${uid}`;
if (realCookies[interactionCookieName]) {
log('Found interaction session cookie: %s', interactionCookieName);
@@ -257,7 +257,7 @@ export const createContextForInteractionDetails = async (
log('Warning: Interaction session cookie not found: %s', interactionCookieName);
}
- // 2. 构建包含真实 Cookie 的 Headers
+ // 2. Build headers containing real cookies
const headers = new Headers({
'host': hostName,
'x-forwarded-host': hostName,
@@ -273,15 +273,15 @@ export const createContextForInteractionDetails = async (
log('No cookies found to set in header');
}
- // 3. 创建模拟的 NextRequest
- // 注意:这里的 IP, geo, ua 等信息可能是 oidc-provider 某些特性需要的,
- // 如果遇到相关问题,可能需要从真实请求头中提取 (e.g., 'x-forwarded-for', 'user-agent')
+ // 3. Create mock NextRequest
+ // Note: IP, geo, ua and other fields here may be required by certain oidc-provider features.
+ // If related issues arise, they may need to be extracted from real request headers (e.g., 'x-forwarded-for', 'user-agent')
const interactionUrl = urlJoin(baseUrl, `/oauth/consent/${uid}`);
log('Creating interaction URL: %s', interactionUrl);
const mockNextRequest = {
cookies: {
- // 模拟 NextRequestCookies 接口
+ // Simulate NextRequestCookies interface
get: (name: string) => cookieStore.get(name)?.value,
getAll: () => cookieStore.getAll(),
has: (name: string) => cookieStore.has(name),
@@ -297,14 +297,14 @@ export const createContextForInteractionDetails = async (
} as unknown as NextRequest;
log('Mock NextRequest created for url: %s', mockNextRequest.url);
- // 4. 使用 createNodeRequest 创建模拟的 Node.js IncomingMessage
- // pathPrefix 设置为 '/' 因为我们的 URL 已经是 Provider 期望的路径格式 /interaction/:uid
+ // 4. Use createNodeRequest to create a mock Node.js IncomingMessage
+ // pathPrefix is set to '/' because our URL is already in the path format expected by the Provider: /interaction/:uid
const req: IncomingMessage = await createNodeRequest(mockNextRequest);
- // @ts-ignore - 将解析出的 cookies 附加到模拟的 Node.js 请求上
+ // @ts-ignore - Attach parsed cookies to the mock Node.js request
req.cookies = realCookies;
log('Node.js IncomingMessage created, attached real cookies');
- // 5. 使用 createNodeResponse 创建模拟的 Node.js ServerResponse
+ // 5. Use createNodeResponse to create a mock Node.js ServerResponse
let resolveFunc: () => void;
new Promise<void>((resolve) => {
resolveFunc = resolve;
diff --git a/src/libs/oidc-provider/interaction-policy.ts b/src/libs/oidc-provider/interaction-policy.ts
index 641c7acb140..8e312c18d1f 100644
--- a/src/libs/oidc-provider/interaction-policy.ts
+++ b/src/libs/oidc-provider/interaction-policy.ts
@@ -5,7 +5,7 @@ const { base } = interactionPolicy; // Import Check and base
const log = debug('lobe-oidc:interaction-policy');
/**
- * 创建自定义交互策略
+ * Create custom interaction policy
*/
export const createInteractionPolicy = () => {
log('Creating custom interaction policy');
diff --git a/src/libs/oidc-provider/jwt.ts b/src/libs/oidc-provider/jwt.ts
index e96628e25cf..ae3ef719e47 100644
--- a/src/libs/oidc-provider/jwt.ts
+++ b/src/libs/oidc-provider/jwt.ts
@@ -14,8 +14,8 @@ const getJwksKeyString = () => {
};
/**
- * 从环境变量中获取 JWKS
- * 该 JWKS 是一个包含 RS256 私钥的 JSON 对象
+ * Get JWKS from environment variables
+ * This JWKS is a JSON object containing RS256 private keys
*/
export const getJWKS = (): object => {
try {
@@ -27,15 +27,15 @@ export const getJWKS = (): object => {
);
}
- // 尝试解析 JWKS JSON 字符串
+ // Attempt to parse JWKS JSON string
const jwks = JSON.parse(jwksString);
- // 检查 JWKS 格式是否正确
+ // Check if JWKS format is valid
if (!jwks.keys || !Array.isArray(jwks.keys) || jwks.keys.length === 0) {
throw new Error('JWKS 格式无效: 缺少或为空的 keys 数组');
}
- // 检查是否有 RS256 算法的密钥
+ // Check if there is an RS256 algorithm key
const hasRS256Key = jwks.keys.some((key: any) => key.alg === 'RS256' && key.kty === 'RSA');
if (!hasRS256Key) {
throw new Error('JWKS 中没有找到 RS256 算法的 RSA 密钥');
@@ -67,8 +67,8 @@ const getVerificationKey = async () => {
throw new Error('JWKS 中没有找到 RS256 算法的 RSA 密钥');
}
- // 创建一个只包含公钥组件的“纯净”JWK对象。
- // RSA公钥的关键字段是 kty, n, e。其他如 kid, alg, use 也是公共的。
+ // Create a “clean” JWK object containing only public key components.
+ // The key fields of an RSA public key are kty, n, e. Others like kid, alg, use are also public.
const publicKeyJwk = {
alg: privateRsaKey.alg,
e: privateRsaKey.e,
@@ -78,14 +78,14 @@ const getVerificationKey = async () => {
use: privateRsaKey.use,
};
- // 移除任何可能存在的 undefined 字段,保持对象干净
+ // Remove any undefined fields to keep the object clean
Object.keys(publicKeyJwk).forEach(
(key) => (publicKeyJwk as any)[key] === undefined && delete (publicKeyJwk as any)[key],
);
const { importJWK } = await import('jose');
- // 现在,无论在哪个环境下,`importJWK` 都会将这个对象正确地识别为一个公钥。
+ // Now, in any environment, `importJWK` will correctly identify this object as a public key.
return await importJWK(publicKeyJwk, 'RS256');
} catch (error) {
log('获取 JWKS 公钥失败: %O', error);
@@ -94,27 +94,27 @@ const getVerificationKey = async () => {
};
/**
- * 验证 OIDC JWT Access Token
+ * Validate OIDC JWT Access Token
* @param token - JWT access token
- * @returns 解析后的 token payload 和用户信息
+ * @returns Parsed token payload and user information
*/
export const validateOIDCJWT = async (token: string) => {
try {
log('开始验证 OIDC JWT token');
- // 获取公钥
+ // Get public key
const publicKey = await getVerificationKey();
- // 验证 JWT
+ // Verify JWT
const { jwtVerify } = await import('jose');
const { payload } = await jwtVerify(token, publicKey, {
algorithms: ['RS256'],
- // 可以添加其他验证选项,如 issuer、audience 等
+ // Additional validation options can be added, such as issuer, audience, etc.
});
log('JWT 验证成功,payload: %O', payload);
- // 提取用户信息
+ // Extract user information
const userId = payload.sub;
const clientId = payload.client_id;
const aud = payload.aud;
diff --git a/src/libs/oidc-provider/provider.ts b/src/libs/oidc-provider/provider.ts
index 7a0de5452f0..2a3390a70a6 100644
--- a/src/libs/oidc-provider/provider.ts
+++ b/src/libs/oidc-provider/provider.ts
@@ -19,7 +19,7 @@ const logProvider = debug('lobe-oidc:provider');
export const API_AUDIENCE = 'urn:lobehub:chat';
/**
- * 获取 Cookie 密钥,使用 KEY_VAULTS_SECRET
+ * Get cookie keys using KEY_VAULTS_SECRET
*/
const getCookieKeys = () => {
const key = serverDBEnv.KEY_VAULTS_SECRET;
@@ -30,38 +30,38 @@ const getCookieKeys = () => {
};
/**
- * 创建 OIDC Provider 实例
- * @param db - 数据库实例
- * @returns 配置好的 OIDC Provider 实例
+ * Create OIDC Provider instance
+ * @param db - Database instance
+ * @returns Configured OIDC Provider instance
*/
export const createOIDCProvider = async (db: LobeChatDatabase): Promise<Provider> => {
- // 获取 JWKS
+ // Get JWKS
const jwks = getJWKS();
const cookieKeys = getCookieKeys();
const configuration: Configuration = {
- // 11. 数据库适配器
+ // 11. Database adapter
adapter: DrizzleAdapter.createAdapterFactory(db),
- // 4. Claims 定义
+ // 4. Claims definition
claims: defaultClaims,
- // 新增:客户端 CORS 控制逻辑
+ // Added: client-based CORS control logic
clientBasedCORS(ctx, origin, client) {
- // 检查客户端是否允许此来源
- // 一个常见的策略是允许所有已注册的 redirect_uris 的来源
+ // Check if the client allows this origin
+ // A common strategy is to allow origins of all registered redirect_uris
if (!client || !client.redirectUris) {
logProvider('clientBasedCORS: No client or redirectUris found, denying origin: %s', origin);
- return false; // 如果没有客户端或重定向URI,则拒绝
+ return false; // Deny if no client or redirect URIs
}
const allowed = client.redirectUris.some((uri) => {
try {
- // 比较来源 (scheme, hostname, port)
+ // Compare origins (scheme, hostname, port)
return new URL(uri).origin === origin;
} catch {
- // 如果 redirect_uri 不是有效的 URL (例如自定义协议),则跳过
+ // Skip if redirect_uri is not a valid URL (e.g. custom protocol)
return false;
}
});
@@ -75,20 +75,20 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<Provider
return allowed;
},
- // 1. 客户端配置
+ // 1. Client configuration
clients: defaultClients,
- // 新增:确保 ID Token 包含所有 scope 对应的 claims,而不仅仅是 openid scope
+ // Added: ensure ID Token includes claims for all scopes, not just openid scope
conformIdTokenClaims: false,
- // 7. Cookie 配置
+ // 7. Cookie configuration
cookies: {
keys: cookieKeys,
long: { path: '/', signed: true },
short: { path: '/', signed: true },
},
- // 5. 特性配置
+ // 5. Features configuration
features: {
backchannelLogout: { enabled: true },
clientCredentials: { enabled: false },
@@ -100,9 +100,9 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<Provider
enabled: true,
getResourceServerInfo: (ctx, resourceIndicator) => {
- logProvider('getResourceServerInfo called with indicator: %s', resourceIndicator); // <-- 添加这行日志
+ logProvider('getResourceServerInfo called with indicator: %s', resourceIndicator); // <-- Add this log line
if (resourceIndicator === API_AUDIENCE) {
- logProvider('Indicator matches API_AUDIENCE, returning JWT config.'); // <-- 添加这行日志
+ logProvider('Indicator matches API_AUDIENCE, returning JWT config.'); // <-- Add this log line
return {
accessTokenFormat: 'jwt',
audience: API_AUDIENCE,
@@ -110,29 +110,29 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<Provider
};
}
- logProvider('Indicator does not match API_AUDIENCE, throwing InvalidTarget.'); // <-- 添加这行日志
+ logProvider('Indicator does not match API_AUDIENCE, throwing InvalidTarget.'); // <-- Add this log line
throw new errors.InvalidTarget();
},
- // 当客户端使用刷新令牌请求新的访问令牌但没有指定资源时,授权服务器会检查原始授权中包含的所有资源,并将这些资源用于新的访问令牌。这提供了一种便捷的方式来维持授权一致性,而不需要客户端在每次刷新时重新指定所有资源
+ // When a client uses a refresh token to request a new access token without specifying a resource, the authorization server checks all resources included in the original authorization and uses them for the new access token. This provides a convenient way to maintain authorization consistency without requiring the client to re-specify all resources on each refresh.
useGrantedResource: () => true,
},
revocation: { enabled: true },
rpInitiatedLogout: { enabled: true },
userinfo: { enabled: true },
},
- // 10. 账户查找
+ // 10. Account lookup
async findAccount(ctx: KoaContextWithOIDC, id: string) {
logProvider('findAccount called for id: %s', id);
- // 检查是否有预先存储的外部账户 ID
- // @ts-ignore - 自定义属性
+ // Check if there is a pre-stored external account ID
+ // @ts-ignore - Custom property
const externalAccountId = ctx.externalAccountId;
if (externalAccountId) {
logProvider('Found externalAccountId in context: %s', externalAccountId);
}
- // 确定要查找的账户 ID
- // 优先级: 1. externalAccountId 2. ctx.oidc.session?.accountId 3. 传入的 id
+ // Determine the account ID to look up
+ // Priority: 1. externalAccountId 2. ctx.oidc.session?.accountId 3. passed-in id
const accountIdToFind = externalAccountId || ctx.oidc?.session?.accountId || id;
const clientId = ctx.oidc?.client?.clientId;
@@ -149,7 +149,7 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<Provider
: 'parameter_id',
);
- // 如果没有可用的 ID,返回 undefined
+ // Return undefined if no account ID is available
if (!accountIdToFind) {
logProvider('findAccount: No account ID available, returning undefined.');
return undefined;
@@ -200,15 +200,15 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<Provider
}
},
- // 9. 交互策略
+ // 9. Interaction policy
interactions: {
policy: createInteractionPolicy(),
url(ctx, interaction) {
- // ---> 添加日志 <---
+ // ---> Add logs <---
logProvider('interactions.url function called');
logProvider('Interaction details: %O', interaction);
- // 读取 OIDC 请求中的 ui_locales 参数(空格分隔的语言优先级)
+ // Read the ui_locales parameter from the OIDC request (space-separated language priorities)
// https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
const uiLocalesRaw = (interaction.params?.ui_locales || ctx.oidc?.params?.ui_locales) as
| string
@@ -216,7 +216,7 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<Provider
let query = '';
if (uiLocalesRaw) {
- // 取第一个优先语言,规范化到站点支持的标签
+ // Take the first priority language and normalize it to a site-supported tag
const first = uiLocalesRaw.split(/[\s,]+/).find(Boolean);
const hl = normalizeLocale(first);
query = `?hl=${encodeURIComponent(hl)}`;
@@ -227,20 +227,20 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<Provider
const interactionUrl = `/oauth/consent/${interaction.uid}${query}`;
logProvider('Generated interaction URL: %s', interactionUrl);
- // ---> 添加日志结束 <---
+ // ---> End of added logs <---
return interactionUrl;
},
},
- // 6. 密钥配置 - 使用 RS256 JWKS
+ // 6. Key configuration - using RS256 JWKS
jwks: jwks as { keys: any[] },
- // 2. PKCE 配置
+ // 2. PKCE configuration
pkce: {
required: () => true,
},
- // 12. 其他配置
+ // 12. Other configuration
renderError: async (ctx, out, error) => {
ctx.type = 'html';
ctx.body = `
@@ -257,7 +257,7 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<Provider
`;
},
- // 新增:启用 Refresh Token 轮换
+ // Added: enable refresh token rotation
rotateRefreshToken: true,
routes: {
@@ -265,10 +265,10 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<Provider
end_session: '/oidc/session/end',
token: '/oidc/token',
},
- // 3. Scopes 定义
+ // 3. Scopes definition
scopes: defaultScopes,
- // 8. 令牌有效期
+ // 8. Token TTL
ttl: {
AccessToken: 7 * 24 * 3600, // 7 days
AuthorizationCode: 600, // 10 minutes
@@ -282,7 +282,7 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<Provider
},
};
- // 创建提供者实例
+ // Create provider instance
const baseUrl = urlJoin(appEnv.APP_URL!, '/oidc');
const provider = new Provider(baseUrl, configuration);