Skip to content

chore: upgrade @unkey/ratelimit#3822

Merged
chronark merged 2 commits intomainfrom
08-21-chore_upgrade_unkey_ratelimit
Aug 21, 2025
Merged

chore: upgrade @unkey/ratelimit#3822
chronark merged 2 commits intomainfrom
08-21-chore_upgrade_unkey_ratelimit

Conversation

@chronark
Copy link
Collaborator

@chronark chronark commented Aug 21, 2025

What does this PR do?

Fixes # (issue)

If there is not an issue for this, please create one first. This is used to tracking purposes and also helps use understand why this PR exists

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Chore (refactoring code, technical debt, workflow improvements)
  • Enhancement (small improvements)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How should this be tested?

  • Test A
  • Test B

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read Contributing Guide
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand areas
  • Ran pnpm build
  • Ran pnpm fmt
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues

Appreciated

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Unkey Docs if changes were necessary

Summary by CodeRabbit

  • Chores

    • Updated third‑party rate limiting dependency to the latest patch release.
  • Bug Fixes

    • Resend and API flows now tolerate rate limiter errors: such errors are logged but won't block user actions, preserving normal resend and request behavior.
  • Impact

    • No change to user-facing interfaces; fewer interruptions when upstream rate-limit checks fail. No user action required.

@changeset-bot
Copy link

changeset-bot bot commented Aug 21, 2025

⚠️ No Changeset found

Latest commit: 23263e2

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@vercel
Copy link

vercel bot commented Aug 21, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
dashboard Ready Ready Preview Comment Aug 21, 2025 1:54pm
1 Skipped Deployment
Project Deployment Preview Comments Updated (UTC)
engineering Ignored Ignored Preview Aug 21, 2025 1:54pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 21, 2025

📝 Walkthrough

Walkthrough

Added an onError fallback to multiple Ratelimit instances so rate-limiter failures log and return a permissive response, and bumped @unkey/ratelimit in the dashboard package.json from ^2.1.2 to ^2.1.3.

Changes

Cohort / File(s) Summary
Dependency bump — Dashboard app
apps/dashboard/package.json
Update dependency version: @unkey/ratelimit ^2.1.2 → ^2.1.3
TRPC rate limiter wiring
apps/dashboard/lib/trpc/trpc.ts
Add local onError callback for Ratelimit that logs errors and returns fallback { success: true, limit: 0, remaining: 1, reset: 1 }; pass onError into trpc_create/read/update/delete and llmRatelimit constructors.
Auth action rate-limit handling
apps/dashboard/app/auth/actions.ts
Use the Ratelimit onError callback in resendAuthCode so rate-limit errors are logged and yield the permissive fallback, preventing errors from blocking the resend flow.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant TRPC as TRPC handler
  participant RL as Ratelimit
  participant Service as Downstream service

  Client->>TRPC: request (resendAuthCode / trpc call)
  TRPC->>RL: rl.limit(key)
  RL-->>TRPC: success OR (error -> onError fallback)
  Note right of TRPC#lightblue: onError logs and returns permissive response
  TRPC->>Service: continue processing (validation, resend)
  Service-->>TRPC: result
  TRPC-->>Client: response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

Needs Approval

Suggested reviewers

  • mcstepp
  • perkinsjr
  • Flo4604
  • ogzhanolguncu

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 08-21-chore_upgrade_unkey_ratelimit

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@chronark chronark marked this pull request as ready for review August 21, 2025 13:19
Copy link
Collaborator Author

This stack of pull requests is managed by Graphite. Learn more about stacking.

@github-actions
Copy link
Contributor

github-actions bot commented Aug 21, 2025

Thank you for following the naming conventions for pull request titles! 🙏

Copy link
Member

Flo4604 commented Aug 21, 2025

Would it make sense to start using the onError callback in our uses as well, its not used anywhere atm.
So that incase the api ever goes down our dashboard still works?

Copy link
Collaborator Author

yes

Copy link
Collaborator Author

I thought we did, let me fix

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
apps/dashboard/app/auth/actions.ts (1)

103-131: Validate input before rate-limiting and centralize PII redaction

Please apply the following changes:

  1. Early email validation
    Move the empty-email check to before you instantiate the rate limiter, so you don’t consume quota or produce unnecessary errors:

    -  const rl = new Ratelimit({
    +  if (!email.trim()) {
    +    return {
    +      success: false,
    +      code: AuthErrorCode.INVALID_EMAIL,
    +      message: "Email address is required.",
    +    };
    +  }
    +
    +  const rl = new Ratelimit({
         namespace: "resend_code",
         duration: "5m",
         limit: 5,
         rootKey: unkeyRootKey,
  2. Enhance the onError hook
    Redact any PII (email addresses or other identifiers) before logging, and return a failure rather than silently swallowing errors:

       onError: (err: Error, identifier: string) => {
    -      console.error(`Error occurred while rate limiting ${identifier}: ${err.message}`);
    -      return { success: true, limit: 0, remaining: 1, reset: 1 };
    +      const redacted =
    +        identifier && identifier.includes("@")
    +          ? identifier.replace(/(^.).*(@.*$)/, "$1***$2")
    +          : `${identifier?.slice(0, 2) ?? ""}***`;
    +      console.error("[ratelimit] resend_code failure for %s", redacted, err);
    +      return { success: false, limit: 0, remaining: 0, reset: 1 };
       },
  3. Audit and refactor existing console/logger calls
    Our scan flagged multiple locations where raw user identifiers or full user objects (with emails) are logged. These should all be replaced with a centralized, PII-aware logging helper. Examples include:

    • In apps/dashboard/app/auth/actions.ts at lines 99–102:
      onError: (err, identifier) => {
        console.error(`${identifier} - ${err.message}`)        // raw identifier
        return fallback(identifier)
      }
    • Anywhere a full user object is logged (e.g. lines 164–167):
      await cache.user.set("userId", { id: "userId", email: "user@email.com" });
      const user = await cache.user.get("userId");
      console.log(user);                                       // logs email in plaintext
    • Multiple other console.log(userId) or console.error("…", error) calls across the codebase.

    Recommendation: introduce a logging utility (e.g. logRedacted(identifier, message, error?)) or wrap your existing logger to automatically mask emails and IDs. Then replace all direct console.* or logger.* calls that surface PII with that helper.

This will both prevent wasted rate-limit calls on invalid input and ensure no sensitive identifiers ever slip into your logs unredacted.

apps/dashboard/lib/trpc/trpc.ts (2)

148-156: Avoid fail-open on LLM ratelimit (cost exposure).

If the ratelimiter goes down, LLM requests could spike costs. Prefer failing closed or a tight local fallback.

   ? new Ratelimit({
       rootKey: env().UNKEY_ROOT_KEY ?? "",
       namespace: "trpc_llm",
       limit: LLM_LIMITS.RATE_LIMIT,
       duration: LLM_LIMITS.RATE_DURATION,
-      onError,
     })

89-121: Avoid repeated env() calls; retrieve once for consistency and micro-optimizations.

env() parses process.env each call. Read once and reuse.

+const rootKey = env().UNKEY_ROOT_KEY ?? "";
-export const ratelimit = env().UNKEY_ROOT_KEY
+export const ratelimit = rootKey
   ? {
       create: new Ratelimit({
-        rootKey: env().UNKEY_ROOT_KEY ?? "",
+        rootKey,
         namespace: "trpc_create",
         limit: 25,
         duration: "3s",
       }),
       read: new Ratelimit({
-        rootKey: env().UNKEY_ROOT_KEY ?? "",
+        rootKey,
         namespace: "trpc_read",
         limit: 100,
         duration: "10s",
         onError,
       }),
       update: new Ratelimit({
-        rootKey: env().UNKEY_ROOT_KEY ?? "",
+        rootKey,
         namespace: "trpc_update",
         limit: 25,
         duration: "5s",
       }),
       delete: new Ratelimit({
-        rootKey: env().UNKEY_ROOT_KEY ?? "",
+        rootKey,
         namespace: "trpc_delete",
         limit: 25,
         duration: "5s",
       }),
     }
   : {};
 
-const llmRatelimit = env().UNKEY_ROOT_KEY
+const llmRatelimit = rootKey
   ? new Ratelimit({
-      rootKey: env().UNKEY_ROOT_KEY ?? "",
+      rootKey,
       namespace: "trpc_llm",
       limit: LLM_LIMITS.RATE_LIMIT,
       duration: LLM_LIMITS.RATE_DURATION,
     })
   : null;

Also applies to: 148-156

📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between c0d3efb and 23263e2.

📒 Files selected for processing (2)
  • apps/dashboard/app/auth/actions.ts (1 hunks)
  • apps/dashboard/lib/trpc/trpc.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{js,jsx,ts,tsx}: Use Biome for formatting and linting in TypeScript/JavaScript projects
Prefer named exports over default exports in TypeScript/JavaScript, except for Next.js pages

Files:

  • apps/dashboard/app/auth/actions.ts
  • apps/dashboard/lib/trpc/trpc.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Follow strict TypeScript configuration
Use Zod for runtime validation in TypeScript projects

Files:

  • apps/dashboard/app/auth/actions.ts
  • apps/dashboard/lib/trpc/trpc.ts
**/*.{env,js,ts,go}

📄 CodeRabbit inference engine (CLAUDE.md)

All environment variables must follow the format: UNKEY_<SERVICE_NAME>_VARNAME

Files:

  • apps/dashboard/app/auth/actions.ts
  • apps/dashboard/lib/trpc/trpc.ts
🧠 Learnings (1)
📚 Learning: 2024-10-23T12:05:31.121Z
Learnt from: chronark
PR: unkeyed/unkey#2544
File: apps/api/src/pkg/env.ts:4-6
Timestamp: 2024-10-23T12:05:31.121Z
Learning: The `cloudflareRatelimiter` type definition in `apps/api/src/pkg/env.ts` should not have its interface changed; it should keep the `limit` method returning `Promise<{ success: boolean }>` without additional error properties.

Applied to files:

  • apps/dashboard/app/auth/actions.ts
  • apps/dashboard/lib/trpc/trpc.ts
🧬 Code graph analysis (1)
apps/dashboard/lib/trpc/trpc.ts (1)
apps/dashboard/lib/env.ts (1)
  • env (3-49)
🔇 Additional comments (1)
apps/dashboard/lib/trpc/trpc.ts (1)

84-87: The TypeScript compiler isn’t available in this environment, so the tsc step failed. Please run a local typecheck (for example: npx tsc -p apps/dashboard/tsconfig.json --noEmit), then verify that the fallback onError handler’s return value:

{ success: true, limit: 0, remaining: 1, reset: 1 }

matches the type expected by @unkey/ratelimit@2.1.3 (in particular, ensure that:

  • reset is meant to be a number (not a Date),
  • there aren’t any additional required properties on the response object).

Once that’s confirmed, we can consider this concern addressed.

@graphite-app
Copy link

graphite-app bot commented Aug 21, 2025

Ad gif. Sitting in front of an old computer, '90s child actor Brent Rambo gives a robust thumbs up to the camera, his mouth a confident upside-down crescent. His autograph is superimposed onto the scene, giving the impression that his stamp of approval truly matters.  (Added via Giphy)

@graphite-app
Copy link

graphite-app bot commented Aug 21, 2025

Graphite Automations

"Post a GIF when PR approved" took an action on this PR • (08/21/25)

1 gif was posted to this PR based on Andreas Thomas's automation.

Copy link
Collaborator Author

the point of the fallback is to not crash our application, so it should return success: true

@chronark chronark enabled auto-merge August 21, 2025 17:21
@chronark chronark added this pull request to the merge queue Aug 21, 2025
Merged via the queue into main with commit 1cc6af7 Aug 21, 2025
19 checks passed
@chronark chronark deleted the 08-21-chore_upgrade_unkey_ratelimit branch August 21, 2025 17:31
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.

3 participants