Skip to content

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

Merged
merged 3 commits into from
Jul 21, 2025

Conversation

nikosdouvlis
Copy link
Member

@nikosdouvlis nikosdouvlis commented Jul 1, 2025

Improves the token cache by adding dynamic TTL calculation based on JWT exp and iat claims.

This change:

  • Adds tests to verify token expiration handling based on JWT TTL.
  • Creates a helper function to generate JWTs with custom TTL values for testing.
  • Ensures tokens with TTLs greater than 60 seconds are handled correctly.

Summary by CodeRabbit

  • Tests
    • Added new tests to verify dynamic token expiration handling in the token cache, including scenarios for both short and long TTLs. These tests ensure tokens are cached and removed at the correct times.

Copy link

changeset-bot bot commented Jul 1, 2025

🦋 Changeset detected

Latest commit: 98b0735

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 0 packages

When 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

Copy link

vercel bot commented Jul 1, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
clerk-js-sandbox ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 21, 2025 10:17am

Copy link
Contributor

coderabbitai bot commented Jul 1, 2025

📝 Walkthrough

Walkthrough

A new empty changeset file .changeset/ten-kiwis-cry.md was added, containing only frontmatter delimiters and no content. In the test suite for MemoryTokenCache, a helper function createJwtWithTtl was introduced to generate JWT strings with customizable expiration and issued-at claims. Two test cases were added under a new "dynamic TTL calculation" describe block. These tests use mocked time and fake timers to verify that the cache correctly calculates token expiration based on the JWT claims, ensuring tokens are cached and removed according to their TTL.

Estimated code review effort

2 (10–30 minutes)


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need 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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

pkg-pr-new bot commented Jul 1, 2025

Open in StackBlitz

@clerk/agent-toolkit

npm i https://pkg.pr.new/@clerk/agent-toolkit@6231

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@6231

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@6231

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@6231

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@6231

@clerk/dev-cli

npm i https://pkg.pr.new/@clerk/dev-cli@6231

@clerk/elements

npm i https://pkg.pr.new/@clerk/elements@6231

@clerk/clerk-expo

npm i https://pkg.pr.new/@clerk/clerk-expo@6231

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@6231

@clerk/express

npm i https://pkg.pr.new/@clerk/express@6231

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@6231

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@6231

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@6231

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@6231

@clerk/clerk-react

npm i https://pkg.pr.new/@clerk/clerk-react@6231

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@6231

@clerk/remix

npm i https://pkg.pr.new/@clerk/remix@6231

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@6231

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@6231

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@6231

@clerk/themes

npm i https://pkg.pr.new/@clerk/themes@6231

@clerk/types

npm i https://pkg.pr.new/@clerk/types@6231

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@6231

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@6231

commit: 98b0735

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between 524c5e0 and 53cdf34.

📒 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
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly 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
Use const assertions for literal types: as const
Use satisfies 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
Prefer unknown over any for performance
Use type-only imports: import type { ... }
Use branded types for domain safety
No any types without justification
Proper error handling with typed errors
Consistent use of readonly 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:

  1. Tokens with short TTL (30s) are properly cached and removed after expiration
  2. Tokens with longer TTL (120s) remain cached before expiration and are removed afterward
  3. 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.

@jacekradko
Copy link
Member

Looks good. The test cleanup suggestions from Coderabbit would be nice to implement

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between 53cdf34 and f7139b4.

📒 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 and iat 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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between f7139b4 and 98b0735.

📒 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.

@nikosdouvlis nikosdouvlis merged commit 62cab9e into main Jul 21, 2025
35 of 36 checks passed
@nikosdouvlis nikosdouvlis deleted the nikos/test-token-cache-ttl branch July 21, 2025 10:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants