Skip to content
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

fix: update expires #1155

Merged
merged 1 commit into from
Dec 12, 2024
Merged

fix: update expires #1155

merged 1 commit into from
Dec 12, 2024

Conversation

markusahlstrand
Copy link

@markusahlstrand markusahlstrand commented Dec 12, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced session and email verification code expiration management.
    • Improved ticket validation logic to prevent reuse of tickets.
  • Bug Fixes

    • Updated error handling for ticket validation to provide clearer feedback.
  • Chores

    • Removed unused constants and updated expiration constants for better clarity and management.

Copy link

coderabbitai bot commented Dec 12, 2024

Walkthrough

The changes in this pull request involve updates to session expiration handling and OTP code generation across several files. Key modifications include the introduction of new constants for session and email verification expiration times, adjustments in the logic for validating and marking OTP codes and tickets, and the enhancement of error handling mechanisms. These changes aim to clarify the management of different types of codes and their respective lifetimes while maintaining the existing overall control flow.

Changes

File Change Summary
src/authentication-flows/password.ts - Added constant LOGIN_SESSION_EXPIRATION_TIME.
- Updated requestPasswordReset to use LOGIN_SESSION_EXPIRATION_TIME instead of CODE_EXPIRATION_TIME.
src/authentication-flows/passwordless.ts - Updated validateCode to mark OTP codes as used via env.data.codes.used.
- Replaced CODE_EXPIRATION_TIME with EMAIL_VERIFICATION_EXPIRATION_TIME in sendEmailVerificationEmail.
src/authentication-flows/ticket.ts - Enhanced ticket validation in ticketAuth to check if a ticket is used.
- Changed method from removing a ticket to marking it as used.
src/constants.ts - Removed commented-out headers object.
- Updated CODE_EXPIRATION_TIME to 30 minutes.
- Added EMAIL_VERIFICATION_EXPIRATION_TIME and LOGIN_SESSION_EXPIRATION_TIME.
src/routes/universal-login/routes.tsx - Imported EMAIL_VERIFICATION_EXPIRATION_TIME and updated its usage in the POST /u/pre-signup route.

Possibly related PRs


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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. (Experiment)
  • @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

@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 and nitpick comments (1)
src/authentication-flows/password.ts (1)

Line range hint 82-91: Consider improving the OTP generation loop

The while loop for ensuring unique OTP generation could be improved for better reliability and performance.

Consider using a more deterministic approach with a maximum retry limit:

-  while (existingCode) {
+  let attempts = 0;
+  const MAX_ATTEMPTS = 5;
+  while (existingCode && attempts < MAX_ATTEMPTS) {
     code_id = generateOTP();
     existingCode = await ctx.env.data.codes.get(
       client.tenant.id,
       code_id,
       "password_reset",
     );
+    attempts++;
   }
+  if (attempts >= MAX_ATTEMPTS) {
+    throw new Error("Failed to generate unique OTP code after maximum attempts");
+  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cc42604 and e3ee2f3.

📒 Files selected for processing (5)
  • src/authentication-flows/password.ts (2 hunks)
  • src/authentication-flows/passwordless.ts (3 hunks)
  • src/authentication-flows/ticket.ts (2 hunks)
  • src/constants.ts (1 hunks)
  • src/routes/universal-login/routes.tsx (2 hunks)
🔇 Additional comments (8)
src/constants.ts (1)

7-9: Significant changes to expiration times - verify impact on existing integrations

The changes introduce a clearer separation of concerns for different types of expiration:

  • OTP codes: 30 minutes (reduced from 24 hours)
  • Login sessions: 24 hours
  • Email verification: 1 week

Consider documenting these timeouts in the API documentation to set clear expectations for integrators.

✅ Verification successful

Changes to CODE_EXPIRATION_TIME are safe to proceed

The codebase analysis shows that:

  • The CODE_EXPIRATION_TIME is used consistently for short-lived codes (OTP, password reset)
  • Tests don't have any hardcoded expectations of 24-hour validity
  • Most test cases use short expiration times (10 seconds) for testing
  • The system already handles expired codes gracefully with proper error messages
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any hardcoded time expectations in tests or documentation
rg -i "expir|valid for|24 hours|1 day" --type md --type test

Length of output: 91


Script:

#!/bin/bash
# Search for any hardcoded time expectations in tests or documentation, using correct file extensions
rg -i "expir|valid for|24 hours|1 day" -g "*.md" -g "*.test.*" -g "*.spec.*"

# Search for usage of the CODE_EXPIRATION_TIME constant
rg "CODE_EXPIRATION_TIME" -A 2 -B 2

# Search for any test files that might be validating expiration times
fd -e test.ts -e spec.ts -e test.js -e spec.js --exec grep -l "expir"

Length of output: 5671

src/authentication-flows/ticket.ts (2)

35-37: Security improvement: Better validation of used tickets

The additional check for code.used_at prevents ticket reuse, improving security.


48-48: Verify implementation of codes.used method

The change from removing codes to marking them as used improves audit capability but requires proper implementation.

src/authentication-flows/password.ts (2)

9-12: Clean import of new constant

The import changes are well-organized and properly grouped.


65-67: Correct usage of LOGIN_SESSION_EXPIRATION_TIME

The login session expiration now uses the dedicated constant, improving clarity and maintainability.

src/authentication-flows/passwordless.ts (2)

171-173: LGTM! Good separation of concerns for different code types.

The use of a separate expiration time for email verification codes is a good practice, as it allows for different lifetimes based on the code's purpose.


81-81: Verify the behavioral change in OTP code handling.

The change from removing OTP codes to marking them as used is a significant behavioral change that improves audit capabilities. However, we should verify that:

  1. The used status is properly checked during code validation
  2. Used codes cannot be reused
✅ Verification successful

Based on the results, I can now generate the final response as I have sufficient information about code validation and reuse prevention.

The change from remove to used is safely implemented with proper validation

The codebase correctly validates codes by checking both existence and usage status:

  • In src/authentication-flows/ticket.ts: if (!code || code.used_at)
  • In src/authentication-flows/passwordless.ts: Basic existence check with if (!code)
  • All code validation paths properly retrieve codes with correct tenant and type parameters

The implementation ensures that:

  1. Codes are validated before use
  2. Used codes are detected via the used_at timestamp
  3. Each code type (otp, ticket, password_reset, email_verification) has its own validation flow
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of code validation and reuse prevention

# Test 1: Check if code validation includes used status check
ast-grep --pattern 'env.data.codes.get($_,$_,$_)' -A 10

# Test 2: Search for other instances of code validation
rg -A 5 'codes\.get'

Length of output: 11322

src/routes/universal-login/routes.tsx (1)

1499-1501: LGTM! Consistent use of email verification expiration time.

The change correctly uses the new EMAIL_VERIFICATION_EXPIRATION_TIME constant in the pre-signup flow, maintaining consistency with the email verification changes in passwordless.ts.

✅ Verification successful

Consistent usage of EMAIL_VERIFICATION_EXPIRATION_TIME confirmed

The constant is correctly defined in constants.ts with a one-week expiration time and is consistently used in both email verification contexts:

  • Pre-signup flow in routes.tsx
  • Passwordless authentication in passwordless.ts
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistent usage of EMAIL_VERIFICATION_EXPIRATION_TIME

# Test: Check if EMAIL_VERIFICATION_EXPIRATION_TIME is used consistently for email verification
rg -A 3 'EMAIL_VERIFICATION_EXPIRATION_TIME'

Length of output: 1359

@markusahlstrand markusahlstrand merged commit 58ca6ed into main Dec 12, 2024
2 checks passed
@markusahlstrand markusahlstrand deleted the ma/expires branch December 12, 2024 12:05
This was referenced Dec 12, 2024
@coderabbitai coderabbitai bot mentioned this pull request Dec 20, 2024
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