Skip to content

fix: don't return null on server routes.#343

Merged
DanielRivers merged 3 commits intorelease/2.5from
fix/router-return
Jun 9, 2025
Merged

fix: don't return null on server routes.#343
DanielRivers merged 3 commits intorelease/2.5from
fix/router-return

Conversation

@DanielRivers
Copy link
Copy Markdown
Member

Explain your changes

Replaced null result on prefetch requests

Checklist

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

@DanielRivers DanielRivers requested review from Yoshify and removed request for DaveOrDead and peterphanouvong June 5, 2025 23:39
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jun 5, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This update introduces a new portal route and handler, adds a corresponding React component, and expands the routes configuration. It refactors authentication middleware and several handlers to improve error handling, token refresh logic, and prefetch request management. Additional utility functions and types are updated or introduced, and the changelog and version are incremented.

Changes

File(s) Change Summary
CHANGELOG.md, src/utils/version.js Changelog updated for v2.6.1 and v2.6.2; version constant updated to '2.6.2'.
eslint.config.mjs ESLint configuration file removed.
src/components/PortalLink.tsx, src/components/index.js New PortalLink React component added and exported.
src/config/index.ts Added portal route to exported routes object.
src/handlers/auth.js, src/handlers/portal.ts New portal handler introduced and registered in route map.
src/handlers/callback.ts Enhanced to handle login_link_expired error and perform reauth redirection.
src/handlers/createOrg.ts, src/handlers/login.ts, src/handlers/logout.ts, src/handlers/register.ts Prefetch requests now return JSON responses instead of null; login/register handlers add supports_reauth parameter.
src/handlers/setup.ts, src/utils/workQueue.ts Refactored setup to use a singleton request queue; added RequestQueueManager class.
src/types.ts Fixed typos in KindeOrganizationProperties property names.
src/authMiddleware/authMiddleware.ts, src/utils/cookies/getSplitSerializedCookies.ts, src/utils/cookies/getStandardCookieOptions.ts Refactored cookie handling to use new utility; improved token refresh and error handling in middleware.
src/utils/validateState.ts Expanded allowed characters in state validation regex.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Router
    participant PortalHandler
    participant Session
    participant Storage
    participant KindeClient

    Client->>Router: Request /portal
    Router->>PortalHandler: Invoke portal()
    PortalHandler->>Session: Get access token
    alt No access token
        PortalHandler->>Router: Redirect to login
    else Access token exists
        PortalHandler->>Storage: Store access token
        PortalHandler->>KindeClient: generatePortalUrl(params)
        alt Success
            PortalHandler->>Router: Redirect to portal URL
        else Failure
            PortalHandler->>Router: Redirect to default URL
        end
    end
Loading
sequenceDiagram
    participant Client
    participant Middleware
    participant KindeClient
    participant Response

    Client->>Middleware: Request protected route
    Middleware->>KindeClient: Validate tokens
    alt Tokens expired
        Middleware->>KindeClient: Refresh tokens
        alt Success
            Middleware->>Response: Set refreshed token cookies
            Middleware->>Client: Continue
        else Failure
            Middleware->>Client: Redirect to login
        end
    else Tokens valid
        Middleware->>Client: Continue
    end
Loading

Possibly related PRs

Suggested reviewers

  • DaveOrDead
  • peterphanouvong

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • 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 docstrings to generate docstrings for this 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.

@DanielRivers DanielRivers changed the base branch from main to release/2.5 June 5, 2025 23:40
Copy link
Copy Markdown
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 4

🧹 Nitpick comments (5)
src/utils/cookies/getStandardCookieOptions.ts (1)

1-14: LGTM! Consider simplifying the domain assignment.

The utility function effectively centralizes cookie configuration and improves maintainability. The typing is correct and the logic is sound.

Consider simplifying the domain assignment since the ternary operator is redundant:

-    domain: config.cookieDomain ? config.cookieDomain : undefined,
+    domain: config.cookieDomain,

When config.cookieDomain is falsy, it will already be undefined or falsy, achieving the same result.

src/utils/workQueue.ts (1)

1-5: Consider improving type safety.

The QueueItem type uses any types which reduces type safety. Consider making it generic to preserve type information.

-type QueueItem = {
-  execute: () => Promise<any>;
-  resolve: (value: any) => void;
-  reject: (error: any) => void;
+type QueueItem<T = unknown> = {
+  execute: () => Promise<T>;
+  resolve: (value: T) => void;
+  reject: (error: any) => void;
 };

Then update the queue property and related methods to use the generic type.

🧰 Tools
🪛 GitHub Actions: Build and test

[warning] 1-1: Prettier formatting check warning. Code style issues found. Run Prettier with --write to fix.

src/components/PortalLink.tsx (2)

17-30: Consider URL encoding for query parameters.

The current implementation doesn't encode the subNav and returnUrl parameters, which could lead to issues if these values contain special characters.

  if (subNav !== undefined) {
-    params.append("subNav", subNav);
+    params.append("subNav", encodeURIComponent(subNav));
  }

  if (returnUrl !== undefined) {
-    params.append("returnUrl", returnUrl);
+    params.append("returnUrl", encodeURIComponent(returnUrl));
  }

Note: URLSearchParams.append() actually handles encoding automatically, so this change may not be necessary. Consider verifying the encoding behavior.


32-38: Simplify conditional rendering logic.

The portalUrl && check is unnecessary since portalUrl is always a non-empty string based on the construction logic above.

  return (
-    portalUrl && (
-      <a href={portalUrl} {...props}>
-        {children}
-      </a>
-    )
+    <a href={portalUrl} {...props}>
+      {children}
+    </a>
  );
src/handlers/portal.ts (1)

36-48: Enhance error handling specificity.

The current error handling catches all errors and redirects to the default URL. Consider logging more specific error information or handling different error types differently.

  } catch (error) {
-    console.error("Portal URL generation failed:", error);
+    console.error("Portal URL generation failed:", {
+      error: error.message,
+      subNav: routerClient.searchParams.get("subNav"),
+      returnUrl,
+      domain: config.issuerURL
+    });
    return routerClient.redirect(config.redirectURL);
  }
🛑 Comments failed to post (4)
src/utils/workQueue.ts (1)

23-23: ⚠️ Potential issue

Fix indentation to resolve Prettier formatting warning.

The indentation on this line is inconsistent with the surrounding code and is causing the pipeline failure.

-        console.debug("enqueue: task added to queue");
+      console.debug("enqueue: task added to queue");
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      console.debug("enqueue: task added to queue");
🤖 Prompt for AI Agents
In src/utils/workQueue.ts at line 23, the console.debug statement has
inconsistent indentation causing a Prettier formatting warning. Adjust the
indentation of this line to match the surrounding code block, ensuring it aligns
properly with other statements at the same scope level.
src/handlers/createOrg.ts (1)

1-1: 💡 Verification agent

🧩 Analysis chain

Verify import path consistency.

The import path uses "src/utils/getHeaders" while line 4 uses "src/utils/isPreFetch". Ensure these paths are consistent with the project's import conventions.


🏁 Script executed:

#!/bin/bash
# Check if the import paths follow consistent patterns across the codebase
echo "Checking import path patterns for utils..."
rg "from [\"']src/utils/" --type ts --type js -A 1 -B 1

echo -e "\nChecking relative vs absolute import patterns..."
rg "from [\"']\.\./utils/" --type ts --type js -A 1 -B 1

Length of output: 6984


Align import paths for utils to use relative imports

In src/handlers/createOrg.ts, the getHeaders and isPreFetch imports are using absolute paths, while the rest of the handlers import from ../utils/.... To match the project convention, please update them to:

-import { getHeaders } from "src/utils/getHeaders";
+import { getHeaders } from "../utils/getHeaders";

-import { isPreFetch } from "src/utils/isPreFetch";
+import { isPreFetch } from "../utils/isPreFetch";

This keeps all utility imports consistent across handlers.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

-import { getHeaders } from "src/utils/getHeaders";
+import { getHeaders } from "../utils/getHeaders";

-import { isPreFetch } from "src/utils/isPreFetch";
+import { isPreFetch } from "../utils/isPreFetch";
🤖 Prompt for AI Agents
In src/handlers/createOrg.ts at line 1, the import path for getHeaders uses an
absolute path "src/utils/getHeaders" which is inconsistent with the project's
convention of using relative imports for utilities. Change the import path to a
relative path like "../utils/getHeaders" to align with other handlers and
maintain consistency in import statements.
src/handlers/portal.ts (1)

23-24: 💡 Verification agent

🧩 Analysis chain

Consider memory storage cleanup.

The memory storage is created and set as active but there's no cleanup mechanism. Consider if this could lead to memory leaks in long-running processes.


🏁 Script executed:

#!/bin/bash
# Check how memory storage is used across the codebase and if cleanup is handled
echo "Checking MemoryStorage usage patterns..."
rg "MemoryStorage|setActiveStorage" --type ts --type js -A 3 -B 1

echo -e "\nChecking for any cleanup patterns..."
rg "cleanup|clear|reset.*storage" --type ts --type js -A 2 -B 2

Length of output: 1692


Add explicit cleanup for MemoryStorage to prevent memory leaks
Currently, we instantiate and activate an in-memory store without ever clearing or disposing it, which can lead to unbounded memory growth in long-running processes.

• File: src/handlers/portal.ts, lines 23–24

  const storage = new MemoryStorage();
  setActiveStorage(storage);

Recommendations:

  • If MemoryStorage supports a clear or dispose method, invoke it once the storage is no longer needed:
    await doYourWork();
    storage.clear();       // or storage.dispose();
    setActiveStorage(null);
  • Otherwise, extend MemoryStorage with a cleanup API and ensure it’s called at the end of the request/handler lifecycle.
🤖 Prompt for AI Agents
In src/handlers/portal.ts at lines 23-24, the MemoryStorage instance is created
and set active without any cleanup, risking memory leaks in long-running
processes. To fix this, check if MemoryStorage has a clear or dispose method and
call it when the storage is no longer needed, such as at the end of the handler
or request lifecycle. Also, reset the active storage by calling
setActiveStorage(null) after cleanup. If no cleanup method exists, extend
MemoryStorage to add one and ensure it is invoked appropriately.
src/handlers/callback.ts (1)

8-14: 🛠️ Refactor suggestion

Fix variable naming conflict to avoid confusion.

The variable reauthState is used both for the search parameter (line 8) and the parsed JSON object (line 12), which creates confusion and potential for bugs.

Apply this diff to use distinct variable names:

-      const reauthState = routerClient.getSearchParam("reauth_state");
-      if (reauthState) {
-        const decodedAuthState = atob(reauthState);
+      const reauthStateParam = routerClient.getSearchParam("reauth_state");
+      if (reauthStateParam) {
+        const decodedAuthState = atob(reauthStateParam);
         try {
           const reauthState = JSON.parse(decodedAuthState);
🤖 Prompt for AI Agents
In src/handlers/callback.ts lines 8 to 14, the variable name reauthState is used
twice for different purposes, causing a naming conflict. Rename the parsed JSON
object variable on line 12 to a distinct name like parsedReauthState to avoid
confusion and potential bugs while keeping the original reauthState for the
search parameter.

Copy link
Copy Markdown
Contributor

@Yoshify Yoshify left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@DanielRivers DanielRivers merged commit d8886cb into release/2.5 Jun 9, 2025
3 checks passed
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