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: ignore pre-fetch requests on auth routes #251

Merged
merged 2 commits into from
Dec 17, 2024

Conversation

DanielRivers
Copy link
Contributor

Explain your changes

Issue: When the auth routes are pre-fetched, this could cause unexpected behaviour.

Fix: When a prefetch is noticed, ignore them.

Checklist

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

Copy link
Contributor

coderabbitai bot commented Dec 1, 2024

Walkthrough

The pull request introduces several modifications across multiple handler functions in the codebase. Key changes include the addition of type definitions for the RouterClient parameter, the implementation of a pre-fetch check using a new utility function, and the simplification of return statements by removing the void keyword. These alterations enhance type safety, improve control flow, and clarify the return behavior of the functions involved.

Changes

File Path Change Summary
src/handlers/createOrg.ts Modified return statement to directly return the result of routerClient.redirect(authUrl.toString()).
src/handlers/login.ts Added type definition for routerClient, implemented pre-fetch check, and simplified return statement.
src/handlers/logout.ts Added type definition for routerClient, implemented pre-fetch check, and simplified return statement.
src/handlers/register.ts Added type definition for routerClient, implemented pre-fetch check, and simplified return statement.
src/utils/isPreFetch.ts Introduced new function isPreFetch(req: NextRequest) to determine if a request is a prefetch request.
src/utils/isPreFetch.test.ts Added test cases for the isPreFetch function covering various header configurations and edge cases.

Possibly related PRs

  • fix: Post logout redirect URL #192: The logout function in src/handlers/logout.ts has a similar change in its return statement, where the void keyword is removed to simplify the return behavior, aligning with the changes made in createOrg.
  • fix: API handler warning #248: The logout function in src/handlers/logout.js has been modified to change its return statement to use void, which is a similar alteration to the return statement change in the createOrg function in the main PR.

Suggested reviewers

  • DaveOrDead
  • peterphanouvong

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 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
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: 1

🧹 Outside diff range and nitpick comments (5)
src/utils/isPreFetch.ts (2)

4-6: Consider using a constant for the 'prefetch' string.

The implementation is correct, but we can improve maintainability by extracting the repeated string.

+const PREFETCH_HEADER_VALUE = 'prefetch';
+
 export function isPreFetch(req: NextRequest): boolean {
-    const isPrefetch = req?.headers['purpose'] === 'prefetch' || 
-        req?.headers['x-purpose'] === 'prefetch' ||
-        req?.headers['x-moz'] === 'prefetch';
+    const isPrefetch = req?.headers['purpose'] === PREFETCH_HEADER_VALUE || 
+        req?.headers['x-purpose'] === PREFETCH_HEADER_VALUE ||
+        req?.headers['x-moz'] === PREFETCH_HEADER_VALUE;

3-9: Add JSDoc documentation for the utility function.

Please add documentation explaining the purpose of this function and its role in handling pre-fetch requests.

+/**
+ * Determines if the incoming request is a pre-fetch request by examining various headers.
+ * This is used to prevent unnecessary processing of pre-fetch requests on auth routes.
+ * 
+ * @param req - The Next.js request object
+ * @returns boolean indicating if the request is a pre-fetch request
+ */
 export function isPreFetch(req: NextRequest): boolean {
src/handlers/createOrg.ts (2)

Line range hint 6-6: Add type safety for the routerClient parameter.

For consistency with other handlers and improved type safety, add explicit typing for the routerClient parameter.

-export const createOrg = async (routerClient) => {
+export const createOrg = async (routerClient: RouterClient) => {

Add pre-fetch check for consistency with other auth handlers

The verification shows that all other auth handlers (login, logout, and register) implement pre-fetch checking using the isPreFetch utility, but createOrg handler doesn't. Add the following at the start of the handler:

if (isPreFetch(routerClient.req)) {
  return null;
}
  • src/handlers/createOrg.ts: Add import statement for isPreFetch from "../utils/isPreFetch"
🔗 Analysis chain

Line range hint 1-19: Consider adding pre-fetch check for consistency.

Other auth handlers now implement pre-fetch checking. Should this handler also ignore pre-fetch requests for consistency?

Let's check if this handler is used in similar contexts:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage patterns of createOrg compared to other handlers
echo "Checking createOrg usage patterns:"
rg -A 2 "createOrg|login|logout|register" --type ts

# Check if this is exposed via similar routes
echo "Checking route definitions:"
fd -e ts -e js --full-path "*/api/*" --exec rg -l "createOrg|login|logout|register" {}

Length of output: 5568


Script:

#!/bin/bash
# Let's check for the isPreFetch function implementation and its usage
echo "Checking isPreFetch implementation and usage:"
rg -A 2 "isPreFetch" --type ts

# Let's also check the createOrg route definition
echo "Checking createOrg route definition:"
rg -A 2 "createOrg.*route" --type ts

Length of output: 1540

src/handlers/logout.ts (1)

Line range hint 18-28: Consider additional URL sanitization

The post-logout redirect URL handling looks good, but consider adding additional validation to prevent open redirect vulnerabilities.

Consider:

  1. Validating against an allowlist of domains
  2. Adding URL pattern validation
  3. Implementing strict URL parsing checks
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c65d265 and 987df3c.

📒 Files selected for processing (5)
  • src/handlers/createOrg.ts (1 hunks)
  • src/handlers/login.ts (2 hunks)
  • src/handlers/logout.ts (2 hunks)
  • src/handlers/register.ts (2 hunks)
  • src/utils/isPreFetch.ts (1 hunks)
🔇 Additional comments (6)
src/handlers/login.ts (2)

2-2: Implementation looks good!

The changes effectively address the pre-fetch handling requirement while maintaining existing functionality:

  • Type safety improvements ✓
  • Pre-fetch detection ✓
  • Existing redirect logic preserved ✓

Also applies to: 8-31


8-11: Verify type safety of null return.

The implementation looks good, but let's ensure the return type allows null.

✅ Verification successful

Let me gather more information about the return type of the login handler and related handlers.


Let me check one more thing to verify the return types of these handlers.


Return type of null is safe in this context

Based on the codebase analysis:

  1. Multiple handlers (register, logout, login) follow the same pattern of returning null for pre-fetch checks
  2. The handlers don't have explicit return type annotations, suggesting flexible return types
  3. Other utility functions in the codebase (getUser, getOrganization, etc.) commonly return null as a valid response
  4. The pattern is consistently used across the authentication flow
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if RouterClient methods or related types define return types
echo "Checking RouterClient type definitions:"
rg -A 5 "interface RouterClient|class RouterClient" --type ts

# Look for similar patterns in other handlers
echo "Checking return types in other handlers:"
rg -B 2 "return null" --type ts

Length of output: 2754


Script:

#!/bin/bash
# Check the type definition or implementation of login handler
ast-grep --pattern 'export const login = async $_: $_) => $_'

# Check other handler implementations for return type patterns
ast-grep --pattern 'export const $_ = async $_: RouterClient) => $_'

# Look for RouterClient usage in type definitions
rg "RouterClient" --type ts -B 2 -A 2

Length of output: 2714


Script:

#!/bin/bash
# Look for type definitions or interfaces that might define handler return types
rg "type|interface.*Handler" --type ts -B 2 -A 2

# Check if there are any type annotations in the handlers
ast-grep --pattern 'export const $_ = async ($_: RouterClient): $_ => $_'

Length of output: 13714

src/handlers/register.ts (3)

8-8: Type safety improvement looks good!

The explicit RouterClient type annotation enhances code reliability and IDE support.


31-31: Clean return statement refactor

Good simplification of the return statement by removing unnecessary void.


9-11: Verify pre-fetch handling across all auth routes

The pre-fetch check implementation looks correct. However, let's verify consistent implementation across other auth routes.

✅ Verification successful

Pre-fetch handling is consistent across auth routes with minor logging difference

The verification shows that isPreFetch check is consistently implemented in all auth handlers (login, logout, and register), with the same pattern:

  • All handlers import isPreFetch from "../utils/isPreFetch"
  • All handlers check isPreFetch(routerClient.req) at the start
  • All handlers return null on pre-fetch

Minor note: The logout handler includes an extra console.log("isPreFetch") statement, but this doesn't affect the functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if isPreFetch is consistently implemented across auth handlers
# Expected: All auth handlers should implement the pre-fetch check similarly

# Search for auth handler files and check for isPreFetch implementation
rg -l "RouterClient" src/handlers/ | xargs rg "isPreFetch" -C 2

Length of output: 1538

src/handlers/logout.ts (1)

29-29: Clean return statement refactor

Good simplification of the return statement, consistent with other handlers.

src/handlers/logout.ts Outdated Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (2)
src/utils/isPreFetch.test.ts (2)

7-11: Consider enhancing mock implementation type safety

While the mock function works, it could benefit from improved type safety and clarity.

Consider this enhanced implementation:

-  const mockNextRequest = (headers: Record<string, string>) => {
-    return {
-      headers: new Headers(headers)
-    } as NextRequest;
+  const mockNextRequest = (headers: Record<string, string>): Pick<NextRequest, 'headers'> => {
+    return {
+      headers: new Headers(headers)
+    };

This change:

  • Uses Pick type to be explicit about partial implementation
  • Removes type assertion in favor of explicit typing
  • Makes it clear which parts of NextRequest are being mocked

13-49: Consider adding additional test cases for completeness

The test suite is well-structured with good coverage of basic scenarios and edge cases. However, consider adding these additional test cases for more comprehensive coverage:

Add these test cases:

it('handles case-insensitive header values', () => {
  const req = mockNextRequest({ 
    purpose: 'PREFETCH',
    'x-purpose': 'Prefetch'
  });
  expect(isPreFetch(req)).toBe(true);
});

it('returns true when multiple prefetch headers are present', () => {
  const req = mockNextRequest({ 
    purpose: 'prefetch',
    'x-purpose': 'navigation'
  });
  expect(isPreFetch(req)).toBe(true);
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 93c855e and 79e91fc.

📒 Files selected for processing (3)
  • src/handlers/logout.ts (2 hunks)
  • src/utils/isPreFetch.test.ts (1 hunks)
  • src/utils/isPreFetch.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/handlers/logout.ts
  • src/utils/isPreFetch.ts
🔇 Additional comments (2)
src/utils/isPreFetch.test.ts (2)

1-5: LGTM! Well-structured test file setup

The import statements are clean and follow TypeScript best practices. The test file naming convention follows the standard pattern.


1-50: Verify integration with auth route handlers

The test coverage for the isPreFetch utility is thorough. However, let's verify its integration with auth routes to ensure it fulfills the PR's objective.

✅ Verification successful

Integration with auth routes verified successfully

The isPreFetch utility is properly integrated across all auth route handlers (register, login, and logout). Each handler correctly:

  • Imports the utility function
  • Checks for prefetch requests early in the handler
  • Returns null for prefetch requests, preventing unnecessary processing
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that auth route handlers properly utilize isPreFetch

# Check for isPreFetch usage in auth-related files
echo "Checking auth route handlers for isPreFetch implementation:"
rg -l "isPreFetch" src/handlers/

Length of output: 231


Script:

#!/bin/bash
# Check implementation in auth handlers to verify proper usage
echo "=== Checking register.ts ==="
rg "isPreFetch" src/handlers/register.ts -B 2 -A 2

echo -e "\n=== Checking login.ts ==="
rg "isPreFetch" src/handlers/login.ts -B 2 -A 2

echo -e "\n=== Checking logout.ts ==="
rg "isPreFetch" src/handlers/logout.ts -B 2 -A 2

Length of output: 1114

@DanielRivers DanielRivers merged commit 14fe7fa into main Dec 17, 2024
3 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Dec 17, 2024
2 tasks
@coderabbitai coderabbitai bot mentioned this pull request Jan 9, 2025
2 tasks
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.

2 participants