Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

fix(content): keep a cut-off 2xx as sent, say why a webhook test failed, and tie the test to a brand (#1605)

Cihan5a1f5a16a7e9
diff --git a/docs/api-reference/webhooks.mdx b/docs/api-reference/webhooks.mdx
index c70d8072a..3a577556a 100644
--- a/docs/api-reference/webhooks.mdx
+++ b/docs/api-reference/webhooks.mdx
@@ -291,10 +291,13 @@ The test uses the URL and secret currently in the form, so you can check an endp
## Delivery
- Each event is sent **once**. There are no automatic retries.
+- Every request carries `User-Agent: Ansvisor-Webhook/1.0 (+https://ansvisor.com)`, so a firewall or WAF in front of your endpoint can let it through.
- Ansvisor waits up to 15 seconds for a response (10 seconds for `webhook.test`).
-- Respond with a 2xx status quickly and do slow work after responding.
-- Redirects aren't followed: a 3xx is the answer, and nothing reaches the address it points to. Use that address; the **Test** button reports a 3xx as a failure.
-- On Ansvisor Cloud the webhook must be a public address. A self-hosted install may also use addresses on its own network.
+- Respond with a 2xx status quickly and do slow work after responding. Once the status has arrived, it counts even if the connection drops before the rest of the answer.
+- Redirects aren't followed: a 3xx is the answer, and nothing reaches the address it points to. Use that address; the **Test** button reports a 3xx as a failure and names where it redirects to.
+- When the **Test** button can't reach the webhook, it adds the network error, such as `ENOTFOUND` (the host name doesn't resolve), `ECONNREFUSED` (nothing listens on that port) or a TLS certificate error.
+- Only admins and managers can test a brand's webhook, up to 10 tests a minute each.
+- The address must be `http://` or `https://`, with no user name or password in it. On Ansvisor Cloud it must also be a public address. A self-hosted install may also use addresses on its own network.
- `content_draft.sent`:
- A 2xx answer marks the send **sent**. Anything else, or no answer, marks it **failed**, and the Library shows why. The first 2,000 characters of the answer are kept.
- A single page is sent while the person waits. A bulk send (up to 25 pages) goes on in the background, one page after another, with a 2-second pause between pages.
diff --git a/server/src/lib/safe-post.js b/server/src/lib/safe-post.js
index 830ac1d69..284d300ef 100644
--- a/server/src/lib/safe-post.js
+++ b/server/src/lib/safe-post.js
@@ -6,9 +6,10 @@
* own automation (n8n, a CMS) often listens on one of its own;
* * every address its host resolves to must be public, checked in the
* connection's own DNS lookup (no DNS rebinding);
- * * no redirect is followed: a 3xx is an answer, as any other non-2xx;
+ * * no redirect is followed: a 3xx is an answer, as any other non-2xx,
+ * handed back with where it points;
* * a time limit for the whole request, and only the start of the answer
- * is read back.
+ * is read back; an answer cut off after its status is still that status.
* Self-hosted, a private address is the workspace's own network (n8n at
* http://n8n:5678), as its other webhooks reach it: only the scheme and
* credentials are checked. Failures carry PageFetchError's codes:
@@ -29,9 +30,21 @@ const USER_AGENT = 'Ansvisor-Webhook/1.0 (+https://ansvisor.com)';
/** A 3xx: an answer that sends elsewhere, so the body never arrived (none is followed). */
export const isRedirect = (status) => status >= 300 && status < 400;
+/** Where a 3xx points, as a full address (a Location may be relative); null without one. */
+function redirectTarget(location, base) {
+ if (!location) return null;
+ try {
+ return new URL(location, base).href;
+ } catch {
+ return location;
+ }
+}
+
/**
* A webhook address, checked as a page's is but on any port; throws
* 'invalid_url' or 'blocked'. `privateOk` (self-hosted) takes a private one.
+ * The scheme and credentials are checked here in both modes, so the test
+ * says them in a webhook's words, not a page's.
*/
export function checkWebhookUrl(value, { privateOk = false } = {}) {
let url;
@@ -40,14 +53,15 @@ export function checkWebhookUrl(value, { privateOk = false } = {}) {
} catch {
throw new PageFetchError('invalid_url', 'Not a URL');
}
- if (!privateOk) return checkPageUrl(value, [url.port]);
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
throw new PageFetchError('invalid_url', 'Only http and https addresses can be posted to');
}
if (url.username || url.password) {
throw new PageFetchError('invalid_url', 'URLs with credentials are not posted to');
}
- return url;
+ if (privateOk) return url;
+ // On Cloud, an address written as an IP must be a public one.
+ return checkPageUrl(value, [url.port]);
}
/**
@@ -56,7 +70,8 @@ export function checkWebhookUrl(value, { privateOk = false } = {}) {
* @param {string} body
* @param {{ headers?: Record<string, string>, timeoutMs?: number, lookup?: Function }} [opts]
* `lookup` replaces the public-only lookup; tests use it to reach a local server.
- * @returns {Promise<{ status: number, answer: string }>} the HTTP status and the start of the answer
+ * @returns {Promise<{ status: number, answer: string, location?: string }>} the HTTP status
+ * and the start of the answer; for a 3xx, where it points, when it says
*/
export async function postJson(address, body, opts = {}) {
const cloud = isCloud();
@@ -83,9 +98,16 @@ export async function postJson(address, body, opts = {}) {
},
(res) => {
const status = res.statusCode ?? 0;
+ const location = isRedirect(status) ? redirectTarget(res.headers.location, url) : null;
const chunks = [];
let size = 0;
- const done = () => resolve({ status, answer: Buffer.concat(chunks).toString('utf8') });
+ // May run more than once (a cut answer, then its error): the first wins.
+ const done = () =>
+ resolve({
+ status,
+ answer: Buffer.concat(chunks).toString('utf8'),
+ ...(location ? { location } : {}),
+ });
res.on('data', (chunk) => {
if (size >= MAX_ANSWER_BYTES) return;
chunks.push(chunk.subarray(0, MAX_ANSWER_BYTES - size));
@@ -97,7 +119,9 @@ export async function postJson(address, body, opts = {}) {
}
});
res.on('end', done);
- res.on('error', (err) => reject(err));
+ // The status has arrived: an answer cut off after it is still that
+ // answer, with what was read of it.
+ res.on('error', done);
},
);
req.on('error', (err) => {
diff --git a/server/src/lib/safe-post.test.js b/server/src/lib/safe-post.test.js
index fa38a0c29..11dc84e5f 100644
--- a/server/src/lib/safe-post.test.js
+++ b/server/src/lib/safe-post.test.js
@@ -28,6 +28,19 @@ describe('checkWebhookUrl', () => {
])('refuses %s', (address, code) => {
expect(() => checkWebhookUrl(address)).toThrow(expect.objectContaining({ code }));
});
+
+ // In a webhook's words on Cloud too, not a page's ("pages can be read").
+ it.each([
+ ['ftp://acme.example/x', 'Only http and https addresses can be posted to'],
+ ['https://user:[email protected]/', 'URLs with credentials are not posted to'],
+ ['https://[email protected]/', 'URLs with credentials are not posted to'],
+ ])('refuses %s in a webhook’s words, Cloud and self-hosted alike', (address, message) => {
+ for (const privateOk of [false, true]) {
+ expect(() => checkWebhookUrl(address, { privateOk })).toThrow(
+ expect.objectContaining({ code: 'invalid_url', message }),
+ );
+ }
+ });
});
describe('isRedirect', () => {
@@ -61,6 +74,24 @@ describe('postJson', () => {
res.writeHead(302, { location: 'http://localhost/admin' });
res.end();
},
+ '/moved-here': (_req, res) => {
+ res.writeHead(307, { location: '/hook-v2?x=1' });
+ res.end();
+ },
+ '/moved-nowhere': (_req, res) => {
+ res.writeHead(301);
+ res.end();
+ },
+ '/created': (_req, res) => {
+ res.writeHead(201, { location: '/items/1' });
+ res.end('made');
+ },
+ // The status and the start of the answer, then the connection drops.
+ '/cut': (_req, res) => {
+ res.writeHead(200, { 'content-length': '100' });
+ res.write('accepted');
+ setTimeout(() => res.socket.destroy(), 20);
+ },
'/long': (_req, res) => {
res.writeHead(200);
res.end('x'.repeat(MAX_ANSWER_BYTES * 3));
@@ -105,7 +136,25 @@ describe('postJson', () => {
it('answers a non-2xx and a redirect as they are, following none', async () => {
await expect(post('/teapot')).resolves.toEqual({ status: 418, answer: 'no' });
- await expect(post('/moved')).resolves.toMatchObject({ status: 302 });
+ await expect(post('/moved')).resolves.toEqual({
+ status: 302,
+ answer: '',
+ location: 'http://localhost/admin',
+ });
+ });
+
+ it('says where a redirect points, as a full address, and only for a 3xx', async () => {
+ await expect(post('/moved-here')).resolves.toEqual({
+ status: 307,
+ answer: '',
+ location: `http://site.test:${port}/hook-v2?x=1`,
+ });
+ await expect(post('/moved-nowhere')).resolves.toEqual({ status: 301, answer: '' });
+ await expect(post('/created')).resolves.toEqual({ status: 201, answer: 'made' });
+ });
+
+ it('keeps the status of an answer cut off after it, with what was read', async () => {
+ await expect(post('/cut')).resolves.toEqual({ status: 200, answer: 'accepted' });
});
it('reads back only the start of a long answer', async () => {
@@ -129,6 +178,18 @@ describe('postJson', () => {
});
});
+ it('refuses another scheme or credentials in a webhook’s words on Cloud', async () => {
+ vi.stubEnv('IS_CLOUD', 'true');
+ await expect(postJson('ftp://acme.example/x', '{}')).rejects.toMatchObject({
+ code: 'invalid_url',
+ message: 'Only http and https addresses can be posted to',
+ });
+ await expect(postJson('https://user:[email protected]/', '{}')).rejects.toMatchObject({
+ code: 'invalid_url',
+ message: 'URLs with credentials are not posted to',
+ });
+ });
+
it('reaches the workspace’s own network when self-hosted, as its other webhooks do', async () => {
vi.stubEnv('IS_CLOUD', 'false');
await expect(postJson(`http://127.0.0.1:${port}/hook`, '{}')).resolves.toMatchObject({
diff --git a/server/src/middleware/rate-limiter.js b/server/src/middleware/rate-limiter.js
index 8296b6867..98e835f51 100644
--- a/server/src/middleware/rate-limiter.js
+++ b/server/src/middleware/rate-limiter.js
@@ -145,6 +145,20 @@ export const cmsLimiter = rateLimit({
},
});
+// Test Webhook (#1568 review): each test posts to an address the caller
+// typed, so a member's are few, 10 a minute.
+export const webhookTestLimiter = rateLimit({
+ windowMs: 60 * 1000,
+ max: 10,
+ keyGenerator: apiLimiterKey,
+ standardHeaders: true,
+ legacyHeaders: false,
+ message: {
+ success: false,
+ message: 'Too many requests, please try again later.',
+ },
+});
+
export const brandFactsLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 30,
diff --git a/server/src/routes/content-webhooks.test.js b/server/src/routes/content-webhooks.test.js
index ca32bb7c1..8225e10d7 100644
--- a/server/src/routes/content-webhooks.test.js
+++ b/server/src/routes/content-webhooks.test.js
@@ -6,13 +6,15 @@ import express from 'express';
* /api/content/:id/send-webhook and /bulk/send-webhook) and the webhook test
* (POST /api/content/webhook-test): they post as Send to CMS does
* (postJson), so on Cloud a private address is refused and a redirect is an
- * answer, not followed (#1437 review, item 5).
+ * answer, not followed (#1437 review, item 5). The test is a brand's, for
+ * those who can edit its webhook, 10 a minute (#1568 review).
*/
import { PageFetchError } from '../lib/safe-fetch.js';
const postJson = vi.fn();
const assertOpportunityAccess = vi.fn();
+const assertBrandAccess = vi.fn();
let rows = {};
let updates = [];
@@ -66,7 +68,7 @@ async function startApp() {
vi.doMock('../lib/job-manager.js', () => ({ createJob: vi.fn(), getJob: vi.fn() }));
vi.doMock('../lib/job-runner.js', () => ({ runContentJob: vi.fn() }));
vi.doMock('../lib/access.js', () => ({
- assertBrandAccess: vi.fn(),
+ assertBrandAccess,
assertOpportunitiesAccess: vi.fn(),
assertOpportunityAccess,
assertPromptAccess: vi.fn(),
@@ -106,6 +108,8 @@ const post = (path, body = {}) =>
body: JSON.stringify(body),
});
+const BRAND_ID = '11111111-1111-4111-8111-111111111111';
+
const OPPORTUNITY = {
id: 'o1',
brand_id: 'b1',
@@ -135,8 +139,10 @@ beforeEach(async () => {
brand_domains: [{ domain: 'acme.example' }],
competitors: [],
content_opportunities: { status: 'sent' },
+ profiles: { role: 'manager' },
};
assertOpportunityAccess.mockResolvedValue(OPPORTUNITY);
+ assertBrandAccess.mockResolvedValue({ brand: { id: BRAND_ID }, orgId: 'org-1' });
postJson.mockResolvedValue({ status: 200, answer: '{"ok":true}' });
await startApp();
});
@@ -146,34 +152,128 @@ afterEach(async () => {
});
describe('POST /api/content/webhook-test', () => {
+ const test = (body) => post('/webhook-test', { brandId: BRAND_ID, ...body });
+
it('posts the test event with the secret, for 10 s, and says how it was answered', async () => {
- const res = await post('/webhook-test', {
- webhookUrl: 'https://hooks.example/abc',
- webhookSecret: 'shh',
- });
+ const res = await test({ webhookUrl: 'https://hooks.example/abc', webhookSecret: 'shh' });
expect(await res.json()).toEqual({ success: true, status: 200, statusText: 'OK' });
+ expect(assertBrandAccess).toHaveBeenCalledWith(BRAND_ID, 'u1');
const [address, body, opts] = postJson.mock.calls[0];
expect(address).toBe('https://hooks.example/abc');
expect(JSON.parse(body)).toMatchObject({ event: 'webhook.test' });
expect(opts).toEqual({ headers: { 'X-Webhook-Secret': 'shh' }, timeoutMs: 10_000 });
});
+ it('lets an admin test too', async () => {
+ rows.profiles = { role: 'admin' };
+ const res = await test({ webhookUrl: 'https://hooks.example/abc' });
+ expect(res.status).toBe(200);
+ expect(postJson).toHaveBeenCalledTimes(1);
+ });
+
it('reads a redirect as an answer, not a success', async () => {
postJson.mockResolvedValue({ status: 302, answer: '' });
- const res = await post('/webhook-test', { webhookUrl: 'https://hooks.example/abc' });
+ const res = await test({ webhookUrl: 'https://hooks.example/abc' });
expect(await res.json()).toEqual({ success: false, status: 302, statusText: 'Found' });
expect(postJson.mock.calls[0][2]).toEqual({ headers: {}, timeoutMs: 10_000 });
});
- it('says why an address it refused or couldn’t reach failed', async () => {
+ it('says where a redirect points', async () => {
+ postJson.mockResolvedValue({ status: 308, answer: '', location: 'https://hooks.example/v2' });
+ const res = await test({ webhookUrl: 'https://hooks.example/abc' });
+ expect(await res.json()).toEqual({
+ success: false,
+ status: 308,
+ statusText: 'Permanent Redirect',
+ location: 'https://hooks.example/v2',
+ });
+ });
+
+ it('says why an address it refused failed', async () => {
postJson.mockRejectedValue(new PageFetchError('blocked', '10.0.0.5 is not a public address'));
- const res = await post('/webhook-test', { webhookUrl: 'http://10.0.0.5/hook' });
+ const res = await test({ webhookUrl: 'http://10.0.0.5/hook' });
expect(await res.json()).toEqual({
success: false,
status: 0,
error: '10.0.0.5 is not a public address',
});
});
+
+ it.each(['ENOTFOUND', 'ECONNREFUSED', 'CERT_HAS_EXPIRED'])(
+ 'names the network error when the webhook can’t be reached (%s)',
+ async (errno) => {
+ postJson.mockRejectedValue(
+ new PageFetchError('unreachable', 'The webhook could not be reached', { errno }),
+ );
+ const res = await test({ webhookUrl: 'https://hooks.example/abc' });
+ expect(await res.json()).toEqual({
+ success: false,
+ status: 0,
+ error: `The webhook could not be reached (${errno})`,
+ });
+ },
+ );
+
+ it('leaves out a system error’s numeric errno', async () => {
+ postJson.mockRejectedValue(Object.assign(new Error('socket hang up'), { errno: -54 }));
+ const res = await test({ webhookUrl: 'https://hooks.example/abc' });
+ expect(await res.json()).toEqual({ success: false, status: 0, error: 'socket hang up' });
+ });
+
+ it.each([
+ ['no brand', { brandId: undefined }],
+ ['a brand that isn’t an id', { brandId: 'acme' }],
+ ['no address', { webhookUrl: ' ' }],
+ ])('answers 400 for %s, posting nothing', async (_what, body) => {
+ const res = await test({ webhookUrl: 'https://hooks.example/abc', ...body });
+ expect(res.status).toBe(400);
+ expect(await res.json()).toMatchObject({ error: 'Invalid request' });
+ expect(postJson).not.toHaveBeenCalled();
+ });
+
+ it.each(['member', undefined])(
+ 'answers 403 to a %s, who can’t edit the webhook, posting nothing',
+ async (role) => {
+ rows.profiles = role ? { role } : null;
+ const res = await test({ webhookUrl: 'https://hooks.example/abc' });
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({
+ error: 'Only admins and managers can test the webhook.',
+ code: 'forbidden',
+ });
+ expect(postJson).not.toHaveBeenCalled();
+ },
+ );
+
+ it('answers 403 for another workspace’s brand, posting nothing', async () => {
+ assertBrandAccess.mockRejectedValue(
+ Object.assign(new Error("This brand isn't in your workspace"), {
+ status: 403,
+ code: 'not_in_workspace',
+ }),
+ );
+ const res = await test({ webhookUrl: 'https://hooks.example/abc' });
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({
+ error: "This brand isn't in your workspace",
+ code: 'not_in_workspace',
+ });
+ expect(postJson).not.toHaveBeenCalled();
+ });
+
+ it('takes 10 tests a minute from a member, then answers 429', async () => {
+ for (let i = 0; i < 10; i++) {
+ const res = await test({ webhookUrl: 'https://hooks.example/abc' });
+ expect(res.status).toBe(200);
+ }
+ const res = await test({ webhookUrl: 'https://hooks.example/abc' });
+ expect(res.status).toBe(429);
+ expect(await res.json()).toEqual({
+ success: false,
+ message: 'Too many requests, please try again later.',
+ });
+ expect(postJson).toHaveBeenCalledTimes(10);
+ });
});
describe('POST /api/content/:id/send-webhook', () => {
diff --git a/server/src/routes/content.js b/server/src/routes/content.js
index d8b0aac1b..0ba149f31 100644
--- a/server/src/routes/content.js
+++ b/server/src/routes/content.js
@@ -18,6 +18,7 @@ import { getLanguageName } from '../lib/languages.js';
import supabaseAdmin from '../config/supabase.js';
import { selectInChunks } from '../lib/chunked-in.js';
import { isRedirect, postJson } from '../lib/safe-post.js';
+import { webhookTestLimiter } from '../middleware/rate-limiter.js';
import {
assertBrandAccess,
assertOpportunitiesAccess,
@@ -1181,18 +1182,58 @@ router.post('/:id/send-webhook', async (req, res) => {
}
});
+/** Who can set up a brand's webhook, and so test one for it. */
+const WEBHOOK_ROLES = ['admin', 'manager'];
+
+/** The brand is the caller's, and the caller can edit its webhook; else 404 / 403. */
+async function assertWebhookEditor(brandId, userId) {
+ await assertBrandAccess(brandId, userId);
+ const { data: profile } = await supabaseAdmin
+ .from('profiles')
+ .select('role')
+ .eq('id', userId)
+ .single();
+ if (!WEBHOOK_ROLES.includes(profile?.role)) {
+ const err = new Error('Only admins and managers can test the webhook.');
+ err.status = 403;
+ err.code = 'forbidden';
+ throw err;
+ }
+}
+
+const webhookTestSchema = z.object({
+ brandId: z.guid(),
+ webhookUrl: z.string().trim().min(1),
+ webhookSecret: z.string().nullish(),
+});
+
/**
* POST /api/content/webhook-test
- * Test a webhook URL with a dummy payload.
+ * Test a webhook URL with a dummy payload, for a brand whose webhook the
+ * caller can edit (admins and managers), 10 a minute.
+ * Body: { brandId, webhookUrl, webhookSecret? }. Answers { success, status,
+ * statusText }, with `location` for a redirect; { success: false, status: 0,
+ * error } when the address is refused or can't be reached (with the network
+ * error's code, e.g. ENOTFOUND).
*/
-router.post('/webhook-test', async (req, res) => {
- try {
- const { webhookUrl, webhookSecret } = req.body;
+router.post('/webhook-test', webhookTestLimiter, async (req, res) => {
+ const parsed = webhookTestSchema.safeParse(req.body);
+ if (!parsed.success) {
+ return res.status(400).json({ error: 'Invalid request', details: parsed.error.issues });
+ }
+ const { brandId, webhookUrl, webhookSecret } = parsed.data;
- if (!webhookUrl) {
- return res.status(400).json({ error: 'webhookUrl is required' });
+ try {
+ await assertWebhookEditor(brandId, req.user.id);
+ } catch (error) {
+ if (error.status) {
+ return res.status(error.status).json({ error: error.message, code: error.code });
}
+ req.log.error({ err: error }, 'webhook test access error');
+ return res.status(500).json({ error: 'Failed to test webhook' });
+ }
+ try {
const payload = {
event: 'webhook.test',
message: 'This is a test webhook from AEO platform.',
@@ -1215,12 +1256,20 @@ router.post('/webhook-test', async (req, res) => {
success: webhookRes.status >= 200 && webhookRes.status < 300,
status: webhookRes.status,
statusText: STATUS_CODES[webhookRes.status] ?? '',
+ // Where a redirect points (postJson gives it for a 3xx only), so the
+ // dialog can name the address to use.
+ ...(webhookRes.location ? { location: webhookRes.location } : {}),
});
} catch (error) {
return res.json({
success: false,
status: 0,
- error: error.message,
+ // Why it couldn't be reached: PageFetchError's errno (ENOTFOUND,
+ // ECONNREFUSED, a TLS error…); a system error's own errno is a number.
+ error:
+ typeof error.errno === 'string' && error.errno
+ ? `${error.message} (${error.errno})`
+ : error.message,
});
}
});
diff --git a/web/messages/en.json b/web/messages/en.json
index f9dae7392..0d7980744 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -5890,6 +5890,8 @@
"testing": "Testing...",
"testSuccess": "Webhook responded successfully!",
"testFailed": "Webhook test failed: {error}",
+ "testRedirect": "The address redirects (HTTP {status}) to {location}. Nothing is sent on to it: use that address instead.",
+ "testForbidden": "Only admins and managers can test the webhook.",
"save": "Save Webhook",
"saving": "Saving...",
"saved": "Webhook saved!",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.test.tsx
new file mode 100644
index 000000000..692cf003d
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.test.tsx
@@ -0,0 +1,109 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../../../../messages/en.json';
+import type { WebhookTestResult } from '@/lib/actions/content';
+
+const getWebhookConfig = vi.hoisted(() => vi.fn());
+const testWebhook = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/actions/content', () => ({
+ getWebhookConfig,
+ saveWebhookConfig: vi.fn(),
+ testWebhook,
+}));
+vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } }));
+
+const { WebhookSettingsDialog } = await import('./_webhook-settings');
+
+/**
+ * Test Webhook (#1568 review): the test is the brand's, and the dialog says
+ * why it failed: who may test, too many tests, where a redirect points, or
+ * the network error that kept the webhook out of reach.
+ */
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let container: HTMLDivElement;
+let root: Root;
+
+async function render() {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <WebhookSettingsDialog open onOpenChange={vi.fn()} brandId="brand-1" />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+const dialog = () => document.querySelector('[role="dialog"]')!;
+const button = (name: string) =>
+ [...dialog().querySelectorAll<HTMLButtonElement>('button')].find((b) => b.textContent === name)!;
+
+/** Presses Test Webhook with the test answering `result`; what the dialog then says. */
+async function runTest(result: WebhookTestResult) {
+ testWebhook.mockResolvedValue(result);
+ await render();
+ await act(async () => button('Test Webhook').click());
+ return dialog().textContent;
+}
+
+beforeEach(() => {
+ getWebhookConfig.mockReset().mockResolvedValue({
+ webhookUrl: 'https://hooks.example/abc',
+ webhookSecret: 'shh',
+ isActive: true,
+ events: ['opportunity.sent'],
+ });
+ testWebhook.mockReset();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('WebhookSettingsDialog – Test Webhook', () => {
+ it('tests the address and secret in the form for this brand', async () => {
+ expect(await runTest({ success: true, status: 200 })).toContain(
+ 'Webhook responded successfully!',
+ );
+ expect(testWebhook).toHaveBeenCalledWith('brand-1', 'https://hooks.example/abc', 'shh');
+ });
+
+ it('says only admins and managers can test', async () => {
+ expect(await runTest({ success: false, status: 0, failure: 'forbidden' })).toContain(
+ 'Only admins and managers can test the webhook.',
+ );
+ });
+
+ it.each([
+ ['busy', 'Too many requests. Wait a minute and try again.'],
+ ['workspace', "This brand isn't in your workspace. Switch to one of your brands."],
+ ['session', 'Your session expired. Sign in again.'],
+ ] as const)('says why the API refused the test (%s)', async (failure, text) => {
+ expect(await runTest({ success: false, status: 0, failure })).toContain(text);
+ });
+
+ it('names the address a redirect points to', async () => {
+ expect(
+ await runTest({ success: false, status: 308, location: 'https://hooks.example/v2' }),
+ ).toContain(
+ 'The address redirects (HTTP 308) to https://hooks.example/v2. Nothing is sent on to it: use that address instead.',
+ );
+ });
+
+ it('shows why the webhook couldn’t be reached, else its status', async () => {
+ expect(
+ await runTest({
+ success: false,
+ status: 0,
+ error: 'The webhook could not be reached (ENOTFOUND)',
+ }),
+ ).toContain('The webhook could not be reached (ENOTFOUND)');
+ expect(await runTest({ success: false, status: 500 })).toContain('HTTP 500');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.tsx
index 560ce0d73..42b3ac18e 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/_webhook-settings.tsx
@@ -15,7 +15,12 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { LoadingDots } from '@/components/ui/loading-dots';
import { CheckCircle2, XCircle } from 'lucide-react';
-import { getWebhookConfig, saveWebhookConfig, testWebhook } from '@/lib/actions/content';
+import {
+ getWebhookConfig,
+ saveWebhookConfig,
+ testWebhook,
+ type WebhookTestResult,
+} from '@/lib/actions/content';
import { toast } from 'sonner';
const WEBHOOK_EVENTS = [
@@ -39,6 +44,7 @@ interface WebhookSettingsDialogProps {
export function WebhookSettingsDialog({ open, onOpenChange, brandId }: WebhookSettingsDialogProps) {
const t = useTranslations('content.webhook');
+ const tFailure = useTranslations('apiFailure');
const [url, setUrl] = useState('');
const [secret, setSecret] = useState('');
@@ -102,6 +108,18 @@ export function WebhookSettingsDialog({ open, onOpenChange, brandId }: WebhookSe
}
};
+ const testMessage = (result: WebhookTestResult) => {
+ if (result.success) return t('testSuccess');
+ // The API didn't run the test: not an admin or manager, too many tests…
+ if (result.failure) {
+ return result.failure === 'forbidden' ? t('testForbidden') : tFailure(result.failure);
+ }
+ if (result.location) {
+ return t('testRedirect', { status: result.status, location: result.location });
+ }
+ return result.error || `HTTP ${result.status}`;
+ };
+
const handleTest = async () => {
if (!url.trim()) {
toast.error(t('urlRequiredTest'));
@@ -110,11 +128,8 @@ export function WebhookSettingsDialog({ open, onOpenChange, brandId }: WebhookSe
setTesting(true);
setTestResult(null);
try {
- const result = await testWebhook(url.trim(), secret.trim() || undefined);
- setTestResult({
- success: result.success,
- message: result.success ? t('testSuccess') : result.error || `HTTP ${result.status}`,
- });
+ const result = await testWebhook(brandId, url.trim(), secret.trim() || undefined);
+ setTestResult({ success: result.success, message: testMessage(result) });
} catch (err) {
setTestResult({
success: false,
diff --git a/web/src/lib/actions/content-webhook.test.ts b/web/src/lib/actions/content-webhook.test.ts
index 5e4cda776..a27ada8c4 100644
--- a/web/src/lib/actions/content-webhook.test.ts
+++ b/web/src/lib/actions/content-webhook.test.ts
@@ -1,14 +1,17 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* The brand's webhook keeps the events it is subscribed to: Content page
- * sent (#1331) among them, anything else left out.
+ * sent (#1331) among them, anything else left out. Test Webhook is the
+ * brand's, and says why the API refused it (#1568 review).
*/
let upserts: unknown[];
+let session: { access_token: string } | null;
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(async () => ({
+ auth: { getSession: async () => ({ data: { session } }) },
from: () => {
let value: Record<string, unknown> = {};
const chain: Record<string, unknown> = {
@@ -21,11 +24,23 @@ vi.mock('@/lib/supabase/server', () => ({
})),
}));
-const { saveWebhookConfig } = await import('./content');
+const { saveWebhookConfig, testWebhook } = await import('./content');
+
+const fetchMock = vi.fn();
beforeEach(() => {
upserts = [];
+ session = { access_token: 'tok' };
+ fetchMock.mockReset();
+ vi.stubGlobal('fetch', fetchMock);
});
+afterEach(() => vi.unstubAllGlobals());
+
+const answer = (status: number, body: unknown) =>
+ new Response(JSON.stringify(body), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ });
describe('saveWebhookConfig', () => {
it('keeps Content page sent and leaves out what no webhook sends', async () => {
@@ -46,3 +61,73 @@ describe('saveWebhookConfig', () => {
expect(upserts).toEqual([]);
});
});
+
+describe('testWebhook', () => {
+ it('tests the address for the brand, with the session, and hands back the answer', async () => {
+ fetchMock.mockResolvedValue(
+ answer(200, {
+ success: false,
+ status: 307,
+ statusText: 'Temporary Redirect',
+ location: 'https://hooks.example/v2',
+ }),
+ );
+ await expect(testWebhook('brand-1', 'https://hooks.example/abc', 'shh')).resolves.toEqual({
+ success: false,
+ status: 307,
+ statusText: 'Temporary Redirect',
+ location: 'https://hooks.example/v2',
+ });
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toMatch(/\/api\/content\/webhook-test$/);
+ expect(init.headers.Authorization).toBe('Bearer tok');
+ expect(JSON.parse(init.body)).toEqual({
+ brandId: 'brand-1',
+ webhookUrl: 'https://hooks.example/abc',
+ webhookSecret: 'shh',
+ });
+ });
+
+ it.each([
+ [
+ 'a member',
+ 403,
+ { error: 'Only admins and managers can test the webhook.', code: 'forbidden' },
+ 'forbidden',
+ ],
+ [
+ 'another workspace’s brand',
+ 403,
+ { error: "This brand isn't in your workspace", code: 'not_in_workspace' },
+ 'workspace',
+ ],
+ [
+ 'too many tests',
+ 429,
+ { success: false, message: 'Too many requests, please try again later.' },
+ 'busy',
+ ],
+ ['an expired session', 401, { error: 'Invalid token' }, 'session'],
+ ['a bad request', 400, { error: 'Invalid request' }, 'failed'],
+ ])(
+ 'says why the API refused it for %s, without throwing',
+ async (_who, status, body, failure) => {
+ fetchMock.mockResolvedValue(answer(status, body));
+ await expect(testWebhook('brand-1', 'https://hooks.example/abc')).resolves.toEqual({
+ success: false,
+ status: 0,
+ failure,
+ });
+ },
+ );
+
+ it('asks to sign in again without a session, calling nothing', async () => {
+ session = null;
+ await expect(testWebhook('brand-1', 'https://hooks.example/abc')).resolves.toEqual({
+ success: false,
+ status: 0,
+ failure: 'session',
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/lib/actions/content.ts b/web/src/lib/actions/content.ts
index 8899f9913..044587a2e 100644
--- a/web/src/lib/actions/content.ts
+++ b/web/src/lib/actions/content.ts
@@ -458,11 +458,32 @@ export async function sendToWebhook(id: string): Promise<SendToWebhookResult> {
};
}
+/** Why the API didn't run a webhook test: not an admin or manager, or a general reason. */
+export type WebhookTestFailure = 'forbidden' | ApiFailure;
+
+export interface WebhookTestResult {
+ success: boolean;
+ /** The webhook's HTTP status; 0 when it wasn't reached or the test didn't run. */
+ status: number;
+ /** Why the address was refused or couldn't be reached. */
+ error?: string;
+ /** Where a redirect (3xx) points. */
+ location?: string;
+ /** Set when the API refused the test itself, rather than the webhook answering. */
+ failure?: WebhookTestFailure;
+}
+
+/**
+ * Test Webhook for a brand whose webhook the caller can edit (#1568 review).
+ * The API's refusals come back as values: thrown, Next.js would hide why.
+ */
export async function testWebhook(
+ brandId: string,
webhookUrl: string,
webhookSecret?: string,
-): Promise<{ success: boolean; status: number; error?: string }> {
- const session = await getSession();
+): Promise<WebhookTestResult> {
+ const session = await sessionOrNull();
+ if (!session) return { success: false, status: 0, failure: 'session' };
const res = await fetch(`${AEO_SERVER_URL}/api/content/webhook-test`, {
method: 'POST',
@@ -470,12 +491,16 @@ export async function testWebhook(
'Content-Type': 'application/json',
Authorization: `Bearer ${session.access_token}`,
},
- body: JSON.stringify({ webhookUrl, webhookSecret }),
+ body: JSON.stringify({ brandId, webhookUrl, webhookSecret }),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
- throw new Error(body.error || `Server error: ${res.status}`);
+ return {
+ success: false,
+ status: 0,
+ failure: body.code === 'forbidden' ? 'forbidden' : apiFailure(res.status, body),
+ };
}
return res.json();