Skip to content

feat: support session cookies #66

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Conversation

DanielRivers
Copy link
Contributor

Explain your changes

Add support for ksp to enable session cookies

Checklist

🛟 If you need help, consider asking for advice over in the Kinde community.

Copy link

coderabbitai bot commented Mar 12, 2025

Walkthrough

This pull request updates the function signature for commitTokenToSession across several modules and test cases by adding a new parameter (e.g., 'persistent' or a derived sessionType). In the production code, the ClientCredentials class now performs JWT verification after fetching the access token and determines a session type from the payload. Furthermore, the SessionManager interface is updated to accept an optional session type when setting a session item. The test suites are also modified to include the new parameter in their calls.

Changes

File(s) Change Summary
lib/__tests__/sdk/…/ClientCredentials.spec.ts
lib/__tests__/sdk/…/token-utils.spec.ts
Updated test cases to pass an additional argument ('persistent') to commitTokenToSession in various scenarios, modifying its expected method signature.
lib/sdk/…/ClientCredentials.ts
lib/sdk/…/utilities/token-utils.ts
Integrated JWT verification using jwtVerify in ClientCredentials.getToken; derived and forwarded a sessionType parameter to commitTokenToSession, and updated internal logic accordingly.
lib/sdk/…/session-managers/types.ts Modified the SessionManager interface to include an optional third parameter (sessionType) for the setSessionItem method.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant CC as ClientCredentials
    participant JW as jwtVerify (jose)
    participant TU as Token Utils
    participant SM as SessionManager

    C->>CC: getToken(sessionManager)
    CC->>CC: fetchAccessTokenFor()
    CC->>JW: jwtVerify(access_token, keyProvider)
    JW-->>CC: verificationResult (payload with ksp)
    Note over CC: Derive sessionType from payload.ksp
    CC->>TU: commitTokenToSession(sessionManager,\naccess_token, 'access_token',\nvalidationDetails, sessionType)
    TU->>SM: setSessionItem(token, sessionType)
    SM-->>TU: Confirmation
    TU-->>CC: Token committed
    CC-->>C: Return access token
Loading

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 docstrings to generate docstrings for 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.

@DanielRivers DanielRivers requested a review from DaveOrDead March 12, 2025 23:30
Copy link

@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 (3)
lib/sdk/utilities/token-utils.ts (2)

17-23: Update JSDoc to reflect the new sessionType parameter

The function signature has been updated to include a new sessionType parameter, but the JSDoc comments don't reflect this change. Please update the function documentation to include the new parameter and explain its purpose.

/**
 * Saves the provided token to the current session.
 *
 * @param {SessionManager} sessionManager
 * @param {string} token
 * @param {TokenType} type
+ * @param {TokenValidationDetailsType} validationDetails
+ * @param {string} sessionType - Determines if the token should be stored as 'session' or 'persistent'
 */

41-41: Consider error handling for session storage issues

While the code properly handles JWT verification errors, it might be good to add error handling around the session storage operation as well.

- await sessionManager.setSessionItem(type, token, sessionType);
+ try {
+   await sessionManager.setSessionItem(type, token, sessionType);
+ } catch (e) {
+   throw new KindeSDKError(
+     KindeSDKErrorCode.SESSION_STORAGE_ERROR,
+     `Failed to store ${type} token to session: ${e.message}`
+   );
+ }
lib/__tests__/sdk/utilities/token-utils.spec.ts (1)

29-52: Add test case for non-persistent session type

The current test cases only verify the 'persistent' session type. Consider adding a test case to verify that tokens with ksp: 'non_persistent' in the payload correctly create 'session' type cookies.

it('uses session type based on ksp claim in the token', async () => {
  // Create a mock token with ksp: 'non_persistent'
  const { token: mockAccessTokenNonPersistent } = await mocks.getMockAccessToken(domain, false, { ksp: 'non_persistent' });
  const { token: mockIdToken } = await mocks.getMockAccessToken(domain);
  const tokenCollection: TokenCollection = {
    refresh_token: 'refresh_token',
    access_token: mockAccessTokenNonPersistent,
    id_token: mockIdToken,
  };
  
  // Mock the setSessionItem method to verify the sessionType parameter
  const setSessionItemSpy = jest.spyOn(sessionManager, 'setSessionItem');
  
  await commitTokensToSession(
    sessionManager,
    tokenCollection,
    validationDetails
  );

  // Verify that 'session' type was used for tokens
  expect(setSessionItemSpy).toHaveBeenCalledWith('access_token', mockAccessTokenNonPersistent, 'session');
  expect(setSessionItemSpy).toHaveBeenCalledWith('refresh_token', 'refresh_token', 'session');
  expect(setSessionItemSpy).toHaveBeenCalledWith('id_token', mockIdToken, 'session');
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a9f596b and b4d3c8b.

⛔ Files ignored due to path filters (1)
  • package.json is excluded by !**/*.json
📒 Files selected for processing (5)
  • lib/__tests__/sdk/oauth2-flows/ClientCredentials.spec.ts (1 hunks)
  • lib/__tests__/sdk/utilities/token-utils.spec.ts (3 hunks)
  • lib/sdk/oauth2-flows/ClientCredentials.ts (2 hunks)
  • lib/sdk/session-managers/types.ts (1 hunks)
  • lib/sdk/utilities/token-utils.ts (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: main (18.x)
🔇 Additional comments (8)
lib/__tests__/sdk/oauth2-flows/ClientCredentials.spec.ts (1)

85-86: Session type addition appears correct.
The addition of the 'persistent' argument here aligns with the updated commitTokenToSession function signature. Consider adding a test scenario for the 'non_persistent' session type to ensure comprehensive coverage of all session state possibilities.

lib/sdk/oauth2-flows/ClientCredentials.ts (2)

1-1: Validate the correctness of the new jwtVerify import.
Importing jwtVerify from 'jose' is the correct approach for verifying JWT payloads. Ensure that the project dependencies are updated to include jose and that any runtime errors from asynchronous verification are properly handled upstream.


58-70: Confirm robust fallback logic for ksp and session type.
When result.payload.ksp is 'non_persistent', this code uses 'session'; otherwise, it defaults to 'persistent'. If unknown or missing ksp values should also default to 'persistent', then this is appropriate. Otherwise, consider explicitly handling unexpected values to avoid misclassifying session types. Also ensure any exceptions from jwtVerify are captured and handled appropriately.

lib/sdk/session-managers/types.ts (1)

10-14: Ensure all session managers handle the new sessionType parameter.
The updated signature adds flexibility for specifying either 'session' or 'persistent'. Verify that all implementations of SessionManager properly apply the sessionType parameter (e.g., cookies, storage, or other underlying session mechanisms) to avoid inconsistent session handling.

lib/sdk/utilities/token-utils.ts (1)

55-59: Good implementation of session persistence detection

The code correctly verifies the JWT and extracts the ksp property to determine the session type. This aligns well with the PR objective of supporting session cookies.

lib/__tests__/sdk/utilities/token-utils.spec.ts (3)

65-67: Test function updated correctly with new parameter

The test has been updated to include the new sessionType parameter, which is good.


83-85: Test function updated correctly with new parameter

This test case has been properly updated to include the new sessionType parameter.


101-103: Test function updated correctly with new parameter

This test case has been properly updated to include the new sessionType parameter.

Copy link

@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

🔭 Outside diff range comments (1)
lib/sdk/utilities/token-utils.ts (1)

139-139: 💡 Verification agent

🧩 Analysis chain

Fix type mismatch in UserType

The pipeline is failing with a type error on line 139. The error indicates that you're trying to assign an object with a phone property to UserType, but phone is not defined in the UserType interface.


🏁 Script executed:

#!/bin/bash
# Check the definition of UserType to verify the correct properties
grep -r "UserType" --include="*.ts" . | grep -v "import" | head -n 10

Length of output: 938


Action Required: Address Type Mismatch on UserType

  • The build failure indicates that at lib/sdk/utilities/token-utils.ts:139 the object being constructed includes a phone property which isn’t defined in the current UserType interface.
  • Please verify if the phone property should be part of the user model. If it is required, update the UserType interface accordingly. Otherwise, remove the phone property from the returned object so that its structure aligns with UserType.
  • Although the shown snippet only displays the assignment of id (i.e., id: idToken.payload.sub!), it appears that additional properties (including phone) are being added elsewhere in the construction of the user object. A review of the complete returned object is needed to ensure full type compliance.
🧰 Tools
🪛 GitHub Check: main (18.x)

[failure] 139-139:
Type '{ family_name: string; given_name: string; picture: string; email: string; phone: string; id: string; }' is not assignable to type 'UserType'.

🪛 GitHub Actions: Build and test TypeScript SDK CI

[error] 139-139: Type '{ family_name: string; given_name: string; picture: string; email: string; phone: string; id: string; }' is not assignable to type 'UserType'.

🧹 Nitpick comments (1)
lib/sdk/utilities/token-utils.ts (1)

58-62: Consider adding error handling for JWT verification

The JWT verification looks good and the logic to determine the session type based on the ksp claim is clear. However, there's no error handling if the JWT verification fails in this function.

 export const commitTokensToSession = async (
   sessionManager: SessionManager,
   tokens: TokenCollection,
   validationDetails: TokenValidationDetailsType
 ): Promise<void> => {
-  const key = await validationDetails.keyProvider();
-  const result = await jwtVerify(tokens.access_token, key);
+  let sessionType = 'persistent'; // Default to persistent
+  try {
+    const key = await validationDetails.keyProvider();
+    const result = await jwtVerify(tokens.access_token, key);
+    sessionType = result.payload.ksp === 'non_persistent' ? 'session' : 'persistent';
+  } catch (e) {
+    // Log error or handle gracefully, but continue with default sessionType
+    console.error('Failed to verify token for session type determination:', e);
+  }

-  const sessionType =
-    result.payload.ksp === 'non_persistent' ? 'session' : 'persistent';
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b4d3c8b and b9e031e.

📒 Files selected for processing (1)
  • lib/sdk/utilities/token-utils.ts (3 hunks)
🧰 Additional context used
🪛 GitHub Actions: Build and test TypeScript SDK CI
lib/sdk/utilities/token-utils.ts

[error] 139-139: Type '{ family_name: string; given_name: string; picture: string; email: string; phone: string; id: string; }' is not assignable to type 'UserType'.

🔇 Additional comments (4)
lib/sdk/utilities/token-utils.ts (4)

16-17: Good addition of JSDoc for the new parameter

The documentation for the new sessionType parameter clearly explains its purpose, which enhances code maintainability.


24-25: Function signature update looks correct

The function signature has been properly updated to include the new sessionType parameter, matching the JSDoc changes.


44-44: Session manager integration looks good

The updated call to setSessionItem now includes the sessionType parameter, allowing for differentiated session storage behavior.


69-70: Function calls correctly updated with the new parameter

All calls to commitTokenToSession have been consistently updated to include the sessionType parameter.

Also applies to: 76-77, 83-84

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant