@venturekit/integrations 0.0.37 → 0.0.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +74 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/migrations/vk_integrations_0001_webhooks.sql +73 -0
- package/dist/webhooks/webhooks.d.ts +188 -0
- package/dist/webhooks/webhooks.d.ts.map +1 -0
- package/dist/webhooks/webhooks.js +366 -0
- package/dist/webhooks/webhooks.js.map +1 -0
- package/package.json +9 -5
- package/src/migrations/vk_integrations_0001_webhooks.sql +73 -0
package/README.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# @venturekit/integrations
|
|
2
|
+
|
|
3
|
+
> **Warning:** This package is in active development and not production-ready. APIs may change without notice.
|
|
4
|
+
|
|
5
|
+
Third-party integration layer for [VentureKit](https://venturekit.dev) — an HTTP
|
|
6
|
+
client with retry, OAuth2 token management, API-key handling for the APIs you
|
|
7
|
+
call, and **outbound webhooks** for the events you deliver to customers.
|
|
8
|
+
|
|
9
|
+
## Installation
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @venturekit/integrations
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Outbound webhooks
|
|
16
|
+
|
|
17
|
+
Deliver your domain events to your customers' endpoints the way Stripe /
|
|
18
|
+
GitHub do: registered endpoints with a signing secret, one delivery row per
|
|
19
|
+
event × endpoint, retries with backoff, a delivery log with replay.
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
import {
|
|
23
|
+
createWebhookEndpoint, enqueueWebhook, deliverWebhooksOnce, verifyWebhookSignature,
|
|
24
|
+
} from '@venturekit/integrations';
|
|
25
|
+
import { query, withTransaction } from '@venturekit/data';
|
|
26
|
+
|
|
27
|
+
// 1. A customer registers an endpoint — the secret is returned once
|
|
28
|
+
const { endpoint, secret } = await createWebhookEndpoint(query, {
|
|
29
|
+
url: 'https://customer.example/hooks', tenantId, eventTypes: ['invoice.paid'],
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
// 2. Your code enqueues in the same transaction as the state change
|
|
33
|
+
await withTransaction(async (tx) => {
|
|
34
|
+
await invoices.markPaid(tx, invoice.id);
|
|
35
|
+
await enqueueWebhook(tx.query, { eventId: `invoice.paid:${invoice.id}`, eventType: 'invoice.paid', payload: invoice, tenantId });
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
// 3. A schedules[] cron (every minute) drains the queue
|
|
39
|
+
export const main = taskHandler(async () => deliverWebhooksOnce(query, { limit: 50 }));
|
|
40
|
+
|
|
41
|
+
// 4. The customer verifies (constant-time, 5-minute replay window)
|
|
42
|
+
verifyWebhookSignature({ secret, timestamp: req.headers['x-vk-timestamp'], rawBody, signature: req.headers['x-vk-signature'] });
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Deliveries are claimed with `FOR UPDATE SKIP LOCKED` (safe to run several
|
|
46
|
+
relays), retried at 30 s → 1 min → 2 min … capped at 6 h, and marked `dead`
|
|
47
|
+
after `maxAttempts` (default 8); `listWebhookDeliveries` / `replayWebhookDelivery`
|
|
48
|
+
back a customer-facing log. The request carries `X-VK-Webhook-Id`,
|
|
49
|
+
`X-VK-Event-Id` (the receiver's idempotency key), `X-VK-Event-Type`,
|
|
50
|
+
`X-VK-Timestamp` and `X-VK-Signature: v1=<HMAC-SHA256("${timestamp}.${body}")>`.
|
|
51
|
+
Endpoints must be `https://` (http only on localhost).
|
|
52
|
+
|
|
53
|
+
Tables `vk_webhook_endpoints` / `vk_webhook_deliveries` ship with the package's
|
|
54
|
+
migrations and are applied by `vk migrate` / `vk deploy` like every other
|
|
55
|
+
package migration.
|
|
56
|
+
|
|
57
|
+
## HTTP client, OAuth2, API keys (outbound)
|
|
58
|
+
|
|
59
|
+
```typescript
|
|
60
|
+
import { apiClient, oauth2, apiKey, apiKeyHeader } from '@venturekit/integrations';
|
|
61
|
+
|
|
62
|
+
const auth = oauth2({ flow: 'client_credentials', tokenUrl: '…', clientId: '…', clientSecret: '…' });
|
|
63
|
+
const provider = apiClient({ baseUrl: 'https://api.provider.com', onRequest: [auth.interceptor()], retry: { maxRetries: 3 } });
|
|
64
|
+
|
|
65
|
+
const key = apiKey({ ssm: '/myapp/prod/api-key' });
|
|
66
|
+
const client = apiClient({ baseUrl: 'https://api.example.com', onRequest: [apiKeyHeader(key, 'X-Api-Key', '')] });
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
For keys your *customers* present to *your* API, see `@venturekit/auth/server`'s
|
|
70
|
+
`createApiKey` / `apiKeyAuth`.
|
|
71
|
+
|
|
72
|
+
## License
|
|
73
|
+
|
|
74
|
+
Apache-2.0 — see [LICENSE](../../LICENSE) for details.
|
package/dist/index.d.ts
CHANGED
|
@@ -44,4 +44,6 @@ export { oauth2, createMemoryTokenStore, createDynamoDBTokenStore, } from './aut
|
|
|
44
44
|
export type { OAuth2Client, OAuth2Options, ClientCredentialsOptions, AuthorizationCodeOptions, TokenSet, TokenStore, DynamoDBTokenStoreOptions, } from './auth/oauth2.js';
|
|
45
45
|
export { apiKey, apiKeyHeader, } from './auth/api-keys.js';
|
|
46
46
|
export type { ApiKeyHandle, ApiKeySource, ApiKeyFromEnv, ApiKeyFromSSM, ApiKeyFromSecret, } from './auth/api-keys.js';
|
|
47
|
+
export { createWebhookEndpoint, listWebhookEndpoints, getWebhookEndpoint, updateWebhookEndpoint, rotateWebhookEndpointSecret, deleteWebhookEndpoint, enqueueWebhook, deliverWebhooksOnce, listWebhookDeliveries, replayWebhookDelivery, signWebhookPayload, verifyWebhookSignature, generateWebhookSecret, webhookBackoffSeconds, WEBHOOK_HEADERS, } from './webhooks/webhooks.js';
|
|
48
|
+
export type { Querier as WebhookQuerier, WebhookEndpoint, WebhookDelivery, WebhookDeliveryStatus, CreateWebhookEndpointInput, EnqueueWebhookInput, DeliverWebhooksOptions, DeliverWebhooksResult, } from './webhooks/webhooks.js';
|
|
47
49
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAGH,OAAO,EACL,SAAS,EACT,QAAQ,GACT,MAAM,kBAAkB,CAAC;AAC1B,YAAY,EACV,SAAS,EACT,gBAAgB,EAChB,iBAAiB,EACjB,WAAW,EACX,YAAY,EACZ,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EACL,MAAM,EACN,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,kBAAkB,CAAC;AAC1B,YAAY,EACV,YAAY,EACZ,aAAa,EACb,wBAAwB,EACxB,wBAAwB,EACxB,QAAQ,EACR,UAAU,EACV,yBAAyB,GAC1B,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EACL,MAAM,EACN,YAAY,GACb,MAAM,oBAAoB,CAAC;AAC5B,YAAY,EACV,YAAY,EACZ,YAAY,EACZ,aAAa,EACb,aAAa,EACb,gBAAgB,GACjB,MAAM,oBAAoB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAGH,OAAO,EACL,SAAS,EACT,QAAQ,GACT,MAAM,kBAAkB,CAAC;AAC1B,YAAY,EACV,SAAS,EACT,gBAAgB,EAChB,iBAAiB,EACjB,WAAW,EACX,YAAY,EACZ,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EACL,MAAM,EACN,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,kBAAkB,CAAC;AAC1B,YAAY,EACV,YAAY,EACZ,aAAa,EACb,wBAAwB,EACxB,wBAAwB,EACxB,QAAQ,EACR,UAAU,EACV,yBAAyB,GAC1B,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EACL,MAAM,EACN,YAAY,GACb,MAAM,oBAAoB,CAAC;AAC5B,YAAY,EACV,YAAY,EACZ,YAAY,EACZ,aAAa,EACb,aAAa,EACb,gBAAgB,GACjB,MAAM,oBAAoB,CAAC;AAG5B,OAAO,EACL,qBAAqB,EACrB,oBAAoB,EACpB,kBAAkB,EAClB,qBAAqB,EACrB,2BAA2B,EAC3B,qBAAqB,EACrB,cAAc,EACd,mBAAmB,EACnB,qBAAqB,EACrB,qBAAqB,EACrB,kBAAkB,EAClB,sBAAsB,EACtB,qBAAqB,EACrB,qBAAqB,EACrB,eAAe,GAChB,MAAM,wBAAwB,CAAC;AAChC,YAAY,EACV,OAAO,IAAI,cAAc,EACzB,eAAe,EACf,eAAe,EACf,qBAAqB,EACrB,0BAA0B,EAC1B,mBAAmB,EACnB,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,wBAAwB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -44,4 +44,6 @@ export { apiClient, ApiError, } from './http/client.js';
|
|
|
44
44
|
export { oauth2, createMemoryTokenStore, createDynamoDBTokenStore, } from './auth/oauth2.js';
|
|
45
45
|
// API Key Management
|
|
46
46
|
export { apiKey, apiKeyHeader, } from './auth/api-keys.js';
|
|
47
|
+
// Outbound webhooks (deliver YOUR events to customers' endpoints)
|
|
48
|
+
export { createWebhookEndpoint, listWebhookEndpoints, getWebhookEndpoint, updateWebhookEndpoint, rotateWebhookEndpointSecret, deleteWebhookEndpoint, enqueueWebhook, deliverWebhooksOnce, listWebhookDeliveries, replayWebhookDelivery, signWebhookPayload, verifyWebhookSignature, generateWebhookSecret, webhookBackoffSeconds, WEBHOOK_HEADERS, } from './webhooks/webhooks.js';
|
|
47
49
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAEH,cAAc;AACd,OAAO,EACL,SAAS,EACT,QAAQ,GACT,MAAM,kBAAkB,CAAC;AAY1B,SAAS;AACT,OAAO,EACL,MAAM,EACN,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,kBAAkB,CAAC;AAW1B,qBAAqB;AACrB,OAAO,EACL,MAAM,EACN,YAAY,GACb,MAAM,oBAAoB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAEH,cAAc;AACd,OAAO,EACL,SAAS,EACT,QAAQ,GACT,MAAM,kBAAkB,CAAC;AAY1B,SAAS;AACT,OAAO,EACL,MAAM,EACN,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,kBAAkB,CAAC;AAW1B,qBAAqB;AACrB,OAAO,EACL,MAAM,EACN,YAAY,GACb,MAAM,oBAAoB,CAAC;AAS5B,kEAAkE;AAClE,OAAO,EACL,qBAAqB,EACrB,oBAAoB,EACpB,kBAAkB,EAClB,qBAAqB,EACrB,2BAA2B,EAC3B,qBAAqB,EACrB,cAAc,EACd,mBAAmB,EACnB,qBAAqB,EACrB,qBAAqB,EACrB,kBAAkB,EAClB,sBAAsB,EACtB,qBAAqB,EACrB,qBAAqB,EACrB,eAAe,GAChB,MAAM,wBAAwB,CAAC"}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
-- @venturekit/integrations — outbound webhooks.
|
|
2
|
+
--
|
|
3
|
+
-- Two tables: the endpoints a customer (tenant) registers, and one delivery
|
|
4
|
+
-- row per (event, endpoint) that the relay drains. The relay
|
|
5
|
+
-- (`deliverWebhooksOnce`) claims due rows with `FOR UPDATE SKIP LOCKED`,
|
|
6
|
+
-- so several concurrent relay invocations never double-send.
|
|
7
|
+
--
|
|
8
|
+
-- Signing secrets are stored as-is: the relay needs the plaintext to
|
|
9
|
+
-- compute the HMAC. They are random 256-bit values that grant nothing on
|
|
10
|
+
-- our side (a leaked secret lets an attacker forge webhooks TO the
|
|
11
|
+
-- customer, not read anything FROM us) — rotate with
|
|
12
|
+
-- `rotateWebhookEndpointSecret`. Wrap the column with pgcrypto / KMS if a
|
|
13
|
+
-- compliance regime requires it.
|
|
14
|
+
--
|
|
15
|
+
-- `tenant_id` is nullable TEXT so single-tenant apps can ignore it and
|
|
16
|
+
-- multi-tenant apps can add their own RLS policy on top (the framework
|
|
17
|
+
-- does not know the app's tenant column type).
|
|
18
|
+
|
|
19
|
+
CREATE TABLE IF NOT EXISTS vk_webhook_endpoints (
|
|
20
|
+
id TEXT PRIMARY KEY,
|
|
21
|
+
tenant_id TEXT,
|
|
22
|
+
url TEXT NOT NULL,
|
|
23
|
+
secret TEXT NOT NULL,
|
|
24
|
+
-- Event types this endpoint subscribes to. Empty = every event.
|
|
25
|
+
event_types TEXT[] NOT NULL DEFAULT '{}',
|
|
26
|
+
description TEXT,
|
|
27
|
+
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
|
28
|
+
-- Consecutive deliveries that ended `dead`; reset on any success. Apps
|
|
29
|
+
-- may auto-disable an endpoint past a threshold.
|
|
30
|
+
failure_streak INTEGER NOT NULL DEFAULT 0,
|
|
31
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
32
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
CREATE INDEX IF NOT EXISTS vk_webhook_endpoints_tenant_idx
|
|
36
|
+
ON vk_webhook_endpoints (tenant_id)
|
|
37
|
+
WHERE enabled;
|
|
38
|
+
|
|
39
|
+
CREATE TABLE IF NOT EXISTS vk_webhook_deliveries (
|
|
40
|
+
id TEXT PRIMARY KEY,
|
|
41
|
+
endpoint_id TEXT NOT NULL REFERENCES vk_webhook_endpoints (id) ON DELETE CASCADE,
|
|
42
|
+
tenant_id TEXT,
|
|
43
|
+
-- The producer's event id — the receiver's idempotency key
|
|
44
|
+
-- (`X-VK-Event-Id`). One delivery per (endpoint, event).
|
|
45
|
+
event_id TEXT NOT NULL,
|
|
46
|
+
event_type TEXT NOT NULL,
|
|
47
|
+
payload JSONB NOT NULL,
|
|
48
|
+
status TEXT NOT NULL DEFAULT 'pending'
|
|
49
|
+
CHECK (status IN ('pending', 'delivered', 'dead')),
|
|
50
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
51
|
+
max_attempts INTEGER NOT NULL DEFAULT 8,
|
|
52
|
+
next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
53
|
+
last_status_code INTEGER,
|
|
54
|
+
last_error TEXT,
|
|
55
|
+
delivered_at TIMESTAMPTZ,
|
|
56
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
57
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
58
|
+
UNIQUE (endpoint_id, event_id)
|
|
59
|
+
);
|
|
60
|
+
|
|
61
|
+
-- The relay's claim query: due pending rows, oldest first.
|
|
62
|
+
CREATE INDEX IF NOT EXISTS vk_webhook_deliveries_due_idx
|
|
63
|
+
ON vk_webhook_deliveries (next_attempt_at)
|
|
64
|
+
WHERE status = 'pending';
|
|
65
|
+
|
|
66
|
+
-- Delivery log per endpoint (customer-facing "recent deliveries" screens).
|
|
67
|
+
CREATE INDEX IF NOT EXISTS vk_webhook_deliveries_endpoint_idx
|
|
68
|
+
ON vk_webhook_deliveries (endpoint_id, created_at DESC);
|
|
69
|
+
|
|
70
|
+
COMMENT ON TABLE vk_webhook_endpoints IS
|
|
71
|
+
'Outbound webhook endpoints registered by customers. Structure owned by @venturekit/integrations.';
|
|
72
|
+
COMMENT ON TABLE vk_webhook_deliveries IS
|
|
73
|
+
'One row per (event, endpoint) delivery attempt series; drained by deliverWebhooksOnce().';
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Outbound webhooks — deliver your events to your customers' endpoints.
|
|
3
|
+
*
|
|
4
|
+
* The missing half of the event story: `@venturekit/data`'s outbox and
|
|
5
|
+
* `@venturekit/runtime`'s `publishEvent` move events INSIDE the platform;
|
|
6
|
+
* this module moves them OUT, the way Stripe / GitHub do it:
|
|
7
|
+
*
|
|
8
|
+
* 1. A customer registers an endpoint ({@link createWebhookEndpoint}) and
|
|
9
|
+
* receives a signing secret once.
|
|
10
|
+
* 2. Your code calls {@link enqueueWebhook} — ideally in the same
|
|
11
|
+
* transaction as the state change — which fans the event out to one
|
|
12
|
+
* delivery row per subscribed, enabled endpoint.
|
|
13
|
+
* 3. A `schedules[]` cron (every minute) calls {@link deliverWebhooksOnce}.
|
|
14
|
+
* It claims due deliveries with `FOR UPDATE SKIP LOCKED`, POSTs the
|
|
15
|
+
* signed JSON, and either marks them delivered or reschedules them
|
|
16
|
+
* with exponential backoff; after `maxAttempts` they go `dead`.
|
|
17
|
+
* 4. The customer verifies `X-VK-Signature` with
|
|
18
|
+
* {@link verifyWebhookSignature} (or its own HMAC code) and dedupes on
|
|
19
|
+
* `X-VK-Event-Id`.
|
|
20
|
+
*
|
|
21
|
+
* Everything takes a caller-supplied {@link Querier} (`@venturekit/data`'s
|
|
22
|
+
* `query`, or a transaction's `tx.query`), so the module has no database
|
|
23
|
+
* dependency of its own. Delivery uses the global `fetch` (Node ≥ 18).
|
|
24
|
+
*
|
|
25
|
+
* Tables: `vk_webhook_endpoints`, `vk_webhook_deliveries` — shipped in
|
|
26
|
+
* this package's migrations and applied by `vk migrate` / `vk deploy`.
|
|
27
|
+
*/
|
|
28
|
+
/**
|
|
29
|
+
* Minimal query surface. Structurally compatible with `@venturekit/data`'s
|
|
30
|
+
* `query` and `Transaction#query`. Row keys are aliased to camelCase in
|
|
31
|
+
* every statement below, so the caller's row mapper (camelCase on or off)
|
|
32
|
+
* makes no difference.
|
|
33
|
+
*/
|
|
34
|
+
export type Querier = <T = Record<string, unknown>[]>(sql: string, params?: unknown[]) => Promise<T>;
|
|
35
|
+
export interface WebhookEndpoint {
|
|
36
|
+
id: string;
|
|
37
|
+
tenantId: string | null;
|
|
38
|
+
url: string;
|
|
39
|
+
/** Subscribed event types; empty = all. */
|
|
40
|
+
eventTypes: string[];
|
|
41
|
+
description: string | null;
|
|
42
|
+
enabled: boolean;
|
|
43
|
+
failureStreak: number;
|
|
44
|
+
createdAt: Date;
|
|
45
|
+
updatedAt: Date;
|
|
46
|
+
}
|
|
47
|
+
export type WebhookDeliveryStatus = 'pending' | 'delivered' | 'dead';
|
|
48
|
+
export interface WebhookDelivery {
|
|
49
|
+
id: string;
|
|
50
|
+
endpointId: string;
|
|
51
|
+
tenantId: string | null;
|
|
52
|
+
eventId: string;
|
|
53
|
+
eventType: string;
|
|
54
|
+
payload: unknown;
|
|
55
|
+
status: WebhookDeliveryStatus;
|
|
56
|
+
attempts: number;
|
|
57
|
+
maxAttempts: number;
|
|
58
|
+
nextAttemptAt: Date;
|
|
59
|
+
lastStatusCode: number | null;
|
|
60
|
+
lastError: string | null;
|
|
61
|
+
deliveredAt: Date | null;
|
|
62
|
+
createdAt: Date;
|
|
63
|
+
}
|
|
64
|
+
export interface CreateWebhookEndpointInput {
|
|
65
|
+
url: string;
|
|
66
|
+
tenantId?: string | null;
|
|
67
|
+
/** Subscribe to these event types only. Omit / empty for every event. */
|
|
68
|
+
eventTypes?: string[];
|
|
69
|
+
description?: string | null;
|
|
70
|
+
/** Supply your own secret (e.g. migrating from another system); otherwise one is generated. */
|
|
71
|
+
secret?: string;
|
|
72
|
+
}
|
|
73
|
+
export interface EnqueueWebhookInput {
|
|
74
|
+
/**
|
|
75
|
+
* Stable id of the event — reuse it on retries of YOUR code path and the
|
|
76
|
+
* `(endpoint, event)` uniqueness makes the enqueue idempotent.
|
|
77
|
+
*/
|
|
78
|
+
eventId: string;
|
|
79
|
+
/** Dotted event type, e.g. `invoice.paid`. */
|
|
80
|
+
eventType: string;
|
|
81
|
+
payload: unknown;
|
|
82
|
+
/** Fan out to this tenant's endpoints only. `null`/omitted = tenant-less endpoints. */
|
|
83
|
+
tenantId?: string | null;
|
|
84
|
+
/** Override the default of 8 attempts. */
|
|
85
|
+
maxAttempts?: number;
|
|
86
|
+
}
|
|
87
|
+
export interface DeliverWebhooksOptions {
|
|
88
|
+
/** Max deliveries to claim per call. Default 25. */
|
|
89
|
+
limit?: number;
|
|
90
|
+
/** Per-request timeout in ms. Default 10 000. */
|
|
91
|
+
timeoutMs?: number;
|
|
92
|
+
/** `fetch` override (tests, custom agents). Default: global `fetch`. */
|
|
93
|
+
fetch?: typeof fetch;
|
|
94
|
+
/** Clock override for tests. */
|
|
95
|
+
now?: () => Date;
|
|
96
|
+
/** Extra static headers (e.g. `User-Agent`). */
|
|
97
|
+
headers?: Record<string, string>;
|
|
98
|
+
}
|
|
99
|
+
export interface DeliverWebhooksResult {
|
|
100
|
+
claimed: number;
|
|
101
|
+
delivered: number;
|
|
102
|
+
retried: number;
|
|
103
|
+
dead: number;
|
|
104
|
+
}
|
|
105
|
+
/** Header names a receiver reads. */
|
|
106
|
+
export declare const WEBHOOK_HEADERS: {
|
|
107
|
+
readonly ID: "x-vk-webhook-id";
|
|
108
|
+
readonly EVENT_ID: "x-vk-event-id";
|
|
109
|
+
readonly EVENT_TYPE: "x-vk-event-type";
|
|
110
|
+
readonly TIMESTAMP: "x-vk-timestamp";
|
|
111
|
+
readonly SIGNATURE: "x-vk-signature";
|
|
112
|
+
};
|
|
113
|
+
/** Signed string is `${timestamp}.${rawBody}`; header value is `v1=<hex>`. */
|
|
114
|
+
export declare function signWebhookPayload(secret: string, timestamp: string, rawBody: string): string;
|
|
115
|
+
/**
|
|
116
|
+
* Receiver-side verification. Constant-time compare; rejects timestamps
|
|
117
|
+
* outside `toleranceSeconds` (default 300) to bound replay.
|
|
118
|
+
*/
|
|
119
|
+
export declare function verifyWebhookSignature(input: {
|
|
120
|
+
secret: string;
|
|
121
|
+
timestamp: string;
|
|
122
|
+
rawBody: string;
|
|
123
|
+
signature: string;
|
|
124
|
+
toleranceSeconds?: number;
|
|
125
|
+
now?: Date;
|
|
126
|
+
}): boolean;
|
|
127
|
+
/** `whsec_` + 32 random bytes, base64url — shown to the customer once. */
|
|
128
|
+
export declare function generateWebhookSecret(): string;
|
|
129
|
+
/**
|
|
130
|
+
* Register an endpoint. Returns the endpoint and the plaintext `secret` —
|
|
131
|
+
* show it once; it is not returned by any list/get call.
|
|
132
|
+
*/
|
|
133
|
+
export declare function createWebhookEndpoint(querier: Querier, input: CreateWebhookEndpointInput): Promise<{
|
|
134
|
+
endpoint: WebhookEndpoint;
|
|
135
|
+
secret: string;
|
|
136
|
+
}>;
|
|
137
|
+
export declare function listWebhookEndpoints(querier: Querier, filter?: {
|
|
138
|
+
tenantId?: string | null;
|
|
139
|
+
includeDisabled?: boolean;
|
|
140
|
+
}): Promise<WebhookEndpoint[]>;
|
|
141
|
+
export declare function getWebhookEndpoint(querier: Querier, id: string): Promise<WebhookEndpoint | null>;
|
|
142
|
+
export declare function updateWebhookEndpoint(querier: Querier, id: string, patch: {
|
|
143
|
+
url?: string;
|
|
144
|
+
eventTypes?: string[];
|
|
145
|
+
description?: string | null;
|
|
146
|
+
enabled?: boolean;
|
|
147
|
+
}): Promise<WebhookEndpoint | null>;
|
|
148
|
+
/** New secret, returned once. Deliveries signed from now on use it. */
|
|
149
|
+
export declare function rotateWebhookEndpointSecret(querier: Querier, id: string): Promise<string | null>;
|
|
150
|
+
/** Removes the endpoint and (by FK cascade) its delivery log. */
|
|
151
|
+
export declare function deleteWebhookEndpoint(querier: Querier, id: string): Promise<boolean>;
|
|
152
|
+
/**
|
|
153
|
+
* Fan an event out to every enabled endpoint subscribed to its type (or to
|
|
154
|
+
* everything) within the tenant scope. Returns the number of NEW delivery
|
|
155
|
+
* rows — an already-enqueued `(endpoint, eventId)` pair is skipped, which
|
|
156
|
+
* is what makes retrying the producer safe.
|
|
157
|
+
*
|
|
158
|
+
* Call it with the transaction's `tx.query` so the deliveries commit (or
|
|
159
|
+
* roll back) with the change they announce.
|
|
160
|
+
*/
|
|
161
|
+
export declare function enqueueWebhook(querier: Querier, input: EnqueueWebhookInput): Promise<number>;
|
|
162
|
+
/**
|
|
163
|
+
* Backoff before attempt `n + 1` after `n` failed attempts: 30 s, 1 min,
|
|
164
|
+
* 2 min, 4 min, … capped at 6 h. With the default 8 attempts a dead
|
|
165
|
+
* endpoint is retried for ~4 h before the delivery is marked `dead`.
|
|
166
|
+
*/
|
|
167
|
+
export declare function webhookBackoffSeconds(attempts: number): number;
|
|
168
|
+
/**
|
|
169
|
+
* Deliver due webhooks once. Safe to run concurrently (row locks are
|
|
170
|
+
* skipped, not waited on). Returns counts for the cron's log line.
|
|
171
|
+
*
|
|
172
|
+
* Each claimed row has `attempts` bumped up front, so a relay that dies
|
|
173
|
+
* mid-request has already spent the attempt and the row is retried later
|
|
174
|
+
* rather than hammered. A 2xx marks `delivered`; anything else (including
|
|
175
|
+
* a timeout) reschedules with {@link webhookBackoffSeconds} or marks the
|
|
176
|
+
* row `dead` once `maxAttempts` is reached. Endpoints disabled in the
|
|
177
|
+
* meantime get their pending deliveries marked `dead` without a request.
|
|
178
|
+
*/
|
|
179
|
+
export declare function deliverWebhooksOnce(querier: Querier, options?: DeliverWebhooksOptions): Promise<DeliverWebhooksResult>;
|
|
180
|
+
export declare function listWebhookDeliveries(querier: Querier, filter: {
|
|
181
|
+
endpointId: string;
|
|
182
|
+
status?: WebhookDeliveryStatus;
|
|
183
|
+
limit?: number;
|
|
184
|
+
before?: Date;
|
|
185
|
+
}): Promise<WebhookDelivery[]>;
|
|
186
|
+
/** Put a `dead` (or `delivered`) delivery back in the queue for an immediate retry. */
|
|
187
|
+
export declare function replayWebhookDelivery(querier: Querier, id: string): Promise<boolean>;
|
|
188
|
+
//# sourceMappingURL=webhooks.d.ts.map
|
|
@@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G,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAOtG;AAED,iEAAiE;AACjE,wBAAsB,qBAAqB,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAG1F;AAMD;;;;;;;;GAQG;AACH,wBAAsB,cAAc,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,mBAAmB,GAAG,OAAO,CAAC,MAAM,CAAC,CAkBlG;AAMD;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAE9D;AAgBD;;;;;;;;;;GAUG;AACH,wBAAsB,mBAAmB,CACvC,OAAO,EAAE,OAAO,EAChB,OAAO,GAAE,sBAA2B,GACnC,OAAO,CAAC,qBAAqB,CAAC,CAiHhC;AAyCD,wBAAsB,qBAAqB,CACzC,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE;IAAE,UAAU,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,qBAAqB,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,IAAI,CAAA;CAAE,GAC5F,OAAO,CAAC,eAAe,EAAE,CAAC,CAmB5B;AAED,uFAAuF;AACvF,wBAAsB,qBAAqB,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAS1F"}
|
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Outbound webhooks — deliver your events to your customers' endpoints.
|
|
3
|
+
*
|
|
4
|
+
* The missing half of the event story: `@venturekit/data`'s outbox and
|
|
5
|
+
* `@venturekit/runtime`'s `publishEvent` move events INSIDE the platform;
|
|
6
|
+
* this module moves them OUT, the way Stripe / GitHub do it:
|
|
7
|
+
*
|
|
8
|
+
* 1. A customer registers an endpoint ({@link createWebhookEndpoint}) and
|
|
9
|
+
* receives a signing secret once.
|
|
10
|
+
* 2. Your code calls {@link enqueueWebhook} — ideally in the same
|
|
11
|
+
* transaction as the state change — which fans the event out to one
|
|
12
|
+
* delivery row per subscribed, enabled endpoint.
|
|
13
|
+
* 3. A `schedules[]` cron (every minute) calls {@link deliverWebhooksOnce}.
|
|
14
|
+
* It claims due deliveries with `FOR UPDATE SKIP LOCKED`, POSTs the
|
|
15
|
+
* signed JSON, and either marks them delivered or reschedules them
|
|
16
|
+
* with exponential backoff; after `maxAttempts` they go `dead`.
|
|
17
|
+
* 4. The customer verifies `X-VK-Signature` with
|
|
18
|
+
* {@link verifyWebhookSignature} (or its own HMAC code) and dedupes on
|
|
19
|
+
* `X-VK-Event-Id`.
|
|
20
|
+
*
|
|
21
|
+
* Everything takes a caller-supplied {@link Querier} (`@venturekit/data`'s
|
|
22
|
+
* `query`, or a transaction's `tx.query`), so the module has no database
|
|
23
|
+
* dependency of its own. Delivery uses the global `fetch` (Node ≥ 18).
|
|
24
|
+
*
|
|
25
|
+
* Tables: `vk_webhook_endpoints`, `vk_webhook_deliveries` — shipped in
|
|
26
|
+
* this package's migrations and applied by `vk migrate` / `vk deploy`.
|
|
27
|
+
*/
|
|
28
|
+
import { createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
// Signing
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
/** Header names a receiver reads. */
|
|
33
|
+
export const WEBHOOK_HEADERS = {
|
|
34
|
+
ID: 'x-vk-webhook-id',
|
|
35
|
+
EVENT_ID: 'x-vk-event-id',
|
|
36
|
+
EVENT_TYPE: 'x-vk-event-type',
|
|
37
|
+
TIMESTAMP: 'x-vk-timestamp',
|
|
38
|
+
SIGNATURE: 'x-vk-signature',
|
|
39
|
+
};
|
|
40
|
+
/** Signed string is `${timestamp}.${rawBody}`; header value is `v1=<hex>`. */
|
|
41
|
+
export function signWebhookPayload(secret, timestamp, rawBody) {
|
|
42
|
+
return `v1=${createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest('hex')}`;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Receiver-side verification. Constant-time compare; rejects timestamps
|
|
46
|
+
* outside `toleranceSeconds` (default 300) to bound replay.
|
|
47
|
+
*/
|
|
48
|
+
export function verifyWebhookSignature(input) {
|
|
49
|
+
const ts = Number(input.timestamp);
|
|
50
|
+
if (!Number.isFinite(ts))
|
|
51
|
+
return false;
|
|
52
|
+
const tolerance = input.toleranceSeconds ?? 300;
|
|
53
|
+
const nowSec = Math.floor((input.now ?? new Date()).getTime() / 1000);
|
|
54
|
+
if (Math.abs(nowSec - ts) > tolerance)
|
|
55
|
+
return false;
|
|
56
|
+
const expected = Buffer.from(signWebhookPayload(input.secret, input.timestamp, input.rawBody));
|
|
57
|
+
// The header may carry several `v1=` values during a secret rotation.
|
|
58
|
+
return input.signature
|
|
59
|
+
.split(',')
|
|
60
|
+
.map((s) => s.trim())
|
|
61
|
+
.some((candidate) => {
|
|
62
|
+
const actual = Buffer.from(candidate);
|
|
63
|
+
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
/** `whsec_` + 32 random bytes, base64url — shown to the customer once. */
|
|
67
|
+
export function generateWebhookSecret() {
|
|
68
|
+
return `whsec_${randomBytes(32).toString('base64url')}`;
|
|
69
|
+
}
|
|
70
|
+
// ---------------------------------------------------------------------------
|
|
71
|
+
// Endpoints
|
|
72
|
+
// ---------------------------------------------------------------------------
|
|
73
|
+
const ENDPOINT_COLUMNS = `
|
|
74
|
+
id,
|
|
75
|
+
tenant_id AS "tenantId",
|
|
76
|
+
url,
|
|
77
|
+
event_types AS "eventTypes",
|
|
78
|
+
description,
|
|
79
|
+
enabled,
|
|
80
|
+
failure_streak AS "failureStreak",
|
|
81
|
+
created_at AS "createdAt",
|
|
82
|
+
updated_at AS "updatedAt"`;
|
|
83
|
+
function assertHttpsUrl(url) {
|
|
84
|
+
let parsed;
|
|
85
|
+
try {
|
|
86
|
+
parsed = new URL(url);
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
throw new Error(`[venturekit/integrations] webhook url is not a valid URL: ${url}`);
|
|
90
|
+
}
|
|
91
|
+
// Plain http only for loopback — a customer's staging box on the LAN is
|
|
92
|
+
// their business, but a production endpoint over http leaks the payload.
|
|
93
|
+
const loopback = parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1' || parsed.hostname === '::1';
|
|
94
|
+
if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && loopback)) {
|
|
95
|
+
throw new Error('[venturekit/integrations] webhook url must be https:// (http:// allowed for localhost only)');
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Register an endpoint. Returns the endpoint and the plaintext `secret` —
|
|
100
|
+
* show it once; it is not returned by any list/get call.
|
|
101
|
+
*/
|
|
102
|
+
export async function createWebhookEndpoint(querier, input) {
|
|
103
|
+
assertHttpsUrl(input.url);
|
|
104
|
+
const secret = input.secret ?? generateWebhookSecret();
|
|
105
|
+
const rows = await querier(`INSERT INTO vk_webhook_endpoints (id, tenant_id, url, secret, event_types, description)
|
|
106
|
+
VALUES ($1, $2, $3, $4, $5, $6)
|
|
107
|
+
RETURNING ${ENDPOINT_COLUMNS}`, [randomUUID(), input.tenantId ?? null, input.url, secret, input.eventTypes ?? [], input.description ?? null]);
|
|
108
|
+
return { endpoint: rows[0], secret };
|
|
109
|
+
}
|
|
110
|
+
export async function listWebhookEndpoints(querier, filter = {}) {
|
|
111
|
+
const where = [];
|
|
112
|
+
const params = [];
|
|
113
|
+
if (filter.tenantId !== undefined) {
|
|
114
|
+
if (filter.tenantId === null)
|
|
115
|
+
where.push('tenant_id IS NULL');
|
|
116
|
+
else {
|
|
117
|
+
params.push(filter.tenantId);
|
|
118
|
+
where.push(`tenant_id = $${params.length}`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (!filter.includeDisabled)
|
|
122
|
+
where.push('enabled');
|
|
123
|
+
return querier(`SELECT ${ENDPOINT_COLUMNS} FROM vk_webhook_endpoints
|
|
124
|
+
${where.length ? `WHERE ${where.join(' AND ')}` : ''}
|
|
125
|
+
ORDER BY created_at DESC`, params);
|
|
126
|
+
}
|
|
127
|
+
export async function getWebhookEndpoint(querier, id) {
|
|
128
|
+
const rows = await querier(`SELECT ${ENDPOINT_COLUMNS} FROM vk_webhook_endpoints WHERE id = $1`, [id]);
|
|
129
|
+
return rows[0] ?? null;
|
|
130
|
+
}
|
|
131
|
+
export async function updateWebhookEndpoint(querier, id, patch) {
|
|
132
|
+
if (patch.url !== undefined)
|
|
133
|
+
assertHttpsUrl(patch.url);
|
|
134
|
+
const rows = await querier(`UPDATE vk_webhook_endpoints SET
|
|
135
|
+
url = COALESCE($2, url),
|
|
136
|
+
event_types = COALESCE($3, event_types),
|
|
137
|
+
description = CASE WHEN $4::boolean THEN $5 ELSE description END,
|
|
138
|
+
enabled = COALESCE($6, enabled),
|
|
139
|
+
updated_at = now()
|
|
140
|
+
WHERE id = $1
|
|
141
|
+
RETURNING ${ENDPOINT_COLUMNS}`, [
|
|
142
|
+
id,
|
|
143
|
+
patch.url ?? null,
|
|
144
|
+
patch.eventTypes ?? null,
|
|
145
|
+
patch.description !== undefined,
|
|
146
|
+
patch.description ?? null,
|
|
147
|
+
patch.enabled ?? null,
|
|
148
|
+
]);
|
|
149
|
+
return rows[0] ?? null;
|
|
150
|
+
}
|
|
151
|
+
/** New secret, returned once. Deliveries signed from now on use it. */
|
|
152
|
+
export async function rotateWebhookEndpointSecret(querier, id) {
|
|
153
|
+
const secret = generateWebhookSecret();
|
|
154
|
+
const rows = await querier(`UPDATE vk_webhook_endpoints SET secret = $2, updated_at = now() WHERE id = $1 RETURNING id`, [id, secret]);
|
|
155
|
+
return rows[0] ? secret : null;
|
|
156
|
+
}
|
|
157
|
+
/** Removes the endpoint and (by FK cascade) its delivery log. */
|
|
158
|
+
export async function deleteWebhookEndpoint(querier, id) {
|
|
159
|
+
const rows = await querier(`DELETE FROM vk_webhook_endpoints WHERE id = $1 RETURNING id`, [id]);
|
|
160
|
+
return rows.length > 0;
|
|
161
|
+
}
|
|
162
|
+
// ---------------------------------------------------------------------------
|
|
163
|
+
// Enqueue
|
|
164
|
+
// ---------------------------------------------------------------------------
|
|
165
|
+
/**
|
|
166
|
+
* Fan an event out to every enabled endpoint subscribed to its type (or to
|
|
167
|
+
* everything) within the tenant scope. Returns the number of NEW delivery
|
|
168
|
+
* rows — an already-enqueued `(endpoint, eventId)` pair is skipped, which
|
|
169
|
+
* is what makes retrying the producer safe.
|
|
170
|
+
*
|
|
171
|
+
* Call it with the transaction's `tx.query` so the deliveries commit (or
|
|
172
|
+
* roll back) with the change they announce.
|
|
173
|
+
*/
|
|
174
|
+
export async function enqueueWebhook(querier, input) {
|
|
175
|
+
if (!input.eventId)
|
|
176
|
+
throw new Error('[venturekit/integrations] enqueueWebhook: eventId is required');
|
|
177
|
+
if (!input.eventType)
|
|
178
|
+
throw new Error('[venturekit/integrations] enqueueWebhook: eventType is required');
|
|
179
|
+
const maxAttempts = input.maxAttempts ?? 8;
|
|
180
|
+
const tenantId = input.tenantId ?? null;
|
|
181
|
+
const rows = await querier(`INSERT INTO vk_webhook_deliveries
|
|
182
|
+
(id, endpoint_id, tenant_id, event_id, event_type, payload, max_attempts)
|
|
183
|
+
SELECT gen_random_uuid()::text, e.id, e.tenant_id, $1, $2, $3::jsonb, $4
|
|
184
|
+
FROM vk_webhook_endpoints e
|
|
185
|
+
WHERE e.enabled
|
|
186
|
+
AND (e.tenant_id IS NOT DISTINCT FROM $5)
|
|
187
|
+
AND (cardinality(e.event_types) = 0 OR $2 = ANY (e.event_types))
|
|
188
|
+
ON CONFLICT (endpoint_id, event_id) DO NOTHING
|
|
189
|
+
RETURNING id`, [input.eventId, input.eventType, JSON.stringify(input.payload ?? null), maxAttempts, tenantId]);
|
|
190
|
+
return rows.length;
|
|
191
|
+
}
|
|
192
|
+
// ---------------------------------------------------------------------------
|
|
193
|
+
// Delivery
|
|
194
|
+
// ---------------------------------------------------------------------------
|
|
195
|
+
/**
|
|
196
|
+
* Backoff before attempt `n + 1` after `n` failed attempts: 30 s, 1 min,
|
|
197
|
+
* 2 min, 4 min, … capped at 6 h. With the default 8 attempts a dead
|
|
198
|
+
* endpoint is retried for ~4 h before the delivery is marked `dead`.
|
|
199
|
+
*/
|
|
200
|
+
export function webhookBackoffSeconds(attempts) {
|
|
201
|
+
return Math.min(30 * 2 ** Math.max(0, attempts - 1), 6 * 3600);
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Deliver due webhooks once. Safe to run concurrently (row locks are
|
|
205
|
+
* skipped, not waited on). Returns counts for the cron's log line.
|
|
206
|
+
*
|
|
207
|
+
* Each claimed row has `attempts` bumped up front, so a relay that dies
|
|
208
|
+
* mid-request has already spent the attempt and the row is retried later
|
|
209
|
+
* rather than hammered. A 2xx marks `delivered`; anything else (including
|
|
210
|
+
* a timeout) reschedules with {@link webhookBackoffSeconds} or marks the
|
|
211
|
+
* row `dead` once `maxAttempts` is reached. Endpoints disabled in the
|
|
212
|
+
* meantime get their pending deliveries marked `dead` without a request.
|
|
213
|
+
*/
|
|
214
|
+
export async function deliverWebhooksOnce(querier, options = {}) {
|
|
215
|
+
const limit = options.limit ?? 25;
|
|
216
|
+
const timeoutMs = options.timeoutMs ?? 10_000;
|
|
217
|
+
const doFetch = options.fetch ?? globalThis.fetch;
|
|
218
|
+
const now = options.now ?? (() => new Date());
|
|
219
|
+
if (typeof doFetch !== 'function') {
|
|
220
|
+
throw new Error('[venturekit/integrations] deliverWebhooksOnce: no fetch available (Node >= 18 or pass options.fetch)');
|
|
221
|
+
}
|
|
222
|
+
const claimed = await querier(`WITH due AS (
|
|
223
|
+
SELECT id FROM vk_webhook_deliveries
|
|
224
|
+
WHERE status = 'pending' AND next_attempt_at <= now()
|
|
225
|
+
ORDER BY next_attempt_at
|
|
226
|
+
LIMIT $1
|
|
227
|
+
FOR UPDATE SKIP LOCKED
|
|
228
|
+
),
|
|
229
|
+
claimed AS (
|
|
230
|
+
UPDATE vk_webhook_deliveries d
|
|
231
|
+
SET attempts = d.attempts + 1,
|
|
232
|
+
-- Park the row past the horizon while in flight; the outcome
|
|
233
|
+
-- below sets the real next_attempt_at or the final status.
|
|
234
|
+
next_attempt_at = now() + interval '1 hour',
|
|
235
|
+
updated_at = now()
|
|
236
|
+
FROM due WHERE d.id = due.id
|
|
237
|
+
RETURNING d.id, d.endpoint_id, d.event_id, d.event_type, d.payload,
|
|
238
|
+
d.attempts, d.max_attempts, d.created_at
|
|
239
|
+
)
|
|
240
|
+
SELECT c.id,
|
|
241
|
+
c.endpoint_id AS "endpointId",
|
|
242
|
+
c.event_id AS "eventId",
|
|
243
|
+
c.event_type AS "eventType",
|
|
244
|
+
c.payload,
|
|
245
|
+
c.attempts,
|
|
246
|
+
c.max_attempts AS "maxAttempts",
|
|
247
|
+
c.created_at AS "createdAt",
|
|
248
|
+
e.url,
|
|
249
|
+
e.secret,
|
|
250
|
+
e.enabled AS "endpointEnabled"
|
|
251
|
+
FROM claimed c JOIN vk_webhook_endpoints e ON e.id = c.endpoint_id`, [limit]);
|
|
252
|
+
const result = { claimed: claimed.length, delivered: 0, retried: 0, dead: 0 };
|
|
253
|
+
for (const d of claimed) {
|
|
254
|
+
if (!d.endpointEnabled) {
|
|
255
|
+
await markDead(querier, d.id, d.endpointId, null, 'endpoint disabled');
|
|
256
|
+
result.dead++;
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
const rawBody = JSON.stringify({
|
|
260
|
+
id: d.eventId,
|
|
261
|
+
type: d.eventType,
|
|
262
|
+
createdAt: new Date(d.createdAt).toISOString(),
|
|
263
|
+
data: d.payload,
|
|
264
|
+
});
|
|
265
|
+
const timestamp = String(Math.floor(now().getTime() / 1000));
|
|
266
|
+
const controller = new AbortController();
|
|
267
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
268
|
+
let statusCode = null;
|
|
269
|
+
let error = null;
|
|
270
|
+
try {
|
|
271
|
+
const res = await doFetch(d.url, {
|
|
272
|
+
method: 'POST',
|
|
273
|
+
headers: {
|
|
274
|
+
'content-type': 'application/json',
|
|
275
|
+
'user-agent': 'VentureKit-Webhooks/1',
|
|
276
|
+
...(options.headers ?? {}),
|
|
277
|
+
[WEBHOOK_HEADERS.ID]: d.id,
|
|
278
|
+
[WEBHOOK_HEADERS.EVENT_ID]: d.eventId,
|
|
279
|
+
[WEBHOOK_HEADERS.EVENT_TYPE]: d.eventType,
|
|
280
|
+
[WEBHOOK_HEADERS.TIMESTAMP]: timestamp,
|
|
281
|
+
[WEBHOOK_HEADERS.SIGNATURE]: signWebhookPayload(d.secret, timestamp, rawBody),
|
|
282
|
+
},
|
|
283
|
+
body: rawBody,
|
|
284
|
+
signal: controller.signal,
|
|
285
|
+
redirect: 'manual',
|
|
286
|
+
});
|
|
287
|
+
statusCode = res.status;
|
|
288
|
+
if (res.status < 200 || res.status >= 300)
|
|
289
|
+
error = `HTTP ${res.status}`;
|
|
290
|
+
}
|
|
291
|
+
catch (err) {
|
|
292
|
+
error = controller.signal.aborted ? `timeout after ${timeoutMs}ms` : err instanceof Error ? err.message : String(err);
|
|
293
|
+
}
|
|
294
|
+
finally {
|
|
295
|
+
clearTimeout(timer);
|
|
296
|
+
}
|
|
297
|
+
if (!error) {
|
|
298
|
+
await querier(`UPDATE vk_webhook_deliveries
|
|
299
|
+
SET status = 'delivered', delivered_at = now(), last_status_code = $2, last_error = NULL, updated_at = now()
|
|
300
|
+
WHERE id = $1`, [d.id, statusCode]);
|
|
301
|
+
await querier(`UPDATE vk_webhook_endpoints SET failure_streak = 0, updated_at = now() WHERE id = $1`, [d.endpointId]);
|
|
302
|
+
result.delivered++;
|
|
303
|
+
}
|
|
304
|
+
else if (d.attempts >= d.maxAttempts) {
|
|
305
|
+
await markDead(querier, d.id, d.endpointId, statusCode, error);
|
|
306
|
+
result.dead++;
|
|
307
|
+
}
|
|
308
|
+
else {
|
|
309
|
+
await querier(`UPDATE vk_webhook_deliveries
|
|
310
|
+
SET next_attempt_at = now() + make_interval(secs => $2), last_status_code = $3, last_error = $4, updated_at = now()
|
|
311
|
+
WHERE id = $1`, [d.id, webhookBackoffSeconds(d.attempts), statusCode, error]);
|
|
312
|
+
result.retried++;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
return result;
|
|
316
|
+
}
|
|
317
|
+
async function markDead(querier, deliveryId, endpointId, statusCode, error) {
|
|
318
|
+
await querier(`UPDATE vk_webhook_deliveries
|
|
319
|
+
SET status = 'dead', last_status_code = $2, last_error = $3, updated_at = now()
|
|
320
|
+
WHERE id = $1`, [deliveryId, statusCode, error]);
|
|
321
|
+
await querier(`UPDATE vk_webhook_endpoints SET failure_streak = failure_streak + 1, updated_at = now() WHERE id = $1`, [endpointId]);
|
|
322
|
+
}
|
|
323
|
+
// ---------------------------------------------------------------------------
|
|
324
|
+
// Delivery log
|
|
325
|
+
// ---------------------------------------------------------------------------
|
|
326
|
+
const DELIVERY_COLUMNS = `
|
|
327
|
+
id,
|
|
328
|
+
endpoint_id AS "endpointId",
|
|
329
|
+
tenant_id AS "tenantId",
|
|
330
|
+
event_id AS "eventId",
|
|
331
|
+
event_type AS "eventType",
|
|
332
|
+
payload,
|
|
333
|
+
status,
|
|
334
|
+
attempts,
|
|
335
|
+
max_attempts AS "maxAttempts",
|
|
336
|
+
next_attempt_at AS "nextAttemptAt",
|
|
337
|
+
last_status_code AS "lastStatusCode",
|
|
338
|
+
last_error AS "lastError",
|
|
339
|
+
delivered_at AS "deliveredAt",
|
|
340
|
+
created_at AS "createdAt"`;
|
|
341
|
+
export async function listWebhookDeliveries(querier, filter) {
|
|
342
|
+
const params = [filter.endpointId];
|
|
343
|
+
const where = ['endpoint_id = $1'];
|
|
344
|
+
if (filter.status) {
|
|
345
|
+
params.push(filter.status);
|
|
346
|
+
where.push(`status = $${params.length}`);
|
|
347
|
+
}
|
|
348
|
+
if (filter.before) {
|
|
349
|
+
params.push(filter.before);
|
|
350
|
+
where.push(`created_at < $${params.length}`);
|
|
351
|
+
}
|
|
352
|
+
params.push(Math.min(Math.max(1, filter.limit ?? 50), 200));
|
|
353
|
+
return querier(`SELECT ${DELIVERY_COLUMNS} FROM vk_webhook_deliveries
|
|
354
|
+
WHERE ${where.join(' AND ')}
|
|
355
|
+
ORDER BY created_at DESC
|
|
356
|
+
LIMIT $${params.length}`, params);
|
|
357
|
+
}
|
|
358
|
+
/** Put a `dead` (or `delivered`) delivery back in the queue for an immediate retry. */
|
|
359
|
+
export async function replayWebhookDelivery(querier, id) {
|
|
360
|
+
const rows = await querier(`UPDATE vk_webhook_deliveries
|
|
361
|
+
SET status = 'pending', attempts = 0, next_attempt_at = now(), last_error = NULL, updated_at = now()
|
|
362
|
+
WHERE id = $1
|
|
363
|
+
RETURNING id`, [id]);
|
|
364
|
+
return rows.length > 0;
|
|
365
|
+
}
|
|
366
|
+
//# sourceMappingURL=webhooks.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"webhooks.js","sourceRoot":"","sources":["../../src/webhooks/webhooks.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AA8FnF,8EAA8E;AAC9E,UAAU;AACV,8EAA8E;AAE9E,qCAAqC;AACrC,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,EAAE,EAAE,iBAAiB;IACrB,QAAQ,EAAE,eAAe;IACzB,UAAU,EAAE,iBAAiB;IAC7B,SAAS,EAAE,gBAAgB;IAC3B,SAAS,EAAE,gBAAgB;CACnB,CAAC;AAEX,8EAA8E;AAC9E,MAAM,UAAU,kBAAkB,CAAC,MAAc,EAAE,SAAiB,EAAE,OAAe;IACnF,OAAO,MAAM,UAAU,CAAC,QAAQ,EAAE,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AC;QAClB,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC3B,KAAK,CAAC,IAAI,CAAC,iBAAiB,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC;IAC/C,CAAC;IACD,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,CAAC,KAAK,IAAI,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;IAC5D,OAAO,OAAO,CACZ,UAAU,gBAAgB;aACjB,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC;;cAElB,MAAM,CAAC,MAAM,EAAE,EACzB,MAAM,CACP,CAAC;AACJ,CAAC;AAED,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,OAAgB,EAAE,EAAU;IACtE,MAAM,IAAI,GAAG,MAAM,OAAO,CACxB;;;kBAGc,EACd,CAAC,EAAE,CAAC,CACL,CAAC;IACF,OAAO,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;AACzB,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@venturekit/integrations",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"description": "VentureKit third-party API integration — HTTP client, OAuth2, API key management, retry, circuit breaker",
|
|
3
|
+
"version": "0.0.39",
|
|
4
|
+
"description": "VentureKit third-party API integration — HTTP client, OAuth2, API key management, outbound webhooks, retry, circuit breaker",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"types": "dist/index.d.ts",
|
|
@@ -12,8 +12,12 @@
|
|
|
12
12
|
}
|
|
13
13
|
},
|
|
14
14
|
"files": [
|
|
15
|
-
"dist"
|
|
15
|
+
"dist",
|
|
16
|
+
"src/migrations/*.sql"
|
|
16
17
|
],
|
|
18
|
+
"vk": {
|
|
19
|
+
"migrations": "src/migrations"
|
|
20
|
+
},
|
|
17
21
|
"repository": {
|
|
18
22
|
"type": "git",
|
|
19
23
|
"url": "https://github.com/venturekit-dev/venturekit.git",
|
|
@@ -36,7 +40,7 @@
|
|
|
36
40
|
],
|
|
37
41
|
"license": "Apache-2.0",
|
|
38
42
|
"dependencies": {
|
|
39
|
-
"@venturekit/core": "0.0.
|
|
43
|
+
"@venturekit/core": "0.0.39"
|
|
40
44
|
},
|
|
41
45
|
"peerDependencies": {
|
|
42
46
|
"@aws-sdk/client-dynamodb": "^3.500.0",
|
|
@@ -63,7 +67,7 @@
|
|
|
63
67
|
"typescript": "^5.3.0"
|
|
64
68
|
},
|
|
65
69
|
"scripts": {
|
|
66
|
-
"build": "tsc",
|
|
70
|
+
"build": "tsc && node -e \"require('fs').cpSync('src/migrations','dist/migrations',{recursive:true})\"",
|
|
67
71
|
"dev": "tsc --watch",
|
|
68
72
|
"clean": "rm -rf dist"
|
|
69
73
|
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
-- @venturekit/integrations — outbound webhooks.
|
|
2
|
+
--
|
|
3
|
+
-- Two tables: the endpoints a customer (tenant) registers, and one delivery
|
|
4
|
+
-- row per (event, endpoint) that the relay drains. The relay
|
|
5
|
+
-- (`deliverWebhooksOnce`) claims due rows with `FOR UPDATE SKIP LOCKED`,
|
|
6
|
+
-- so several concurrent relay invocations never double-send.
|
|
7
|
+
--
|
|
8
|
+
-- Signing secrets are stored as-is: the relay needs the plaintext to
|
|
9
|
+
-- compute the HMAC. They are random 256-bit values that grant nothing on
|
|
10
|
+
-- our side (a leaked secret lets an attacker forge webhooks TO the
|
|
11
|
+
-- customer, not read anything FROM us) — rotate with
|
|
12
|
+
-- `rotateWebhookEndpointSecret`. Wrap the column with pgcrypto / KMS if a
|
|
13
|
+
-- compliance regime requires it.
|
|
14
|
+
--
|
|
15
|
+
-- `tenant_id` is nullable TEXT so single-tenant apps can ignore it and
|
|
16
|
+
-- multi-tenant apps can add their own RLS policy on top (the framework
|
|
17
|
+
-- does not know the app's tenant column type).
|
|
18
|
+
|
|
19
|
+
CREATE TABLE IF NOT EXISTS vk_webhook_endpoints (
|
|
20
|
+
id TEXT PRIMARY KEY,
|
|
21
|
+
tenant_id TEXT,
|
|
22
|
+
url TEXT NOT NULL,
|
|
23
|
+
secret TEXT NOT NULL,
|
|
24
|
+
-- Event types this endpoint subscribes to. Empty = every event.
|
|
25
|
+
event_types TEXT[] NOT NULL DEFAULT '{}',
|
|
26
|
+
description TEXT,
|
|
27
|
+
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
|
28
|
+
-- Consecutive deliveries that ended `dead`; reset on any success. Apps
|
|
29
|
+
-- may auto-disable an endpoint past a threshold.
|
|
30
|
+
failure_streak INTEGER NOT NULL DEFAULT 0,
|
|
31
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
32
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
CREATE INDEX IF NOT EXISTS vk_webhook_endpoints_tenant_idx
|
|
36
|
+
ON vk_webhook_endpoints (tenant_id)
|
|
37
|
+
WHERE enabled;
|
|
38
|
+
|
|
39
|
+
CREATE TABLE IF NOT EXISTS vk_webhook_deliveries (
|
|
40
|
+
id TEXT PRIMARY KEY,
|
|
41
|
+
endpoint_id TEXT NOT NULL REFERENCES vk_webhook_endpoints (id) ON DELETE CASCADE,
|
|
42
|
+
tenant_id TEXT,
|
|
43
|
+
-- The producer's event id — the receiver's idempotency key
|
|
44
|
+
-- (`X-VK-Event-Id`). One delivery per (endpoint, event).
|
|
45
|
+
event_id TEXT NOT NULL,
|
|
46
|
+
event_type TEXT NOT NULL,
|
|
47
|
+
payload JSONB NOT NULL,
|
|
48
|
+
status TEXT NOT NULL DEFAULT 'pending'
|
|
49
|
+
CHECK (status IN ('pending', 'delivered', 'dead')),
|
|
50
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
51
|
+
max_attempts INTEGER NOT NULL DEFAULT 8,
|
|
52
|
+
next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
53
|
+
last_status_code INTEGER,
|
|
54
|
+
last_error TEXT,
|
|
55
|
+
delivered_at TIMESTAMPTZ,
|
|
56
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
57
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
58
|
+
UNIQUE (endpoint_id, event_id)
|
|
59
|
+
);
|
|
60
|
+
|
|
61
|
+
-- The relay's claim query: due pending rows, oldest first.
|
|
62
|
+
CREATE INDEX IF NOT EXISTS vk_webhook_deliveries_due_idx
|
|
63
|
+
ON vk_webhook_deliveries (next_attempt_at)
|
|
64
|
+
WHERE status = 'pending';
|
|
65
|
+
|
|
66
|
+
-- Delivery log per endpoint (customer-facing "recent deliveries" screens).
|
|
67
|
+
CREATE INDEX IF NOT EXISTS vk_webhook_deliveries_endpoint_idx
|
|
68
|
+
ON vk_webhook_deliveries (endpoint_id, created_at DESC);
|
|
69
|
+
|
|
70
|
+
COMMENT ON TABLE vk_webhook_endpoints IS
|
|
71
|
+
'Outbound webhook endpoints registered by customers. Structure owned by @venturekit/integrations.';
|
|
72
|
+
COMMENT ON TABLE vk_webhook_deliveries IS
|
|
73
|
+
'One row per (event, endpoint) delivery attempt series; drained by deliverWebhooksOnce().';
|