mirror of
https://github.com/bitbaum/orangecat.git
synced 2026-12-04 06:18:00 +01:00
feat(webhooks): events actually fire on entity create + retry worker
This commit closes the gap between the persistence/signing/SDK foundations (211188a3/7dfdab2f/6cc7e4ba) and the public-facing contract in docs/api/CONVENTIONS.md §6: every /api/v1 entity POST now emits a signed delivery to every active endpoint bound to the actor. Schema (migration 20260603000005, applied to remote): webhook_endpoints.secret_hash → secret_plaintext.211188a3stored sha256 hashes, but the firing worker needs the plaintext to sign each delivery. Zero rows existed so the column swap is risk-free. Documented as PHASE-2 debt to encrypt-at-rest with a master KMS key (user-confirmed approach). Service (src/services/webhooks/deliveryService.ts): - enqueueWebhookEvent fans out across active endpoints, one webhook_deliveries row per endpoint, event_id shared across the fan-out so receivers can dedupe. - pickDueDeliveries SELECT pending rows with next_attempt_at <= now - claimDelivery atomic UPDATE WHERE attempt_count = expected (optimistic claim — two cron invocations can't double-process the same row). - markDelivered 2xx outcome. - markFailedOrRetry non-2xx / network error. Exp-backoff: 1m, 5m, 25m, 2h, 12h, 24h, then status=failed. - truncateResponseBody 4KB cap so misbehaving receivers can't bloat the table. Service (webhookEndpointsService additions): - getEndpointSigningContext worker-only fetch of (url, secret, actorId). Returns null for revoked endpoints. - touchEndpointLastDelivery bump last_delivery_at on successful POST for /settings/integrations UI freshness. Worker (/api/cron/webhook-worker, scheduled "* * * * *"): - CRON_SECRET-gated like /api/cron/cleanup. - BATCH_SIZE 20 per invocation, 5s POST timeout, maxDuration 60s. - Headers: X-OrangeCat-Signature (v1 HMAC), X-OrangeCat-Event-Id, X-OrangeCat-Event-Type, User-Agent. - Reports per-outcome summary (delivered/retry/failed/skipped) for Vercel log inspection. Handler glue (entityPostHandler.ts): - Both success paths (custom createEntity + default insert) fire void enqueueWebhookEvent immediately before returning the response. - Fire-and-forget: never blocks user response; enqueue swallows its own errors. vercel.json: new cron entry every minute. Tests still green: 46 suites · 604 tests · 0 failures. tsc + eslint clean. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
6cc7e4ba3f
commit
2755a8a57b
6 files changed
+479
-7
No files matched your search
@@ -0,0 +1,162 @@
|
||||
/**
|
||||
* Webhook delivery worker.
|
||||
*
|
||||
* Vercel Cron: runs every minute.
|
||||
* vercel.json: { "path": "/api/cron/webhook-worker", "schedule": "* * * * *" }
|
||||
*
|
||||
* For each due delivery row:
|
||||
* 1. Optimistically claim (atomic UPDATE WHERE attempt_count = expected)
|
||||
* 2. Fetch the endpoint's signing context (url + plaintext secret)
|
||||
* 3. POST the JSON payload with X-OrangeCat-Signature + X-OrangeCat-Event-Id
|
||||
* 4. 2xx → markDelivered; non-2xx / error → markFailedOrRetry (which
|
||||
* either reschedules with exp-backoff or flips to status='failed'
|
||||
* after MAX_ATTEMPTS).
|
||||
*
|
||||
* Concurrency: two cron invocations can interleave; the optimistic claim
|
||||
* (attempt_count match) prevents double-processing. If we lose the race
|
||||
* we just skip the row — the winner processes it.
|
||||
*
|
||||
* Created: 2026-06-03
|
||||
*/
|
||||
|
||||
import { logger } from '@/utils/logger';
|
||||
import { apiSuccess, apiError, apiUnauthorized } from '@/lib/api/standardResponse';
|
||||
import {
|
||||
pickDueDeliveries,
|
||||
claimDelivery,
|
||||
markDelivered,
|
||||
markFailedOrRetry,
|
||||
type DeliveryRow,
|
||||
} from '@/services/webhooks/deliveryService';
|
||||
import {
|
||||
getEndpointSigningContext,
|
||||
touchEndpointLastDelivery,
|
||||
} from '@/services/webhooks/webhookEndpointsService';
|
||||
import { signWebhookPayload } from '@/services/webhooks/signing';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
export const maxDuration = 60;
|
||||
|
||||
const LOG_SOURCE = 'CronWebhookWorker';
|
||||
const BATCH_SIZE = 20;
|
||||
const POST_TIMEOUT_MS = 5_000;
|
||||
|
||||
function verifyCronSecret(request: Request): boolean {
|
||||
const authHeader = request.headers.get('authorization');
|
||||
return authHeader === `Bearer ${process.env.CRON_SECRET}`;
|
||||
}
|
||||
|
||||
interface DeliveryOutcome {
|
||||
deliveryId: string;
|
||||
outcome: 'delivered' | 'retry' | 'failed' | 'skipped';
|
||||
responseStatus: number | null;
|
||||
}
|
||||
|
||||
async function processDelivery(delivery: DeliveryRow): Promise<DeliveryOutcome> {
|
||||
// 1. Claim. If we lose the race, skip — another worker has it.
|
||||
const claimed = await claimDelivery(delivery.id, delivery.attempt_count);
|
||||
if (!claimed) {
|
||||
return { deliveryId: delivery.id, outcome: 'skipped', responseStatus: null };
|
||||
}
|
||||
const claimedDelivery: DeliveryRow = {
|
||||
...delivery,
|
||||
attempt_count: delivery.attempt_count + 1,
|
||||
};
|
||||
|
||||
// 2. Fetch the endpoint. Revoked / deleted → mark delivered (drop on
|
||||
// floor; the partial active index excludes revoked rows, so this
|
||||
// only happens if the user revoked between enqueue and fire).
|
||||
const ctx = await getEndpointSigningContext(delivery.endpoint_id);
|
||||
if (!ctx) {
|
||||
await markDelivered(delivery.id, 0, '[endpoint revoked]');
|
||||
return { deliveryId: delivery.id, outcome: 'delivered', responseStatus: 0 };
|
||||
}
|
||||
|
||||
// 3. Sign + POST.
|
||||
const rawBody = JSON.stringify(delivery.payload);
|
||||
const signature = signWebhookPayload(rawBody, ctx.secret);
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), POST_TIMEOUT_MS);
|
||||
|
||||
try {
|
||||
const res = await fetch(ctx.url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-OrangeCat-Signature': signature,
|
||||
'X-OrangeCat-Event-Id': delivery.event_id,
|
||||
'X-OrangeCat-Event-Type': delivery.event_type,
|
||||
'User-Agent': 'OrangeCat-Webhooks/1.0',
|
||||
},
|
||||
body: rawBody,
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
const responseText = await res.text().catch(() => '');
|
||||
|
||||
if (res.status >= 200 && res.status < 300) {
|
||||
await markDelivered(delivery.id, res.status, responseText);
|
||||
void touchEndpointLastDelivery(delivery.endpoint_id);
|
||||
return { deliveryId: delivery.id, outcome: 'delivered', responseStatus: res.status };
|
||||
}
|
||||
|
||||
await markFailedOrRetry(claimedDelivery, res.status, responseText);
|
||||
const outcome = claimedDelivery.attempt_count >= 6 ? ('failed' as const) : ('retry' as const);
|
||||
return { deliveryId: delivery.id, outcome, responseStatus: res.status };
|
||||
} catch (err) {
|
||||
// Network error / timeout.
|
||||
const reason = err instanceof Error ? err.message : 'unknown';
|
||||
await markFailedOrRetry(claimedDelivery, null, `[network] ${reason}`);
|
||||
const outcome = claimedDelivery.attempt_count >= 6 ? ('failed' as const) : ('retry' as const);
|
||||
return { deliveryId: delivery.id, outcome, responseStatus: null };
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
if (!verifyCronSecret(request)) {
|
||||
return apiUnauthorized();
|
||||
}
|
||||
|
||||
try {
|
||||
const due = await pickDueDeliveries(BATCH_SIZE);
|
||||
if (due.length === 0) {
|
||||
return apiSuccess({ processed: 0, ranAt: new Date().toISOString() });
|
||||
}
|
||||
|
||||
// Process sequentially within the budget — webhook receivers may be
|
||||
// slow, and Vercel cron runs every minute so latency is fine.
|
||||
const outcomes: DeliveryOutcome[] = [];
|
||||
for (const delivery of due) {
|
||||
const outcome = await processDelivery(delivery);
|
||||
outcomes.push(outcome);
|
||||
}
|
||||
|
||||
const summary = outcomes.reduce(
|
||||
(acc, o) => {
|
||||
acc[o.outcome] = (acc[o.outcome] ?? 0) + 1;
|
||||
return acc;
|
||||
},
|
||||
{ delivered: 0, retry: 0, failed: 0, skipped: 0 } as Record<
|
||||
DeliveryOutcome['outcome'],
|
||||
number
|
||||
>
|
||||
);
|
||||
|
||||
logger.info('Webhook worker batch complete', { summary, processed: due.length }, LOG_SOURCE);
|
||||
return apiSuccess({
|
||||
processed: due.length,
|
||||
summary,
|
||||
ranAt: new Date().toISOString(),
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
'Webhook worker failed',
|
||||
{ error: error instanceof Error ? error.message : error },
|
||||
LOG_SOURCE
|
||||
);
|
||||
return apiError('Internal error', 'INTERNAL_ERROR', 500);
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
shouldCacheStatus,
|
||||
waitForIdempotencyResult,
|
||||
} from '@/services/idempotency/idempotencyResults';
|
||||
import { enqueueWebhookEvent } from '@/services/webhooks/deliveryService';
|
||||
|
||||
// Type for the awaited Supabase client
|
||||
type SupabaseClient = Awaited<ReturnType<typeof createServerClient>>;
|
||||
@@ -294,6 +295,13 @@ export function createEntityPostHandler(config: EntityPostHandlerConfig) {
|
||||
const bodyForCreate = { ...bodyForHandler, _resolved_actor_id: resolvedActor.id };
|
||||
const entity = await createEntity(userId, bodyForCreate, supabase);
|
||||
logger.info(`${meta.name} created successfully`, { [`${entityType}Id`]: entity.id });
|
||||
// Fire-and-forget: never block the user response on webhook
|
||||
// enqueue. enqueueWebhookEvent swallows its own errors.
|
||||
void enqueueWebhookEvent({
|
||||
actorId: resolvedActor.id,
|
||||
eventType: `${entityType}.created`,
|
||||
payload: entity,
|
||||
});
|
||||
return cacheResult(
|
||||
applyRateLimitHeaders(apiSuccess(entity, { status: 201 }), rateLimit as RateLimitResult)
|
||||
);
|
||||
@@ -392,6 +400,11 @@ export function createEntityPostHandler(config: EntityPostHandlerConfig) {
|
||||
}
|
||||
}
|
||||
|
||||
void enqueueWebhookEvent({
|
||||
actorId: resolvedActor.id,
|
||||
eventType: `${entityType}.created`,
|
||||
payload: createdEntity,
|
||||
});
|
||||
return cacheResult(
|
||||
applyRateLimitHeaders(
|
||||
apiSuccess(createdEntity, { status: 201 }),
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
/**
|
||||
* Webhook delivery service — enqueue + retry-schedule + outcome capture.
|
||||
*
|
||||
* The firing path is:
|
||||
* 1. /api/v1 entity POST succeeds → entityPostHandler calls
|
||||
* enqueueWebhookEvent (fire-and-forget, never blocks user response).
|
||||
* 2. enqueueWebhookEvent fans out across active endpoints for the
|
||||
* bound actor, inserting one webhook_deliveries row per endpoint
|
||||
* with status='pending' and next_attempt_at=now.
|
||||
* 3. /api/cron/webhook-worker polls due rows every minute, POSTs
|
||||
* with the X-OrangeCat-Signature header, records the outcome.
|
||||
* 4. Failed deliveries reschedule with exponential backoff (capped
|
||||
* attempt count); succeeded ones flip to status='delivered'.
|
||||
*
|
||||
* The receiving integration is expected to be idempotent on event_id —
|
||||
* we surface it in the payload + the X-OrangeCat-Event-Id header so
|
||||
* worker retries do not double-affect downstream state.
|
||||
*
|
||||
* Created: 2026-06-03
|
||||
*/
|
||||
|
||||
import { randomUUID } from 'crypto';
|
||||
import { createAdminClient } from '@/lib/supabase/admin';
|
||||
import { logger } from '@/utils/logger';
|
||||
import { DATABASE_TABLES } from '@/config/database-tables';
|
||||
import { listActiveEndpointsForActor } from './webhookEndpointsService';
|
||||
|
||||
export interface DeliveryRow {
|
||||
id: string;
|
||||
endpoint_id: string;
|
||||
event_type: string;
|
||||
event_id: string;
|
||||
payload: unknown;
|
||||
status: 'pending' | 'delivered' | 'failed';
|
||||
response_status: number | null;
|
||||
response_body: string | null;
|
||||
attempt_count: number;
|
||||
last_attempt_at: string | null;
|
||||
next_attempt_at: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
/** Cap response body storage so misbehaving receivers can't bloat the table. */
|
||||
const MAX_RESPONSE_BODY_BYTES = 4 * 1024;
|
||||
|
||||
/**
|
||||
* Exponential backoff schedule (minutes from the failing attempt):
|
||||
* attempt 1 → 1m, 2 → 5m, 3 → 25m, 4 → 2h, 5 → 12h, 6 → 24h, then fail.
|
||||
* After MAX_ATTEMPTS the delivery flips to status='failed' and stops.
|
||||
*/
|
||||
const MAX_ATTEMPTS = 6;
|
||||
const BACKOFF_MINUTES = [1, 5, 25, 120, 720, 1440];
|
||||
|
||||
export function computeNextAttempt(
|
||||
attemptCount: number,
|
||||
now: Date = new Date()
|
||||
): { nextAttemptAt: Date | null; shouldFail: boolean } {
|
||||
if (attemptCount >= MAX_ATTEMPTS) {
|
||||
return { nextAttemptAt: null, shouldFail: true };
|
||||
}
|
||||
const minutes = BACKOFF_MINUTES[attemptCount - 1] ?? BACKOFF_MINUTES[BACKOFF_MINUTES.length - 1];
|
||||
return {
|
||||
nextAttemptAt: new Date(now.getTime() + minutes * 60_000),
|
||||
shouldFail: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function truncateResponseBody(body: string | null | undefined): string | null {
|
||||
if (body === null || body === undefined) {
|
||||
return null;
|
||||
}
|
||||
if (body.length <= MAX_RESPONSE_BODY_BYTES) {
|
||||
return body;
|
||||
}
|
||||
return body.slice(0, MAX_RESPONSE_BODY_BYTES) + '\n…[truncated]';
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueue a webhook event for fan-out to every active endpoint bound to
|
||||
* the actor. Fire-and-forget from the API handler: callers MUST not
|
||||
* await this from the user response path — wrap in `void enqueue...`
|
||||
* or `.catch(...)`. We swallow errors here too as a belt-and-braces.
|
||||
*
|
||||
* Returns the number of delivery rows inserted (one per active endpoint).
|
||||
*/
|
||||
export async function enqueueWebhookEvent(params: {
|
||||
actorId: string;
|
||||
eventType: string;
|
||||
payload: unknown;
|
||||
}): Promise<number> {
|
||||
try {
|
||||
const endpoints = await listActiveEndpointsForActor(params.actorId);
|
||||
if (endpoints.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const eventId = randomUUID();
|
||||
const filtered = endpoints.filter(
|
||||
ep =>
|
||||
!ep.event_types || ep.event_types.length === 0 || ep.event_types.includes(params.eventType)
|
||||
);
|
||||
if (filtered.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const rows = filtered.map(ep => ({
|
||||
endpoint_id: ep.id,
|
||||
event_type: params.eventType,
|
||||
event_id: eventId,
|
||||
payload: params.payload,
|
||||
status: 'pending' as const,
|
||||
next_attempt_at: new Date().toISOString(),
|
||||
}));
|
||||
|
||||
const admin = createAdminClient();
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const { error } = await (admin.from(DATABASE_TABLES.WEBHOOK_DELIVERIES) as any).insert(rows);
|
||||
if (error) {
|
||||
logger.error('enqueueWebhookEvent: insert failed', { error, eventType: params.eventType });
|
||||
return 0;
|
||||
}
|
||||
return rows.length;
|
||||
} catch (error) {
|
||||
logger.error('enqueueWebhookEvent: unhandled', {
|
||||
error: error instanceof Error ? error.message : error,
|
||||
});
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick up to `limit` deliveries that are due now. The worker calls this
|
||||
* once per cron invocation; rows are returned newest-first so a slow
|
||||
* receiver can't starve fresher events.
|
||||
*/
|
||||
export async function pickDueDeliveries(
|
||||
limit: number,
|
||||
now: Date = new Date()
|
||||
): Promise<DeliveryRow[]> {
|
||||
const admin = createAdminClient();
|
||||
const { data, error } = await admin
|
||||
.from(DATABASE_TABLES.WEBHOOK_DELIVERIES)
|
||||
.select('*')
|
||||
.eq('status', 'pending')
|
||||
.lte('next_attempt_at', now.toISOString())
|
||||
.order('created_at', { ascending: true })
|
||||
.limit(limit);
|
||||
|
||||
if (error) {
|
||||
logger.error('pickDueDeliveries: query failed', { error });
|
||||
return [];
|
||||
}
|
||||
return (data ?? []) as DeliveryRow[];
|
||||
}
|
||||
|
||||
/** Atomic claim: flip pending → in-flight by bumping attempt_count + last_attempt_at.
|
||||
* Returns true if we won the row (no other worker already claimed it).
|
||||
* We don't change status here — only attempt_count is the claim signal,
|
||||
* so a failed POST can still resume with a richer backoff schedule.
|
||||
*/
|
||||
export async function claimDelivery(deliveryId: string, expectedAttempt: number): Promise<boolean> {
|
||||
const admin = createAdminClient();
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const { data, error } = await (admin.from(DATABASE_TABLES.WEBHOOK_DELIVERIES) as any)
|
||||
.update({ attempt_count: expectedAttempt + 1, last_attempt_at: new Date().toISOString() })
|
||||
.eq('id', deliveryId)
|
||||
.eq('attempt_count', expectedAttempt)
|
||||
.eq('status', 'pending')
|
||||
.select('id')
|
||||
.maybeSingle();
|
||||
|
||||
if (error) {
|
||||
logger.warn('claimDelivery: update failed', { error, deliveryId });
|
||||
return false;
|
||||
}
|
||||
return !!data;
|
||||
}
|
||||
|
||||
export async function markDelivered(
|
||||
deliveryId: string,
|
||||
responseStatus: number,
|
||||
responseBody: string | null
|
||||
): Promise<void> {
|
||||
const admin = createAdminClient();
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const { error } = await (admin.from(DATABASE_TABLES.WEBHOOK_DELIVERIES) as any)
|
||||
.update({
|
||||
status: 'delivered',
|
||||
response_status: responseStatus,
|
||||
response_body: truncateResponseBody(responseBody),
|
||||
next_attempt_at: null,
|
||||
})
|
||||
.eq('id', deliveryId);
|
||||
if (error) {
|
||||
logger.warn('markDelivered failed (non-fatal)', { error, deliveryId });
|
||||
}
|
||||
}
|
||||
|
||||
export async function markFailedOrRetry(
|
||||
delivery: DeliveryRow,
|
||||
responseStatus: number | null,
|
||||
responseBody: string | null
|
||||
): Promise<void> {
|
||||
const admin = createAdminClient();
|
||||
// delivery.attempt_count was already bumped by claimDelivery, so it
|
||||
// reflects "how many attempts have happened including this one".
|
||||
const { nextAttemptAt, shouldFail } = computeNextAttempt(delivery.attempt_count);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const { error } = await (admin.from(DATABASE_TABLES.WEBHOOK_DELIVERIES) as any)
|
||||
.update({
|
||||
status: shouldFail ? 'failed' : 'pending',
|
||||
response_status: responseStatus,
|
||||
response_body: truncateResponseBody(responseBody),
|
||||
next_attempt_at: nextAttemptAt ? nextAttemptAt.toISOString() : null,
|
||||
})
|
||||
.eq('id', delivery.id);
|
||||
if (error) {
|
||||
logger.warn('markFailedOrRetry failed (non-fatal)', { error, deliveryId: delivery.id });
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@
|
||||
* Created: 2026-06-03
|
||||
*/
|
||||
|
||||
import { createHash, randomBytes } from 'crypto';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { createAdminClient } from '@/lib/supabase/admin';
|
||||
import { logger } from '@/utils/logger';
|
||||
import { DATABASE_TABLES } from '@/config/database-tables';
|
||||
@@ -60,10 +60,6 @@ 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';
|
||||
|
||||
@@ -86,7 +82,6 @@ export async function createWebhookEndpoint(params: {
|
||||
await resolveCreationActor(userId, actorId);
|
||||
|
||||
const secret = generateSecret();
|
||||
const secretHash = hashSecret(secret);
|
||||
const secretPrefix = secret.slice(0, DISPLAY_PREFIX_LENGTH);
|
||||
|
||||
const admin = createAdminClient();
|
||||
@@ -101,7 +96,7 @@ export async function createWebhookEndpoint(params: {
|
||||
actor_id: actorId,
|
||||
name: name.trim(),
|
||||
url: url.trim(),
|
||||
secret_hash: secretHash,
|
||||
secret_plaintext: secret,
|
||||
secret_prefix: secretPrefix,
|
||||
event_types: eventTypes && eventTypes.length > 0 ? eventTypes : null,
|
||||
})
|
||||
@@ -154,6 +149,59 @@ export async function listActiveEndpointsForActor(actorId: string): Promise<Webh
|
||||
return (data ?? []) as WebhookEndpoint[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the signing secret + url for a single endpoint — the firing
|
||||
* worker needs both to actually POST a delivery. Returns null if the
|
||||
* endpoint was revoked or deleted between enqueue and fire.
|
||||
*
|
||||
* INTERNAL ONLY. Never expose the secret via the user-facing API.
|
||||
*/
|
||||
export async function getEndpointSigningContext(
|
||||
endpointId: string
|
||||
): Promise<{ url: string; secret: string; actorId: string } | null> {
|
||||
const admin = createAdminClient();
|
||||
const { data, error } = await admin
|
||||
.from(DATABASE_TABLES.WEBHOOK_ENDPOINTS)
|
||||
.select('url, secret_plaintext, actor_id, revoked_at')
|
||||
.eq('id', endpointId)
|
||||
.maybeSingle();
|
||||
|
||||
if (error) {
|
||||
logger.error('getEndpointSigningContext: query failed', { error, endpointId });
|
||||
return null;
|
||||
}
|
||||
if (!data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const row = data as {
|
||||
url: string;
|
||||
secret_plaintext: string;
|
||||
actor_id: string;
|
||||
revoked_at: string | null;
|
||||
};
|
||||
if (row.revoked_at) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { url: row.url, secret: row.secret_plaintext, actorId: row.actor_id };
|
||||
}
|
||||
|
||||
/**
|
||||
* Bump last_delivery_at on the endpoint — fire-and-forget from the worker
|
||||
* after a successful POST so the /settings/integrations UI shows freshness.
|
||||
*/
|
||||
export async function touchEndpointLastDelivery(endpointId: string): Promise<void> {
|
||||
const admin = createAdminClient();
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const { error } = await (admin.from(DATABASE_TABLES.WEBHOOK_ENDPOINTS) as any)
|
||||
.update({ last_delivery_at: new Date().toISOString() })
|
||||
.eq('id', endpointId);
|
||||
if (error) {
|
||||
logger.warn('touchEndpointLastDelivery failed (non-fatal)', { error, endpointId });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Soft-revoke (sets revoked_at). The partial index excludes revoked
|
||||
* rows so the firing loop skips them on the next query.
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
-- ============================================================================
|
||||
-- webhook_endpoints — swap secret_hash → secret_plaintext
|
||||
-- ============================================================================
|
||||
-- 211188a3 stored signing secrets as sha256 hashes, but the firing worker
|
||||
-- needs the plaintext to compute X-OrangeCat-Signature on every delivery.
|
||||
-- This migration drops the hash column and adds a plaintext column.
|
||||
--
|
||||
-- PHASE-2 DEBT: encrypt at rest with a master KMS key (AES-256-GCM with
|
||||
-- WEBHOOK_SECRET_KEY from env). Tracked at docs/api/CONVENTIONS.md §6.
|
||||
--
|
||||
-- Zero rows exist when this lands (table created hours earlier in
|
||||
-- 20260603000004), so dropping the column without preserving data is
|
||||
-- risk-free.
|
||||
--
|
||||
-- Created: 2026-06-03
|
||||
-- ============================================================================
|
||||
|
||||
ALTER TABLE webhook_endpoints DROP COLUMN secret_hash;
|
||||
ALTER TABLE webhook_endpoints ADD COLUMN secret_plaintext TEXT NOT NULL;
|
||||
ALTER TABLE webhook_endpoints ADD CONSTRAINT webhook_endpoints_secret_not_blank
|
||||
CHECK (length(trim(secret_plaintext)) > 0);
|
||||
|
||||
COMMENT ON COLUMN webhook_endpoints.secret_plaintext IS
|
||||
'Webhook signing secret in plaintext. PHASE-2 DEBT: encrypt at rest with a master KMS key.';
|
||||
@@ -126,6 +126,10 @@
|
||||
{
|
||||
"path": "/api/cron/cleanup",
|
||||
"schedule": "0 2 * * *"
|
||||
},
|
||||
{
|
||||
"path": "/api/cron/webhook-worker",
|
||||
"schedule": "* * * * *"
|
||||
}
|
||||
],
|
||||
|
||||
|
||||
Reference in new issue
Block a user