Skip to content

Conversation

@SGFGOV
Copy link
Contributor

@SGFGOV SGFGOV commented May 14, 2025

An attempt to build a webhook with a x-signature-header

Summary by CodeRabbit

  • New Features
    • Webhook payloads are now cryptographically signed with an HMAC signature for enhanced security.
  • Improvements
    • Stronger typing for webhook payloads to ensure better data consistency.
  • Other
    • Minor cleanup to remove unnecessary debug logging.
    • Updated documentation with a new configuration option for webhook secret management.

@SGFGOV SGFGOV requested a review from Copilot May 14, 2025 08:58
@coderabbitai
Copy link

coderabbitai bot commented May 14, 2025

Walkthrough

The WebhooksService class was updated to support HMAC signature generation for webhook payloads using a secret key. The constructor and method signatures were refined for stronger typing, and a new method for creating HMAC signatures was added. Webhook requests now include an x-webhook-signature header with the computed signature.

Changes

File(s) Change Summary
plugins/webhooks/src/modules/webhooks/service.ts - Added HMAC signature generation for webhook payloads
- Extended options to include secretKey
- Updated constructor and method signatures for stricter typing
- Added createHmacSignature method
- Modified send to include signature in headers
- Removed debug log from sendWebhooksEvents
plugins/webhooks/README.md - Added secretKey configuration option example to plugin setup snippet

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant WebhooksService
    participant WebhookEndpoint

    Client->>WebhooksService: sendWebhooksEvents(webhooks, payload)
    loop for each webhook in webhooks
        WebhooksService->>WebhooksService: createHmacSignature(payload)
        WebhooksService->>WebhookEndpoint: POST payload + x-webhook-signature header
        WebhookEndpoint-->>WebhooksService: Response
    end
    WebhooksService-->>Client: PromiseFulfilledResult[]
Loading

Suggested reviewers

  • antony-lambdacurry

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 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 188cf25 and eff113f.

📒 Files selected for processing (1)
  • plugins/webhooks/src/modules/webhooks/service.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • plugins/webhooks/src/modules/webhooks/service.ts
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 docstrings to generate docstrings for this 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

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR introduces HMAC signing for webhook requests by generating a signature header using the node:crypto module.

  • Introduces a helper method to generate HMAC signatures for payloads.
  • Updates the payload type definitions for enhanced type safety.
  • Adjusts the options type passed to the service to include a webhook secret key.

logger: Logger;
};

type WebhookOptions = LoaderOptions & { subscriptions: string[] & { secretKey: string } };
Copy link

Copilot AI May 14, 2025

Choose a reason for hiding this comment

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

The type definition for WebhookOptions seems off; combining subscriptions as string[] with an embedded secretKey is confusing. Consider separating secretKey from subscriptions, e.g., 'LoaderOptions & { secretKey: string, subscriptions: string[] }'.

Copilot uses AI. Check for mistakes.
Copy link
Contributor Author

Choose a reason for hiding this comment

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

old

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

🧹 Nitpick comments (4)
plugins/webhooks/src/modules/webhooks/service.ts (4)

47-52: Add validation for payload before signature creation.

The current implementation doesn't validate that the payload is properly serializable before creating the signature. This could lead to unexpected errors if the payload contains circular references or non-serializable values.

  createHmacSignature(payload: Record<string, unknown>) {
+   // Ensure payload is serializable to prevent unexpected errors
+   try {
+     const stringifiedPayload = JSON.stringify(payload);
+     return Crypto
+       .createHmac("sha256", this.options.secretKey)
+       .update(stringifiedPayload)
+       .digest("hex");
+   } catch (error) {
+     this.logger.error("Failed to create signature for payload", error);
+     throw new Error("Failed to create signature: payload contains non-serializable values");
+   }
-   return Crypto
-     .createHmac("sha256", this.options.secretKey)
-     .update(JSON.stringify(payload))
-     .digest("hex");
  }

67-67: Improve webhook signature header with timestamp.

The current implementation only includes the signature hex digest. Industry standard practice is to also include a timestamp to prevent replay attacks. This allows receivers to verify that the webhook was sent within an acceptable time window.

Consider enhancing the signature header format to include a timestamp:

- "x-webhook-signature": this.createHmacSignature(payload),
+ const timestamp = Math.floor(Date.now() / 1000).toString();
+ "x-webhook-signature": `t=${timestamp},v1=${this.createHmacSignature({ ...payload, timestamp })}`,

This would require updating the createHmacSignature method signature and implementation to handle the enhanced payload, but it significantly improves security against replay attacks.


88-88: Apply consistent documentation for method parameters.

You've updated the method signature with stronger typing, but it lacks JSDoc documentation that describes the parameters and return values. This would be helpful for developers using this API.

+ /**
+  * Sends webhook events to multiple webhook endpoints
+  * @param webhooks - Array of webhook models to send events to
+  * @param payload - The data payload to send with the webhook
+  * @returns Promise resolving to an array of webhook send responses
+  */
  public async sendWebhooksEvents(webhooks: WebhookModel[], payload: Record<string, unknown>) {

123-125: Update test webhook method to use the same payload type.

The testWebhookSubscription method still uses a simple object { test: true } as payload, while other methods now expect Record<string, unknown>. This is technically compatible, but it would be better to be explicit for consistency.

- const response = await this.send(testData, {
-   test: true,
- });
+ const response = await this.send(testData, {
+   test: true,
+   timestamp: new Date().toISOString(),
+ } as Record<string, unknown>);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b5837c2 and 69db6f7.

📒 Files selected for processing (1)
  • plugins/webhooks/src/modules/webhooks/service.ts (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
plugins/webhooks/src/modules/webhooks/service.ts (1)
plugins/webhooks/src/common.ts (1)
  • WebhookModel (4-4)
🔇 Additional comments (1)
plugins/webhooks/src/modules/webhooks/service.ts (1)

5-5:

✅ Verification successful

Consider using the crypto module more securely.

Using the Node.js crypto module is appropriate, but you should consider the impact on environments like browsers if this code needs to run there.


🏁 Script executed:

#!/bin/bash
# Check if the service might be used in browser environments
echo "Checking for browser usage indications..."
rg -i "browser|isomorphic|universal" --type ts
echo "Checking for package.json browser field..."
cat package.json 2>/dev/null | grep -i "\"browser\""

Length of output: 277


No browser usage detected; Node.js crypto is safe here
We’ve searched for any browser/isomorphic/universal indicators in the TypeScript code and no browser field exists in package.json. This service lives on the server side, so importing node:crypto is appropriate.

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

🧹 Nitpick comments (1)
plugins/webhooks/README.md (1)

32-32: Prefer formatting consistency and avoid hardcoding secrets
The snippet currently reads:

secretKey:"Your-webhook-secret"
  1. Add a space after the colon and a trailing comma for uniform JSON style:
-    secretKey:"Your-webhook-secret"
+    secretKey: "Your-webhook-secret",
  1. (Optional) Instead of hardcoding, demonstrate reading the secret from an environment variable to follow security best practices:
-    secretKey: "Your-webhook-secret",
+    secretKey: process.env.WEBHOOK_SECRET_KEY,
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 69db6f7 and f9792f2.

📒 Files selected for processing (2)
  • plugins/webhooks/README.md (1 hunks)
  • plugins/webhooks/src/modules/webhooks/service.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • plugins/webhooks/src/modules/webhooks/service.ts

@SGFGOV SGFGOV added the enhancement New feature or request label May 14, 2025
@SGFGOV
Copy link
Contributor Author

SGFGOV commented May 15, 2025

@dwene can you approve this :)

this.options = options;
this.subscriptions = options.subscriptions;
if (!this.options.secretKey) {
this.logger.warn('No secretKey provided for webhook signatures. Webhook security will be compromised.');
Copy link
Contributor

Choose a reason for hiding this comment

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

The wording here is a little extreme haha. Can we tweak this a bit?

No webhook secret key was found. Please provide a secretKey in the plugin options. A default will be used instead, but this may reduce the security of webhook signatures.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Sure.. Will fix it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants