-
-
Notifications
You must be signed in to change notification settings - Fork 13.5k
✨ feat: Implement API Key management functionality #8535
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
- Added new components for API Key management including creation, deletion, and display. - Introduced a new database schema for storing API Keys. - Implemented server and client services for API Key operations. - Integrated API Key management into the profile section with appropriate routing and feature flags. - Enhanced localization support for API Key related UI elements. This commit lays the groundwork for managing API Keys within the application, allowing users to create, view, and manage their keys effectively.
@MarioJames is attempting to deploy a commit to the LobeHub Community Team on Vercel. A member of the Team first needs to authorize it. |
Reviewer's GuideThis PR adds a complete API Key management feature by introducing a new database schema and migration for api_keys, implementing an ApiKeyModel with encrypted CRUD operations, defining service interfaces and client/server implementations, exposing TRPC routes with encryption middleware, providing utility functions for key generation and validation, extending feature flags and translations, and building frontend pages and components for listing, creating, editing, and deleting API keys. Sequence diagram for API Key creation via TRPC routesequenceDiagram
actor User
participant Frontend as Frontend (React)
participant TRPC as TRPC API (apiKeyRouter)
participant Model as ApiKeyModel
participant GateKeeper as KeyVaultsGateKeeper
participant DB as Database
User->>Frontend: Submit create API Key form
Frontend->>TRPC: createApiKey mutation (name, expiresAt)
TRPC->>GateKeeper: encrypt(generatedKey)
TRPC->>Model: create({name, expiresAt}, encryptor)
Model->>DB: INSERT api_keys (encrypted key, name, ...)
DB-->>Model: Inserted record
Model-->>TRPC: Created API Key record
TRPC-->>Frontend: API Key info (without plaintext key)
Frontend-->>User: Show API Key created
Class diagram for API Key model and service structureclassDiagram
class ApiKeyModel {
- userId: string
- db: LobeChatDatabase
+ create(params, encryptor?)
+ delete(id)
+ deleteAll()
+ query(decryptor?)
+ findByKey(key, encryptor?)
+ validateKey(key)
+ update(id, value)
+ findById(id)
+ updateLastUsed(id)
}
class IApiKeyService {
+ create(params)
+ delete(id)
+ deleteAll()
+ getById(id)
+ list()
+ update(id, params)
+ validate(key)
}
class ClientService {
+ create(params)
+ delete(id)
+ deleteAll()
+ getById(id)
+ list()
+ update(id, params)
+ validate(key)
}
class ServerService {
+ create(params)
+ delete(id)
+ deleteAll()
+ getById(id)
+ list()
+ update(id, params)
+ validate(key)
}
IApiKeyService <|.. ClientService
IApiKeyService <|.. ServerService
ClientService --> ApiKeyModel
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Thank you for raising your pull request and contributing to our Community |
There is too much information in the pull request to test. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hey @MarioJames - I've reviewed your changes - here's some feedback:
- The regex in validateApiKeyFormat only allows hex chars (0–9, a–f) but generateApiKey produces base36 strings – update the pattern or generator so they match.
- For better entropy and unpredictability, replace Math.random/performance.now key generation with a crypto-secure RNG (e.g. crypto.getRandomValues).
- The SQL migration adds an accessed_at column that isn’t in your Drizzle schema – either remove it from the migration or add it to the schema so they stay in sync.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The regex in validateApiKeyFormat only allows hex chars (0–9, a–f) but generateApiKey produces base36 strings – update the pattern or generator so they match.
- For better entropy and unpredictability, replace Math.random/performance.now key generation with a crypto-secure RNG (e.g. crypto.getRandomValues).
- The SQL migration adds an accessed_at column that isn’t in your Drizzle schema – either remove it from the migration or add it to the schema so they stay in sync.
## Individual Comments
### Comment 1
<location> `src/utils/apiKey.ts:58` </location>
<code_context>
+ */
+export function validateApiKeyFormat(key: string): boolean {
+ // Check format: lb-{random}
+ const pattern = /^lb-[\da-f]{16}$/;
+ return pattern.test(key);
+}
</code_context>
<issue_to_address>
API key validation pattern restricts to hexadecimal characters.
The regex only allows a-f and 0-9, but key generation uses all lowercase letters and digits (base36). Update the pattern to match the full character set used.
</issue_to_address>
### Comment 2
<location> `src/app/[variants]/(main)/profile/apikey/index.tsx:135` </location>
<code_context>
+ }}
+ placeholder={t('apikey.display.neverExpires')}
+ type="date"
+ value={apiKey.expiresAt?.toLocaleString() || t('apikey.display.neverExpires')}
+ />
+ ),
</code_context>
<issue_to_address>
Passing a localized string as a value to EditableCell may cause type issues.
Consider passing null instead of a localized string when 'expiresAt' is null to ensure the 'value' prop remains type-consistent for date fields.
</issue_to_address>
<suggested_fix>
<<<<<<< SEARCH
value={apiKey.expiresAt?.toLocaleString() || t('apikey.display.neverExpires')}
=======
value={apiKey.expiresAt ? apiKey.expiresAt.toLocaleString() : null}
>>>>>>> REPLACE
</suggested_fix>
### Comment 3
<location> `src/app/[variants]/(main)/profile/apikey/features/ApiKeyDatePicker/index.tsx:26` </location>
<code_context>
+ key={value?.valueOf() || 'EMPTY'}
+ value={value}
+ {...props}
+ minDate={dayjs()}
+ onChange={handleOnChange}
+ placeholder={t('apikey.form.fields.expiresAt.placeholder')}
</code_context>
<issue_to_address>
Setting minDate to current time may prevent selecting today.
Using 'dayjs()' sets minDate to the current time, which can block selection of today's date later in the day. Use 'dayjs().startOf('day')' to allow selecting today.
</issue_to_address>
<suggested_fix>
<<<<<<< SEARCH
minDate={dayjs()}
=======
minDate={dayjs().startOf('day')}
>>>>>>> REPLACE
</suggested_fix>
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
src/app/[variants]/(main)/profile/apikey/features/ApiKeyDatePicker/index.tsx
Show resolved
Hide resolved
Codecov ReportAll modified and coverable lines are covered by tests ✅
Additional details and impacted files@@ Coverage Diff @@
## main #8535 +/- ##
=========================================
Coverage 85.57% 85.57%
=========================================
Files 909 910 +1
Lines 69019 69039 +20
Branches 6395 4763 -1632
=========================================
+ Hits 59060 59080 +20
Misses 9959 9959
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
- Added a conditional check to create the "api_keys" table only if it does not already exist. - Ensured the foreign key constraint for "user_id" references the "users" table remains intact. This change enhances the migration process by preventing errors during table creation if the table already exists.
- Introduced a new Client component for managing API keys, including creation, updating, and deletion functionalities. - Replaced the previous page component with the new Client component in the API key management page. - Removed obsolete client and server service files related to API key management, streamlining the service layer. This update enhances the user experience by providing a dedicated interface for API key operations.
❤️ Great PR @MarioJames ❤️ The growth of project is inseparable from user feedback and contribution, thanks for your contribution! If you are interesting with the lobehub developer community, please join our discord and then dm @arvinxx or @canisminor1990. They will invite you to our private developer channel. We are talking about the lobe-chat development or sharing ai newsletter around the world. |
## [Version 1.105.0](v1.104.5...v1.105.0) <sup>Released on **2025-07-28**</sup> #### ✨ Features - **misc**: Implement API Key management functionality. <br/> <details> <summary><kbd>Improvements and Fixes</kbd></summary> #### What's improved * **misc**: Implement API Key management functionality, closes [#8535](#8535) ([fdaa725](fdaa725)) </details> <div align="right"> [](#readme-top) </div>
🎉 This PR is included in version 1.105.0 🎉 The release is available on: Your semantic-release bot 📦🚀 |
## [Version 1.104.0](v1.103.3...v1.104.0) <sup>Released on **2025-07-28**</sup> #### ✨ Features - **misc**: Implement API Key management functionality, support custom hotkey on desktop. #### 🐛 Bug Fixes - **misc**: Fix update hotkey invalid when input mod in desktop, update convertUsage to handle XAI provider and adjust OpenAIStream to pass provider. #### 💄 Styles - **misc**: Add Gemini 2.5 Flash-Lite GA model, fix setting window layout size, fix setting window layout when in desktop was disappear, update i18n. <br/> <details> <summary><kbd>Improvements and Fixes</kbd></summary> #### What's improved * **misc**: Implement API Key management functionality, closes [lobehub#8535](https://github.com/jaworldwideorg/OneJA-Bot/issues/8535) ([fdaa725](fdaa725)) * **misc**: Support custom hotkey on desktop, closes [lobehub#8559](https://github.com/jaworldwideorg/OneJA-Bot/issues/8559) ([b50f121](b50f121)) #### What's fixed * **misc**: Fix update hotkey invalid when input mod in desktop, closes [lobehub#8572](https://github.com/jaworldwideorg/OneJA-Bot/issues/8572) ([07f3e6a](07f3e6a)) * **misc**: Update convertUsage to handle XAI provider and adjust OpenAIStream to pass provider, closes [lobehub#8557](https://github.com/jaworldwideorg/OneJA-Bot/issues/8557) ([d1e4a54](d1e4a54)) #### Styles * **misc**: Add Gemini 2.5 Flash-Lite GA model, closes [lobehub#8539](https://github.com/jaworldwideorg/OneJA-Bot/issues/8539) ([404ac21](404ac21)) * **misc**: Fix setting window layout size, closes [lobehub#8483](https://github.com/jaworldwideorg/OneJA-Bot/issues/8483) ([4902341](4902341)) * **misc**: Fix setting window layout when in desktop was disappear, closes [lobehub#8585](https://github.com/jaworldwideorg/OneJA-Bot/issues/8585) ([74ab822](74ab822)) * **misc**: Update i18n, closes [lobehub#8579](https://github.com/jaworldwideorg/OneJA-Bot/issues/8579) ([2eccbc7](2eccbc7)) </details> <div align="right"> [](#readme-top) </div>
* ✨ feat: Implement API Key management functionality - Added new components for API Key management including creation, deletion, and display. - Introduced a new database schema for storing API Keys. - Implemented server and client services for API Key operations. - Integrated API Key management into the profile section with appropriate routing and feature flags. - Enhanced localization support for API Key related UI elements. This commit lays the groundwork for managing API Keys within the application, allowing users to create, view, and manage their keys effectively. * fix: server config unit test * ✨ feat(database): Create api_keys table with conditional existence check - Added a conditional check to create the "api_keys" table only if it does not already exist. - Ensured the foreign key constraint for "user_id" references the "users" table remains intact. This change enhances the migration process by preventing errors during table creation if the table already exists. * feat: Implement API Key management interface - Introduced a new Client component for managing API keys, including creation, updating, and deletion functionalities. - Replaced the previous page component with the new Client component in the API key management page. - Removed obsolete client and server service files related to API key management, streamlining the service layer. This update enhances the user experience by providing a dedicated interface for API key operations.
## [Version 1.105.0](lobehub/lobe-chat@v1.104.5...v1.105.0) <sup>Released on **2025-07-28**</sup> #### ✨ Features - **misc**: Implement API Key management functionality. <br/> <details> <summary><kbd>Improvements and Fixes</kbd></summary> #### What's improved * **misc**: Implement API Key management functionality, closes [lobehub#8535](lobehub#8535) ([9d49c7b](lobehub@9d49c7b)) </details> <div align="right"> [](#readme-top) </div>
* ✨ feat: Implement API Key management functionality - Added new components for API Key management including creation, deletion, and display. - Introduced a new database schema for storing API Keys. - Implemented server and client services for API Key operations. - Integrated API Key management into the profile section with appropriate routing and feature flags. - Enhanced localization support for API Key related UI elements. This commit lays the groundwork for managing API Keys within the application, allowing users to create, view, and manage their keys effectively. * fix: server config unit test * ✨ feat(database): Create api_keys table with conditional existence check - Added a conditional check to create the "api_keys" table only if it does not already exist. - Ensured the foreign key constraint for "user_id" references the "users" table remains intact. This change enhances the migration process by preventing errors during table creation if the table already exists. * feat: Implement API Key management interface - Introduced a new Client component for managing API keys, including creation, updating, and deletion functionalities. - Replaced the previous page component with the new Client component in the API key management page. - Removed obsolete client and server service files related to API key management, streamlining the service layer. This update enhances the user experience by providing a dedicated interface for API key operations.
## [Version 1.105.0](lobehub/lobe-chat@v1.104.5...v1.105.0) <sup>Released on **2025-07-28**</sup> #### ✨ Features - **misc**: Implement API Key management functionality. <br/> <details> <summary><kbd>Improvements and Fixes</kbd></summary> #### What's improved * **misc**: Implement API Key management functionality, closes [lobehub#8535](lobehub#8535) ([fdaa725](lobehub@fdaa725)) </details> <div align="right"> [](#readme-top) </div>
💻 变更类型 | Change Type
🔀 变更说明 | Description of Change
在 LobeChat 中初始化 API-KEY 功能相关表结构及工具
本次提交包含几个方面的内容:
数据访问层
src/database/schemas/apiKey.ts
):使用 Drizzle ORM 定义数据表结构src/database/models/apiKey.ts
):封装数据库操作逻辑数据库约束
表关联关系 ER 图如下,User 与 APIKey 关联关系为 1:n
服务层
src/services/apiKey/type.ts
):定义统一的服务接口src/services/apiKey/client.ts
):客户端模式下的服务实现src/services/apiKey/server.ts
):服务器模式下的服务实现src/services/apiKey/index.ts
):根据运行环境自动选择服务实现API 路由层
src/server/routers/lambda/apiKey.ts
):提供类型安全的 API 接口,有两个比较特殊的接口create
接口:创建API-Key 时,对生成的字符串进行加密存储findByKey
:由于在数据库中使用密文存储,用户看到的是明文,所以在通过明文查找对应的 API-KEY 信息时,在生成查找条件时,需要进行一次明文-密文的转换工具函数
src/utils/apiKey.ts
):安全的随机密钥生成算法📝 补充信息 | Additional Information
页面路径:账户管理 - API Key 管理
Summary by Sourcery
Implement end-to-end API Key management functionality including database schema, ORM model, service and API routes, feature-flagged UI components, and localization support.
New Features:
Enhancements:
Documentation: