// © 2026 Evntx FZCO, Dubai, UAE. All rights reserved. // Reference connector (#DEVKIT-REFERENCE-CONNECTORS-1): a webhook trigger. Switching the flow on registers the // installation's webhook URL with the service and keeps the signing secret it returns; every delivery's HMAC-SHA256 // signature is checked before a flow starts; the service's URL check (a challenge) is answered; the subscription is // renewed daily; switching off removes it. Built only against the public connector framework package. // The API is a generic event service (https://events.example.net/v1). import { createHmac, timingSafeEqual } from 'node:crypto'; import { createConnector, createTrigger, ConnectorAuth, Property, TriggerStrategy, WebhookHandshakeStrategy, WebhookRenewStrategy } from '@aancer/connector-framework'; export const API = 'https://events.example.net/v1'; const SUB = 'subscription'; type Subscription = { id: string; secret: string }; export type Event = { id: string; type: string; occurredAt: string; data: Record }; export async function call(apiKey: string, method: 'GET' | 'POST' | 'DELETE', path: string, body?: unknown): Promise { const res = await fetch(`${API}${path}`, { method, headers: { authorization: `Bearer ${apiKey}`, accept: 'application/json', ...(body === undefined ? {} : { 'content-type': 'application/json' }) }, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(30_000), }); if (method === 'DELETE' && res.status === 404) return undefined as T; // already gone: switching off still succeeds if (!res.ok) throw new Error(`Example Events ${method} ${path}: HTTP ${res.status} ${(await res.text()).slice(0, 300)}`); return (res.status === 204 ? undefined : await res.json()) as T; } /** The raw body as the service signed it: the installation passes it as rawBody when it has it, else the parsed body. */ export function rawBytes(rawBody: unknown, body: unknown): Buffer { if (Buffer.isBuffer(rawBody)) return rawBody; if (typeof rawBody === 'string') return Buffer.from(rawBody, 'utf8'); return Buffer.from(typeof body === 'string' ? body : JSON.stringify(body ?? {}), 'utf8'); } /** `x-signature: t=,v1=`; refused when wrong or older than `toleranceS`. */ export function verifySignature(header: string | undefined, raw: Buffer, secret: string, nowS = Math.floor(Date.now() / 1000), toleranceS = 300): boolean { if (!header || !secret) return false; const parts = Object.fromEntries(header.split(',').map((p) => p.trim().split('=', 2) as [string, string])); const t = Number(parts.t); const v1 = parts.v1 ?? ''; if (!Number.isInteger(t) || Math.abs(nowS - t) > toleranceS || !/^[0-9a-f]{64}$/.test(v1)) return false; const want = createHmac('sha256', secret).update(`${t}.`).update(raw).digest(); return timingSafeEqual(want, Buffer.from(v1, 'hex')); } export const auth = ConnectorAuth.SecretText({ displayName: 'API key', description: 'An Example Events key that may manage webhooks.', required: true }); export const eventReceived = createTrigger({ auth, name: 'event_received', displayName: 'Event received', description: 'Starts for each signed event of the chosen types that the service pushes.', type: TriggerStrategy.WEBHOOK, props: { types: Property.StaticMultiSelectDropdown({ displayName: 'Event types', required: true, options: { options: [{ label: 'Order created', value: 'order.created' }, { label: 'Order paid', value: 'order.paid' }, { label: 'Order cancelled', value: 'order.cancelled' }] }, }), }, sampleData: { id: 'evt_1', type: 'order.created', occurredAt: '2026-01-01T00:00:00Z', data: { orderId: 'o_1' } }, // The service checks a new URL with GET ?challenge= and expects the value back. handshakeConfiguration: { strategy: WebhookHandshakeStrategy.QUERY_PRESENT, paramName: 'challenge' }, async onHandshake({ payload }) { return { status: 200, body: { challenge: payload.queryParams['challenge'] ?? '' }, headers: { 'content-type': 'application/json' } }; }, renewConfiguration: { strategy: WebhookRenewStrategy.CRON, cronExpression: '17 3 * * *' }, async onRenew({ auth, store }) { const sub = await store.get(SUB); if (sub) await call(auth.secret_text, 'POST', `/webhooks/${encodeURIComponent(sub.id)}/renew`); }, async onEnable({ auth, propsValue, webhookUrl, store }) { const sub = await call(auth.secret_text, 'POST', '/webhooks', { url: webhookUrl, events: propsValue.types }); if (!sub?.id || !sub.secret) throw new Error('Example Events: the webhook was created without an id or a signing secret'); await store.put(SUB, { id: sub.id, secret: sub.secret }); }, async onDisable({ auth, store }) { const sub = await store.get(SUB); if (sub) await call(auth.secret_text, 'DELETE', `/webhooks/${encodeURIComponent(sub.id)}`); await store.delete(SUB); }, async run({ payload, store, propsValue }) { const sub = await store.get(SUB); const sig = Object.entries(payload.headers ?? {}).find(([k]) => k.toLowerCase() === 'x-signature')?.[1]; // An unsigned, wrongly signed or replayed delivery starts nothing (and tells nobody why: no oracle for a forger). if (!sub || !verifySignature(sig, rawBytes(payload.rawBody, payload.body), sub.secret)) return []; const ev = payload.body as Event; return ev && propsValue.types.includes(ev.type) ? [ev] : []; }, async test({ auth }) { const r = await call<{ items: Event[] }>(auth.secret_text, 'GET', '/events?limit=3'); return r.items; }, }); export const exampleEvents = createConnector({ displayName: 'Reference: signed webhooks', description: 'Starts a flow for each signed event the service pushes.', logoUrl: 'https://events.example.net/logo.svg', minimumSupportedRelease: '0.0.0', authors: ['aancer'], auth, actions: [], triggers: [eventReceived], });