-
Notifications
You must be signed in to change notification settings - Fork 371
test(clerk-js): Add dynamic TTL calculation tests for JWT expiration handling #6231
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
🦋 Changeset detectedLatest commit: 98b0735 The changes in this PR will be included in the next version bump. This PR includes changesets to release 0 packagesWhen changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
📝 WalkthroughWalkthroughA new empty changeset file Estimated code review effort2 (10–30 minutes) 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
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.
Actionable comments posted: 2
🧹 Nitpick comments (1)
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts (1)
19-41
: Improve type safety and add JSDoc documentation.The helper function is well-implemented but could benefit from explicit typing and documentation.
+/** + * Creates a JWT with custom TTL for testing purposes + * @param ttlSeconds - Time to live in seconds + * @returns JWT string with custom expiration + */ -function createJwtWithTtl(ttlSeconds: number): string { +function createJwtWithTtl(ttlSeconds: number): string {
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
.changeset/ten-kiwis-cry.md
(1 hunks)packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
(2 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
`**/*.{js,jsx,ts,tsx}`: All code must pass ESLint checks with the project's conf...
**/*.{js,jsx,ts,tsx}
: All code must pass ESLint checks with the project's configuration
Use Prettier for consistent code formatting
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Validate all inputs and sanitize outputs
Implement proper logging with different levels
📄 Source: CodeRabbit Inference Engine (.cursor/rules/development.mdc)
List of files the instruction was applied to:
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
`packages/**/*.ts`: TypeScript is required for all packages
packages/**/*.ts
: TypeScript is required for all packages
📄 Source: CodeRabbit Inference Engine (.cursor/rules/development.mdc)
List of files the instruction was applied to:
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
`**/{__tests__,**/__tests__}/**/*.{js,jsx,ts,tsx}`: Test files should be co-located with source files or in `__tests__` directories
**/{__tests__,**/__tests__}/**/*.{js,jsx,ts,tsx}
: Test files should be co-located with source files or in__tests__
directories
📄 Source: CodeRabbit Inference Engine (.cursor/rules/development.mdc)
List of files the instruction was applied to:
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
`packages/**/*.{ts,tsx,d.ts}`: Packages should export TypeScript types alongside runtime code
packages/**/*.{ts,tsx,d.ts}
: Packages should export TypeScript types alongside runtime code
📄 Source: CodeRabbit Inference Engine (.cursor/rules/development.mdc)
List of files the instruction was applied to:
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
`**/*.{ts,tsx}`: Use proper TypeScript error types
**/*.{ts,tsx}
: Use proper TypeScript error types
📄 Source: CodeRabbit Inference Engine (.cursor/rules/development.mdc)
List of files the instruction was applied to:
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
`**/*.{test,spec}.{js,ts,tsx}`: Unit tests should use Jest or Vitest as the test runner.
**/*.{test,spec}.{js,ts,tsx}
: Unit tests should use Jest or Vitest as the test runner.
📄 Source: CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
List of files the instruction was applied to:
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
`packages/{clerk-js,elements,themes}/**/*`: Visual regression testing should be performed for UI components.
packages/{clerk-js,elements,themes}/**/*
: Visual regression testing should be performed for UI components.
📄 Source: CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
List of files the instruction was applied to:
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
`**/*.{ts,tsx}`: Always define explicit return types for functions, especially p...
**/*.{ts,tsx}
: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
for properties that shouldn't change after construction
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Document public functions and APIs with JSDoc-style comments including @param, @returns, @throws, and @example
Define custom error classes for domain-specific errors
Use the Result pattern for error handling instead of throwing exceptions
Use optional chaining and nullish coalescing for safe property access
Let TypeScript infer types when types are obvious
Useconst assertions
for literal types:as const
Usesatisfies
operator for type checking without widening
Use readonly arrays and objects for immutability
Use immutable update patterns (spread, etc.) for objects and arrays
Use lazy loading for large types
Preferunknown
overany
for performance
Use type-only imports:import type { ... }
Use branded types for domain safety
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
for immutable data
Proper generic constraints in TypeScript generics
No unused type parameters in generics
Proper use of utility types instead of manual type construction
Type-only imports where possible for performance
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
📄 Source: CodeRabbit Inference Engine (.cursor/rules/typescript.mdc)
List of files the instruction was applied to:
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
`**/__tests__/**/*.{ts,tsx}`: Use Vitest for type-safe testing in TypeScript Cre...
**/__tests__/**/*.{ts,tsx}
: Use Vitest for type-safe testing in TypeScript
Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces in tests
📄 Source: CodeRabbit Inference Engine (.cursor/rules/typescript.mdc)
List of files the instruction was applied to:
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
🧠 Learnings (3)
📓 Common learnings
Learnt from: dstaley
PR: clerk/javascript#6116
File: .changeset/tangy-garlics-say.md:1-2
Timestamp: 2025-06-13T16:09:53.061Z
Learning: In the Clerk JavaScript repository, contributors create intentionally empty changeset files (containing only the YAML delimiters) when a PR touches only non-published parts of the codebase (e.g., sandbox assets). This signals that no package release is required, so such changesets should not be flagged as missing content.
.changeset/ten-kiwis-cry.md (1)
Learnt from: dstaley
PR: clerk/javascript#6116
File: .changeset/tangy-garlics-say.md:1-2
Timestamp: 2025-06-13T16:09:53.061Z
Learning: In the Clerk JavaScript repository, contributors create intentionally empty changeset files (containing only the YAML delimiters) when a PR touches only non-published parts of the codebase (e.g., sandbox assets). This signals that no package release is required, so such changesets should not be flagged as missing content.
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts (7)
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/typescript.mdc:0-0
Timestamp: 2025-06-30T10:33:45.961Z
Learning: Applies to **/__tests__/**/*.{ts,tsx} : Create type-safe test builders/factories
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/monorepo.mdc:0-0
Timestamp: 2025-06-30T10:30:56.197Z
Learning: Applies to packages/clerk-react/**/*.{test,spec}.{js,ts,tsx} : Component testing should use React Testing Library.
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/typescript.mdc:0-0
Timestamp: 2025-06-30T10:33:45.961Z
Learning: Applies to **/__tests__/**/*.{ts,tsx} : Use branded types for test isolation
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/monorepo.mdc:0-0
Timestamp: 2025-06-30T10:30:56.197Z
Learning: Applies to packages/@clerk/*/jest.config.{js,ts} : Each framework integration package must have its own test configuration.
Learnt from: wobsoriano
PR: clerk/javascript#6123
File: packages/nextjs/src/server/__tests__/getAuthDataFromRequest.test.ts:63-75
Timestamp: 2025-06-16T01:27:54.563Z
Learning: In packages/nextjs/src/server/data/getAuthDataFromRequest.ts, the tokenType behavior on mismatch is intentionally different between array and single acceptsToken values: when acceptsToken is an array and the token type doesn't match any in the array, tokenType returns null; when acceptsToken is a single value and the token type doesn't match, tokenType returns the requested single value. This design aligns with developer intent and provides a more ergonomic API for common use cases.
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/development.mdc:0-0
Timestamp: 2025-06-30T10:29:42.997Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Implement proper caching strategies
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/typescript.mdc:0-0
Timestamp: 2025-06-30T10:33:45.961Z
Learning: Applies to **/__tests__/**/*.{ts,tsx} : Implement proper mock types that match interfaces in tests
🧬 Code Graph Analysis (1)
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts (1)
packages/clerk-js/src/core/tokenCache.ts (1)
SessionTokenCache
(136-136)
🪛 Gitleaks (8.26.0)
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
23-23: Uncovered a JSON Web Token, which may lead to unauthorized access to web applications and sensitive user data.
(jwt)
⏰ Context from checks skipped due to timeout of 90000ms (23)
- GitHub Check: Integration Tests (vue, chrome)
- GitHub Check: Integration Tests (nextjs, chrome, 13)
- GitHub Check: Integration Tests (tanstack-react-start, chrome)
- GitHub Check: Integration Tests (nextjs, chrome, 15)
- GitHub Check: Integration Tests (nextjs, chrome, 14)
- GitHub Check: Integration Tests (nuxt, chrome)
- GitHub Check: Integration Tests (react-router, chrome)
- GitHub Check: Integration Tests (sessions, chrome)
- GitHub Check: Integration Tests (tanstack-react-router, chrome)
- GitHub Check: Integration Tests (astro, chrome)
- GitHub Check: Integration Tests (localhost, chrome)
- GitHub Check: Integration Tests (billing, chrome)
- GitHub Check: Integration Tests (generic, chrome)
- GitHub Check: Integration Tests (expo-web, chrome)
- GitHub Check: Integration Tests (quickstart, chrome)
- GitHub Check: Integration Tests (express, chrome)
- GitHub Check: Integration Tests (elements, chrome)
- GitHub Check: Integration Tests (ap-flows, chrome)
- GitHub Check: Static analysis
- GitHub Check: Publish with pkg-pr-new
- GitHub Check: Unit Tests (22, **)
- GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
.changeset/ten-kiwis-cry.md (1)
1-3
: LGTM! Empty changeset follows established convention.This empty changeset correctly signals that no package release is required since the PR only touches test files.
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts (1)
191-264
: Excellent test coverage for dynamic TTL calculation.The test structure and logic are well-designed. These tests effectively verify that:
- Tokens with short TTL (30s) are properly cached and removed after expiration
- Tokens with longer TTL (120s) remain cached before expiration and are removed afterward
- The cache correctly calculates expiration based on JWT claims rather than fixed timeouts
The use of fake timers and controlled time advancement provides reliable, deterministic testing of time-based behavior.
Looks good. The test cleanup suggestions from Coderabbit would be nice to implement |
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.
Actionable comments posted: 0
🧹 Nitpick comments (1)
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts (1)
19-41
: Add explicit return type and JSDoc documentation.The helper function should follow TypeScript coding guidelines by including an explicit return type and JSDoc documentation.
+/** + * Helper function to create JWT with custom TTL for testing purposes. + * Note: The resulting JWT maintains the original signature for consistency, + * making it suitable for cache expiration testing but not cryptographic validation. + * @param ttlSeconds - Time to live in seconds for the JWT + * @returns JWT string with custom expiration time + */ -function createJwtWithTtl(ttlSeconds: number): string { +function createJwtWithTtl(ttlSeconds: number): string {
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
(3 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{js,jsx,ts,tsx}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/development.mdc
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/development.mdc
packages/**/*.{ts,tsx}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/development.mdc
packages/**/*.{ts,tsx,d.ts}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/development.mdc
**/*.{ts,tsx}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/development.mdc
- .cursor/rules/typescript.mdc
packages/**/*.{test,spec}.{js,jsx,ts,tsx}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/monorepo.mdc
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/monorepo.mdc
**/*.{js,ts,tsx,jsx}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/monorepo.mdc
**/__tests__/**/*.{ts,tsx}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/typescript.mdc
**/*
Instructions used from:
Sources:
⚙️ CodeRabbit Configuration File
🧬 Code Graph Analysis (1)
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts (1)
packages/clerk-js/src/core/tokenCache.ts (1)
SessionTokenCache
(136-136)
🪛 Gitleaks (8.27.2)
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
23-23: Uncovered a JSON Web Token, which may lead to unauthorized access to web applications and sensitive user data.
(jwt)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: Build Packages
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (3)
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts (3)
191-196
: Excellent mock cleanup implementation!The centralized Date.now mock setup with proper cleanup in
afterEach
effectively addresses the test isolation concerns from previous reviews. This ensures each test starts with a clean mock state.
198-228
: Well-implemented dynamic TTL test.This test effectively verifies that the cache correctly calculates and respects JWT expiration based on the
exp
andiat
claims. The use of the helper function and proper mock management makes the test reliable and maintainable.
230-269
: Comprehensive test for longer TTL tokens.This test thoroughly validates the handling of tokens with TTL greater than 60 seconds by checking multiple time points. The multi-stage verification (initial cache, pre-expiration persistence, post-expiration removal) provides excellent coverage for the dynamic TTL calculation feature.
f7139b4
to
98b0735
Compare
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.
Actionable comments posted: 0
🧹 Nitpick comments (1)
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts (1)
19-41
: LGTM: Well-implemented helper function with proper JWT structure.The helper function correctly implements base64url encoding and maintains consistency with the existing JWT structure. The approach of reusing the header and signature while only modifying the payload is appropriate for testing cache behavior.
Consider adding basic parameter validation for robustness:
function createJwtWithTtl(ttlSeconds: number): string { + if (ttlSeconds <= 0) { + throw new Error('TTL must be positive'); + } // Use the existing JWT as template const baseJwt =
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
.changeset/ten-kiwis-cry.md
(1 hunks)packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
(3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- .changeset/ten-kiwis-cry.md
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{js,jsx,ts,tsx}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/development.mdc
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/development.mdc
packages/**/*.{ts,tsx}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/development.mdc
packages/**/*.{ts,tsx,d.ts}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/development.mdc
**/*.{ts,tsx}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/development.mdc
- .cursor/rules/typescript.mdc
packages/**/*.{test,spec}.{js,jsx,ts,tsx}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/monorepo.mdc
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/monorepo.mdc
**/*.{js,ts,tsx,jsx}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/monorepo.mdc
**/__tests__/**/*.{ts,tsx}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/typescript.mdc
**/*
Instructions used from:
Sources:
⚙️ CodeRabbit Configuration File
🧬 Code Graph Analysis (1)
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts (1)
packages/clerk-js/src/core/tokenCache.ts (1)
SessionTokenCache
(136-136)
🪛 Gitleaks (8.27.2)
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
23-23: Uncovered a JSON Web Token, which may lead to unauthorized access to web applications and sensitive user data.
(jwt)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
- GitHub Check: Build Packages
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (4)
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts (4)
2-2
: LGTM: Import addition is correctly structured.The
afterEach
import is properly added and necessary for the new test cleanup functionality.
191-196
: Excellent test setup addressing previous mock cleanup concerns.The describe-level spy variable with afterEach cleanup properly addresses the Date.now mock restoration issues identified in previous reviews. This ensures proper test isolation and follows testing best practices.
198-228
: LGTM: Comprehensive test for dynamic TTL calculation.The test correctly validates dynamic TTL calculation by:
- Creating a JWT with custom 30-second TTL
- Properly synchronizing fake timers with mocked Date.now
- Verifying cache behavior before and after token expiration
The test logic is sound and effectively validates the core functionality.
230-269
: LGTM: Thorough test coverage for longer TTL tokens.The test comprehensively validates handling of tokens with TTLs greater than 60 seconds by testing intermediate states (90s) and final expiration (121s). This provides excellent coverage for the edge cases mentioned in the PR objectives and ensures the cache correctly handles various TTL durations.
Improves the token cache by adding dynamic TTL calculation based on JWT
exp
andiat
claims.This change:
Summary by CodeRabbit