Skip to content

fix: Add a webhook for WorkOS, update middleware to allow webhooks#3048

Merged
perkinsjr merged 5 commits intomainfrom
workos-auth-extras
Mar 30, 2025
Merged

fix: Add a webhook for WorkOS, update middleware to allow webhooks#3048
perkinsjr merged 5 commits intomainfrom
workos-auth-extras

Conversation

@perkinsjr
Copy link
Member

@perkinsjr perkinsjr commented Mar 30, 2025

What does this PR do?

A few tune ups for WorkOS

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

  • New Features

    • Added a new API endpoint to process WorkOS webhook events that support automated notifications and user onboarding.
    • Expanded public access to key integration endpoints, making interactions with services like Stripe and GitHub smoother.
    • Introduced an optional environment variable for enhanced configuration flexibility.
  • Removed

    • Discontinued the legacy webhook endpoint previously used for handling user events.

@changeset-bot
Copy link

changeset-bot bot commented Mar 30, 2025

⚠️ No Changeset found

Latest commit: 147a65a

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 Mar 30, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
dashboard ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 30, 2025 5:54pm
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 30, 2025 5:54pm
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 30, 2025 5:54pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 30, 2025 5:54pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 30, 2025

📝 Walkthrough

Walkthrough

The pull request introduces an optional environment variable (WORKOS_WEBHOOK_SECRET) into the environment configuration and extends middleware to include three additional public API paths. It removes the Clerk webhook endpoint along with its associated types and constants, and it adds a new WorkOS webhook API endpoint. The new WorkOS endpoint validates incoming POST requests, processes "user.created" events, and interacts with external services for notifications and email handling.

Changes

File(s) Change Summary
apps/dashboard/lib/env.ts Added optional environment variable WORKOS_WEBHOOK_SECRET to the environment schema.
apps/dashboard/middleware.ts Added new public paths: "/api/webhooks/stripe", "/api/v1/workos/webhooks", and "/api/v1/github/verify" to allow unauthenticated access.
apps/dashboard/pages/api/v1/clerk/webhooks.ts Removed the Clerk webhook endpoint (including its handler, types, and config).
apps/dashboard/pages/api/v1/workos/webhooks.ts Added a new WorkOS webhook endpoint that validates requests, processes events, and invokes Slack notifications and email actions.
internal/db/src/schema/audit_logs.ts Reformatted import statements for readability and added .notNull() constraint to auditLogId field in auditLogTarget table.

Suggested labels

Bug, 🕹️ oss.gg, :joystick: 150 points, hacktoberfest

Suggested reviewers

  • mcstepp
  • perkinsjr

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 147a65a and c2efbdd.

📒 Files selected for processing (1)
  • internal/db/src/schema/audit_logs.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/db/src/schema/audit_logs.ts
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Test Agent Local / test_agent_local
  • GitHub Check: Test API / API Test Local
  • GitHub Check: autofix
  • GitHub Check: Analyze (javascript-typescript)

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@github-actions
Copy link
Contributor

github-actions bot commented Mar 30, 2025

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

@perkinsjr perkinsjr requested a review from MichaelUnkey as a code owner March 30, 2025 17:34
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

🧹 Nitpick comments (5)
apps/dashboard/pages/api/v1/workos/webhooks.ts (5)

16-17: Remove console.log statements before production

Console statements should be removed from production code as they can expose sensitive information in logs.

-        console.info("payload",payload);
-        console.info(req.headers);

7-8: Consider handling all HTTP methods explicitly

The current implementation only checks for POST requests but doesn't explicitly return an error for other methods.

 export default async (req: NextApiRequest, res: NextApiResponse) => {
   if (req.method === 'POST') {
+  } else {
+    return res.status(405).json({ error: "Method not allowed" });
   }
 };

63-102: Improve error handling in alertSlack function

The current implementation swallows errors from the Slack notification. Consider at least logging the error more descriptively or propagating it up to be handled by the caller.

 async function alertSlack(email: string): Promise<void> {
     const url = process.env.SLACK_WEBHOOK_URL_SIGNUP;
     if (!url) {
+        console.warn("SLACK_WEBHOOK_URL_SIGNUP not configured");
         return;
     }
     const domain = email.split("@").at(-1);
     if (!domain) {
+        console.warn(`Could not extract domain from email: ${email}`);
         return;
     }
     if (freeDomains.includes(domain)) {
+        console.debug(`Skipping Slack notification for free email domain: ${domain}`);
         return;
     }

     await fetch(url, {
         method: "POST",
         headers: {
             "Content-Type": "application/json",
         },
         body: JSON.stringify({
             text: `${email} signed up`,
             blocks: [
                 {
                     type: "section",
                     fields: [
                         {
                             type: "mrkdwn",
                             text: `${email} signed up`,
                         },
                         {
                             type: "mrkdwn",
                             text: `<https://${domain}>`,
                         },
                     ],
                 },
             ],
         }),
     }).catch((err: Error) => {
-        console.error(err);
+        console.error(`Failed to send Slack notification: ${err.message}`);
+        // Consider whether you want to throw the error to propagate it
+        // throw new Error(`Slack notification failed: ${err.message}`);
     });
 }

40-42: Add email format validation

Consider validating the email format before processing it, as invalid email formats could cause issues downstream.

 if (!webhookData.email) {
     return res.status(400).json({ Error: "No email address found" });
 }
+// Simple regex for basic email validation
+const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+if (!emailRegex.test(webhookData.email)) {
+    return res.status(400).json({ Error: "Invalid email format" });
+}

65-74: Consider extracting email domain validation to a separate utility function

The domain validation logic could be useful elsewhere in the codebase.

+/**
+ * Checks if an email is from a business domain (not a free email provider)
+ */
+function isBusinessEmail(email: string): boolean {
+    const domain = email.split("@").at(-1);
+    if (!domain) return false;
+    return !freeDomains.includes(domain);
+}

 async function alertSlack(email: string): Promise<void> {
     const url = process.env.SLACK_WEBHOOK_URL_SIGNUP;
     if (!url) {
         return;
     }
     const domain = email.split("@").at(-1);
     if (!domain) {
         return;
     }
-    if (freeDomains.includes(domain)) {
+    if (!isBusinessEmail(email)) {
         return;
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2d0ed03 and cb82a09.

📒 Files selected for processing (4)
  • apps/dashboard/lib/env.ts (1 hunks)
  • apps/dashboard/middleware.ts (1 hunks)
  • apps/dashboard/pages/api/v1/clerk/webhooks.ts (0 hunks)
  • apps/dashboard/pages/api/v1/workos/webhooks.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • apps/dashboard/pages/api/v1/clerk/webhooks.ts
🧰 Additional context used
🧬 Code Definitions (1)
apps/dashboard/pages/api/v1/workos/webhooks.ts (1)
apps/dashboard/lib/env.ts (1)
  • env (3-52)
⏰ Context from checks skipped due to timeout of 90000ms (19)
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Go API Local / Test (Shard 8/8)
  • GitHub Check: Test Go API Local / Test (Shard 2/8)
  • GitHub Check: Test Go API Local / Test (Shard 4/8)
  • GitHub Check: Test Packages / Test ./packages/api
  • GitHub Check: Test Packages / Test ./packages/nextjs
  • GitHub Check: Test Go API Local / Test (Shard 3/8)
  • GitHub Check: Test Packages / Test ./packages/hono
  • GitHub Check: Test Go API Local / Test (Shard 1/8)
  • GitHub Check: Test Packages / Test ./internal/resend
  • GitHub Check: Test API / API Test Local
  • GitHub Check: Test Packages / Test ./internal/keys
  • GitHub Check: Test Packages / Test ./internal/id
  • GitHub Check: Test Packages / Test ./internal/encryption
  • GitHub Check: Test Packages / Test ./internal/hash
  • GitHub Check: Test Packages / Test ./internal/billing
  • GitHub Check: Build / Build
  • GitHub Check: Test Agent Local / test_agent_local
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
apps/dashboard/lib/env.ts (1)

46-46: LGTM: New environment variable for WorkOS webhook

The addition of WORKOS_WEBHOOK_SECRET as an optional environment variable is correctly implemented and appropriately placed with other WorkOS-related configurations.

apps/dashboard/middleware.ts (1)

26-28: Webhook paths correctly added to public routes

The addition of these webhook paths to the publicPaths array ensures they'll be accessible without authentication, which is necessary for external services to call these endpoints.

@vercel vercel bot temporarily deployed to Preview – dashboard March 30, 2025 17:36 Inactive
@vercel vercel bot temporarily deployed to Preview – www March 30, 2025 17:36 Inactive
@vercel vercel bot temporarily deployed to Preview – engineering March 30, 2025 17:37 Inactive
@vercel vercel bot temporarily deployed to Preview – play March 30, 2025 17:38 Inactive
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

♻️ Duplicate comments (1)
apps/dashboard/pages/api/v1/workos/webhooks.ts (1)

21-29: ⚠️ Potential issue

Missing try/catch around WorkOS webhook construction

The webhook construction is missing error handling. If the signature validation fails, it will throw an exception that isn't currently caught, potentially causing unhandled promise rejections.

    const workos = new WorkOS(WORKOS_API_KEY);

-    const webhook = await workos.webhooks.constructEvent({
-      payload: payload,
-      sigHeader: sigHeader,
-      secret: WORKOS_WEBHOOK_SECRET,
-    });
-
-    if (!webhook) {
-      return res.status(400).json({ Error: "Invalid payload" });
-    }
+    try {
+      const webhook = await workos.webhooks.constructEvent({
+        payload: payload,
+        sigHeader: sigHeader,
+        secret: WORKOS_WEBHOOK_SECRET,
+      });
+
+      if (!webhook) {
+        return res.status(400).json({ Error: "Invalid payload" });
+      }
🧹 Nitpick comments (3)
apps/dashboard/pages/api/v1/workos/webhooks.ts (3)

72-97: Improve error handling in the Slack notification

The current implementation catches errors but only logs them. Consider returning the error or at least adding more context to the log.

  await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      text: `${email} signed up`,
      blocks: [
        {
          type: "section",
          fields: [
            {
              type: "mrkdwn",
              text: `${email} signed up`,
            },
            {
              type: "mrkdwn",
              text: `<https://${domain}>`,
            },
          ],
        },
      ],
    }),
-  }).catch((err: Error) => {
-    console.error(err);
-  });
+  }).catch((err: Error) => {
+    console.error("Failed to send Slack notification:", err);
+  });

64-67: Improve domain extraction robustness

The current domain extraction assumes the email format is valid and contains an "@" symbol. Add validation to handle malformed emails.

-  const domain = email.split("@").at(-1);
-  if (!domain) {
+  // Ensure the email format is valid before extracting domain
+  if (!email.includes("@")) {
+    console.warn(`Invalid email format: ${email}`);
     return;
   }
+  const domain = email.split("@").at(-1);
+  if (!domain) {
+    console.warn(`Could not extract domain from: ${email}`);
+    return;
+  }

16-18: Improve error message for missing payload or signature

The current error message "Nope" is not descriptive enough. Consider providing a more informative error message.

  if (!payload || !sigHeader) {
-    return res.status(400).json({ Error: "Nope" });
+    return res.status(400).json({ Error: "Missing payload or signature header" });
  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6c302cf and 147a65a.

📒 Files selected for processing (1)
  • apps/dashboard/pages/api/v1/workos/webhooks.ts (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
apps/dashboard/pages/api/v1/workos/webhooks.ts (1)
apps/dashboard/lib/env.ts (1)
  • env (3-52)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test Agent Local / test_agent_local
🔇 Additional comments (3)
apps/dashboard/pages/api/v1/workos/webhooks.ts (3)

9-14: Good job validating environment variables

The code properly checks for all required environment variables before proceeding, which prevents runtime errors.


39-54: Well-structured try-catch block for operations

The code correctly wraps the Resend operations and Slack notification in a try-catch block, providing appropriate error handling.


68-70: Good filtering of free email domains

The implementation correctly filters out notifications for free email domains, which helps reduce noise in the Slack channel.

@vercel vercel bot temporarily deployed to Preview – www March 30, 2025 17:41 Inactive
@vercel vercel bot temporarily deployed to Preview – engineering March 30, 2025 17:42 Inactive
@vercel vercel bot temporarily deployed to Preview – play March 30, 2025 17:43 Inactive
@vercel vercel bot temporarily deployed to Preview – dashboard March 30, 2025 17:44 Inactive
@vercel vercel bot temporarily deployed to Preview – www March 30, 2025 17:53 Inactive
@vercel vercel bot temporarily deployed to Preview – engineering March 30, 2025 17:54 Inactive
@vercel vercel bot temporarily deployed to Preview – dashboard March 30, 2025 17:54 Inactive
@vercel vercel bot temporarily deployed to Preview – play March 30, 2025 17:54 Inactive
@perkinsjr perkinsjr merged commit 635c687 into main Mar 30, 2025
34 of 36 checks passed
@perkinsjr perkinsjr deleted the workos-auth-extras branch March 30, 2025 17:57
@coderabbitai coderabbitai bot mentioned this pull request Mar 31, 2025
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