Conversation
Add functionality to restrict which API clients (CLI tools/IDEs) can use a user's API keys based on User-Agent header matching. Features: - New `allowedClients` field on users table (JSONB array) - ProxyClientGuard validates User-Agent in proxy pipeline (after auth) - Admin UI with preset client checkboxes + custom pattern input - Display allowed clients info visible to both admin and user Preset client patterns: - claude-cli: Claude Code CLI - gemini-cli: Gemini CLI - factory-cli: Droid CLI (Factory AI) - codex-cli: Codex CLI Behavior: - Empty array = no restrictions (all clients allowed) - Non-empty array = only listed patterns allowed (case-insensitive) - Missing/empty User-Agent with restrictions → 400 error - Non-matching User-Agent with restrictions → 400 error 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Change other ranks (4+) from plain text to outline Badge - Add placeholder div for icon alignment consistency - Unify gap to 1.5, icon size to h-4 w-4, Badge min-width to 32px - Apply same changes to both TodayLeaderboard and LeaderboardTable Closes #344 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add clearLabel prop and handleClear function - Show clear button only when value is set - Close popover after clearing - Add i18n support for clear button text (5 languages) - Pass clearLabel to user-form, add-key-form, edit-key-form Closes #345 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Change USER_LIMITS.DAILY_QUOTA.MIN from 0.01 to 0 - Fix server action to preserve 0 value (not fallback to default) - Add helperText prop to TextField component - Add i18n support for daily quota helper text (5 languages) - Remove required attribute from dailyQuota field 0 now means unlimited daily quota, consistent with backend logic. Closes #346 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
feat: add client (CLI/IDE) restrictions for user management
- Add allowedModels field to users table (JSONB array) - Add ModelGuard to proxy pipeline to enforce model restrictions - Display allowed models in key-list-header component - Add allowedModels input to user form with tag-style UI - Add i18n translations for all supported languages (en, ja, ru, zh-CN, zh-TW) - Add field permission for allowedModels (admin-only) - Add database migration 0035_add_allowed_models.sql 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
…types - Introduced new error handling responses for input length, validation, context, token, and model-related errors. - Each error type now includes a specific message in Chinese to guide users on how to resolve the issues. - Enhanced user experience by providing clear feedback for common error scenarios. This update improves the clarity and usability of error messages returned by the API.
## 主要改进 ### 1. API 文档优化 - 为所有 39 个端点添加 summary 字段 - 优化 10 个标签分组的详细描述(从 ~10 字扩展到 ~40 字) - 统一 servers、contact、license、externalDocs 描述格式 - 修复 Scalar UI 左侧导航显示 URL 路径问题(现在全部显示中文文案) ### 2. 技术改进 - 添加 argsMapper 参数映射功能,支持多参数 Server Actions 正确调用 - 完善错误响应 schema(errorCode 和 errorParams) - 改进 OpenAPI 文档生成逻辑 ### 3. 依赖更新 - 添加 server-only 依赖(修复测试环境问题) - 添加测试脚本到 package.json(为未来测试做准备) ## 技术细节 **文档改进效果**: - summary 覆盖率: 65% → 100% - tags description 长度: ~10 字 → ~40 字 - 文档可读性: 显著提升 **影响范围**: - OpenAPI 文档自动生成 - Scalar UI 和 Swagger UI 展示 - 不影响现有 API 功能 ## 测试验证 - ✅ TypeScript 类型检查通过 - ✅ 所有端点路径正确注册 - ✅ OpenAPI 规范验证通过
## 主要改进 ### 1. 测试框架迁移 - 将测试框架从 Bun 迁移到 Vitest,支持更灵活的测试配置和报告。 - 添加 Vitest 配置文件,定义全局测试设置和路径别名。 ### 2. API 文档更新 - 为 API 认证添加详细指南,提供用户如何通过 Web UI 登录获取 auth-token 的步骤。 - 优化 API 文档中的请求参数描述,确保所有接口的请求参数清晰可见。 ### 3. 依赖更新 - 更新 package.json,添加 Vitest 及其相关依赖,确保测试环境的兼容性。 ## 技术细节 - 新增多个测试脚本,支持 E2E 测试和单元测试的自动化执行。 - 通过 GitHub Actions 配置 CI 流程,确保每次提交都能自动运行测试。 ## 测试验证 - ✅ 所有测试通过,确保功能完整性和稳定性。 - ✅ API 文档符合 OpenAPI 3.1.0 规范,确保文档的准确性和可读性。
- Restore original 0035_snapshot.json (allowed_clients) - Regenerate 0036 migration using `bun run db:generate` - Migration now properly generated, not manually edited 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Feat/api-docs-summary
…ompatibility Fixed: - Replace Bun with Node.js 22-slim for build-base stage - Change 'bun install' to 'npm install --production=false' - Change 'bun run build' to 'npm run build' Root Cause: Bun has incomplete N-API support for native modules used by next-intl/plugin, causing 'symbol napi_register_module_v1 not found' error during Next.js build. This fix was previously applied in commit 940609f on branch claude-fix-pr-355-20300261542 but was not included when PR #355 was merged. CI Run: https://github.com/ding113/claude-code-hub/actions/runs/20309519848 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
feat(users): add allowed models restriction for users
The Docker build was failing with ERESOLVE unable to resolve dependency tree error because @lobehub/icons@2.48.0 requires antd@^5.23.0 as a peer dependency, but the project uses antd@6.1.1. npm is stricter than bun about peer dependency conflicts. Adding --legacy-peer-deps makes npm behave like bun and ignore peer dependency conflicts, allowing the build to complete. CI Run: https://github.com/ding113/claude-code-hub/actions/runs/20311163413 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
## 核心改进 ### 1. 限额检查顺序优化(基于 Codex 专业分析) - 实现 11 步科学检查顺序: 1-2. 永久硬限制:Key 总限额 → User 总限额 3-4. 资源/频率保护:Key 并发 → User RPM 5-7. 短期周期限额:Key 5h → User 5h → User 每日 8-11. 中长期周期限额:Key 周 → User 周 → Key 月 → User 月 - 实现 Key/User 混合检查(同一窗口 Key → User 交替) - 设计原则:硬上限优先、短窗口优先、细粒度优先 ### 2. 新增 User 层 5h/周/月限额支持 - 扩展 RateLimitService.checkCostLimits 支持 user 类型 - 新增 sumUserCostInTimeRange() 数据库查询函数 - 支持 User 层多维度限额控制 ### 3. 错误响应优化 - 状态码优化:RPM/并发用 429,消费限额用 402 - 所有错误统一添加 code 字段 - 修正 User 类型的错误文案 ## 测试验证 - ✅ 11 步检查顺序全部验证通过 - ✅ 混合检查逻辑正确 - ✅ 错误响应格式统一 - ✅ Codex 代码审核通过(8/10) ## 相关文件 - src/app/v1/_lib/proxy/rate-limit-guard.ts - src/lib/rate-limit/service.ts - src/repository/statistics.ts - src/app/v1/_lib/proxy/error-handler.ts - src/app/v1/_lib/proxy/responses.ts Co-authored-by: Codex <gpt-5.2@openai.com>
Remove explicit 'number' type annotation that conflicts with Recharts' Formatter type definition, which expects 'number | undefined'. CI Run: https://github.com/ding113/claude-code-hub/actions/runs/20329503404
- Update biome schema version to 2.3.10 for CI compatibility - Add test file overrides to ignore unused variables and imports - Fix import ordering in non-test files
- Extract rate limit status code calculation to helper function - Refactor regex parsing logic to shared utility function - Replace nested ternary operators with switch statements Co-authored-by: Gemini Code Assist <gemini@google.com>
Feat/rate limit optimization
Add REDIS_TLS_REJECT_UNAUTHORIZED env variable to allow connections to Redis servers using self-signed or shared certificates. - Add buildTlsConfig() function for unified TLS configuration - Support rejectUnauthorized option in both getRedisClient and buildRedisOptionsForUrl - Update .env.example with new configuration option - Update README.md and README.en.md documentation
Apply REDIS_TLS_REJECT_UNAUTHORIZED to Bull queues and scripts: - cleanup-queue.ts: log cleanup job queue - notification-queue.ts: notification job queue - clear-session-bindings.ts: session cleanup script
Some cloud Redis providers (e.g., Northflank) require SNI for TLS. Without servername in TLS config, ioredis fails with ECONNRESET. Changes: - Add servername to TLS config in all Redis connection points - This enables compatibility with cloud Redis that use shared certificates
Add the new environment variable to Zod schema for type validation and automatic boolean transformation.
fix: 支持跳过 Redis TLS 证书验证(自签/共享证书场景)
- Added new error message for failed key loading in multiple languages (English, Japanese, Russian, Simplified Chinese, Traditional Chinese). - Enhanced global error component to differentiate between network errors and general errors, providing specific guidance for network issues. - Updated forms to include error handling for provider group loading and key retrieval, improving user feedback on failures.
There was a problem hiding this comment.
Code Review Summary
This PR (release v0.3.31) is an extensive release containing numerous feature additions including client/model restrictions, user daily reset modes, enhanced rate limiting, and Redis TLS configuration improvements. Due to the XL size (131 files, ~20K lines), I've focused on the core logic changes.
PR Size: XL
- Lines changed: 19,651 additions + 678 deletions
- Files changed: 131
Split Suggestion: Future releases should consider smaller, focused PRs:
- Rate limiting changes as separate PR
- Client/Model restriction guards as separate PR
- UI form components as separate PR
- Test infrastructure as separate PR
Issues Found
| Category | Critical | High | Medium | Low |
|---|---|---|---|---|
| Logic/Bugs | 0 | 0 | 1 | 0 |
| Security | 0 | 0 | 0 | 0 |
| Error Handling | 0 | 0 | 0 | 0 |
| Types | 0 | 0 | 0 | 0 |
| Comments/Docs | 0 | 0 | 1 | 0 |
| Tests | 0 | 0 | 1 | 0 |
| Simplification | 0 | 0 | 0 | 0 |
Medium Priority Issues (Should Fix)
1. [LOGIC-BUG] Potential inconsistency in rate limit check order between diff and file state
- The diff shows a significant refactoring of
ProxyRateLimitGuardwith reordered checks (Key total → User total → Key concurrent → User RPM → etc.) - However, the actual file appears to have the original order
- Impact: Rate limit bypass could occur if limits aren't checked in the intended priority order
- Recommendation: Verify the intended check order is deployed; the diff's approach (hardcoded limits first) is logically sound
2. [COMMENT-OUTDATED] Error handler comment mismatch
- File:
src/app/v1/_lib/proxy/error-handler.ts, lines 227-230 - Comment says "构建详细的 429 响应" but the function now returns 402 for spending limits
- Suggestion: Update comment to reflect the new 402/429 dynamic behavior
3. [TEST-MISSING-CRITICAL] New features lack unit test coverage
- New files added:
src/app/v1/_lib/proxy/client-guard.ts- No corresponding unit testssrc/app/v1/_lib/proxy/model-guard.ts- No corresponding unit testssrc/lib/utils/error-detection.ts- No corresponding unit tests
- While e2e tests exist, unit tests for these guards would catch edge cases
Positive Observations (Not Comments)
The following were verified as correctly implemented:
- ✅ Error handling in
syncUserProviderGroupFromKeyscatches and logs errors without failing silently - ✅ Redis TLS configuration properly handles
rejectUnauthorizedsetting - ✅ Client/Model guards correctly handle empty allowedClients/allowedModels as "no restrictions"
- ✅ Global error boundary properly sanitizes error messages (doesn't leak sensitive info)
- ✅ Validation schemas include proper constraints for new fields
Review Coverage
- Logic and correctness
- Security (OWASP Top 10) - No injection vulnerabilities found
- Error handling - Properly logged with appropriate fallbacks
- Type safety - New fields properly typed
- Documentation accuracy - Minor comment drift noted
- Test coverage - Missing unit tests for new guards
- Code clarity - Good
Automated review by Claude AI
There was a problem hiding this comment.
Code Review Summary
This PR (release v0.3.31) is an extensive release containing numerous feature additions including client/model restrictions, user daily reset modes, enhanced rate limiting, and Redis TLS configuration improvements. Due to the XL size (131 files, ~20K lines), I've focused on the core logic changes.
PR Size: XL
- Lines changed: 19,651 additions + 678 deletions
- Files changed: 131
Split Suggestion: Future releases should consider smaller, focused PRs:
- Rate limiting changes as separate PR
- Client/Model restriction guards as separate PR
- UI form components as separate PR
- Test infrastructure as separate PR
Issues Found
| Category | Critical | High | Medium | Low |
|---|---|---|---|---|
| Logic/Bugs | 0 | 0 | 1 | 0 |
| Security | 0 | 0 | 0 | 0 |
| Error Handling | 0 | 0 | 0 | 0 |
| Types | 0 | 0 | 0 | 0 |
| Comments/Docs | 0 | 0 | 1 | 0 |
| Tests | 0 | 0 | 1 | 0 |
| Simplification | 0 | 0 | 0 | 0 |
Medium Priority Issues (Should Fix)
1. [COMMENT-OUTDATED] Error handler comment mismatch
- File:
src/app/v1/_lib/proxy/error-handler.ts - Comment says "构建详细的 429 响应" but the function now returns 402 for spending limits
- Suggestion: Update comment to reflect the new 402/429 dynamic behavior
2. [TEST-MISSING-CRITICAL] New features lack unit test coverage
- New files added:
src/app/v1/_lib/proxy/client-guard.ts- No corresponding unit testssrc/app/v1/_lib/proxy/model-guard.ts- No corresponding unit testssrc/lib/utils/error-detection.ts- No corresponding unit tests
- While e2e tests exist, unit tests for these guards would catch edge cases
Positive Observations (Verified as correct)
The following were verified as correctly implemented:
- Error handling in
syncUserProviderGroupFromKeyscatches and logs errors without failing silently - Redis TLS configuration properly handles
rejectUnauthorizedsetting - Client/Model guards correctly handle empty allowedClients/allowedModels as "no restrictions"
- Global error boundary properly sanitizes error messages (doesn't leak sensitive info)
- Validation schemas include proper constraints for new fields
Review Coverage
- Logic and correctness
- Security (OWASP Top 10) - No injection vulnerabilities found
- Error handling - Properly logged with appropriate fallbacks
- Type safety - New fields properly typed
- Documentation accuracy - Minor comment drift noted
- Test coverage - Missing unit tests for new guards
- Code clarity - Good
Automated review by Claude AI
|
|
||
| /** | ||
| * 构建 429 Rate Limit 响应 | ||
| * 构建 Rate Limit 响应(402/429) |
There was a problem hiding this comment.
[Medium] [COMMENT-OUTDATED] Comment-code mismatch
Why this is a problem: The comment still says "构建 429 Rate Limit 响应" but the function now dynamically returns 402 or 429 based on limitType.
Suggested fix: Update the header comment to "构建 Rate Limit 响应(402/429)"
…process - Switched from Node.js to Bun as the base image for building and running the application. - Replaced npm commands with Bun commands for installing dependencies and running the build. - Updated the CMD instruction to use Bun for starting the server. These changes optimize the Dockerfile for performance and modernize the build process.
…tgreSQL installation - Changed base image from `oven/bun:slim` to `oven/bun:debian` for both production and development Dockerfiles. - Simplified PostgreSQL client installation by removing the need for an external APT repository, leveraging the version included in Debian Trixie. - Updated commands for installing dependencies and running the application to enhance consistency and performance. These changes modernize the Docker setup and improve the build process.
- Modified the user ownership in both production and development Dockerfiles from 'node:node' to 'bun:bun' for all copied files. - Ensured consistency in user permissions across the Docker setup. These changes align the Docker configuration with the updated user management strategy.
- Modified the description in the user management table to include a placeholder for the user's name, enhancing the localization support. - This change improves the clarity and relevance of the displayed information for users. These updates ensure a better user experience by providing more personalized content in the user management interface.
- Added a new function `getUsageLogsBatch` to support cursor-based pagination, optimizing performance for large datasets. - Updated the `UsageLogsView` component to utilize virtualized rendering for improved loading and scrolling experience. - Enhanced localization support in dashboard messages across multiple languages to include new loading and record count messages. These changes improve the efficiency and user experience of the usage logs feature, particularly in scenarios with extensive data.
- Introduced an "overwriteHint" message in multiple language files to inform users that saving a limit type will overwrite any existing value. - Updated the user interface components to display this hint when selecting an existing limit type, enhancing user awareness and preventing accidental data loss. These changes improve the user experience by providing clear guidance on the implications of their actions in the dashboard.
- Added a new function to clean response headers by removing transport-related headers such as "transfer-encoding" and "content-length". This addresses issues with Bun's Response API that can lead to duplicate headers when handling ReadableStreams or modified bodies. - Updated the ProxyResponseHandler to utilize this new function, ensuring that headers are managed correctly and improving compatibility with Bun. These changes enhance the reliability of response handling in the application.
Fixed issues: - Updated UpdateUserData type to allow null for quota fields (dailyQuota, limit5hUsd, limitWeeklyUsd, limitMonthlyUsd, limitConcurrentSessions) - Updated UpdateDbData interface to accept null for string quota fields - Updated addUser and editUser function signatures to accept null for dailyQuota - Fixed onChange prop type in KeyEditSection and UserEditSection to use overloaded signature supporting both single-field and batch updates - Updated emitChange helper to properly handle both call patterns - Fixed onChange wrapper in UnifiedEditDialog with proper type casting These changes ensure null values can be properly passed through the type system when clearing quota limits. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Auto-fix CI failures for PR #370
- Updated the Biome schema version in `biome.json` for compatibility. - Refined file inclusion patterns in `biome.json` to be more specific. - Changed the type checking command in `package.json` from `tsc` to `tsgo` and added a new command for `tsc`. - Enhanced the TypeScript configuration in `tsconfig.json` by re-adding source maps and adjusting include/exclude patterns. - Improved the `UsageLogsViewContent` component by utilizing `useMemo` for filters and managing refresh timeout with `useRef`. - Optimized the `VirtualizedLogsTable` component to reduce unnecessary calculations and improve performance. - Simplified database queries in `usage-logs.ts` by removing redundant key lookups and adding inner joins for better filtering. These changes enhance the overall performance, maintainability, and clarity of the codebase.
- Renamed the composite index from `idx_message_request_logs_cursor` to `idx_message_request_cursor` for clarity. - Changed the target table from `message_request_logs` to `message_request` to reflect the correct data structure. These changes improve the accuracy and maintainability of the database schema related to cursor-based pagination.
- Updated the `CardContent` component in `UsageLogsViewContent` to include padding. - Refined the header and row structure in `VirtualizedLogsTable` for better responsiveness and alignment. - Adjusted column widths and added padding to enhance readability and user experience. These changes enhance the visual presentation and usability of the usage logs interface.
- Modified column flex properties in the `VirtualizedLogsTable` to improve layout and responsiveness. - Enhanced readability by adjusting widths for user, key, and cache read columns. These changes optimize the visual structure of the logs table for better user experience.
feat: implement cursor-based pagination for usage logs
…e management - Removed the `getFilterOptions` function and replaced it with lazy loading hooks for models, status codes, and endpoints to improve performance. - Introduced a constant for common status codes and merged it with dynamically loaded status codes to streamline the selection process. - Updated the component to handle loading states and improved user experience with clearer loading indicators. These changes optimize the filter options management in the usage logs interface.
- Moved import statements for `getEndpointList`, `getModelList`, and `getStatusCodeList` to improve code clarity. - Added a comment to clarify the use of the `fetcher` parameter in the lazy loading hook, ensuring better understanding of its lifecycle. These changes enhance code readability and maintainability in the usage logs filtering logic.
- Added `e.stopPropagation()` in the form submission handler of the `LimitRulePicker` component to prevent unintended event bubbling. This change improves the form's behavior by ensuring that the submission event does not trigger other event listeners unintentionally.
- Removed the fallback to undefined for dailyQuota, ensuring it directly reflects the user's data. This change improves data consistency and clarity in the component's state management.
Summary
Release v0.3.31 - A major update featuring enhanced user management UI, improved rate limiting, expanded error handling, API documentation enhancements, and multiple bug fixes including Codex compatibility and Redis TLS support.
Key Changes in This Release
🎯 User Management Enhancements (#362, #341, #347)
New User Management Panel - Complete overhaul of the user management interface:
Access Restrictions:
Database Migrations:
0035_blushing_fabian_cortez.sql- Addsallowed_clientscolumn to users table0036_stale_iron_fist.sql- Addsallowed_modelscolumn to users table⚡ Rate Limiting & Quota Optimization (#359)
📝 API Documentation Improvements (#355)
docs/api-authentication-guide.md,docs/api-docs-summary.md🔧 Bug Fixes
stream=truefor Codex requests, fixing the/v1/responses/compactendpoint (Fix #368: Remove forced stream=true for Codex requests #369)🔐 Redis TLS Improvements (#360)
REDIS_TLS_REJECT_UNAUTHORIZED🎨 UI/UX Improvements
🌐 Internationalization
🔧 Infrastructure & DevOps
.github/workflows/test.yml)Related Issues & PRs
Directly Fixed:
Partially Addresses:
Related Work:
Merged PRs Included
Breaking Changes
AUTO_MIGRATE=trueor run Drizzle migrations manuallyREDIS_TLS_REJECT_UNAUTHORIZEDTesting
Automated Tests
scripts/run-e2e-tests.sh) and Windows (scripts/run-e2e-tests.ps1)Manual Testing Checklist
/v1/responses/compactendpointChecklist
Description enhanced by Claude AI