feat(webhooks): persistence layer for outbound webhook endpoints + deliveries

docs/api/CONVENTIONS.md §6 advertises HMAC-SHA-256 signed webhooks so
integrations (FleetCrown, hirn.li, ...) can react to entity events
without polling. This commit lands the persistence layer only — the
signing util, event firing, and retry worker land in follow-ups,
none of which need a schema change.

Tables (applied to remote ohkueislstxomdjavyhs):
  - webhook_endpoints   user/actor-bound, soft-revoke via revoked_at,
                        secret stored as sha256 + 15-char display prefix,
                        optional event_types allowlist, partial index
                        on (actor_id) WHERE revoked_at IS NULL for the
                        firing-loop hot path
  - webhook_deliveries  log + retry queue, status pending|delivered|failed,
                        next_attempt_at indexed for the worker poll,
                        endpoint_id+created_at index for the UI listing

RLS denies all user access on both tables — admin-client only,
authorisation happens at the service boundary by user_id (same model
as integration_keys + idempotency_results, all platform plumbing).

Service (src/services/webhooks/webhookEndpointsService.ts):
  - createWebhookEndpoint  reuses resolveCreationActor as the mint gate,
                           returns the plaintext secret ONCE
  - listWebhookEndpoints   user-scoped, no secret leaks
  - listActiveEndpointsForActor  fan-out for the firing loop
  - revokeWebhookEndpoint  soft-revoke, excluded by the partial index

Tests still green: 45 suites · 579 tests · 0 failures. tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georgy ButaevandClaude Opus 4.7 committed 2026-06-03 23:21:05 +02:00
1 parent ba0d5b0279
commit 211188a396
3 files changed
+302

No files matched your search

+2
View File
@@ -97,6 +97,8 @@ export const DATABASE_TABLES = {
// Platform integration (outbound API keys for FleetCrown, hirn.li, ...)
INTEGRATION_KEYS: 'integration_keys',
IDEMPOTENCY_RESULTS: 'idempotency_results',
WEBHOOK_ENDPOINTS: 'webhook_endpoints',
WEBHOOK_DELIVERIES: 'webhook_deliveries',
// Bookings
BOOKINGS: 'bookings',
@@ -0,0 +1,183 @@
/**
* Webhook endpoints — outbound delivery configuration service.
*
* docs/api/CONVENTIONS.md §6 advertises HMAC-SHA-256 signed webhooks
* so integrations can react to entity-create / status-change events
* without polling. This file is the persistence layer only: mint /
* list / revoke. The signing util, event firing, and retry worker are
* separate commits.
*
* Shape mirrors integration_keys (same actor-bound model, same
* soft-revocation pattern, same admin-only RLS posture). The minting
* user must already be authorised to act as the bound actor — once
* minted, every event for that actor flows through this endpoint with
* no per-event membership recheck.
*
* - createWebhookEndpoint: mints a new endpoint, returns the secret
* ONCE. The secret is the signing key the integration uses to verify
* delivery authenticity.
* - listWebhookEndpoints: lists a user's endpoints (no secret, ever).
* - revokeWebhookEndpoint: marks revoked. The active-target index
* excludes revoked rows so the firing loop skips them immediately.
*
* Created: 2026-06-03
*/
import { createHash, randomBytes } from 'crypto';
import { createAdminClient } from '@/lib/supabase/admin';
import { logger } from '@/utils/logger';
import { DATABASE_TABLES } from '@/config/database-tables';
import {
resolveCreationActor,
ActorNotPermittedError,
} from '@/services/actors/resolveCreationActor';
const SECRET_PREFIX = 'ock_whk_' as const;
const SECRET_RANDOM_BYTES = 24; // 48 hex chars → ~192 bits of entropy
const DISPLAY_PREFIX_LENGTH = 15; // "ock_whk_a1b2c3d"
export interface WebhookEndpoint {
id: string;
user_id: string;
actor_id: string;
name: string;
url: string;
secret_prefix: string;
event_types: string[] | null;
created_at: string;
last_delivery_at: string | null;
revoked_at: string | null;
}
export interface MintedWebhookEndpoint {
/** Stored record (no secret). */
endpoint: WebhookEndpoint;
/** Plaintext signing secret — show to user ONCE and never again. */
secret: string;
}
function generateSecret(): string {
return `${SECRET_PREFIX}${randomBytes(SECRET_RANDOM_BYTES).toString('hex')}`;
}
function hashSecret(plaintext: string): string {
return createHash('sha256').update(plaintext).digest('hex');
}
const ENDPOINT_SELECT =
'id, user_id, actor_id, name, url, secret_prefix, event_types, created_at, last_delivery_at, revoked_at';
/**
* Mint a new webhook endpoint. The caller must already be authorised
* to act as the requested actor (same gate as integration-key mint
* and entity creation).
*
* @throws ActorNotPermittedError when the user can't act as `actorId`.
*/
export async function createWebhookEndpoint(params: {
userId: string;
actorId: string;
name: string;
url: string;
eventTypes?: string[] | null;
}): Promise<MintedWebhookEndpoint> {
const { userId, actorId, name, url, eventTypes } = params;
await resolveCreationActor(userId, actorId);
const secret = generateSecret();
const secretHash = hashSecret(secret);
const secretPrefix = secret.slice(0, DISPLAY_PREFIX_LENGTH);
const admin = createAdminClient();
const { data, error } = await (
admin.from(DATABASE_TABLES.WEBHOOK_ENDPOINTS) as ReturnType<
typeof admin.from
// eslint-disable-next-line @typescript-eslint/no-explicit-any
> as any
)
.insert({
user_id: userId,
actor_id: actorId,
name: name.trim(),
url: url.trim(),
secret_hash: secretHash,
secret_prefix: secretPrefix,
event_types: eventTypes && eventTypes.length > 0 ? eventTypes : null,
})
.select(ENDPOINT_SELECT)
.single();
if (error || !data) {
logger.error('createWebhookEndpoint: insert failed', { error, userId, actorId });
throw error ?? new Error('Failed to create webhook endpoint');
}
return { endpoint: data as WebhookEndpoint, secret };
}
/** List the user's endpoints — never returns the secret or its hash. */
export async function listWebhookEndpoints(userId: string): Promise<WebhookEndpoint[]> {
const admin = createAdminClient();
const { data, error } = await admin
.from(DATABASE_TABLES.WEBHOOK_ENDPOINTS)
.select(ENDPOINT_SELECT)
.eq('user_id', userId)
.order('created_at', { ascending: false });
if (error) {
logger.error('listWebhookEndpoints: query failed', { error, userId });
throw error;
}
return (data ?? []) as WebhookEndpoint[];
}
/**
* List the LIVE endpoints bound to a given actor — used by the firing
* loop to fan an event out to every active subscriber. Excludes
* revoked endpoints via the partial index.
*/
export async function listActiveEndpointsForActor(actorId: string): Promise<WebhookEndpoint[]> {
const admin = createAdminClient();
const { data, error } = await admin
.from(DATABASE_TABLES.WEBHOOK_ENDPOINTS)
.select(ENDPOINT_SELECT)
.eq('actor_id', actorId)
.is('revoked_at', null);
if (error) {
logger.error('listActiveEndpointsForActor: query failed', { error, actorId });
throw error;
}
return (data ?? []) as WebhookEndpoint[];
}
/**
* Soft-revoke (sets revoked_at). The partial index excludes revoked
* rows so the firing loop skips them on the next query.
*
* @returns true when the endpoint was found and revoked; false if it
* didn't belong to the user (or was already revoked).
*/
export async function revokeWebhookEndpoint(endpointId: string, userId: string): Promise<boolean> {
const admin = createAdminClient();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { data, error } = await (admin.from(DATABASE_TABLES.WEBHOOK_ENDPOINTS) as any)
.update({ revoked_at: new Date().toISOString() })
.eq('id', endpointId)
.eq('user_id', userId)
.is('revoked_at', null)
.select('id')
.maybeSingle();
if (error) {
logger.error('revokeWebhookEndpoint: update failed', { error, userId, endpointId });
throw error;
}
return !!data;
}
export { ActorNotPermittedError };
@@ -0,0 +1,117 @@
-- ============================================================================
-- Webhook endpoints + delivery log
-- ============================================================================
-- docs/api/CONVENTIONS.md §6 advertises HMAC-SHA-256 signed webhook
-- delivery so integrations (FleetCrown, hirn.li, third parties) can react
-- to entity-create / status-change events without polling. This migration
-- lands the persistence layer only. The signing util, event firing, and
-- delivery worker are separate commits — none of those need a schema
-- change.
--
-- Shape mirrors integration_keys (same actor-bound model, same soft-
-- revocation pattern, same admin-only RLS posture):
-- - A webhook endpoint is minted by a user, bound to one actor.
-- - Only events for that bound actor are delivered to that endpoint.
-- - Soft-revoke via revoked_at; the active-target index excludes them.
--
-- Created: 2026-06-03
-- ============================================================================
-- ==================== ENDPOINTS ====================
CREATE TABLE IF NOT EXISTS webhook_endpoints (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
-- Who minted the endpoint (audit + revocation authority).
user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
-- Which actor's events flow to this endpoint. Same shape as actor_id
-- everywhere else in the schema.
actor_id UUID NOT NULL REFERENCES actors(id) ON DELETE CASCADE,
-- Human-readable label ("FleetCrown production webhook", ...).
name TEXT NOT NULL,
-- Target URL the worker POSTs deliveries to. Must be https in prod;
-- the app layer enforces that — DB just stores the string.
url TEXT NOT NULL,
-- HMAC signing secret. SHA-256-hashed at rest the same way
-- integration_keys does it. Plaintext shown to the user ONCE at mint.
secret_hash TEXT NOT NULL,
-- First 11 chars of the plaintext secret for UI display ("ock_whk_a..."
-- or whatever prefix we pick — value doesn't matter to the schema).
secret_prefix TEXT NOT NULL,
-- Optional event-type allowlist. NULL = receive every event for the
-- bound actor. Array of strings like ['product.created', 'service.updated'].
event_types TEXT[],
-- Lifecycle timestamps.
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
last_delivery_at TIMESTAMPTZ,
revoked_at TIMESTAMPTZ,
CONSTRAINT webhook_endpoints_name_not_blank CHECK (length(trim(name)) > 0),
CONSTRAINT webhook_endpoints_url_not_blank CHECK (length(trim(url)) > 0)
);
-- Hot path: "what live endpoints does this actor have?"
CREATE INDEX IF NOT EXISTS webhook_endpoints_actor_active_idx
ON webhook_endpoints (actor_id)
WHERE revoked_at IS NULL;
-- For the /settings/integrations UI listing.
CREATE INDEX IF NOT EXISTS webhook_endpoints_user_id_idx
ON webhook_endpoints (user_id);
ALTER TABLE webhook_endpoints ENABLE ROW LEVEL SECURITY;
-- Deny by default. The application layer uses the admin client to read +
-- write (same model as integration_keys + idempotency_results — these
-- are plumbing tables, not user-facing entities).
COMMENT ON TABLE webhook_endpoints IS
'Outbound webhook configuration. Admin-client only — RLS denies all user access. App layer authorises by user_id at the service boundary.';
-- ==================== DELIVERIES ====================
CREATE TABLE IF NOT EXISTS webhook_deliveries (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
endpoint_id UUID NOT NULL REFERENCES webhook_endpoints(id) ON DELETE CASCADE,
-- The event being delivered. Free-form on purpose — new entity types
-- and event kinds get added without schema changes.
event_type TEXT NOT NULL,
event_id UUID NOT NULL, -- stable per logical event, retries share it
payload JSONB NOT NULL,
-- Delivery outcome. NULL response_status = not attempted yet.
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'delivered', 'failed')),
response_status INTEGER,
response_body TEXT, -- truncated to ~4KB at the service layer
attempt_count INTEGER NOT NULL DEFAULT 0,
last_attempt_at TIMESTAMPTZ,
next_attempt_at TIMESTAMPTZ, -- worker polls this to pick what to retry
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT webhook_deliveries_event_type_not_blank CHECK (length(trim(event_type)) > 0)
);
-- Hot path for the worker: "which deliveries are due now?"
CREATE INDEX IF NOT EXISTS webhook_deliveries_due_idx
ON webhook_deliveries (next_attempt_at)
WHERE status = 'pending';
-- For the /settings/integrations UI to show recent deliveries per endpoint.
CREATE INDEX IF NOT EXISTS webhook_deliveries_endpoint_recent_idx
ON webhook_deliveries (endpoint_id, created_at DESC);
ALTER TABLE webhook_deliveries ENABLE ROW LEVEL SECURITY;
COMMENT ON TABLE webhook_deliveries IS
'Webhook delivery log + retry queue. Admin-client only — RLS denies all user access.';