Skip to content

Beautiful Open-Source Form Builder

Webhooks protection (#945)

Julien Nahum5d78af8cdf0f
diff --git a/api/app/Http/Requests/Integration/FormIntegrationsRequest.php b/api/app/Http/Requests/Integration/FormIntegrationsRequest.php
index bfba08f9f..d4aa76b3e 100644
--- a/api/app/Http/Requests/Integration/FormIntegrationsRequest.php
+++ b/api/app/Http/Requests/Integration/FormIntegrationsRequest.php
@@ -41,16 +41,26 @@ class FormIntegrationsRequest extends FormRequest
*/
public function rules()
{
- return array_merge([
+ $rules = array_merge([
'integration_id' => ['required', Rule::in(array_keys(FormIntegration::getAllIntegrations()))],
'oauth_id' => [
$this->isOAuthRequired() ? 'required' : 'nullable',
Rule::exists('oauth_providers', 'id')
],
- 'settings' => 'present|array',
- 'status' => 'required|boolean',
+ 'data' => [
+ 'present',
+ 'array',
+ function ($attribute, $value, $fail) {
+ if (empty($value)) {
+ $fail('The data field cannot be empty.');
+ }
+ }
+ ],
+ 'status' => ['required', Rule::in([FormIntegration::STATUS_ACTIVE, FormIntegration::STATUS_INACTIVE])],
'logic' => [new IntegrationLogicRule()],
], $this->integrationRules);
+
+ return $rules;
}
/**
@@ -65,7 +75,7 @@ class FormIntegrationsRequest extends FormRequest
$fields = [];
foreach ($this->rules() as $key => $value) {
$fields[$key] = $attributes[$key] ?? Str::of($key)
- ->replace('settings.', '')
+ ->replace('data.', '')
->headline()
->toString();
}
@@ -81,18 +91,16 @@ class FormIntegrationsRequest extends FormRequest
private function loadIntegrationRules()
{
foreach ($this->integrationClassName::getValidationRules($this->form) as $key => $value) {
- $this->integrationRules['settings.' . $key] = $value;
+ $this->integrationRules['data.' . $key] = $value;
}
}
public function toIntegrationData(): array
{
return $this->integrationClassName::formatData([
- 'status' => ($this->validated(
- 'status'
- )) ? FormIntegration::STATUS_ACTIVE : FormIntegration::STATUS_INACTIVE,
+ 'status' => $this->validated('status'),
'integration_id' => $this->validated('integration_id'),
- 'data' => $this->validated('settings') ?? [],
+ 'data' => $this->validated('data') ?? [],
'logic' => $this->validated('logic') ?? [],
'oauth_id' => $this->validated('oauth_id'),
]);
diff --git a/api/app/Integrations/Handlers/EmailIntegration.php b/api/app/Integrations/Handlers/EmailIntegration.php
index 643213ae9..15f0c2697 100644
--- a/api/app/Integrations/Handlers/EmailIntegration.php
+++ b/api/app/Integrations/Handlers/EmailIntegration.php
@@ -59,7 +59,7 @@ class EmailIntegration extends AbstractIntegrationHandler
->count();
if ($existingEmailIntegrations > 0) {
throw ValidationException::withMessages([
- 'settings.send_to' => ['Free users are limited to 1 email integration per form.']
+ 'data.send_to' => ['Free users are limited to 1 email integration per form.']
]);
}
}
diff --git a/api/app/Integrations/Handlers/WebhookIntegration.php b/api/app/Integrations/Handlers/WebhookIntegration.php
index 2d745743a..366fe5076 100644
--- a/api/app/Integrations/Handlers/WebhookIntegration.php
+++ b/api/app/Integrations/Handlers/WebhookIntegration.php
@@ -3,13 +3,80 @@
namespace App\Integrations\Handlers;
use App\Models\Forms\Form;
+use Illuminate\Support\Facades\Http;
class WebhookIntegration extends AbstractIntegrationHandler
{
+ // Headers that should not be customizable for security reasons
+ private const BLOCKED_HEADERS = [
+ 'Authorization',
+ 'X-Webhook-Signature',
+ 'Content-Type',
+ 'Content-Length',
+ 'Host',
+ 'Cookie',
+ 'X-CSRF-Token',
+ 'X-CSRF-TOKEN',
+ 'X-Forwarded-For',
+ 'X-Forwarded-Proto',
+ 'X-Real-IP',
+ 'X-Requested-With',
+ 'Accept-Encoding',
+ 'Transfer-Encoding',
+ ];
+
public static function getValidationRules(?Form $form): array
{
return [
- 'webhook_url' => 'required|url'
+ 'webhook_url' => 'required|url',
+ 'webhook_secret' => 'nullable|string|min:12',
+ 'webhook_headers' => [
+ 'nullable',
+ 'array',
+ function ($attribute, $value, $fail) {
+ if (!is_array($value)) {
+ return;
+ }
+
+ // Check max 10 headers
+ if (count($value) > 10) {
+ $fail('Maximum 10 custom headers allowed.');
+ return;
+ }
+
+ // Validate each header
+ foreach ($value as $headerName => $headerValue) {
+ // Validate header name
+ if (!is_string($headerName) || empty($headerName)) {
+ $fail('Header names must be non-empty strings.');
+ return;
+ }
+
+ // Check header name length
+ if (strlen($headerName) > 255) {
+ $fail("Header name '{$headerName}' exceeds 255 characters.");
+ return;
+ }
+
+ // Check for blocked headers (case-insensitive)
+ if (in_array(strtolower($headerName), array_map('strtolower', self::BLOCKED_HEADERS))) {
+ $fail("The '{$headerName}' header cannot be customized for security reasons.");
+ return;
+ }
+
+ // Validate header value
+ if (!is_string($headerValue)) {
+ $fail("Header values must be strings. '{$headerName}' has invalid value type.");
+ return;
+ }
+
+ if (strlen($headerValue) > 255) {
+ $fail("Header value for '{$headerName}' exceeds 255 characters.");
+ return;
+ }
+ }
+ }
+ ]
];
}
@@ -18,8 +85,105 @@ class WebhookIntegration extends AbstractIntegrationHandler
return $this->integrationData->webhook_url;
}
+ protected function getWebhookSecret(): ?string
+ {
+ return $this->integrationData->webhook_secret ?? null;
+ }
+
+ protected function getWebhookHeaders(): array
+ {
+ $headers = isset($this->integrationData->webhook_headers) && is_object($this->integrationData->webhook_headers)
+ ? (array) $this->integrationData->webhook_headers
+ : [];
+
+ // Ensure Content-Type is set
+ if (!isset($headers['Content-Type'])) {
+ $headers['Content-Type'] = 'application/json';
+ }
+
+ return $headers;
+ }
+
+ /**
+ * Generate HMAC-SHA256 signature for webhook payload
+ */
+ protected function generateSignature(string $payload): string
+ {
+ $secret = $this->getWebhookSecret();
+ if (!$secret) {
+ return '';
+ }
+
+ return 'sha256=' . hash_hmac('sha256', $payload, $secret);
+ }
+
protected function shouldRun(): bool
{
return !is_null($this->getWebhookUrl()) && parent::shouldRun();
}
+
+ /**
+ * Override handle to inject signature and custom headers
+ */
+ public function handle(): void
+ {
+ if (!$this->shouldRun()) {
+ return;
+ }
+
+ $data = $this->getWebhookData();
+ $payload = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
+ $headers = $this->buildRequestHeaders($payload);
+
+ Http::throw()
+ ->timeout(5)
+ ->withHeaders($headers)
+ ->withBody($payload, 'application/json')
+ ->post($this->getWebhookUrl());
+ }
+
+ /**
+ * Build request headers with signature and custom headers
+ */
+ protected function buildRequestHeaders(string $payload): array
+ {
+ $headers = [];
+
+ // Add signature header if secret is configured
+ $signature = $this->generateSignature($payload);
+ if ($signature) {
+ $headers['X-Webhook-Signature'] = $signature;
+ }
+
+ // Add custom headers
+ $customHeaders = $this->getWebhookHeaders();
+ $headers = array_merge($customHeaders, $headers);
+
+ return $headers;
+ }
+
+ public static function formatData(array $data): array
+ {
+ // Filter and format the integration data
+ if (isset($data['data']) && is_array($data['data'])) {
+ $filtered = [];
+
+ // Keep only webhook-specific fields
+ if (isset($data['data']['webhook_url'])) {
+ $filtered['webhook_url'] = $data['data']['webhook_url'];
+ }
+ if (isset($data['data']['webhook_secret'])) {
+ $filtered['webhook_secret'] = $data['data']['webhook_secret'];
+ }
+
+ // Convert webhook_headers array to object for consistent storage
+ if (isset($data['data']['webhook_headers']) && is_array($data['data']['webhook_headers'])) {
+ $filtered['webhook_headers'] = (object) $data['data']['webhook_headers'];
+ }
+
+ $data['data'] = $filtered;
+ }
+
+ return $data;
+ }
}
diff --git a/api/tests/Feature/Forms/FormIntegrationEventTest.php b/api/tests/Feature/Forms/FormIntegrationEventTest.php
index 421c46f1e..445f3270f 100644
--- a/api/tests/Feature/Forms/FormIntegrationEventTest.php
+++ b/api/tests/Feature/Forms/FormIntegrationEventTest.php
@@ -6,10 +6,10 @@ it('can fetch form integration events', function () {
$form = $this->createForm($user, $workspace);
$data = [
- 'status' => true,
+ 'status' => 'active',
'integration_id' => 'email',
'logic' => null,
- 'settings' => [
+ 'data' => [
'send_to' => '[email protected]',
'sender_name' => 'OpnForm',
'subject' => 'New form submission',
diff --git a/api/tests/Feature/Forms/FormIntegrationTest.php b/api/tests/Feature/Forms/FormIntegrationTest.php
index 2b1b11f44..e028ff248 100644
--- a/api/tests/Feature/Forms/FormIntegrationTest.php
+++ b/api/tests/Feature/Forms/FormIntegrationTest.php
@@ -6,10 +6,10 @@ it('can CRUD form integration', function () {
$form = $this->createForm($user, $workspace);
$data = [
- 'status' => true,
+ 'status' => 'active',
'integration_id' => 'email',
'logic' => null,
- 'settings' => [
+ 'data' => [
'send_to' => '[email protected]',
'sender_name' => 'OpnForm',
'subject' => 'New form submission',
@@ -53,10 +53,10 @@ it('forbids non-admin users from viewing integrations and events', function () {
// Create one integration as owner
$this->postJson(route('open.forms.integrations.create', $form), [
- 'status' => true,
+ 'status' => 'active',
'integration_id' => 'email',
'logic' => null,
- 'settings' => [
+ 'data' => [
'send_to' => '[email protected]',
'sender_name' => 'OpnForm',
'subject' => 'Subject',
@@ -104,7 +104,7 @@ it('can create form integration with checkbox logic', function () {
]);
$data = [
- 'status' => true,
+ 'status' => 'active',
'integration_id' => 'email',
'logic' => [
'operatorIdentifier' => 'and',
@@ -121,7 +121,7 @@ it('can create form integration with checkbox logic', function () {
],
],
],
- 'settings' => [
+ 'data' => [
'send_to' => '[email protected]',
'sender_name' => 'OpnForm',
'subject' => 'New form submission with checkbox logic',
@@ -139,3 +139,363 @@ it('can create form integration with checkbox logic', function () {
'message' => 'Form Integration was created.'
]);
});
+
+describe('Webhook Integration', function () {
+ it('can create webhook with secret and custom headers', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+
+ $data = [
+ 'status' => 'active',
+ 'integration_id' => 'webhook',
+ 'logic' => null,
+ 'data' => [
+ 'webhook_url' => 'https://example.com/webhook',
+ 'webhook_secret' => 'whsec_1234567890abcdefghijklmnop',
+ 'webhook_headers' => [
+ 'X-API-Key' => 'my-api-key',
+ 'X-Custom-ID' => 'custom-value'
+ ]
+ ]
+ ];
+
+ $response = $this->postJson(route('open.forms.integrations.create', $form), $data)
+ ->assertSuccessful()
+ ->assertJson([
+ 'type' => 'success',
+ 'message' => 'Form Integration was created.'
+ ]);
+
+ expect($response->json('form_integration.data.webhook_url'))
+ ->toBe('https://example.com/webhook');
+ expect($response->json('form_integration.data.webhook_secret'))
+ ->toBe('whsec_1234567890abcdefghijklmnop');
+ expect($response->json('form_integration.data.webhook_headers'))
+ ->toHaveKeys(['X-API-Key', 'X-Custom-ID']);
+ });
+
+ it('can create webhook with secret only', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+
+ $data = [
+ 'status' => 'active',
+ 'integration_id' => 'webhook',
+ 'logic' => null,
+ 'data' => [
+ 'webhook_url' => 'https://example.com/webhook',
+ 'webhook_secret' => 'whsec_verylongsecretstring123456'
+ ]
+ ];
+
+ $response = $this->postJson(route('open.forms.integrations.create', $form), $data)
+ ->assertSuccessful();
+
+ expect($response->json('form_integration.data.webhook_secret'))
+ ->toBe('whsec_verylongsecretstring123456');
+ expect($response->json('form_integration.data.webhook_headers'))
+ ->toBeNull();
+ });
+
+ it('can create webhook with headers only', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+
+ $data = [
+ 'status' => 'active',
+ 'integration_id' => 'webhook',
+ 'logic' => null,
+ 'data' => [
+ 'webhook_url' => 'https://example.com/webhook',
+ 'webhook_headers' => [
+ 'X-Event-Type' => 'submission',
+ 'X-User-Agent' => 'my-app/1.0'
+ ]
+ ]
+ ];
+
+ $response = $this->postJson(route('open.forms.integrations.create', $form), $data)
+ ->assertSuccessful();
+
+ expect($response->json('form_integration.data.webhook_headers'))
+ ->toHaveKeys(['X-Event-Type', 'X-User-Agent']);
+ expect($response->json('form_integration.data.webhook_secret'))
+ ->toBeNull();
+ });
+
+ it('can create webhook without secret or headers', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+
+ $data = [
+ 'status' => 'active',
+ 'integration_id' => 'webhook',
+ 'logic' => null,
+ 'data' => [
+ 'webhook_url' => 'https://example.com/webhook'
+ ]
+ ];
+
+ $response = $this->postJson(route('open.forms.integrations.create', $form), $data)
+ ->assertSuccessful();
+
+ expect($response->json('form_integration.data.webhook_url'))
+ ->toBe('https://example.com/webhook');
+ });
+
+ it('rejects webhook with secret shorter than 12 characters', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+
+ $data = [
+ 'status' => 'active',
+ 'integration_id' => 'webhook',
+ 'logic' => null,
+ 'data' => [
+ 'webhook_url' => 'https://example.com/webhook',
+ 'webhook_secret' => 'short'
+ ]
+ ];
+
+ $this->postJson(route('open.forms.integrations.create', $form), $data)
+ ->assertStatus(422)
+ ->assertJsonValidationErrors(['data.webhook_secret']);
+ });
+
+ it('rejects webhook with blocked Authorization header', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+
+ $data = [
+ 'status' => 'active',
+ 'integration_id' => 'webhook',
+ 'logic' => null,
+ 'data' => [
+ 'webhook_url' => 'https://example.com/webhook',
+ 'webhook_headers' => [
+ 'Authorization' => 'Bearer token123'
+ ]
+ ]
+ ];
+
+ $this->postJson(route('open.forms.integrations.create', $form), $data)
+ ->assertStatus(422)
+ ->assertJsonValidationErrors(['data.webhook_headers']);
+ });
+
+ it('rejects webhook with blocked Cookie header', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+
+ $data = [
+ 'status' => 'active',
+ 'integration_id' => 'webhook',
+ 'logic' => null,
+ 'data' => [
+ 'webhook_url' => 'https://example.com/webhook',
+ 'webhook_headers' => [
+ 'Cookie' => 'session=abc123'
+ ]
+ ]
+ ];
+
+ $this->postJson(route('open.forms.integrations.create', $form), $data)
+ ->assertStatus(422)
+ ->assertJsonValidationErrors(['data.webhook_headers']);
+ });
+
+ it('rejects webhook with blocked X-CSRF-Token header (case-insensitive)', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+
+ $data = [
+ 'status' => 'active',
+ 'integration_id' => 'webhook',
+ 'logic' => null,
+ 'data' => [
+ 'webhook_url' => 'https://example.com/webhook',
+ 'webhook_headers' => [
+ 'x-csrf-token' => 'token123'
+ ]
+ ]
+ ];
+
+ $this->postJson(route('open.forms.integrations.create', $form), $data)
+ ->assertStatus(422)
+ ->assertJsonValidationErrors(['data.webhook_headers']);
+ });
+
+ it('rejects webhook with more than 10 custom headers', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+
+ $tooManyHeaders = [
+ 'X-Header-1' => 'value1',
+ 'X-Header-2' => 'value2',
+ 'X-Header-3' => 'value3',
+ 'X-Header-4' => 'value4',
+ 'X-Header-5' => 'value5',
+ 'X-Header-6' => 'value6',
+ 'X-Header-7' => 'value7',
+ 'X-Header-8' => 'value8',
+ 'X-Header-9' => 'value9',
+ 'X-Header-10' => 'value10',
+ 'X-Header-11' => 'value11'
+ ];
+
+ $data = [
+ 'status' => 'active',
+ 'integration_id' => 'webhook',
+ 'logic' => null,
+ 'data' => [
+ 'webhook_url' => 'https://example.com/webhook',
+ 'webhook_headers' => $tooManyHeaders
+ ]
+ ];
+
+ $this->postJson(route('open.forms.integrations.create', $form), $data)
+ ->assertStatus(422)
+ ->assertJsonValidationErrors(['data.webhook_headers']);
+ });
+
+ it('rejects webhook with header name exceeding 255 characters', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+
+ $longHeaderName = str_repeat('X', 256);
+
+ $data = [
+ 'status' => 'active',
+ 'integration_id' => 'webhook',
+ 'logic' => null,
+ 'data' => [
+ 'webhook_url' => 'https://example.com/webhook',
+ 'webhook_headers' => [
+ $longHeaderName => 'value'
+ ]
+ ]
+ ];
+
+ $this->postJson(route('open.forms.integrations.create', $form), $data)
+ ->assertStatus(422)
+ ->assertJsonValidationErrors(['data.webhook_headers']);
+ });
+
+ it('rejects webhook with header value exceeding 255 characters', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+
+ $longHeaderValue = str_repeat('x', 256);
+
+ $data = [
+ 'status' => 'active',
+ 'integration_id' => 'webhook',
+ 'logic' => null,
+ 'data' => [
+ 'webhook_url' => 'https://example.com/webhook',
+ 'webhook_headers' => [
+ 'X-API-Key' => $longHeaderValue
+ ]
+ ]
+ ];
+
+ $this->postJson(route('open.forms.integrations.create', $form), $data)
+ ->assertStatus(422)
+ ->assertJsonValidationErrors(['data.webhook_headers']);
+ });
+
+ it('can update webhook to rotate secret', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+
+ // Create webhook with initial secret
+ $createData = [
+ 'status' => 'active',
+ 'integration_id' => 'webhook',
+ 'logic' => null,
+ 'data' => [
+ 'webhook_url' => 'https://example.com/webhook',
+ 'webhook_secret' => 'whsec_oldsecret1234567890abc'
+ ]
+ ];
+
+ $createResponse = $this->postJson(route('open.forms.integrations.create', $form), $createData)
+ ->assertSuccessful();
+
+ $integrationId = $createResponse->json('form_integration.id');
+
+ // Update with new secret
+ $updateData = [
+ 'status' => 'active',
+ 'integration_id' => 'webhook',
+ 'logic' => null,
+ 'data' => [
+ 'webhook_url' => 'https://example.com/webhook',
+ 'webhook_secret' => 'whsec_newsecret1234567890xyz'
+ ]
+ ];
+
+ $updateResponse = $this->putJson(route('open.forms.integrations.update', [$form, $integrationId]), $updateData)
+ ->assertSuccessful();
+
+ expect($updateResponse->json('form_integration.data.webhook_secret'))
+ ->toBe('whsec_newsecret1234567890xyz');
+ });
+
+ it('can update webhook headers', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+
+ // Create webhook with initial headers
+ $createData = [
+ 'status' => 'active',
+ 'integration_id' => 'webhook',
+ 'logic' => null,
+ 'data' => [
+ 'webhook_url' => 'https://example.com/webhook',
+ 'webhook_headers' => [
+ 'X-API-Key' => 'old-key'
+ ]
+ ]
+ ];
+
+ $createResponse = $this->postJson(route('open.forms.integrations.create', $form), $createData)
+ ->assertSuccessful();
+
+ $integrationId = $createResponse->json('form_integration.id');
+
+ // Update with new headers
+ $updateData = [
+ 'status' => 'active',
+ 'integration_id' => 'webhook',
+ 'logic' => null,
+ 'data' => [
+ 'webhook_url' => 'https://example.com/webhook',
+ 'webhook_headers' => [
+ 'X-API-Key' => 'new-key',
+ 'X-Request-ID' => 'req-123'
+ ]
+ ]
+ ];
+
+ $updateResponse = $this->putJson(route('open.forms.integrations.update', [$form, $integrationId]), $updateData)
+ ->assertSuccessful();
+
+ $headers = $updateResponse->json('form_integration.data.webhook_headers');
+ expect($headers['X-API-Key'])->toBe('new-key');
+ expect($headers['X-Request-ID'])->toBe('req-123');
+ });
+});
diff --git a/api/tests/Feature/Integrations/Email/EmailIntegrationTest.php b/api/tests/Feature/Integrations/Email/EmailIntegrationTest.php
index 858dede00..60bc38cb8 100644
--- a/api/tests/Feature/Integrations/Email/EmailIntegrationTest.php
+++ b/api/tests/Feature/Integrations/Email/EmailIntegrationTest.php
@@ -10,8 +10,8 @@ test('free user can create one email integration to their own email', function (
// First email integration should succeed with user's own email
$response = $this->postJson(route('open.forms.integrations.create', $form), [
'integration_id' => 'email',
- 'status' => true,
- 'settings' => [
+ 'status' => 'active',
+ 'data' => [
'send_to' => $user->email,
'sender_name' => 'Test Sender',
'subject' => 'Test Subject',
@@ -26,8 +26,8 @@ test('free user can create one email integration to their own email', function (
// Second email integration should fail
$response = $this->postJson(route('open.forms.integrations.create', $form), [
'integration_id' => 'email',
- 'status' => true,
- 'settings' => [
+ 'status' => 'active',
+ 'data' => [
'send_to' => $user->email,
'sender_name' => 'Test Sender',
'subject' => 'Test Subject',
@@ -37,11 +37,7 @@ test('free user can create one email integration to their own email', function (
]);
$response->assertStatus(422)
- ->assertJson([
- 'errors' => [
- 'settings.send_to' => ['Free users are limited to 1 email integration per form.']
- ]
- ]);
+ ->assertJsonValidationErrors(['data.send_to']);
});
test('free user cannot send to other email addresses', function () {
@@ -51,8 +47,8 @@ test('free user cannot send to other email addresses', function () {
$response = $this->postJson(route('open.forms.integrations.create', $form), [
'integration_id' => 'email',
- 'status' => true,
- 'settings' => [
+ 'status' => 'active',
+ 'data' => [
'send_to' => '[email protected]',
'sender_name' => 'Test Sender',
'subject' => 'Test Subject',
@@ -62,11 +58,11 @@ test('free user cannot send to other email addresses', function () {
]);
$response->assertStatus(422)
- ->assertJsonValidationErrors(['settings.send_to']);
+ ->assertJsonValidationErrors(['data.send_to']);
// Check that the error message contains the expected text with user's email
$responseData = $response->json();
- $errorMessage = $responseData['errors']['settings.send_to'][0];
+ $errorMessage = $responseData['errors']['data.send_to'][0];
expect($errorMessage)->toContain('You can only send email notification to your own email address');
expect($errorMessage)->toContain($user->email);
expect($errorMessage)->toContain('Please upgrade to the Pro plan to send to other email addresses.');
@@ -80,8 +76,8 @@ test('pro user can create multiple email integrations', function () {
// First email integration
$response = $this->postJson(route('open.forms.integrations.create', $form), [
'integration_id' => 'email',
- 'status' => true,
- 'settings' => [
+ 'status' => 'active',
+ 'data' => [
'send_to' => '[email protected]',
'sender_name' => 'Test Sender',
'subject' => 'Test Subject',
@@ -95,8 +91,8 @@ test('pro user can create multiple email integrations', function () {
// Second email integration should also succeed for pro users
$response = $this->postJson(route('open.forms.integrations.create', $form), [
'integration_id' => 'email',
- 'status' => true,
- 'settings' => [
+ 'status' => 'active',
+ 'data' => [
'send_to' => '[email protected]',
'sender_name' => 'Test Sender',
'subject' => 'Test Subject',
@@ -116,8 +112,8 @@ test('free user cannot add multiple emails', function () {
$response = $this->postJson(route('open.forms.integrations.create', $form), [
'integration_id' => 'email',
- 'status' => true,
- 'settings' => [
+ 'status' => 'active',
+ 'data' => [
'sender_name' => 'Test Sender',
'subject' => 'Test Subject',
@@ -127,10 +123,10 @@ test('free user cannot add multiple emails', function () {
]);
$response->assertStatus(422)
- ->assertJsonValidationErrors(['settings.send_to'])
+ ->assertJsonValidationErrors(['data.send_to'])
->assertJson([
'errors' => [
- 'settings.send_to' => ['You can only send to a single email address on the free plan. Please upgrade to the Pro plan to create a new integration.']
+ 'data.send_to' => ['You can only send to a single email address on the free plan. Please upgrade to the Pro plan to create a new integration.']
]
]);
});
@@ -142,8 +138,8 @@ test('pro user can add multiple emails', function () {
$response = $this->postJson(route('open.forms.integrations.create', $form), [
'integration_id' => 'email',
- 'status' => true,
- 'settings' => [
+ 'status' => 'active',
+ 'data' => [
'sender_name' => 'Test Sender',
'subject' => 'Test Subject',
@@ -169,8 +165,8 @@ test('free user can update their single email integration to their own email', f
// Create initial integration with user's email
$response = $this->postJson(route('open.forms.integrations.create', $form), [
'integration_id' => 'email',
- 'status' => true,
- 'settings' => [
+ 'status' => 'active',
+ 'data' => [
'send_to' => $user->email,
'sender_name' => 'Test Sender',
'subject' => 'Test Subject',
@@ -185,8 +181,8 @@ test('free user can update their single email integration to their own email', f
// Update the integration - still with user's email
$response = $this->putJson(route('open.forms.integrations.update', [$form, $integrationId]), [
'integration_id' => 'email',
- 'status' => true,
- 'settings' => [
+ 'status' => 'active',
+ 'data' => [
'send_to' => $user->email,
'sender_name' => 'Updated Sender',
'subject' => 'Updated Subject',
@@ -210,8 +206,8 @@ test('free user cannot update integration to other email addresses', function ()
// Create initial integration with user's email
$response = $this->postJson(route('open.forms.integrations.create', $form), [
'integration_id' => 'email',
- 'status' => true,
- 'settings' => [
+ 'status' => 'active',
+ 'data' => [
'send_to' => $user->email,
'sender_name' => 'Test Sender',
'subject' => 'Test Subject',
@@ -226,8 +222,8 @@ test('free user cannot update integration to other email addresses', function ()
// Try to update to another email address - should fail
$response = $this->putJson(route('open.forms.integrations.update', [$form, $integrationId]), [
'integration_id' => 'email',
- 'status' => true,
- 'settings' => [
+ 'status' => 'active',
+ 'data' => [
'send_to' => '[email protected]',
'sender_name' => 'Updated Sender',
'subject' => 'Updated Subject',
@@ -237,11 +233,11 @@ test('free user cannot update integration to other email addresses', function ()
]);
$response->assertStatus(422)
- ->assertJsonValidationErrors(['settings.send_to']);
+ ->assertJsonValidationErrors(['data.send_to']);
// Check that the error message contains the expected text with user's email
$responseData = $response->json();
- $errorMessage = $responseData['errors']['settings.send_to'][0];
+ $errorMessage = $responseData['errors']['data.send_to'][0];
expect($errorMessage)->toContain('You can only send email notification to your own email address');
expect($errorMessage)->toContain($user->email);
expect($errorMessage)->toContain('Please upgrade to the Pro plan to send to other email addresses.');
diff --git a/api/tests/TestHelpers.php b/api/tests/TestHelpers.php
index 507d4d7b3..70116a0e9 100644
--- a/api/tests/TestHelpers.php
+++ b/api/tests/TestHelpers.php
@@ -254,10 +254,10 @@ trait TestHelpers
public function createFormIntegration($integrationId, $formId, $settings = [])
{
$data = [
- 'status' => true,
+ 'status' => 'active',
'integration_id' => $integrationId,
'logic' => null,
- 'settings' => $settings
+ 'data' => $settings
];
$response = $this->postJson(route('open.forms.integrations.create', $formId), $data)
diff --git a/client/components/forms/heavy/MentionInput.vue b/client/components/forms/heavy/MentionInput.vue
index 5909e2969..c718c646a 100644
--- a/client/components/forms/heavy/MentionInput.vue
+++ b/client/components/forms/heavy/MentionInput.vue
@@ -164,8 +164,21 @@ const restoreSelection = () => {
}
}
+const getPlainText = (html) => {
+ if (!html) return ''
+ // Create a temporary div to parse HTML
+ const temp = document.createElement('div')
+ temp.innerHTML = html
+ // Get text content and trim
+ return temp.textContent.trim()
+}
+
const updateCompVal = () => {
- compVal.value = editableDiv.value.innerHTML
+ const html = editableDiv.value.innerHTML
+ const plainText = getPlainText(html)
+
+ // If plain text is empty, store empty string; otherwise store HTML
+ compVal.value = plainText ? html : ''
}
const onInput = () => {
diff --git a/client/components/open/integrations/DiscordIntegration.vue b/client/components/open/integrations/DiscordIntegration.vue
index 172cb7c2a..b0113b649 100644
--- a/client/components/open/integrations/DiscordIntegration.vue
+++ b/client/components/open/integrations/DiscordIntegration.vue
@@ -6,7 +6,7 @@
>
<text-input
:form="integrationData"
- name="settings.discord_webhook_url"
+ name="data.discord_webhook_url"
label="Discord webhook url"
help="help"
required
@@ -30,7 +30,7 @@
Discord message options
</h4>
<notifications-message-actions
- v-model="integrationData.settings"
+ v-model="integrationData.data"
:form="form"
/>
</IntegrationWrapper>
diff --git a/client/components/open/integrations/EmailIntegration.vue b/client/components/open/integrations/EmailIntegration.vue
index 635c476d0..cd6a87ba4 100644
--- a/client/components/open/integrations/EmailIntegration.vue
+++ b/client/components/open/integrations/EmailIntegration.vue
@@ -18,7 +18,7 @@
:mentions="form.properties"
:disable-mention="!form.is_pro"
:disabled="!form.is_pro"
- name="settings.send_to"
+ name="data.send_to"
required
label="Send To"
>
@@ -41,14 +41,14 @@
<MentionInput
:form="integrationData"
:mentions="form.properties"
- name="settings.sender_name"
+ name="data.sender_name"
label="Sender Name"
class="flex-1"
/>
<text-input
v-if="selfHosted"
:form="integrationData"
- name="settings.sender_email"
+ name="data.sender_email"
label="Sender Email"
help="If supported by email provider - default otherwise"
class="flex-1"
@@ -58,27 +58,27 @@
:form="integrationData"
:mentions="form.properties"
required
- name="settings.subject"
+ name="data.subject"
label="Subject"
/>
<rich-text-area-input
:form="integrationData"
:enable-mentions="true"
:mentions="form.properties"
- name="settings.email_content"
+ name="data.email_content"
label="Email Content"
/>
<toggle-switch-input
:form="integrationData"
- name="settings.include_submission_data"
+ name="data.include_submission_data"
class="mt-4"
label="Include submission data"
help="If enabled the email will contain form submission answers"
/>
<toggle-switch-input
- v-if="integrationData.settings.include_submission_data"
+ v-if="integrationData.data.include_submission_data"
:form="integrationData"
- name="settings.include_hidden_fields_submission_data"
+ name="data.include_hidden_fields_submission_data"
class="mt-4"
label="Include hidden fields"
help="If enabled the email will contain hidden fields"
@@ -86,7 +86,7 @@
<toggle-switch-input
v-if="form.editable_submissions"
:form="integrationData"
- name="settings.link_edit_submission"
+ name="data.link_edit_submission"
class="mt-4"
label="Edit Submission Link"
/>
@@ -94,7 +94,7 @@
:form="integrationData"
:mentions="form.properties"
class="mt-4"
- name="settings.reply_to"
+ name="data.reply_to"
label="Reply To"
help="If empty, Reply-to will be your own email."
/>
@@ -135,8 +135,8 @@ onBeforeMount(() => {
include_submission_data: true,
include_hidden_fields_submission_data: false,
})) {
- if (props.integrationData.settings[keyname] === undefined) {
- props.integrationData.settings[keyname] = defaultValue
+ if (props.integrationData.data[keyname] === undefined) {
+ props.integrationData.data[keyname] = defaultValue
}
}
})
diff --git a/client/components/open/integrations/SlackIntegration.vue b/client/components/open/integrations/SlackIntegration.vue
index 1cd5a60d5..c265208b8 100644
--- a/client/components/open/integrations/SlackIntegration.vue
+++ b/client/components/open/integrations/SlackIntegration.vue
@@ -6,7 +6,7 @@
>
<text-input
:form="integrationData"
- name="settings.slack_webhook_url"
+ name="data.slack_webhook_url"
label="Slack webhook url"
help="help"
required
@@ -30,7 +30,7 @@
Slack message actions
</h4>
<notifications-message-actions
- v-model="integrationData.settings"
+ v-model="integrationData.data"
:form="form"
/>
</IntegrationWrapper>
diff --git a/client/components/open/integrations/TelegramIntegration.vue b/client/components/open/integrations/TelegramIntegration.vue
index 92405e2ad..28a762412 100644
--- a/client/components/open/integrations/TelegramIntegration.vue
+++ b/client/components/open/integrations/TelegramIntegration.vue
@@ -38,7 +38,7 @@
Telegram message actions
</h4>
<notifications-message-actions
- v-model="integrationData.settings"
+ v-model="integrationData.data"
:form="form"
/>
</template>
diff --git a/client/components/open/integrations/WebhookIntegration.vue b/client/components/open/integrations/WebhookIntegration.vue
index 69ce7a7e9..a9be30b09 100644
--- a/client/components/open/integrations/WebhookIntegration.vue
+++ b/client/components/open/integrations/WebhookIntegration.vue
@@ -6,17 +6,133 @@
>
<text-input
:form="integrationData"
- name="settings.webhook_url"
+ name="data.webhook_url"
class="mt-4"
- label="Webhook url"
+ label="Webhook URL"
help="We will post form submissions to this endpoint"
required
/>
+
+ <!-- Advanced Section -->
+ <div class="border-t mt-6 pt-6">
+ <collapse
+ v-model="showAdvanced"
+ class="w-full"
+ >
+ <template #title>
+ <div class="flex gap-x-3 items-start pr-8">
+ <div
+ class="transition-colors"
+ :class="{
+ 'text-blue-600': showAdvanced,
+ 'text-neutral-300': !showAdvanced,
+ }"
+ >
+ <Icon
+ name="material-symbols:webhook"
+ size="30px"
+ />
+ </div>
+ <div class="flex-grow">
+ <h3 class="font-semibold">
+ Advanced
+ </h3>
+ <p class="text-neutral-500 text-xs">
+ Configure signing secret and custom headers
+ </p>
+ </div>
+ </div>
+ </template>
+
+ <!-- Webhook Secret -->
+ <text-input
+ :form="integrationData"
+ name="data.webhook_secret"
+ class="mt-4"
+ label="Webhook Secret"
+ help="Minimum 12 characters. Used to sign webhook requests with HMAC-SHA256"
+ placeholder="whsec_..."
+ />
+
+ <!-- Webhook Headers -->
+ <div class="mt-4">
+ <label class="block text-sm font-medium text-neutral-700 mb-2">
+ Custom Headers
+ </label>
+ <p class="text-xs text-neutral-500 mb-3">
+ Add custom HTTP headers to be sent with each webhook (max 10 headers)
+ </p>
+
+ <!-- Headers List -->
+ <div
+ v-if="Object.keys(webhookHeaders).length > 0"
+ class="space-y-2 mb-4"
+ >
+ <div
+ v-for="(value, key) in webhookHeaders"
+ :key="key"
+ class="flex items-center justify-between gap-3 bg-neutral-50 p-3 rounded border border-neutral-200"
+ >
+ <div class="flex-grow">
+ <code class="text-sm font-mono text-neutral-700">
+ {{ key }}<span class="text-neutral-400">:</span> <span class="text-neutral-600">{{ value }}</span>
+ </code>
+ </div>
+ <UTooltip text="Remove header" arrow>
+ <UButton
+ icon="i-material-symbols:delete-outline"
+ color="error"
+ variant="ghost"
+ size="xs"
+ @click="removeHeader(key)"
+ />
+ </UTooltip>
+ </div>
+ </div>
+
+ <!-- Add Header Form -->
+ <div class="space-y-2 bg-neutral-50 p-3 rounded border border-neutral-200">
+ <div class="grid grid-cols-2 gap-2">
+ <TextInput
+ v-model="newHeaderKey"
+ name="webhook-header-key"
+ placeholder="Header name"
+ size="sm"
+ :disabled="Object.keys(webhookHeaders).length >= 10"
+ />
+ <TextInput
+ v-model="newHeaderValue"
+ name="webhook-header-value"
+ placeholder="Header value"
+ size="sm"
+ :disabled="Object.keys(webhookHeaders).length >= 10"
+ />
+ </div>
+ <UButton
+ type="button"
+ block
+ :disabled="!newHeaderKey || !newHeaderValue || Object.keys(webhookHeaders).length >= 10"
+ @click="addHeader"
+ >
+ Add Header
+ </UButton>
+ <p
+ v-if="Object.keys(webhookHeaders).length >= 10"
+ class="text-xs text-red-600"
+ >
+ Maximum 10 headers reached
+ </p>
+ </div>
+ </div>
+ </collapse>
+ </div>
</IntegrationWrapper>
</template>
<script setup>
import IntegrationWrapper from "./components/IntegrationWrapper.vue"
+import Collapse from "~/components/app/Collapse.vue"
+import TextInput from "~/components/forms/core/TextInput.vue"
const props = defineProps({
integration: { type: Object, required: true },
@@ -24,4 +140,41 @@ const props = defineProps({
integrationData: { type: Object, required: true },
formIntegrationId: { type: Number, required: false, default: null },
})
+
+const showAdvanced = ref(!!props.integrationData?.data?.webhook_secret)
+
+// Webhook Headers Management
+const newHeaderKey = ref('')
+const newHeaderValue = ref('')
+
+const webhookHeaders = computed({
+ get: () => {
+ if (typeof props.integrationData?.data?.webhook_headers === 'object') {
+ return props.integrationData.data.webhook_headers
+ }
+ return {}
+ },
+ set: (value) => {
+ if (props.integrationData?.data) {
+ props.integrationData.data.webhook_headers = value
+ }
+ }
+})
+
+const addHeader = () => {
+ if (newHeaderKey.value && newHeaderValue.value && Object.keys(webhookHeaders.value).length < 10) {
+ webhookHeaders.value = {
+ ...webhookHeaders.value,
+ [newHeaderKey.value]: newHeaderValue.value
+ }
+ newHeaderKey.value = ''
+ newHeaderValue.value = ''
+ }
+}
+
+const removeHeader = (key) => {
+ const updated = { ...webhookHeaders.value }
+ delete updated[key]
+ webhookHeaders.value = updated
+}
</script>
diff --git a/client/components/open/integrations/components/IntegrationModal.vue b/client/components/open/integrations/components/IntegrationModal.vue
index e0f641721..ec3182790 100644
--- a/client/components/open/integrations/components/IntegrationModal.vue
+++ b/client/components/open/integrations/components/IntegrationModal.vue
@@ -137,7 +137,7 @@ const component = computed(() => {
return getIntegrationComponent(props.integration.id)
})
-const integrationData = ref(null)
+let integrationData = null
watch(
() => props.integrationKey,
@@ -147,14 +147,14 @@ watch(
)
const initIntegrationData = () => {
- integrationData.value = useForm({
+ integrationData = useForm({
integration_id: props.formIntegrationId && formIntegration.value
? formIntegration.value.integration_id
: props.integrationKey,
status: props.formIntegrationId && formIntegration.value
- ? formIntegration.value.status === "active"
- : true,
- settings: props.formIntegrationId && formIntegration.value
+ ? formIntegration.value.status
+ : 'active',
+ data: props.formIntegrationId && formIntegration.value
? formIntegration.value.data ?? {}
: {},
logic: props.formIntegrationId && formIntegration.value
@@ -174,9 +174,8 @@ const save = () => {
const isUpdating = !!toValue(formIntegrationId)
const mutation = isUpdating ? updateIntegrationMutation : createIntegrationMutation
- const promise = integrationData.value.mutate(mutation)
-
- promise
+ // Use Form's mutate which handles data extraction and error handling
+ integrationData.mutate(mutation)
.then((result) => {
alert.success(result.message)
emit('close')
diff --git a/client/components/open/integrations/components/IntegrationWrapper.vue b/client/components/open/integrations/components/IntegrationWrapper.vue
index 30f32bdd9..5c58f5ddf 100644
--- a/client/components/open/integrations/components/IntegrationWrapper.vue
+++ b/client/components/open/integrations/components/IntegrationWrapper.vue
@@ -6,7 +6,7 @@
<div class="flex justify-between">
<slot name="status">
<toggle-switch-input
- v-model="modelValue.status"
+ v-model="statusToggle"
name="status"
label="Enabled"
/>
@@ -71,6 +71,13 @@ const props = defineProps({
defineEmits(["close"])
const showLogic = ref(!!props.modelValue.logic)
+
+const statusToggle = computed({
+ get: () => props.modelValue.status === 'active',
+ set: (value) => {
+ props.modelValue.status = value ? 'active' : 'inactive'
+ }
+})
</script>
<style lang="scss">
diff --git a/client/components/open/integrations/components/N8nIntegrationActions.vue b/client/components/open/integrations/components/N8nIntegrationActions.vue
index a4413ba6d..ce22ac142 100644
--- a/client/components/open/integrations/components/N8nIntegrationActions.vue
+++ b/client/components/open/integrations/components/N8nIntegrationActions.vue
@@ -8,7 +8,7 @@
color="neutral"
variant="ghost"
size="sm"
- :to="`${providerUrl}?utm_source=opnform-edit`"
+ :href="`${providerUrl}?utm_source=opnform-edit`"
target="_blank"
external
>
diff --git a/client/composables/lib/vForm/Form.js b/client/composables/lib/vForm/Form.js
index abbd2939d..9918b870d 100644
--- a/client/composables/lib/vForm/Form.js
+++ b/client/composables/lib/vForm/Form.js
@@ -51,16 +51,21 @@ class Form {
}
data() {
- return this.keys().reduce(
- (data, key) => ({ ...data, [key]: this[key] }),
- {},
- )
+ return this._getSerializableData()
}
keys() {
return Object.keys(this).filter((key) => !Form.ignore.includes(key))
}
+ // Internal helper to safely collect form values even if a field is named "data"
+ _getSerializableData() {
+ return this.keys().reduce(
+ (acc, key) => ({ ...acc, [key]: this[key] }),
+ {},
+ )
+ }
+
startProcessing() {
this.errors.clear()
this.busy = true
@@ -145,9 +150,9 @@ class Form {
}
if (method.toLowerCase() === "get") {
- config.params = { ...this.data(), ...config.params }
+ config.params = { ...this._getSerializableData(), ...config.params }
} else {
- config.body = { ...this.data(), ...config.data, ...config.body }
+ config.body = { ...this._getSerializableData(), ...config.data, ...config.body }
if (hasFiles(config.data) && !config.transformRequest) {
config.transformRequest = [(data) => serialize(data)]
@@ -182,9 +187,9 @@ class Form {
...config,
}
if (method.toLowerCase() === "get") {
- config.params = { ...this.data(), ...config.params }
+ config.params = { ...this._getSerializableData(), ...config.params }
} else {
- config.body = { ...this.data(), ...config.data }
+ config.body = { ...this._getSerializableData(), ...config.data }
if (hasFiles(config.data) && !config.transformRequest) {
config.transformRequest = [(data) => serialize(data)]
@@ -246,7 +251,7 @@ class Form {
mutateAsync(mutation, options = {}) {
this.startProcessing()
- const payload = { ...this.data(), ...options.data }
+ const payload = { ...this._getSerializableData(), ...options.data }
// Handle file uploads if needed
const processedPayload = hasFiles(payload) && options.transformRequest
diff --git a/client/data/forms/integrations.json b/client/data/forms/integrations.json
index 645d45533..dadd624fe 100644
--- a/client/data/forms/integrations.json
+++ b/client/data/forms/integrations.json
@@ -14,7 +14,8 @@
"section_name": "Notifications",
"file_name": "SlackIntegration",
"actions_file_name": "SlackIntegrationActions",
- "is_pro": true
+ "is_pro": true,
+ "crisp_help_page_slug": "do-you-want-to-get-notified-of-new-submissions-via-slack-21mhhh"
},
"discord": {
"name": "Discord Notification",
@@ -22,7 +23,8 @@
"section_name": "Notifications",
"file_name": "DiscordIntegration",
"actions_file_name": "DiscordIntegrationActions",
- "is_pro": true
+ "is_pro": true,
+ "crisp_help_page_slug": "do-you-want-to-get-notified-of-new-submissions-via-discord-1b2oxcx"
},
"telegram": {
"name": "Telegram Notification",
@@ -30,7 +32,8 @@
"section_name": "Notifications",
"file_name": "TelegramIntegration",
"actions_file_name": "TelegramIntegrationActions",
- "is_pro": true
+ "is_pro": true,
+ "crisp_help_page_slug": "how-to-connect-telegram-to-your-opnform-bxqqq2"
},
"webhook": {
"name": "Webhook Notification",
@@ -38,7 +41,8 @@
"section_name": "Automation",
"file_name": "WebhookIntegration",
"actions_file_name": "WebhookIntegrationActions",
- "is_pro": false
+ "is_pro": false,
+ "crisp_help_page_slug": "can-i-trigger-another-service-whenever-my-form-receives-a-submission-webhooks-6nrnfn"
},
"zapier": {
"name": "Zapier",
@@ -48,7 +52,8 @@
"is_pro": false,
"is_external": true,
"is_editable": false,
- "url": "https://zapier.com/apps/opnform/integrations"
+ "url": "https://zapier.com/apps/opnform/integrations",
+ "crisp_help_page_slug": "how-to-connect-your-form-with-zapier-t1t45"
},
"n8n": {
"name": "n8n",
diff --git a/docs/api-reference/integrations/create-webhook-integration.mdx b/docs/api-reference/integrations/create-webhook-integration.mdx
index cdd0f34ad..9bd412666 100644
--- a/docs/api-reference/integrations/create-webhook-integration.mdx
+++ b/docs/api-reference/integrations/create-webhook-integration.mdx
@@ -13,15 +13,15 @@ This endpoint requires a **Personal Access Token** with the `manage-integrations
## Request
<ParamField path="form" type="number" required>
-The ID of the form to which the webhook will be added.
+ The ID of the form to which the webhook will be added.
</ParamField>
<ParamField body="integration_id" type="string" required>
-Must be set to `"webhook"` for webhook integrations.
+ Must be set to `"webhook"` for webhook integrations.
</ParamField>
-<ParamField body="status" type="string">
-The initial status of the webhook. Allowed values: `"active"` (default), `"inactive"`.
+<ParamField body="status" type="string" required>
+ The initial status of the webhook. Allowed values: `"active"`, `"inactive"`.
</ParamField>
<ParamField body="data" type="object" required>
@@ -30,10 +30,38 @@ Configuration object containing webhook details.
<Expandable title="data properties">
<ParamField body="webhook_url" type="string" required>
The URL where form submissions will be sent. Must be a valid HTTP/HTTPS URL.
+</ParamField>
+
+<ParamField body="webhook_secret" type="string">
+ Optional signing secret for HMAC-SHA256 validation. When provided, webhook
+ requests will include an `X-Webhook-Signature` header. Must be at least 12
+ characters. Recommended for security. Should be a random, cryptographically
+ secure string.
+</ParamField>
+
+<ParamField body="webhook_headers" type="object">
+Optional custom HTTP headers to send with each webhook request. Provided as key-value pairs where both keys and values are strings. Maximum 10 headers allowed, each value max 255 characters.
+
+**Blocked headers** (cannot be customized): `Authorization`, `X-Webhook-Signature`, `Content-Type`, `Host`, `Cookie`, `X-CSRF-Token`, `Content-Length`, and others reserved for security.
+
+Example:
+
+```json
+{
+ "X-API-Key": "your-api-key",
+ "X-Custom-ID": "custom-value"
+}
+```
+
</ParamField>
</Expandable>
</ParamField>
+<ParamField body="logic" type="object">
+ Optional conditional logic to trigger the webhook only when specific
+ conditions are met.
+</ParamField>
+
<RequestExample>
```bash cURL
curl -X POST 'https://api.opnform.com/open/forms/123/integrations' \
@@ -43,7 +71,12 @@ curl -X POST 'https://api.opnform.com/open/forms/123/integrations' \
"integration_id": "webhook",
"status": "active",
"data": {
- "webhook_url": "https://example.com/opnform-hook"
+ "webhook_url": "https://example.com/opnform-hook",
+ "webhook_secret": "whsec_1234567890abcdefghijklmnop",
+ "webhook_headers": {
+ "X-API-Key": "my-api-key",
+ "X-Custom-Header": "custom-value"
+ }
}
}'
```
@@ -63,7 +96,12 @@ curl -X POST 'https://api.opnform.com/open/forms/123/integrations' \
"integration_id": "webhook",
"status": "active",
"data": {
- "webhook_url": "https://example.com/opnform-hook"
+ "webhook_url": "https://example.com/opnform-hook",
+ "webhook_secret": "whsec_1234567890abcdefghijklmnop",
+ "webhook_headers": {
+ "X-API-Key": "my-api-key",
+ "X-Custom-Header": "custom-value"
+ }
}
}
}
@@ -74,15 +112,48 @@ curl -X POST 'https://api.opnform.com/open/forms/123/integrations' \
`404 Not Found` – Form not found.
-`422 Unprocessable Entity` – Validation error (e.g., invalid webhook URL).
+`422 Unprocessable Entity` – Validation error (e.g., invalid webhook URL, webhook_secret too short, blocked header).
<ResponseExample>
```json Error
{
- "message": "The webhook url must be a valid URL.",
+ "message": "The given data was invalid.",
"errors": {
- "data.webhook_url": ["The webhook url must be a valid URL."]
+ "data.webhook_url": ["The webhook url must be a valid URL."],
+ "data.webhook_secret": ["The webhook secret must be at least 12 characters."],
+ "data.webhook_headers": ["The 'Authorization' header cannot be customized for security reasons."]
}
}
```
</ResponseExample>
+
+## Security
+
+If you provide a `webhook_secret` when creating the webhook, OpnForm will sign each webhook request with an HMAC-SHA256 signature. This allows you to verify that the webhook came from OpnForm and hasn't been tampered with.
+
+Each webhook request will include:
+
+- **`X-Webhook-Signature` header**: Contains the signature in format `sha256=HEXADECIMAL_VALUE`
+- **Custom headers**: Any headers you specified in `webhook_headers` (except blocked headers)
+
+### Blocked Headers
+
+For security reasons, the following headers cannot be customized:
+
+- `Authorization`
+- `X-Webhook-Signature`
+- `Content-Type`
+- `Content-Length`
+- `Host`
+- `Cookie`
+- `X-CSRF-Token`
+- `X-Forwarded-For`
+- `X-Forwarded-Proto`
+- `X-Real-IP`
+
+See [Validating Webhook Signatures](/api-reference/integrations/webhook-security) for implementation examples.
+
+<Warning>
+ Do not commit webhook secrets to version control. Use environment variables
+ or secure vaults to manage them.
+</Warning>
diff --git a/docs/api-reference/integrations/list-form-integrations.mdx b/docs/api-reference/integrations/list-form-integrations.mdx
index 68ae517ec..6b86ba5a7 100644
--- a/docs/api-reference/integrations/list-form-integrations.mdx
+++ b/docs/api-reference/integrations/list-form-integrations.mdx
@@ -13,7 +13,7 @@ This endpoint requires a **Personal Access Token** with the `manage-integrations
## Request
<ParamField path="form" type="number" required>
-The ID of the form for which to list integrations.
+ The ID of the form for which to list integrations.
</ParamField>
```http
diff --git a/docs/api-reference/integrations/update-webhook-integration.mdx b/docs/api-reference/integrations/update-webhook-integration.mdx
index 383af38b4..350e4dc13 100644
--- a/docs/api-reference/integrations/update-webhook-integration.mdx
+++ b/docs/api-reference/integrations/update-webhook-integration.mdx
@@ -4,7 +4,7 @@ openapi: put /open/forms/{form}/integrations/{integrationid}
# Update Webhook Integration
-Modify an existing webhook integration's URL or status.
+Modify an existing webhook integration's URL, secret, headers, or status.
## Authentication & Scope
@@ -13,31 +13,44 @@ This endpoint requires a **Personal Access Token** with the `manage-integrations
## Request
<ParamField path="form" type="number" required>
-The ID of the form containing the webhook.
+ The ID of the form containing the webhook.
</ParamField>
<ParamField path="integrationid" type="number" required>
-The ID of the webhook integration to update.
+ The ID of the webhook integration to update.
</ParamField>
<ParamField body="integration_id" type="string" required>
-Must be set to `"webhook"`.
+ Must be set to `"webhook"`.
</ParamField>
<ParamField body="status" type="string">
-The status of the webhook. Allowed values: `"active"`, `"inactive"`.
+ The status of the webhook. Allowed values: `"active"`, `"inactive"`.
</ParamField>
<ParamField body="data" type="object" required>
-Configuration object containing webhook details.
+Configuration object containing webhook details. All fields are optional.
<Expandable title="data properties">
<ParamField body="webhook_url" type="string">
The updated URL where form submissions will be sent. Must be a valid HTTP/HTTPS URL.
</ParamField>
+
+<ParamField body="webhook_secret" type="string">
+ Update the signing secret for HMAC-SHA256 validation. Must be at least 12
+ characters. Provide a new value to rotate the secret.
+</ParamField>
+
+<ParamField body="webhook_headers" type="object">
+Update custom HTTP headers. Replaces all existing headers with the provided ones. Maximum 10 headers allowed. See blocked headers list below for restricted header names.
+</ParamField>
</Expandable>
</ParamField>
+<ParamField body="logic" type="object">
+ Update the conditional logic for webhook triggering.
+</ParamField>
+
<RequestExample>
```bash cURL
curl -X PUT 'https://api.opnform.com/open/forms/123/integrations/42' \
@@ -47,7 +60,12 @@ curl -X PUT 'https://api.opnform.com/open/forms/123/integrations/42' \
"integration_id": "webhook",
"status": "active",
"data": {
- "webhook_url": "https://new-endpoint.com/opnform-hook"
+ "webhook_url": "https://new-endpoint.com/opnform-hook",
+ "webhook_secret": "whsec_newsecret123456789abcdef",
+ "webhook_headers": {
+ "X-API-Key": "new-api-key",
+ "X-Custom-ID": "updated-value"
+ }
}
}'
```
@@ -67,7 +85,12 @@ curl -X PUT 'https://api.opnform.com/open/forms/123/integrations/42' \
"integration_id": "webhook",
"status": "active",
"data": {
- "webhook_url": "https://new-endpoint.com/opnform-hook"
+ "webhook_url": "https://new-endpoint.com/opnform-hook",
+ "webhook_secret": "whsec_newsecret123456789abcdef",
+ "webhook_headers": {
+ "X-API-Key": "new-api-key",
+ "X-Custom-ID": "updated-value"
+ }
}
}
}
@@ -83,10 +106,36 @@ curl -X PUT 'https://api.opnform.com/open/forms/123/integrations/42' \
<ResponseExample>
```json Error
{
- "message": "The webhook url must be a valid URL.",
+ "message": "The given data was invalid.",
"errors": {
- "data.webhook_url": ["The webhook url must be a valid URL."]
+ "data.webhook_secret": ["The webhook secret must be at least 12 characters."],
+ "data.webhook_headers": ["The 'Authorization' header cannot be customized for security reasons."]
}
}
```
</ResponseExample>
+
+## Security
+
+### Secret Rotation
+
+When updating the `webhook_secret`, the new secret will be used for all future webhook requests. Existing webhook attempts with the old secret will fail validation on the receiver's end.
+
+If you need to rotate your secret, consider implementing a grace period on your receiving endpoint to accept both old and new secrets during the transition.
+
+### Blocked Headers
+
+For security reasons, the following headers cannot be customized in `webhook_headers`:
+
+- `Authorization`
+- `X-Webhook-Signature`
+- `Content-Type`
+- `Content-Length`
+- `Host`
+- `Cookie`
+- `X-CSRF-Token`
+- `X-Forwarded-For`
+- `X-Forwarded-Proto`
+- `X-Real-IP`
+
+For signature validation implementation examples, see [Validating Webhook Signatures](/api-reference/integrations/webhook-security).
diff --git a/docs/api-reference/integrations/webhook-security.mdx b/docs/api-reference/integrations/webhook-security.mdx
new file mode 100644
index 000000000..c858edc78
--- /dev/null
+++ b/docs/api-reference/integrations/webhook-security.mdx
@@ -0,0 +1,233 @@
+---
+title: "Validating Webhook Signatures"
+description: "Learn how to validate webhook signatures from OpnForm to ensure authenticity and integrity"
+---
+
+# Validating Webhook Signatures
+
+When you configure a webhook with a signing secret, OpnForm signs each webhook request with an HMAC-SHA256 signature. This allows you to verify that:
+
+1. The webhook came from OpnForm (authenticity)
+2. The payload hasn't been modified in transit (integrity)
+
+## Understanding the Signature
+
+Each webhook request includes an `X-Webhook-Signature` header with the format:
+
+```
+X-Webhook-Signature: sha256=HEXADECIMAL_VALUE
+```
+
+The signature is calculated as:
+
+```
+signature = HMAC-SHA256(webhook_secret, request_body)
+```
+
+Where:
+- `webhook_secret` is the secret you provided when creating the webhook
+- `request_body` is the raw JSON payload
+
+## Validation Steps
+
+1. Extract the signature from the `X-Webhook-Signature` header
+2. Remove the `sha256=` prefix
+3. Calculate the expected signature using your webhook secret and the raw request body
+4. Compare the received signature with the calculated signature
+5. Reject the webhook if signatures don't match
+
+<Warning>
+Always use the **raw request body** (as bytes/string before parsing) when calculating the signature. Parsing JSON and re-serializing can produce different output and cause signature mismatches.
+</Warning>
+
+## Implementation Examples
+
+<CodeGroup>
+```javascript Node.js / Express
+const express = require('express');
+const crypto = require('crypto');
+
+const app = express();
+
+// Important: Use raw body middleware to access raw request data
+app.use(express.raw({ type: 'application/json' }));
+
+app.post('/webhook', (req, res) => {
+ const signature = req.headers['x-webhook-signature'];
+ const secret = process.env.OPNFORM_WEBHOOK_SECRET;
+
+ if (!signature || !secret) {
+ return res.status(401).send('Unauthorized: Missing signature or secret');
+ }
+
+ // Calculate expected signature using raw body
+ const expectedSignature = 'sha256=' + crypto
+ .createHmac('sha256', secret)
+ .update(req.body)
+ .digest('hex');
+
+ // Constant-time comparison to prevent timing attacks
+ if (!crypto.timingSafeEqual(signature, expectedSignature)) {
+ return res.status(401).send('Unauthorized: Invalid signature');
+ }
+
+ // Signature is valid, parse and process the webhook
+ const data = JSON.parse(req.body);
+ console.log('Webhook received:', data);
+
+ res.status(200).send('Webhook received');
+});
+
+app.listen(3000, () => console.log('Webhook server running on port 3000'));
+```
+
+```python Python / Flask
+from flask import Flask, request
+import hmac
+import hashlib
+import json
+import os
+
+app = Flask(__name__)
+
[email protected]('/webhook', methods=['POST'])
+def webhook():
+ signature = request.headers.get('X-Webhook-Signature')
+ secret = os.environ.get('OPNFORM_WEBHOOK_SECRET')
+
+ if not signature or not secret:
+ return 'Unauthorized: Missing signature or secret', 401
+
+ # Get raw request body
+ raw_body = request.get_data()
+
+ # Calculate expected signature
+ expected_signature = 'sha256=' + hmac.new(
+ secret.encode(),
+ raw_body,
+ hashlib.sha256
+ ).hexdigest()
+
+ # Constant-time comparison
+ if not hmac.compare_digest(signature, expected_signature):
+ return 'Unauthorized: Invalid signature', 401
+
+ # Signature is valid, parse and process the webhook
+ data = request.get_json()
+ print('Webhook received:', data)
+
+ return 'Webhook received', 200
+
+if __name__ == '__main__':
+ app.run(port=3000, debug=True)
+```
+
+```php PHP / Laravel
+<?php
+
+use Illuminate\Http\Request;
+
+Route::post('/webhook', function (Request $request) {
+ $signature = $request->header('X-Webhook-Signature');
+ $secret = env('OPNFORM_WEBHOOK_SECRET');
+
+ if (!$signature || !$secret) {
+ return response('Unauthorized: Missing signature or secret', 401);
+ }
+
+ // Get raw request body
+ $rawBody = $request->getContent();
+
+ // Calculate expected signature
+ $expectedSignature = 'sha256=' . hash_hmac(
+ 'sha256',
+ $rawBody,
+ $secret
+ );
+
+ // Constant-time comparison
+ if (!hash_equals($signature, $expectedSignature)) {
+ return response('Unauthorized: Invalid signature', 401);
+ }
+
+ // Signature is valid, parse and process the webhook
+ $data = $request->json()->all();
+ \Log::info('Webhook received:', $data);
+
+ return response('Webhook received', 200);
+});
+```
+
+```bash cURL Testing
+# Generate a webhook secret for testing
+SECRET="whsec_1234567890abcdefghijklmnopqr"
+BODY='{"form_title":"My Form","submission":{"email":"[email protected]"}}'
+
+# Calculate signature
+SIGNATURE="sha256=$(echo -n "$BODY" | openssl dgst -sha256 -hmac "$SECRET" -hex | cut -d' ' -f2)"
+
+# Send webhook request
+curl -X POST http://localhost:3000/webhook \
+ -H "Content-Type: application/json" \
+ -H "X-Webhook-Signature: $SIGNATURE" \
+ -d "$BODY"
+```
+</CodeGroup>
+
+## Custom Headers
+
+In addition to the signature header, OpnForm will send any custom headers you configured when creating the webhook. These can include authentication tokens, API keys, or other identifiers.
+
+Example webhook request with custom headers:
+
+```bash
+POST /webhook HTTP/1.1
+Host: example.com
+Content-Type: application/json
+X-Webhook-Signature: sha256=abc123def456...
+Authorization: Bearer my-api-token
+X-Custom-Header: custom-value
+
+{
+ "form_title": "Contact Form",
+ "submission": { ... }
+}
+```
+
+## Security Best Practices
+
+<Tip>
+1. **Use HTTPS only**: Always use HTTPS endpoints for webhooks to prevent man-in-the-middle attacks
+2. **Strong secrets**: Use cryptographically random secrets at least 12 characters long
+3. **Constant-time comparison**: Use timing-safe comparison functions to prevent timing attacks
+4. **Validate signatures first**: Verify the signature before parsing or processing the webhook data
+5. **Store secrets securely**: Never commit secrets to version control; use environment variables or secret managers
+6. **Rotate regularly**: Consider rotating your webhook secret periodically
+7. **Log verification failures**: Track failed signature validations to detect potential attacks
+</Tip>
+
+## Troubleshooting
+
+### Signature Mismatch
+
+If you're consistently getting signature mismatches:
+
+1. **Verify the raw body**: Ensure you're using the raw request body (before JSON parsing) to calculate the signature
+2. **Check the secret**: Confirm you're using the exact secret from the webhook configuration
+3. **Character encoding**: Ensure both the secret and body are handled with correct UTF-8 encoding
+4. **Middleware order**: If using middleware, ensure raw body capture happens before JSON parsing
+5. **Test with cURL**: Use the cURL example above to manually test signature generation
+
+### Missing Signature Header
+
+If the `X-Webhook-Signature` header is missing:
+
+1. Verify you provided a `webhook_secret` when creating the webhook
+2. Check your webhook status is `active`
+3. Review the integration event logs for any errors during webhook delivery
+
+## Testing Your Webhook
+
+Use a webhook testing service like [webhook.site](https://webhook.site) or [RequestBin](https://requestbin.com) to inspect webhook requests during development. These services display headers, body, and other request details.
+
+You can also implement local webhook testing by running a simple server on your machine and using a tool like [ngrok](https://ngrok.com) to expose it to the internet.
diff --git a/docs/docs.json b/docs/docs.json
index e4b17a898..72f1be845 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -91,7 +91,8 @@
"api-reference/integrations/create-webhook-integration",
"api-reference/integrations/update-webhook-integration",
"api-reference/integrations/delete-webhook-integration",
- "api-reference/integrations/list-webhook-events"
+ "api-reference/integrations/list-webhook-events",
+ "api-reference/integrations/webhook-security"
]
},
{
diff --git a/integrations/n8n/nodes/OpnformTrigger/OpnformTrigger.node.ts b/integrations/n8n/nodes/OpnformTrigger/OpnformTrigger.node.ts
index 2bec09ac1..29ee39844 100644
--- a/integrations/n8n/nodes/OpnformTrigger/OpnformTrigger.node.ts
+++ b/integrations/n8n/nodes/OpnformTrigger/OpnformTrigger.node.ts
@@ -252,8 +252,8 @@ export class OpnformTrigger implements INodeType {
const body = {
integration_id: 'n8n',
- status: true,
- settings: {
+ status: 'active',
+ data: {
webhook_url: hookUrl,
...(providerUrl && { provider_url: providerUrl }),
},
diff --git a/integrations/n8n/package-lock.json b/integrations/n8n/package-lock.json
index 430df2c06..821d48774 100644
--- a/integrations/n8n/package-lock.json
+++ b/integrations/n8n/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "n8n-nodes-opnform",
- "version": "0.1.5",
+ "version": "0.1.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "n8n-nodes-opnform",
- "version": "0.1.5",
+ "version": "0.1.6",
"license": "MIT",
"devDependencies": {
"@n8n/node-cli": "*",
diff --git a/integrations/n8n/package.json b/integrations/n8n/package.json
index 360188c5a..e1a903c53 100644
--- a/integrations/n8n/package.json
+++ b/integrations/n8n/package.json
@@ -1,6 +1,6 @@
{
"name": "n8n-nodes-opnform",
- "version": "0.1.5",
+ "version": "0.1.6",
"description": "n8n community node to receive OpnForm submissions via webhook subscription",
"keywords": [
"n8n-community-node-package",