import React, { useEffect, useState } from 'react'; import { __, _n, sprintf } from '@wordpress/i18n'; import { api } from '../api'; import { Card, Button, Badge, Notice, Field, Switch, CodeBlock } from './ui'; import Explain from './Explain'; /** * Outgoing webhooks — the plugin's events, delivered to a URL. * * Every subscription is a URL, a set of events, a secret and a switch. The * secret signs each delivery (HMAC-SHA256 of the raw body, `X-AIRS-Signature`) * in the shape GitHub and Stripe use, so a Zapier, Make, n8n or hand-written * receiver verifies it the way it already knows. The last forty deliveries are * kept so "did it fire?" has an answer. */ export default function Webhooks() { const [data, setData] = useState(null); const [error, setError] = useState(null); const [form, setForm] = useState(null); // null = closed; {} = new; {id} = edit const [busy, setBusy] = useState(''); const [minted, setMinted] = useState(null); const [testResult, setTestResult] = useState(null); const load = () => api.get('/webhooks').then(setData).catch((e) => setError(e.message)); useEffect(() => { load(); }, []); const run = async (name, fn) => { setBusy(name); setError(null); try { await fn(); } catch (e) { setError(e.message); } finally { setBusy(''); } }; const save = () => run('save', async () => { const r = await api.post('/webhooks', form); setData(r); if (r.saved?.minted) setMinted({ id: r.saved.id, secret: r.saved.minted }); setForm(null); }); const remove = (id) => run(`del-${id}`, async () => setData(await api.del(`/webhooks/${id}`))); const test = (id) => run(`test-${id}`, async () => { const r = await api.post(`/webhooks/${id}/test`, {}); setData(r); setTestResult({ id, ...r.result }); }); const toggle = (h) => run(`toggle-${h.id}`, async () => setData(await api.post('/webhooks', { id: h.id, url: h.url, events: h.events, label: h.label, active: !h.active }))); if (!data) return null; const events = Object.entries(data.events || {}); const hooks = data.hooks || []; const deliveries = data.deliveries || []; const hookLabel = (id) => hooks.find((h) => h.id === id)?.label || hooks.find((h) => h.id === id)?.url || id.slice(0, 8); return (
{error && {error}} {minted && (
{__('Signing secret for this webhook — shown once, copy it now.', 'ai-rank-suite')} {minted.secret} {__('Verify each delivery:', 'ai-rank-suite')}sha256=HMAC_SHA256(raw_body, secret) {__('must equal the', 'ai-rank-suite')}{' '} {__('X-AIRS-Signature', 'ai-rank-suite')} {__('header. To rotate, edit the webhook and enter a new secret.', 'ai-rank-suite')}
)} setForm({ url: '', label: '', events: ['audit.finished', 'score.recalculated'], secret: '', active: true })}>{__('Add webhook', 'ai-rank-suite')} ) } flush > {form && (
setForm({ ...form, url: e.target.value })} placeholder="https://hooks.zapier.com/hooks/catch/…" style={{ width: '100%' }} /> setForm({ ...form, label: e.target.value })} placeholder={__('Slack #seo', 'ai-rank-suite')} style={{ width: '100%' }} />
{events.map(([key, ev]) => { const on = form.events.includes(key); return ( ); })}
setForm({ ...form, secret: e.target.value })} placeholder={__('optional', 'ai-rank-suite')} style={{ maxWidth: 360 }} />
)} {hooks.length === 0 && !form ? (
{__('No webhooks yet.', 'ai-rank-suite')} {__('Add one and the plugin will POST a signed JSON envelope —', 'ai-rank-suite')}event, site,{' '} time, data {__('— to that URL whenever a selected event happens.', 'ai-rank-suite')}
) : (
{hooks.map((h) => ( ))}
{__('Endpoint', 'ai-rank-suite')} {__('Events', 'ai-rank-suite')} {__('Last delivery', 'ai-rank-suite')}
{h.label || h.url} {h.label && {h.url}}
{h.events.map((ev) => ( {ev} ))} {h.last ? ( {h.last_ok ? sprintf(__('%s ok', 'ai-rank-suite'), h.last_status) : h.last_status ? `HTTP ${h.last_status}` : __('unreachable', 'ai-rank-suite')} {new Date(h.last * 1000).toLocaleString()} {h.failures > 1 ? ` · ${sprintf(_n('%d failure in a row', '%d failures in a row', h.failures, 'ai-rank-suite'), h.failures)}` : ''} ) : ( {__('never', 'ai-rank-suite')} )}
toggle(h)} label="" />
)} {testResult && (

{sprintf(__('Test to %s:', 'ai-rank-suite'), hookLabel(testResult.id))} {testResult.ok ? sprintf(__('delivered, HTTP %1$s in %2$s ms', 'ai-rank-suite'), testResult.status, testResult.ms) : sprintf(__('failed — %s', 'ai-rank-suite'), testResult.error || `HTTP ${testResult.status}`)}

)}
{deliveries.length === 0 ? (
{__('Nothing delivered yet — press Test on a webhook.', 'ai-rank-suite')}
) : (
{deliveries.slice(0, 20).map((d, i) => ( ))}
{__('When', 'ai-rank-suite')} {__('Event', 'ai-rank-suite')} {__('To', 'ai-rank-suite')} {__('Result', 'ai-rank-suite')}
{new Date(d.time * 1000).toLocaleString()} {d.event} {hookLabel(d.hook)} {d.ok ? `${d.status} · ${d.ms} ms` : d.status ? `HTTP ${d.status}` : __('unreachable', 'ai-rank-suite')}
)}

hash_equals('sha256=' . hash_hmac('sha256', $rawBody, $secret), $_SERVER['HTTP_X_AIRANKSUITE_SIGNATURE']) {' '}{__('— the same in Node with', 'ai-rank-suite')} crypto.createHmac('sha256', secret).update(rawBody).digest('hex'). {__('In n8n or Make, add a Crypto/HMAC step on the raw body and compare with the header. Reject anything that does not match; a 2xx from your side marks the delivery as ok here.', 'ai-rank-suite')}

{__('On the same install, no HTTP is needed:', 'ai-rank-suite')}add_action('airanksuite/event', fn($name, $envelope) => …) {__('or', 'ai-rank-suite')}{' '} add_action('airanksuite/event/audit.finished', …) {__('receive every event as a PHP action.', 'ai-rank-suite')}

); }