Skip to content

Conversation

@d4mr
Copy link
Contributor

@d4mr d4mr commented Sep 4, 2025

PR-Codex overview

This PR improves error handling in the auth.ts middleware by refining the hash comparison logic for POST requests. It adds detailed information to the error message, including both the hash from the access token and the computed hash from the request.

Detailed summary

  • Simplified the conditional structure for checking bodyHash.
  • Introduced a variable computedBodyHash to store the hash of the request body.
  • Enhanced the error message to include both the expected and computed hashes for better debugging.

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Summary by CodeRabbit

  • New Features
    • None
  • Bug Fixes
    • Clearer error when a signed POST body hash mismatches, including both hashes for easier debugging.
    • Error message now links to the updated v2 documentation.
  • Refactor
    • Streamlined body hash computation to run once per request for improved efficiency.

@coderabbitai
Copy link

coderabbitai bot commented Sep 4, 2025

Walkthrough

Refactors body hash validation in handleKeypairAuth to compute the request body hash once for POST requests when a bodyHash is present, compares it to the token’s bodyHash, and throws a detailed error on mismatch with updated documentation link. Other logic remains unchanged.

Changes

Cohort / File(s) Summary
Auth middleware refactor
src/server/middleware/auth.ts
Consolidated POST body hash computation; replaced inline comparison with a single calculation and equality check; enhanced mismatch error to include both hashes and updated docs URL; removed previous static error and v1 link; no other logic changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant S as Server
  participant A as Auth Middleware
  participant H as BodyHash Calculator
  participant T as Token (bodyHash)

  C->>S: HTTP Request (may be POST)
  S->>A: Invoke handleKeypairAuth
  alt POST with bodyHash in payload
    A->>H: Compute request body hash
    H-->>A: bodyHash(request)
    A->>T: Compare bodyHash(request) vs token.bodyHash
    alt Hash mismatch
      A-->>S: Throw error (includes both hashes, v2 docs URL)
      S-->>C: 4xx Error
    else Hash match
      A-->>S: Auth continues
      S-->>C: Proceed
    end
  else Non-POST or no bodyHash
    A-->>S: Skip body hash validation
    S-->>C: Proceed
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch pb/better-keypair-auth-error-message

🪧 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 or @coderabbit 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.

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

Caution

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

⚠️ Outside diff range comments (1)
src/server/middleware/auth.ts (1)

513-517: Make hashing robust and stable (handle undefined/raw body, avoid stringify pitfalls)

JSON.stringify(req.body) can be undefined or reorder keys; prefer raw bytes when available and fall back safely to strings/JSON. Consider:

// Replace implementation of hashRequestBody:
const hashRequestBody = (req: FastifyRequest): string => {
  const rawBody = (req as any).rawBody; // if using fastify-raw-body or equivalent
  if (Buffer.isBuffer(rawBody)) {
    return createHash("sha256").update(rawBody).digest("hex");
  }
  const bodyStr =
    typeof rawBody === "string"
      ? rawBody
      : typeof req.body === "string"
      ? req.body
      : JSON.stringify(req.body ?? {});
  return createHash("sha256").update(bodyStr, "utf8").digest("hex");
};
🧹 Nitpick comments (1)
src/server/middleware/auth.ts (1)

334-340: Optional: use constant‑time comparison for hashes

Mitigate timing side-channels when comparing hashes.

  • Add import:
    import { createHash, timingSafeEqual } from "node:crypto";
  • Compare using Buffers:
const a = Buffer.from(computedBodyHash, "hex");
const b = Buffer.from(payload.bodyHash, "hex");
const equal = a.length === b.length && timingSafeEqual(a, b);
if (!equal) {
  error =
    "The request body does not match the hash in the token. See: https://portal.thirdweb.com/engine/v2/features/keypair-authentication";
  throw new Error(error);
}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

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 357c402 and 8219e2d.

📒 Files selected for processing (1)
  • src/server/middleware/auth.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build
  • GitHub Check: lint
🔇 Additional comments (1)
src/server/middleware/auth.ts (1)

334-340: Docs URL Verified
The v2 docs page exists and includes the bodyHash validation section as expected.

Comment on lines +334 to 340
if (req.method === "POST" && payload?.bodyHash) {
const computedBodyHash = hashRequestBody(req);
if (computedBodyHash !== payload.bodyHash) {
error = `The request body does not match the hash in the access token. See: https://portal.thirdweb.com/engine/v2/features/keypair-authentication. [hash in access token: ${payload.bodyHash}, hash computed from request: ${computedBodyHash}]`;
throw error;
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Harden bodyHash validation: handle empty bodies, avoid echoing hashes, support more HTTP methods, and throw Error objects

  • JSON.stringify(undefined) can throw via createHash.update; guard for missing/empty body.
  • Returning both hashes in the client-visible error leaks unnecessary detail.
  • Restricting to POST misses PUT/PATCH/DELETE with bodies.
  • Prefer throwing Error objects over strings for consistency.

Apply this diff within this block:

-    // If `bodyHash` is provided, it must match a hash of the POST request body.
-    if (req.method === "POST" && payload?.bodyHash) {
-      const computedBodyHash = hashRequestBody(req);
-      if (computedBodyHash !== payload.bodyHash) {
-        error = `The request body does not match the hash in the access token. See: https://portal.thirdweb.com/engine/v2/features/keypair-authentication. [hash in access token: ${payload.bodyHash}, hash computed from request: ${computedBodyHash}]`;
-        throw error;
-      }
-    }
+    // If `bodyHash` is provided, it must match a hash of the request body.
+    if (payload?.bodyHash && ["POST", "PUT", "PATCH", "DELETE"].includes(req.method)) {
+      const hasBody =
+        typeof req.body === "string" ||
+        (req.body !== null &&
+          typeof req.body === "object" &&
+          Object.keys(req.body as Record<string, unknown>).length > 0);
+      if (!hasBody) {
+        error =
+          'Request body is missing or empty while the token includes a "bodyHash". See: https://portal.thirdweb.com/engine/v2/features/keypair-authentication';
+        throw new Error(error);
+      }
+      const computedBodyHash = hashRequestBody(req);
+      if (computedBodyHash !== payload.bodyHash) {
+        error =
+          "The request body does not match the hash in the token. See: https://portal.thirdweb.com/engine/v2/features/keypair-authentication";
+        throw new Error(error);
+      }
+    }
📝 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 (req.method === "POST" && payload?.bodyHash) {
const computedBodyHash = hashRequestBody(req);
if (computedBodyHash !== payload.bodyHash) {
error = `The request body does not match the hash in the access token. See: https://portal.thirdweb.com/engine/v2/features/keypair-authentication. [hash in access token: ${payload.bodyHash}, hash computed from request: ${computedBodyHash}]`;
throw error;
}
}
// If `bodyHash` is provided, it must match a hash of the request body.
if (payload?.bodyHash && ["POST", "PUT", "PATCH", "DELETE"].includes(req.method)) {
const hasBody =
typeof req.body === "string" ||
(req.body !== null &&
typeof req.body === "object" &&
Object.keys(req.body as Record<string, unknown>).length > 0);
if (!hasBody) {
error =
'Request body is missing or empty while the token includes a "bodyHash". See: https://portal.thirdweb.com/engine/v2/features/keypair-authentication';
throw new Error(error);
}
const computedBodyHash = hashRequestBody(req);
if (computedBodyHash !== payload.bodyHash) {
error =
"The request body does not match the hash in the token. See: https://portal.thirdweb.com/engine/v2/features/keypair-authentication";
throw new Error(error);
}
}

@d4mr d4mr merged commit bd30727 into main Sep 4, 2025
8 checks passed
@d4mr d4mr deleted the pb/better-keypair-auth-error-message branch September 4, 2025 19:20
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