Skip to content

Conversation

turkaturki
Copy link
Collaborator

@turkaturki turkaturki commented Sep 14, 2025

Summary
This pull request performs code cleanup and formatting improvements for the following middleware files:

rateLimit.ts
auth.ts
Changes
Removed duplicate imports and unused code.
Fixed malformed block comments for clarity and documentation consistency.
Improved type usage and formatting for better readability and maintainability.
Ensured both files follow consistent code style and best practices.

Summary by CodeRabbit

  • Refactor
    • Improved type safety for request handling in authentication and rate limiting without changing runtime behavior.
  • Documentation
    • Clarified internal comments and docblocks to better explain rate limiting configuration and error handling.
  • Style
    • Minor formatting cleanups for consistency, including trailing comma adjustments and whitespace tidy-ups.

No user-facing functionality changed; behavior and public interfaces remain the same.

Copy link
Contributor

coderabbitai bot commented Sep 14, 2025

Walkthrough

Type annotations were tightened in auth middleware for wallet signature verification. Rate limiting middleware received minor formatting/comment updates and a slightly safer walletAddress extraction in the key generator. No control flow or exported API changes.

Changes

Cohort / File(s) Summary of Changes
Auth middleware typing
src/middleware/auth.ts
Narrowed request body typing in verifyWalletSignature to { walletAddress: string; message: string; signature: string }; retained runtime string checks; minor whitespace cleanup.
Rate limiting middleware maintenance
src/middleware/rateLimit.ts
Formatting/comment adjustments; safer cast for walletAddress in rateLimitKeyGenerator; added trailing comma in retryAfter response field; removed inline comment in registerRateLimiting; no behavior changes.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested reviewers

  • metanodreamer

Poem

A nibble of types, a hop through the gates,
I tightened the fields, aligned all the states.
Rate limits groomed with a tidy little comb,
Wallets verified—thump-thump—I roam.
In burrows of code where safe casts dwell,
This rabbit stamps OK: all is well. 🐇✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "chore: code cleanup and formatting for middleware files" accurately and concisely summarizes the primary change set, which is non-functional cleanup and formatting applied to middleware files (auth.ts and rateLimit.ts) as shown in the PR summary. It uses the conventional "chore:" prefix and is clear enough for a teammate scanning history to understand the main intent without being overly verbose.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore/code-cleanup-middleware

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

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

🧹 Nitpick comments (5)
src/middleware/auth.ts (1)

27-27: Avoid asserting a concrete body shape; either keep it unknown or type the request Body

Asserting { walletAddress: string; message: string; signature: string } can mislead TS since the values can still be undefined at runtime. Two safer options:

  • Minimal: destructure from a generic record and keep your existing runtime typeof checks.
  • Better: type the Fastify request Body so the middleware is sound at compile time.

Minimal change (within this line):

-const { walletAddress, message, signature } = request.body as { walletAddress: string; message: string; signature: string };
+const { walletAddress, message, signature } = request.body as Record<string, unknown>;

Stronger typing (outside this line; adjust the function signature):

 export async function verifyWalletSignature(
-  request: FastifyRequest,
+  request: FastifyRequest<{ Body: { walletAddress: string; message: string; signature: string } }>,
   reply: FastifyReply
 ) {
src/middleware/rateLimit.ts (4)

54-61: Type the rate‑limit context instead of any

Use a minimal structural type to document usage (or import the plugin’s exported context type if available).

-export const rateLimitErrorHandler = (request: FastifyRequest, context: any) => {
+export const rateLimitErrorHandler = (request: FastifyRequest, context: { ttl: number }) => {

If the plugin exports a dedicated type, prefer it:

// import type { RateLimitContext } from '@fastify/rate-limit';
// export const rateLimitErrorHandler = (_req: FastifyRequest, context: RateLimitContext) => { ... }

If you want me to confirm the exact exported type from @fastify/rate-limit, I can look it up.


4-7: Fix duplicated docblock openings

There’s a repeated /** line inside each block. Clean these up for clarity.

-/**
-/**
+/**

Also applies to: 50-53, 63-66, 82-85, 104-107


9-16: Safer env parsing for max values (radix + fallback)

Current parseInt(process.env.X || 'N') lacks a radix and will propagate NaN if X is set but invalid. Suggest a tiny helper and switch callers.

Add once near the top:

const envInt = (name: string, fallback: number) => {
  const v = process.env[name];
  if (v == null || v === '') return fallback;
  const n = Number.parseInt(v, 10);
  return Number.isNaN(n) ? fallback : n;
};

Then replace e.g.:

- max: parseInt(process.env.RATE_LIMIT_GENERAL_MAX || '100'),
+ max: envInt('RATE_LIMIT_GENERAL_MAX', 100),

(Apply similarly to auth, apiKeyCreation, registration, health.)

Also applies to: 17-24, 25-32, 33-40, 41-48


112-115: Minor: drop unnecessary return

preHandler can just await and fall through; return; is redundant.

-      // Custom logic can be added here if needed
-      return;
+      // Custom logic can be added here if needed
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3d60144 and faaf5a4.

📒 Files selected for processing (2)
  • src/middleware/auth.ts (1 hunks)
  • src/middleware/rateLimit.ts (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
src/middleware/auth.ts (1)
src/utils/verifySignature.ts (1)
  • verifySignature (10-25)
src/middleware/rateLimit.ts (1)
test/utils/verifySignature.test.ts (1)
  • wallet (169-196)
🔇 Additional comments (1)
src/middleware/rateLimit.ts (1)

88-101: Formatting/trailing commas: LGTM

Consistent trailing commas and minor formatting improve diffs and readability. No behavior changes.

Comment on lines 70 to 79
if (request.body && typeof request.body === 'object' && 'walletAddress' in request.body) {
walletAddress = (request.body as any).walletAddress;
walletAddress = (request.body as { walletAddress?: string }).walletAddress;
}
if (!walletAddress && request.headers['x-wallet-address']) {
walletAddress = String(request.headers['x-wallet-address']);
}
// If wallet address is available, use IP + wallet for more granular control
if (walletAddress) {
return `${ip}:${walletAddress.toLowerCase()}`;
}
// Fallback to just IP
return ip;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Guard walletAddress before calling toLowerCase to prevent runtime crashes

walletAddress from the body can be non‑string (e.g., number/array), which would throw on .toLowerCase(). Add a type check (and optionally trim) before usage. Also gate the final branch on a string.

   let walletAddress: string | undefined;
   if (request.body && typeof request.body === 'object' && 'walletAddress' in request.body) {
-    walletAddress = (request.body as { walletAddress?: string }).walletAddress;
+    const raw = (request.body as { walletAddress?: unknown }).walletAddress;
+    if (typeof raw === 'string' && raw.trim() !== '') {
+      walletAddress = raw;
+    }
   }
   if (!walletAddress && request.headers['x-wallet-address']) {
     walletAddress = String(request.headers['x-wallet-address']);
   }
-  if (walletAddress) {
+  if (typeof walletAddress === 'string' && walletAddress) {
     return `${ip}:${walletAddress.toLowerCase()}`;
   }
📝 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.

Suggested change
if (request.body && typeof request.body === 'object' && 'walletAddress' in request.body) {
walletAddress = (request.body as any).walletAddress;
walletAddress = (request.body as { walletAddress?: string }).walletAddress;
}
if (!walletAddress && request.headers['x-wallet-address']) {
walletAddress = String(request.headers['x-wallet-address']);
}
// If wallet address is available, use IP + wallet for more granular control
if (walletAddress) {
return `${ip}:${walletAddress.toLowerCase()}`;
}
// Fallback to just IP
return ip;
if (request.body && typeof request.body === 'object' && 'walletAddress' in request.body) {
const raw = (request.body as { walletAddress?: unknown }).walletAddress;
if (typeof raw === 'string' && raw.trim() !== '') {
walletAddress = raw;
}
}
if (!walletAddress && request.headers['x-wallet-address']) {
walletAddress = String(request.headers['x-wallet-address']);
}
if (typeof walletAddress === 'string' && walletAddress) {
return `${ip}:${walletAddress.toLowerCase()}`;
}
return ip;
🤖 Prompt for AI Agents
In src/middleware/rateLimit.ts around lines 70 to 79, the code calls
walletAddress.toLowerCase() without ensuring walletAddress is a string; if the
body/header contains a non-string (number, array, object) this will throw. Fix
by checking typeof walletAddress === 'string' (and optionally trimming) before
calling toLowerCase; when reading from request.headers coerce to string only
after verifying it's a string-like value or use String(...) and then guard that
the resulting value is a non-empty string before lowercasing; if walletAddress
is not a valid string, fall back to returning ip.

@metanodreamer metanodreamer merged commit aa43be1 into main Sep 14, 2025
1 check 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