Skip to content

Conversation

@jaredpiedt
Copy link
Contributor

@jaredpiedt jaredpiedt commented Jun 19, 2025

Description

This adds the event_attributes property to webhook events.

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • New Features
    • Webhook events now include additional information about the originating HTTP request, such as client IP and user agent, providing more context for each event.

@changeset-bot
Copy link

changeset-bot bot commented Jun 19, 2025

🦋 Changeset detected

Latest commit: 728110a

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 11 packages
Name Type
@clerk/backend Patch
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch

Not sure what this means? Click here to learn what changesets are.

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

@vercel
Copy link

vercel bot commented Jun 19, 2025

@jaredpiedt is attempting to deploy a commit to the Clerk Production Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 19, 2025

📝 Walkthrough

Walkthrough

The changes introduce a new field, event_attributes, to the Webhook entity within the @clerk/backend package. The Webhook type is updated to include this property, which contains HTTP request metadata such as client_ip and user_agent, structured under an http_request object. The verifyWebhook function is modified to include the event_attributes from the webhook payload in its returned event object. No other logic or public API signatures are altered, and the update is categorized as a patch.


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 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.

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 comments (1)
packages/backend/src/webhooks.ts (1)

83-85: Critical: Fix inverted signature verification logic.

The signature verification logic is inverted. Currently, it throws an error when the constructed signature IS found in the svix signature list, which means it rejects valid signatures and accepts invalid ones. This is a critical security vulnerability.

Apply this fix:

-  if (svixSignature.split(' ').includes(constructedSignature)) {
+  if (!svixSignature.split(' ').includes(constructedSignature)) {
     return errorThrower.throw('Incoming webhook does not have a valid signature');
   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 545999c and cd2ea92.

📒 Files selected for processing (3)
  • .changeset/sixty-regions-camp.md (1 hunks)
  • packages/backend/src/api/resources/Webhooks.ts (1 hunks)
  • packages/backend/src/webhooks.ts (1 hunks)
🔇 Additional comments (3)
packages/backend/src/api/resources/Webhooks.ts (2)

16-21: Well-structured type definition for HTTP request metadata.

The WebhookEventAttributes type properly encapsulates HTTP request information with appropriate nesting under http_request.


23-23: Verify backward compatibility for required event_attributes property.

Adding event_attributes as a required property to the Webhook type could be a breaking change if existing webhook payloads don't include this field. Consider making it optional initially or ensure all webhook sources provide this field.

#!/bin/bash
# Description: Search for existing Webhook type usage to assess potential breaking changes
# Expected: Find usages that might be affected by the new required property

echo "Searching for Webhook type usage patterns..."
rg -A 3 -B 3 "Webhook<" --type ts

echo -e "\nSearching for webhook payload parsing..."
rg -A 5 -B 5 "JSON\.parse.*payload|payload.*JSON\.parse" --type ts

echo -e "\nSearching for webhook event creation/construction..."
rg -A 5 -B 5 "type.*event.*object.*data" --type ts
.changeset/sixty-regions-camp.md (1)

1-6: Changeset documentation looks good.

The changeset correctly documents this as a patch-level change with a clear description.

type: payload.type,
object: 'event',
data: payload.data,
event_attributes: payload.event_attributes,
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add null safety for event_attributes extraction.

The code assumes payload.event_attributes exists, but it should handle cases where this property might be missing from older webhook payloads to maintain backward compatibility.

Apply this diff to add null safety:

-    event_attributes: payload.event_attributes,
+    event_attributes: payload.event_attributes || { http_request: { client_ip: '', user_agent: '' } },

Or make the property optional in the type definition if it's acceptable for it to be undefined.

📝 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
event_attributes: payload.event_attributes,
event_attributes: payload.event_attributes || { http_request: { client_ip: '', user_agent: '' } },
🤖 Prompt for AI Agents
In packages/backend/src/webhooks.ts at line 93, the code accesses
payload.event_attributes without checking if it exists, which can cause errors
with older webhook payloads. To fix this, add a null check or use optional
chaining when extracting event_attributes to safely handle cases where it might
be undefined. Alternatively, update the type definition to make event_attributes
optional if that aligns with the expected data structure.

@kylemac kylemac requested a review from a team July 9, 2025 12:14
Copy link
Member

@brkalow brkalow left a comment

Choose a reason for hiding this comment

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

Awesome, thanks!

@pkg-pr-new
Copy link

pkg-pr-new bot commented Jul 9, 2025

Open in StackBlitz

@clerk/agent-toolkit

npm i https://pkg.pr.new/@clerk/agent-toolkit@6162

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@6162

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@6162

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@6162

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@6162

@clerk/dev-cli

npm i https://pkg.pr.new/@clerk/dev-cli@6162

@clerk/elements

npm i https://pkg.pr.new/@clerk/elements@6162

@clerk/clerk-expo

npm i https://pkg.pr.new/@clerk/clerk-expo@6162

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@6162

@clerk/express

npm i https://pkg.pr.new/@clerk/express@6162

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@6162

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@6162

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@6162

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@6162

@clerk/clerk-react

npm i https://pkg.pr.new/@clerk/clerk-react@6162

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@6162

@clerk/remix

npm i https://pkg.pr.new/@clerk/remix@6162

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@6162

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@6162

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@6162

@clerk/themes

npm i https://pkg.pr.new/@clerk/themes@6162

@clerk/types

npm i https://pkg.pr.new/@clerk/types@6162

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@6162

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@6162

commit: 8879e7b

@brkalow
Copy link
Member

brkalow commented Jul 9, 2025

@jaredpiedt Can you ensure we also have an associated test case here? You can use the existing test cases as a reference.

https://github.com/clerk/javascript/blob/main/packages/backend/src/__tests__/webhooks.test.ts

@jaredpiedt
Copy link
Contributor Author

@jaredpiedt Can you ensure we also have an associated test case here? You can use the existing test cases as a reference.

https://github.com/clerk/javascript/blob/main/packages/backend/src/__tests__/webhooks.test.ts

@brkalow definitely, I'll get that added today

@jaredpiedt
Copy link
Contributor Author

@brkalow test case has been added

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

🧹 Nitpick comments (1)
packages/backend/src/__tests__/webhooks.test.ts (1)

221-250: Well-structured test case for event_attributes functionality.

The test correctly validates the new event_attributes property and follows the established patterns in the test suite. The test structure, assertions, and usage of the helper function are appropriate.

Consider adding a few more test cases to ensure comprehensive coverage:

  1. Test with empty event_attributes: Verify behavior when event_attributes is an empty object or missing entirely
  2. Test with partial http_request data: Test cases where only client_ip or user_agent is present
  3. Test with additional nested properties: If event_attributes might contain other properties beyond http_request
it('should handle missing event_attributes gracefully', async () => {
  const clerkPayload = JSON.stringify({
    type: 'user.created',
    data: { id: 'user_123', email: '[email protected]' },
    // event_attributes intentionally omitted
  });
  
  const svixId = 'msg_123';
  const svixTimestamp = (Date.now() / 1000).toString();
  const validSignature = createValidSignature(svixId, svixTimestamp, clerkPayload);

  const mockRequest = new Request('https://clerk.com/webhooks', {
    method: 'POST',
    body: clerkPayload,
    headers: new Headers({
      'svix-id': svixId,
      'svix-timestamp': svixTimestamp,
      'svix-signature': validSignature,
    }),
  });

  const result = await verifyWebhook(mockRequest, { signingSecret: mockSecret });
  expect(result).toHaveProperty('type', 'user.created');
  expect(result).not.toHaveProperty('event_attributes');
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8879e7b and 728110a.

📒 Files selected for processing (1)
  • packages/backend/src/__tests__/webhooks.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
`**/*.{js,jsx,ts,tsx}`: All code must pass ESLint checks with the project's conf...

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Use Prettier for consistent code formatting
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Validate all inputs and sanitize outputs
Implement proper logging with different levels

📄 Source: CodeRabbit Inference Engine (.cursor/rules/development.mdc)

List of files the instruction was applied to:

  • packages/backend/src/__tests__/webhooks.test.ts
`packages/**/*.ts`: TypeScript is required for all packages

packages/**/*.ts: TypeScript is required for all packages

📄 Source: CodeRabbit Inference Engine (.cursor/rules/development.mdc)

List of files the instruction was applied to:

  • packages/backend/src/__tests__/webhooks.test.ts
`**/{__tests__,**/__tests__}/**/*.{js,jsx,ts,tsx}`: Test files should be co-located with source files or in `__tests__` directories

**/{__tests__,**/__tests__}/**/*.{js,jsx,ts,tsx}: Test files should be co-located with source files or in __tests__ directories

📄 Source: CodeRabbit Inference Engine (.cursor/rules/development.mdc)

List of files the instruction was applied to:

  • packages/backend/src/__tests__/webhooks.test.ts
`packages/**/*.{ts,tsx,d.ts}`: Packages should export TypeScript types alongside runtime code

packages/**/*.{ts,tsx,d.ts}: Packages should export TypeScript types alongside runtime code

📄 Source: CodeRabbit Inference Engine (.cursor/rules/development.mdc)

List of files the instruction was applied to:

  • packages/backend/src/__tests__/webhooks.test.ts
`**/*.{ts,tsx}`: Use proper TypeScript error types

**/*.{ts,tsx}: Use proper TypeScript error types

📄 Source: CodeRabbit Inference Engine (.cursor/rules/development.mdc)

List of files the instruction was applied to:

  • packages/backend/src/__tests__/webhooks.test.ts
`**/*.{test,spec}.{js,ts,tsx}`: Unit tests should use Jest or Vitest as the test runner.

**/*.{test,spec}.{js,ts,tsx}: Unit tests should use Jest or Vitest as the test runner.

📄 Source: CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

List of files the instruction was applied to:

  • packages/backend/src/__tests__/webhooks.test.ts
`**/*.{ts,tsx}`: Always define explicit return types for functions, especially p...

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Document public functions and APIs with JSDoc-style comments including @param, @returns, @throws, and @example
Define custom error classes for domain-specific errors
Use the Result pattern for error handling instead of throwing exceptions
Use optional chaining and nullish coalescing for safe property access
Let TypeScript infer types when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use readonly arrays and objects for immutability
Use immutable update patterns (spread, etc.) for objects and arrays
Use lazy loading for large types
Prefer unknown over any for performance
Use type-only imports: import type { ... }
Use branded types for domain safety
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints in TypeScript generics
No unused type parameters in generics
Proper use of utility types instead of manual type construction
Type-only imports where possible for performance
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

📄 Source: CodeRabbit Inference Engine (.cursor/rules/typescript.mdc)

List of files the instruction was applied to:

  • packages/backend/src/__tests__/webhooks.test.ts
`**/__tests__/**/*.{ts,tsx}`: Use Vitest for type-safe testing in TypeScript Cre...

**/__tests__/**/*.{ts,tsx}: Use Vitest for type-safe testing in TypeScript
Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces in tests

📄 Source: CodeRabbit Inference Engine (.cursor/rules/typescript.mdc)

List of files the instruction was applied to:

  • packages/backend/src/__tests__/webhooks.test.ts
`**/*.ts`: If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

**/*.ts: If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • packages/backend/src/__tests__/webhooks.test.ts
🧠 Learnings (2)
📓 Common learnings
Learnt from: dstaley
PR: clerk/javascript#6116
File: .changeset/tangy-garlics-say.md:1-2
Timestamp: 2025-06-13T16:09:53.061Z
Learning: In the Clerk JavaScript repository, contributors create intentionally empty changeset files (containing only the YAML delimiters) when a PR touches only non-published parts of the codebase (e.g., sandbox assets). This signals that no package release is required, so such changesets should not be flagged as missing content.
Learnt from: wobsoriano
PR: clerk/javascript#6163
File: packages/backend/src/api/endpoints/APIKeysApi.ts:60-70
Timestamp: 2025-06-20T17:44:17.570Z
Learning: The Clerk codebase uses POST method for API key update operations instead of the typical PATCH method, as clarified by the maintainer wobsoriano.
packages/backend/src/__tests__/webhooks.test.ts (2)
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/react.mdc:0-0
Timestamp: 2025-06-30T10:32:37.848Z
Learning: Applies to **/*.test.{jsx,tsx} : Implement proper test assertions
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/typescript.mdc:0-0
Timestamp: 2025-06-30T10:33:45.961Z
Learning: Applies to **/__tests__/**/*.{ts,tsx} : Implement proper mock types that match interfaces in tests

@brkalow brkalow merged commit e3da9f4 into clerk:main Jul 9, 2025
2 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants