🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🌐 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.tsindex 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 objectconst url = new URL(req.url);- // 计算相对于前缀的路径+ // Compute path relative to prefixlet 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 propertiesheaders: 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-typeson: (event: string, handler: Function) => {if (event === 'end') {@@ -93,7 +93,7 @@ export const createNodeRequest = async (req: NextRequest): Promise<IncomingMessahandler();}},- // 添加 Node.js 服务器所期望的额外属性+ // Add extra properties expected by the Node.js serversocket: {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 stateconst 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 headersconst parsedUrl = new URL(baseUrl);const hostName = parsedUrl.host;const protocol = parsedUrl.protocol.replace(':', '');- // 1. 获取真实的 Cookies+ // 1. Get real cookiesconst 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 cookieconst 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 cookiesconst 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 interfaceget: (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/:uidconst req: IncomingMessage = await createNodeRequest(mockNextRequest);- // @ts-ignore - 将解析出的 cookies 附加到模拟的 Node.js 请求上+ // @ts-ignore - Attach parsed cookies to the mock Node.js requestreq.cookies = realCookies;log('Node.js IncomingMessage created, attached real cookies');- // 5. 使用 createNodeResponse 创建模拟的 Node.js ServerResponse+ // 5. Use createNodeResponse to create a mock Node.js ServerResponselet 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.tsindex 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 baseconst 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.tsindex 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 stringconst jwks = JSON.parse(jwksString);- // 检查 JWKS 格式是否正确+ // Check if JWKS format is validif (!jwks.keys || !Array.isArray(jwks.keys) || jwks.keys.length === 0) {throw new Error('JWKS 格式无效: 缺少或为空的 keys 数组');}- // 检查是否有 RS256 算法的密钥+ // Check if there is an RS256 algorithm keyconst 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 cleanObject.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 keyconst publicKey = await getVerificationKey();- // 验证 JWT+ // Verify JWTconst { 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 informationconst 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.tsindex 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 JWKSconst jwks = getJWKS();const cookieKeys = getCookieKeys();const configuration: Configuration = {- // 11. 数据库适配器+ // 11. Database adapteradapter: DrizzleAdapter.createAdapterFactory(db),- // 4. Claims 定义+ // 4. Claims definitionclaims: defaultClaims,- // 新增:客户端 CORS 控制逻辑+ // Added: client-based CORS control logicclientBasedCORS(ctx, origin, client) {- // 检查客户端是否允许此来源- // 一个常见的策略是允许所有已注册的 redirect_uris 的来源+ // Check if the client allows this origin+ // A common strategy is to allow origins of all registered redirect_urisif (!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<Providerreturn allowed;},- // 1. 客户端配置+ // 1. Client configurationclients: defaultClients,- // 新增:确保 ID Token 包含所有 scope 对应的 claims,而不仅仅是 openid scope+ // Added: ensure ID Token includes claims for all scopes, not just openid scopeconformIdTokenClaims: false,- // 7. Cookie 配置+ // 7. Cookie configurationcookies: {keys: cookieKeys,long: { path: '/', signed: true },short: { path: '/', signed: true },},- // 5. 特性配置+ // 5. Features configurationfeatures: {backchannelLogout: { enabled: true },clientCredentials: { enabled: false },@@ -100,9 +100,9 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<Providerenabled: true,getResourceServerInfo: (ctx, resourceIndicator) => {- logProvider('getResourceServerInfo called with indicator: %s', resourceIndicator); // <-- 添加这行日志+ logProvider('getResourceServerInfo called with indicator: %s', resourceIndicator); // <-- Add this log lineif (resourceIndicator === API_AUDIENCE) {- logProvider('Indicator matches API_AUDIENCE, returning JWT config.'); // <-- 添加这行日志+ logProvider('Indicator matches API_AUDIENCE, returning JWT config.'); // <-- Add this log linereturn {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 linethrow 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 lookupasync 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 propertyconst 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 idconst 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 availableif (!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 policyinteractions: {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#AuthRequestconst uiLocalesRaw = (interaction.params?.ui_locales || ctx.oidc?.params?.ui_locales) as| string@@ -216,7 +216,7 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<Providerlet query = '';if (uiLocalesRaw) {- // 取第一个优先语言,规范化到站点支持的标签+ // Take the first priority language and normalize it to a site-supported tagconst 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<Providerconst 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 JWKSjwks: jwks as { keys: any[] },- // 2. PKCE 配置+ // 2. PKCE configurationpkce: {required: () => true,},- // 12. 其他配置+ // 12. Other configurationrenderError: 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 rotationrotateRefreshToken: true,routes: {@@ -265,10 +265,10 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<Providerend_session: '/oidc/session/end',token: '/oidc/token',},- // 3. Scopes 定义+ // 3. Scopes definitionscopes: defaultScopes,- // 8. 令牌有效期+ // 8. Token TTLttl: {AccessToken: 7 * 24 * 3600, // 7 daysAuthorizationCode: 600, // 10 minutes@@ -282,7 +282,7 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<Provider},};- // 创建提供者实例+ // Create provider instanceconst baseUrl = urlJoin(appEnv.APP_URL!, '/oidc');const provider = new Provider(baseUrl, configuration);