@krak-stack/registry 0.1.59 → 0.1.61
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/CHANGELOG.md +13 -1
- package/dist/components/ui/data-table.d.ts +2 -0
- package/dist/components/ui/data-table.js +6 -2
- package/dist/components/ui/item.d.ts +22 -0
- package/dist/components/ui/trace.d.ts +18 -0
- package/dist/services/agent/client/index.js +584 -434
- package/dist/services/agent/client/widget.d.ts +1 -0
- package/dist/services/events/browser.js +29 -3
- package/dist/services/events/client/audit-log-table.js +6 -2
- package/dist/services/events/client/tracking-notice.js +2 -1
- package/dist/services/events/index.d.ts +26 -56
- package/dist/services/events/index.js +118 -7
- package/dist/services/events/schema.d.ts +66 -24
- package/dist/services/events/schema.js +34 -3
- package/dist/services/opentelemetry/api.js +2 -1
- package/dist/services/opentelemetry/browser.d.ts +1 -1
- package/dist/services/opentelemetry/browser.js +2 -1
- package/dist/services/opentelemetry/events.d.ts +1 -1
- package/dist/services/opentelemetry/index.d.ts +1 -1
- package/dist/services/opentelemetry/index.js +2 -1
- package/dist/services/opentelemetry/schema.d.ts +3 -1
- package/dist/services/opentelemetry/web-vitals.js +2 -1
- package/dist/services/webhooks/client/delivery-table.d.ts +62 -0
- package/dist/services/webhooks/client/delivery-table.js +4698 -0
- package/dist/services/webhooks/http-client.d.ts +8 -0
- package/dist/services/webhooks/http-client.js +69 -0
- package/dist/services/webhooks/index.d.ts +343 -0
- package/dist/services/webhooks/index.js +872 -0
- package/dist/services/webhooks/migrations.d.ts +8 -0
- package/dist/services/webhooks/migrations.js +63 -0
- package/dist/services/webhooks/receiver.d.ts +41 -0
- package/dist/services/webhooks/schema.d.ts +251 -0
- package/dist/services/webhooks/schema.js +353 -0
- package/dist/services/webhooks/url.d.ts +8 -0
- package/dist/services/webhooks/url.js +48 -0
- package/package.json +29 -1
- package/dist/components/ui/marker.d.ts +0 -10
|
@@ -0,0 +1,872 @@
|
|
|
1
|
+
// ../../src/services/webhooks/index.ts
|
|
2
|
+
import { PgClient } from "@effect/sql-pg";
|
|
3
|
+
import {
|
|
4
|
+
Cause,
|
|
5
|
+
Context as Context3,
|
|
6
|
+
DateTime as DateTime3,
|
|
7
|
+
Duration,
|
|
8
|
+
Effect as Effect5,
|
|
9
|
+
Layer as Layer4,
|
|
10
|
+
Option as Option3,
|
|
11
|
+
Schedule,
|
|
12
|
+
Schema as Schema4
|
|
13
|
+
} from "effect";
|
|
14
|
+
import { HttpClient as HttpClient2, HttpClientRequest } from "effect/http";
|
|
15
|
+
import { Activity, DurableClock, Workflow } from "effect/workflow";
|
|
16
|
+
import { SqlClient as SqlClient3, SqlSchema as SqlSchema2 } from "effect/sql";
|
|
17
|
+
import { Mac as Mac2, SecureRandom as SecureRandom2 } from "effect/crypto";
|
|
18
|
+
import { Hex as Hex2 } from "effect/encoding";
|
|
19
|
+
|
|
20
|
+
// ../../src/services/webhooks/migrations.ts
|
|
21
|
+
import { Effect, Layer } from "effect";
|
|
22
|
+
import { Migrator, SqlClient } from "effect/sql";
|
|
23
|
+
var webhookMigrations = Migrator.fromRecord({
|
|
24
|
+
"1_webhooks_initial": Effect.gen(function* () {
|
|
25
|
+
const sql = yield* SqlClient.SqlClient;
|
|
26
|
+
yield* sql`CREATE TABLE IF NOT EXISTS webhooks (
|
|
27
|
+
id text PRIMARY KEY, organization_id text NOT NULL, url text NOT NULL,
|
|
28
|
+
description text, headers jsonb, events jsonb, secret text NOT NULL,
|
|
29
|
+
enabled boolean NOT NULL DEFAULT true,
|
|
30
|
+
created_at timestamp NOT NULL DEFAULT now(), updated_at timestamp NOT NULL DEFAULT now()
|
|
31
|
+
)`;
|
|
32
|
+
yield* sql`CREATE TABLE IF NOT EXISTS webhook_deliveries (
|
|
33
|
+
id text PRIMARY KEY, webhook_id text NOT NULL REFERENCES webhooks(id) ON DELETE CASCADE,
|
|
34
|
+
event text NOT NULL, data jsonb NOT NULL DEFAULT '{}', status text NOT NULL DEFAULT 'pending',
|
|
35
|
+
completed_at timestamp, retry_at timestamp NOT NULL DEFAULT now(), retries integer NOT NULL DEFAULT 0,
|
|
36
|
+
created_at timestamp NOT NULL DEFAULT now(), updated_at timestamp NOT NULL DEFAULT now()
|
|
37
|
+
)`;
|
|
38
|
+
yield* sql`ALTER TABLE webhook_deliveries ADD COLUMN IF NOT EXISTS event_id text`;
|
|
39
|
+
yield* sql`CREATE UNIQUE INDEX IF NOT EXISTS krakstack_webhook_event_endpoint ON webhook_deliveries (webhook_id, event_id) WHERE event_id IS NOT NULL`;
|
|
40
|
+
yield* sql`CREATE INDEX IF NOT EXISTS krakstack_webhook_pending ON webhook_deliveries (retry_at) WHERE status = 'pending'`;
|
|
41
|
+
yield* sql`CREATE INDEX IF NOT EXISTS krakstack_webhook_organization ON webhooks (organization_id)`;
|
|
42
|
+
yield* sql`CREATE TABLE IF NOT EXISTS webhook_publications (
|
|
43
|
+
organization_id text NOT NULL, event_id text NOT NULL, event text NOT NULL, data jsonb NOT NULL,
|
|
44
|
+
PRIMARY KEY (organization_id, event_id)
|
|
45
|
+
)`;
|
|
46
|
+
}),
|
|
47
|
+
"2_webhook_names": Effect.gen(function* () {
|
|
48
|
+
const sql = yield* SqlClient.SqlClient;
|
|
49
|
+
yield* sql`ALTER TABLE webhooks ADD COLUMN name text`;
|
|
50
|
+
yield* sql`UPDATE webhooks SET name = url WHERE name IS NULL`;
|
|
51
|
+
yield* sql`ALTER TABLE webhook_deliveries ADD COLUMN error text`;
|
|
52
|
+
})
|
|
53
|
+
});
|
|
54
|
+
var migrateWebhooks = Migrator.make({})({
|
|
55
|
+
loader: webhookMigrations,
|
|
56
|
+
table: "krakstack_webhook_migrations"
|
|
57
|
+
});
|
|
58
|
+
var webhookMigrationsLayer = Layer.effectDiscard(migrateWebhooks);
|
|
59
|
+
var webhookReceiverMigrations = Migrator.fromRecord({
|
|
60
|
+
"1_webhook_receipts": Effect.gen(function* () {
|
|
61
|
+
const sql = yield* SqlClient.SqlClient;
|
|
62
|
+
yield* sql`CREATE TABLE webhook_receipts (
|
|
63
|
+
receiver text NOT NULL, event_id text NOT NULL, body_hash text NOT NULL,
|
|
64
|
+
completed_at timestamptz NOT NULL DEFAULT now(),
|
|
65
|
+
PRIMARY KEY (receiver, event_id)
|
|
66
|
+
)`;
|
|
67
|
+
yield* sql`CREATE INDEX webhook_receipts_completed ON webhook_receipts (completed_at)`;
|
|
68
|
+
})
|
|
69
|
+
});
|
|
70
|
+
var migrateWebhookReceiver = Migrator.make({})({
|
|
71
|
+
loader: webhookReceiverMigrations,
|
|
72
|
+
table: "krakstack_webhook_receiver_migrations"
|
|
73
|
+
});
|
|
74
|
+
var webhookReceiverMigrationsLayer = Layer.effectDiscard(migrateWebhookReceiver);
|
|
75
|
+
|
|
76
|
+
// ../../src/services/webhooks/url.ts
|
|
77
|
+
import { Context } from "effect";
|
|
78
|
+
var hostname = (value) => value.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
|
|
79
|
+
var isPublicIpAddress = (value) => {
|
|
80
|
+
const address = hostname(value);
|
|
81
|
+
const octets = address.split(".");
|
|
82
|
+
if (octets.length === 4 && octets.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255)) {
|
|
83
|
+
const [a = 0, b = 0, c = 0] = octets.map(Number);
|
|
84
|
+
return !(a === 0 || a === 10 || a === 127 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && (b === 0 || b === 168 || b === 88 && c === 99) || a === 198 && (b === 18 || b === 19 || b === 51) || a === 203 && b === 0 || a >= 224);
|
|
85
|
+
}
|
|
86
|
+
const first = Number.parseInt(address.split(":")[0] ?? "", 16);
|
|
87
|
+
return address.includes(":") && first >= 8192 && first <= 16383 && !address.startsWith("2001:") && !address.startsWith("2002:") && !address.startsWith("3fff:");
|
|
88
|
+
};
|
|
89
|
+
var isPublicWebhookUrl = (url) => {
|
|
90
|
+
if (!["https:", "http:"].includes(url.protocol) || url.username || url.password)
|
|
91
|
+
return false;
|
|
92
|
+
const host = hostname(url.hostname);
|
|
93
|
+
if (!host || host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local"))
|
|
94
|
+
return false;
|
|
95
|
+
return !(host.includes(":") || /^\d+(?:\.\d+){3}$/.test(host)) || isPublicIpAddress(host);
|
|
96
|
+
};
|
|
97
|
+
var isPublicWebhookUrlString = (value) => {
|
|
98
|
+
try {
|
|
99
|
+
return isPublicWebhookUrl(new URL(value));
|
|
100
|
+
} catch {
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
var isAllowedWebhookUrlString = (value, allowLoopback) => {
|
|
105
|
+
try {
|
|
106
|
+
const url = new URL(value);
|
|
107
|
+
return isPublicWebhookUrl(url) || allowLoopback && isLoopbackWebhookUrl(url);
|
|
108
|
+
} catch {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
var WebhookAllowLoopback = Context.Reference("Webhooks/AllowLoopback", {
|
|
113
|
+
defaultValue: () => false
|
|
114
|
+
});
|
|
115
|
+
var isLoopbackWebhookUrl = (url) => ["http:", "https:"].includes(url.protocol) && !url.username && !url.password && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
|
|
116
|
+
// ../../src/services/webhooks/http-client.ts
|
|
117
|
+
import { Effect as Effect2, Layer as Layer2, Result } from "effect";
|
|
118
|
+
import { Dns, NetAddress } from "effect/net";
|
|
119
|
+
import { FetchHttpClient, HttpClient, HttpClientError } from "effect/http";
|
|
120
|
+
var isPublicWebhookDestination = Effect2.fn("Webhooks.isPublicDestination")(function* (url) {
|
|
121
|
+
if (!isPublicWebhookUrl(url))
|
|
122
|
+
return false;
|
|
123
|
+
const hostname = url.hostname.replace(/^\[|\]$/g, "");
|
|
124
|
+
if (Result.isSuccess(NetAddress.ipFromString(hostname)))
|
|
125
|
+
return true;
|
|
126
|
+
const dns = yield* Dns.Dns;
|
|
127
|
+
return yield* dns.lookup(hostname).pipe(Effect2.map((addresses) => addresses.every((address) => isPublicIpAddress(NetAddress.formatIp(address)))), Effect2.catch(() => Effect2.succeed(false)));
|
|
128
|
+
});
|
|
129
|
+
var isAllowedWebhookDestination = Effect2.fn("Webhooks.isAllowedDestination")(function* (url) {
|
|
130
|
+
if ((yield* WebhookAllowLoopback) && isLoopbackWebhookUrl(url))
|
|
131
|
+
return true;
|
|
132
|
+
return yield* isPublicWebhookDestination(url);
|
|
133
|
+
});
|
|
134
|
+
var layer = Layer2.effect(HttpClient.HttpClient, Effect2.gen(function* () {
|
|
135
|
+
const client = yield* HttpClient.HttpClient;
|
|
136
|
+
const dns = yield* Dns.Dns;
|
|
137
|
+
const allowLoopback = yield* WebhookAllowLoopback;
|
|
138
|
+
return client.pipe(HttpClient.transform((response, request) => Effect2.gen(function* () {
|
|
139
|
+
if (!(yield* isAllowedWebhookDestination(new URL(request.url)).pipe(Effect2.provideService(Dns.Dns, dns), Effect2.provideService(WebhookAllowLoopback, allowLoopback)))) {
|
|
140
|
+
return yield* new HttpClientError.HttpClientError({
|
|
141
|
+
reason: new HttpClientError.TransportError({
|
|
142
|
+
request,
|
|
143
|
+
description: "Webhook destination is not public"
|
|
144
|
+
})
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
return yield* response.pipe(Effect2.provideService(FetchHttpClient.RequestInit, {
|
|
148
|
+
redirect: "error"
|
|
149
|
+
}));
|
|
150
|
+
})));
|
|
151
|
+
})).pipe(Layer2.provide(FetchHttpClient.layer));
|
|
152
|
+
|
|
153
|
+
// ../../src/services/webhooks/schema.ts
|
|
154
|
+
import { Schema as Schema2 } from "effect";
|
|
155
|
+
|
|
156
|
+
// ../../src/lib/query.ts
|
|
157
|
+
import {
|
|
158
|
+
DateTime,
|
|
159
|
+
Effect as Effect3,
|
|
160
|
+
Option,
|
|
161
|
+
Schema,
|
|
162
|
+
SchemaGetter,
|
|
163
|
+
SchemaIssue,
|
|
164
|
+
SchemaTransformation
|
|
165
|
+
} from "effect";
|
|
166
|
+
var parseSortParam = (sort) => {
|
|
167
|
+
const id = sort.startsWith("-") ? sort.slice(1) : sort;
|
|
168
|
+
if (!id || id.includes(",") || id.includes(":")) {
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
return { id, direction: sort.startsWith("-") ? "desc" : "asc" };
|
|
172
|
+
};
|
|
173
|
+
var SortDirection = Schema.Union([
|
|
174
|
+
Schema.Literal("asc"),
|
|
175
|
+
Schema.Literal("desc")
|
|
176
|
+
]).pipe(Schema.annotate({
|
|
177
|
+
identifier: "SortDirection",
|
|
178
|
+
title: "Sort Direction",
|
|
179
|
+
description: "Sort direction for list query results.",
|
|
180
|
+
examples: ["asc", "desc"]
|
|
181
|
+
}));
|
|
182
|
+
var SortParam = Schema.Struct({
|
|
183
|
+
id: Schema.NonEmptyString,
|
|
184
|
+
direction: SortDirection
|
|
185
|
+
}).pipe(Schema.annotate({
|
|
186
|
+
identifier: "SortParam",
|
|
187
|
+
title: "Sort Parameter",
|
|
188
|
+
description: "Decoded sort parameter with a field id and direction.",
|
|
189
|
+
examples: [{ id: "publicName", direction: "asc" }]
|
|
190
|
+
}));
|
|
191
|
+
var SortParamFromString = Schema.String.pipe(Schema.decodeTo(SortParam, SchemaTransformation.transformEffect({
|
|
192
|
+
decode: (sort) => {
|
|
193
|
+
const sortParam = parseSortParam(sort);
|
|
194
|
+
if (!sortParam) {
|
|
195
|
+
return Effect3.fail(new SchemaIssue.InvalidValue({ message: 'Expected sort in the format "field" or "-field"' }, sort));
|
|
196
|
+
}
|
|
197
|
+
return Effect3.succeed(sortParam);
|
|
198
|
+
},
|
|
199
|
+
encode: (sort) => Effect3.succeed(sort.direction === "desc" ? `-${sort.id}` : sort.id)
|
|
200
|
+
})), Schema.annotate({
|
|
201
|
+
identifier: "SortParamFromString",
|
|
202
|
+
title: "Sort Parameter From String",
|
|
203
|
+
description: 'URL encoded single sort parameter where descending fields are prefixed with "-".',
|
|
204
|
+
examples: [{ id: "publicName", direction: "asc" }]
|
|
205
|
+
}));
|
|
206
|
+
var SortParamsFromString = Schema.String.pipe(Schema.decodeTo(Schema.Array(SortParam), SchemaTransformation.transformEffect({
|
|
207
|
+
decode: (sort) => {
|
|
208
|
+
if (sort === "")
|
|
209
|
+
return Effect3.succeed([]);
|
|
210
|
+
const parts = sort.split(",");
|
|
211
|
+
const sortParams = [];
|
|
212
|
+
for (const part of parts) {
|
|
213
|
+
const sortParam = parseSortParam(part);
|
|
214
|
+
if (!sortParam) {
|
|
215
|
+
return Effect3.fail(new SchemaIssue.InvalidValue({ message: 'Expected sort in the format "field,-otherField"' }, sort));
|
|
216
|
+
}
|
|
217
|
+
sortParams.push(sortParam);
|
|
218
|
+
}
|
|
219
|
+
return Effect3.succeed(sortParams);
|
|
220
|
+
},
|
|
221
|
+
encode: (sort) => Effect3.succeed(sort.map((part) => Schema.encodeSync(SortParamFromString)(part)).join(","))
|
|
222
|
+
})), Schema.annotate({
|
|
223
|
+
identifier: "SortParamsFromString",
|
|
224
|
+
title: "Sort Parameters From String",
|
|
225
|
+
description: 'URL encoded sort parameters where descending fields are prefixed with "-" and multiple fields are comma-separated.',
|
|
226
|
+
examples: [
|
|
227
|
+
[
|
|
228
|
+
{ id: "name", direction: "desc" },
|
|
229
|
+
{ id: "age", direction: "asc" }
|
|
230
|
+
]
|
|
231
|
+
]
|
|
232
|
+
}));
|
|
233
|
+
var SortParamsArray = Schema.Array(SortParam);
|
|
234
|
+
var SortParams = Schema.declare(Schema.is(SortParamsArray), {
|
|
235
|
+
identifier: "SortParams",
|
|
236
|
+
toCodec: () => Schema.link()(SortParamsArray, SchemaTransformation.passthrough()),
|
|
237
|
+
toCodecStringTree: () => Schema.link()(SortParamsFromString, SchemaTransformation.passthrough())
|
|
238
|
+
});
|
|
239
|
+
var TextFilterOperator = Schema.Literals([
|
|
240
|
+
"contains",
|
|
241
|
+
"equals",
|
|
242
|
+
"startsWith",
|
|
243
|
+
"endsWith"
|
|
244
|
+
]).annotate({ identifier: "TextFilterOperator" });
|
|
245
|
+
var FilterCalendarDate = Schema.String.check(Schema.isPattern(/^\d{4}-\d{2}-\d{2}$/), Schema.makeFilter((value) => Option.exists(DateTime.make(value), (date) => DateTime.formatIsoDateUtc(date) === value))).annotate({ identifier: "FilterCalendarDate" });
|
|
246
|
+
var ColumnFilter = Schema.Union([
|
|
247
|
+
Schema.Struct({
|
|
248
|
+
id: Schema.NonEmptyString,
|
|
249
|
+
kind: Schema.Literal("text"),
|
|
250
|
+
operator: TextFilterOperator,
|
|
251
|
+
value: Schema.NonEmptyString
|
|
252
|
+
}),
|
|
253
|
+
Schema.Struct({
|
|
254
|
+
id: Schema.NonEmptyString,
|
|
255
|
+
kind: Schema.Literal("number"),
|
|
256
|
+
min: Schema.optional(Schema.Finite),
|
|
257
|
+
max: Schema.optional(Schema.Finite)
|
|
258
|
+
}).check(Schema.makeFilter((range) => (range.min !== undefined || range.max !== undefined) && (range.min === undefined || range.max === undefined || range.min <= range.max))),
|
|
259
|
+
Schema.Struct({
|
|
260
|
+
id: Schema.NonEmptyString,
|
|
261
|
+
kind: Schema.Literal("date"),
|
|
262
|
+
from: Schema.optional(FilterCalendarDate),
|
|
263
|
+
to: Schema.optional(FilterCalendarDate)
|
|
264
|
+
}).check(Schema.makeFilter((range) => (range.from !== undefined || range.to !== undefined) && (range.from === undefined || range.to === undefined || range.from <= range.to))),
|
|
265
|
+
Schema.Struct({
|
|
266
|
+
id: Schema.NonEmptyString,
|
|
267
|
+
kind: Schema.Literal("boolean"),
|
|
268
|
+
value: Schema.Boolean
|
|
269
|
+
}),
|
|
270
|
+
Schema.Struct({
|
|
271
|
+
id: Schema.NonEmptyString,
|
|
272
|
+
kind: Schema.Literal("values"),
|
|
273
|
+
values: Schema.NonEmptyArray(Schema.String)
|
|
274
|
+
})
|
|
275
|
+
]).annotate({ identifier: "ColumnFilter" });
|
|
276
|
+
var ColumnFiltersArray = Schema.Array(ColumnFilter);
|
|
277
|
+
var ColumnFilters = Schema.declare(Schema.is(ColumnFiltersArray), {
|
|
278
|
+
identifier: "ColumnFilters",
|
|
279
|
+
toCodec: () => Schema.link()(ColumnFiltersArray, SchemaTransformation.passthrough()),
|
|
280
|
+
toCodecStringTree: () => Schema.link()(Schema.fromJsonString(ColumnFiltersArray), SchemaTransformation.passthrough())
|
|
281
|
+
});
|
|
282
|
+
var Query = Schema.Struct({
|
|
283
|
+
page: Schema.optional(Schema.Union([Schema.Number, Schema.NumberFromString]).check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))).pipe(Schema.decodeTo(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), {
|
|
284
|
+
decode: SchemaGetter.withDefault(Effect3.succeed(0)),
|
|
285
|
+
encode: SchemaGetter.transformOptional(Option.filter((page) => page !== 0))
|
|
286
|
+
})),
|
|
287
|
+
pageSize: Schema.optional(Schema.Union([Schema.Number, Schema.NumberFromString]).check(Schema.isInt(), Schema.isBetween({ minimum: 1, maximum: 100 }))).pipe(Schema.decodeTo(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 })), {
|
|
288
|
+
decode: SchemaGetter.withDefault(Effect3.succeed(20)),
|
|
289
|
+
encode: SchemaGetter.transformOptional(Option.filter((pageSize) => pageSize !== 20))
|
|
290
|
+
})),
|
|
291
|
+
globalFilter: Schema.optional(Schema.String),
|
|
292
|
+
sort: Schema.optional(SortParams),
|
|
293
|
+
filters: Schema.optional(ColumnFilters)
|
|
294
|
+
}).annotate({
|
|
295
|
+
identifier: "Query",
|
|
296
|
+
title: "Query",
|
|
297
|
+
description: "Zero-based page request parameters with optional filtering and sorting for list endpoints.",
|
|
298
|
+
examples: [
|
|
299
|
+
{
|
|
300
|
+
page: 0,
|
|
301
|
+
pageSize: 20,
|
|
302
|
+
globalFilter: "housing",
|
|
303
|
+
sort: [
|
|
304
|
+
{ id: "publicName", direction: "desc" },
|
|
305
|
+
{ id: "createdAt", direction: "asc" }
|
|
306
|
+
]
|
|
307
|
+
}
|
|
308
|
+
]
|
|
309
|
+
});
|
|
310
|
+
var QueryStandard = Schema.toStandardSchemaV1(Query);
|
|
311
|
+
var PaginationMeta = Schema.Struct({
|
|
312
|
+
page: Schema.Int,
|
|
313
|
+
pageSize: Schema.Int,
|
|
314
|
+
total: Schema.Int,
|
|
315
|
+
pageCount: Schema.Int
|
|
316
|
+
}).pipe(Schema.annotate({
|
|
317
|
+
identifier: "PaginationMeta",
|
|
318
|
+
title: "Pagination Metadata",
|
|
319
|
+
description: "Pagination metadata returned with a paginated list response.",
|
|
320
|
+
examples: [{ page: 0, pageSize: 20, total: 125, pageCount: 7 }]
|
|
321
|
+
}));
|
|
322
|
+
var PaginatedResponse = (items) => Schema.Struct({
|
|
323
|
+
data: Schema.Array(items),
|
|
324
|
+
meta: PaginationMeta
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
// ../../src/services/webhooks/schema.ts
|
|
328
|
+
var webhookColumns = 'id, organization_id AS "organizationId", COALESCE(name, url) AS name, url, description, headers, events, secret, enabled, created_at AS "createdAt", updated_at AS "updatedAt"';
|
|
329
|
+
var deliveryColumns = 'd.id, d.webhook_id AS "webhookId", d.event, d.data, d.status, d.error, d.completed_at AS "completedAt", d.retry_at AS "retryAt", d.retries, d.created_at AS "createdAt", d.updated_at AS "updatedAt"';
|
|
330
|
+
var WebhookScope = Schema2.Struct({
|
|
331
|
+
organizationId: Schema2.NonEmptyString
|
|
332
|
+
}).annotate({ identifier: "WebhookScope" });
|
|
333
|
+
var WebhookRequest = Schema2.Struct({
|
|
334
|
+
organizationId: Schema2.NonEmptyString,
|
|
335
|
+
id: Schema2.NonEmptyString
|
|
336
|
+
}).annotate({ identifier: "WebhookRequest" });
|
|
337
|
+
var WebhookStatisticsInterval = Schema2.Literals([
|
|
338
|
+
"hour",
|
|
339
|
+
"day"
|
|
340
|
+
]).annotate({ identifier: "WebhookStatisticsInterval" });
|
|
341
|
+
var WebhookStatisticsRequest = Schema2.Struct({
|
|
342
|
+
...WebhookRequest.fields,
|
|
343
|
+
interval: WebhookStatisticsInterval
|
|
344
|
+
}).annotate({ identifier: "WebhookStatisticsRequest" });
|
|
345
|
+
var WebhookDeliveryCounts = Schema2.Struct({
|
|
346
|
+
total: Schema2.Int,
|
|
347
|
+
success: Schema2.Int,
|
|
348
|
+
failed: Schema2.Int
|
|
349
|
+
}).annotate({ identifier: "WebhookDeliveryCounts" });
|
|
350
|
+
var WebhookEventCount = Schema2.Struct({
|
|
351
|
+
event: Schema2.String,
|
|
352
|
+
total: Schema2.Int
|
|
353
|
+
}).annotate({ identifier: "WebhookEventCount" });
|
|
354
|
+
var WebhookDeliveryBucket = Schema2.Struct({
|
|
355
|
+
...WebhookDeliveryCounts.fields,
|
|
356
|
+
bucket: Schema2.Date,
|
|
357
|
+
events: Schema2.Array(WebhookEventCount)
|
|
358
|
+
}).annotate({ identifier: "WebhookDeliveryBucket" });
|
|
359
|
+
var WebhookStatistics = Schema2.Struct({
|
|
360
|
+
...WebhookDeliveryCounts.fields,
|
|
361
|
+
buckets: Schema2.Array(WebhookDeliveryBucket)
|
|
362
|
+
}).annotate({ identifier: "WebhookStatistics" });
|
|
363
|
+
var WebhookName = Schema2.Trim.check(Schema2.isMinLength(1), Schema2.isMaxLength(200)).annotate({ identifier: "WebhookName" });
|
|
364
|
+
var WebhookPayload = Schema2.Struct({
|
|
365
|
+
name: Schema2.optional(WebhookName),
|
|
366
|
+
url: Schema2.String.check(Schema2.makeFilter(isPublicWebhookUrlString, {
|
|
367
|
+
expected: "a public HTTP or HTTPS URL without credentials"
|
|
368
|
+
})),
|
|
369
|
+
description: Schema2.NullOr(Schema2.String),
|
|
370
|
+
enabled: Schema2.Boolean,
|
|
371
|
+
events: Schema2.NullOr(Schema2.Array(Schema2.NonEmptyString)),
|
|
372
|
+
customHeaders: Schema2.NullOr(Schema2.Record(Schema2.String, Schema2.String)).check(Schema2.makeFilter((headers) => Object.keys(headers ?? {}).every((name) => ![
|
|
373
|
+
"content-type",
|
|
374
|
+
"webhook-id",
|
|
375
|
+
"webhook-timestamp",
|
|
376
|
+
"webhook-signature"
|
|
377
|
+
].includes(name.toLowerCase())), { expected: "headers that do not override webhook protocol headers" }))
|
|
378
|
+
}).annotate({ identifier: "WebhookPayload" });
|
|
379
|
+
var webhookPayloadSchema = (allowLoopback) => Schema2.Struct({
|
|
380
|
+
...WebhookPayload.fields,
|
|
381
|
+
url: Schema2.String.check(Schema2.makeFilter((value) => isAllowedWebhookUrlString(value, allowLoopback), {
|
|
382
|
+
expected: "a public HTTP(S) URL, or an explicitly enabled development loopback URL"
|
|
383
|
+
}))
|
|
384
|
+
}).annotate({ identifier: "ConfiguredWebhookPayload" });
|
|
385
|
+
var Webhook = Schema2.Struct({
|
|
386
|
+
id: Schema2.String,
|
|
387
|
+
name: Schema2.String,
|
|
388
|
+
organizationId: Schema2.String,
|
|
389
|
+
url: Schema2.String,
|
|
390
|
+
description: Schema2.NullOr(Schema2.String),
|
|
391
|
+
headers: Schema2.NullOr(Schema2.Record(Schema2.String, Schema2.String)),
|
|
392
|
+
events: Schema2.NullOr(Schema2.Array(Schema2.String)),
|
|
393
|
+
secret: Schema2.String,
|
|
394
|
+
enabled: Schema2.Boolean,
|
|
395
|
+
createdAt: Schema2.Date,
|
|
396
|
+
updatedAt: Schema2.Date
|
|
397
|
+
}).annotate({ identifier: "Webhook" });
|
|
398
|
+
var WebhookDelivery = Schema2.Struct({
|
|
399
|
+
id: Schema2.String,
|
|
400
|
+
webhookId: Schema2.String,
|
|
401
|
+
event: Schema2.String,
|
|
402
|
+
data: Schema2.Json,
|
|
403
|
+
status: Schema2.Literals(["pending", "success", "failed"]),
|
|
404
|
+
error: Schema2.NullOr(Schema2.String),
|
|
405
|
+
completedAt: Schema2.NullOr(Schema2.Date),
|
|
406
|
+
retryAt: Schema2.Date,
|
|
407
|
+
retries: Schema2.Int,
|
|
408
|
+
createdAt: Schema2.Date,
|
|
409
|
+
updatedAt: Schema2.Date
|
|
410
|
+
}).annotate({ identifier: "WebhookDelivery" });
|
|
411
|
+
var WebhookDeliverySortId = Schema2.Literals([
|
|
412
|
+
"id",
|
|
413
|
+
"event",
|
|
414
|
+
"status",
|
|
415
|
+
"createdAt",
|
|
416
|
+
"completedAt"
|
|
417
|
+
]).annotate({ identifier: "WebhookDeliverySortId" });
|
|
418
|
+
var DeliveryFilter = ColumnFilter.check(Schema2.makeFilter((filter) => filter.id === "id" ? filter.kind === "text" : filter.id === "event" ? filter.kind === "values" : filter.id === "status" ? filter.kind === "values" && filter.values.every((value) => ["pending", "success", "failed"].includes(value)) : ["createdAt", "completedAt"].includes(filter.id) && filter.kind === "date")).annotate({ identifier: "WebhookDeliveryFilter" });
|
|
419
|
+
var WebhookDeliveriesQuery = Schema2.Struct({
|
|
420
|
+
...Query.fields,
|
|
421
|
+
filters: Schema2.optional(ColumnFilters.check(Schema2.makeFilter((filters) => filters.every(Schema2.is(DeliveryFilter))))),
|
|
422
|
+
sort: Schema2.optional(SortParams.check(Schema2.makeFilter((sort) => sort.every((part) => Schema2.is(WebhookDeliverySortId)(part.id)))))
|
|
423
|
+
}).annotate({ identifier: "WebhookDeliveriesQuery" });
|
|
424
|
+
var ListWebhookDeliveries = Schema2.Struct({
|
|
425
|
+
...WebhookRequest.fields,
|
|
426
|
+
...WebhookDeliveriesQuery.fields
|
|
427
|
+
}).annotate({ identifier: "ListWebhookDeliveries" });
|
|
428
|
+
var WebhookDeliveries = PaginatedResponse(WebhookDelivery).annotate({
|
|
429
|
+
identifier: "WebhookDeliveries"
|
|
430
|
+
});
|
|
431
|
+
var PublishWebhook = Schema2.Struct({
|
|
432
|
+
organizationId: Schema2.NonEmptyString,
|
|
433
|
+
eventId: Schema2.NonEmptyString,
|
|
434
|
+
event: Schema2.NonEmptyString,
|
|
435
|
+
data: Schema2.Json
|
|
436
|
+
}).annotate({ identifier: "PublishWebhook" });
|
|
437
|
+
|
|
438
|
+
class WebhookError extends Schema2.TaggedError()("WebhookError", {
|
|
439
|
+
message: Schema2.String
|
|
440
|
+
}) {
|
|
441
|
+
}
|
|
442
|
+
// ../../src/services/webhooks/receiver.ts
|
|
443
|
+
import {
|
|
444
|
+
Context as Context2,
|
|
445
|
+
DateTime as DateTime2,
|
|
446
|
+
Effect as Effect4,
|
|
447
|
+
Layer as Layer3,
|
|
448
|
+
Option as Option2,
|
|
449
|
+
Redacted,
|
|
450
|
+
Schema as Schema3
|
|
451
|
+
} from "effect";
|
|
452
|
+
import { Digest, Mac, SecureRandom } from "effect/crypto";
|
|
453
|
+
import { Hex } from "effect/encoding";
|
|
454
|
+
import { SqlClient as SqlClient2, SqlSchema } from "effect/sql";
|
|
455
|
+
class WebhookVerificationError extends Schema3.TaggedError()("WebhookVerificationError", {
|
|
456
|
+
reason: Schema3.Literals(["headers", "timestamp", "signature", "payload"])
|
|
457
|
+
}) {
|
|
458
|
+
}
|
|
459
|
+
var ProtocolHeaders = Schema3.Struct({
|
|
460
|
+
"webhook-id": Schema3.NonEmptyString,
|
|
461
|
+
"webhook-timestamp": Schema3.String,
|
|
462
|
+
"webhook-signature": Schema3.String.check(Schema3.isPattern(/^[a-fA-F0-9]{64}$/))
|
|
463
|
+
}).annotate({ identifier: "WebhookProtocolHeaders" });
|
|
464
|
+
|
|
465
|
+
class WebhookReceiptConflict extends Schema3.TaggedError()("WebhookReceiptConflict", {}) {
|
|
466
|
+
}
|
|
467
|
+
var ReceiptRequest = Schema3.Struct({
|
|
468
|
+
receiver: Schema3.NonEmptyString,
|
|
469
|
+
eventId: Schema3.NonEmptyString,
|
|
470
|
+
bodyHash: Schema3.NonEmptyString
|
|
471
|
+
}).annotate({ identifier: "WebhookReceiptRequest" });
|
|
472
|
+
var Receipt = Schema3.Struct({ bodyHash: Schema3.String }).annotate({
|
|
473
|
+
identifier: "WebhookReceipt"
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
class WebhooksReceiver extends Context2.Service()("krakstack/webhooks/WebhooksReceiver", {
|
|
477
|
+
make: Effect4.gen(function* () {
|
|
478
|
+
const sql = (yield* SqlClient2.SqlClient).withoutTransforms();
|
|
479
|
+
const mac = yield* Mac.Mac.pipe(Effect4.provide(Mac.layerWebCrypto.pipe(Layer3.provide(SecureRandom.layerWebCrypto))));
|
|
480
|
+
const digest = yield* Digest.Digest.pipe(Effect4.provide(Digest.layerWebCrypto));
|
|
481
|
+
const receive = Effect4.fn("WebhooksReceiver.receive")(function* (input) {
|
|
482
|
+
const headers = yield* Schema3.decodeUnknownEffect(ProtocolHeaders)(input.headers).pipe(Effect4.mapError(() => new WebhookVerificationError({ reason: "headers" })));
|
|
483
|
+
const timestamp = headers["webhook-timestamp"];
|
|
484
|
+
const date = DateTime2.make(timestamp);
|
|
485
|
+
const now = yield* DateTime2.now;
|
|
486
|
+
if (Option2.isNone(date) || Math.abs(DateTime2.toEpochMillis(now) - DateTime2.toEpochMillis(date.value)) > 300000) {
|
|
487
|
+
return yield* new WebhookVerificationError({ reason: "timestamp" });
|
|
488
|
+
}
|
|
489
|
+
const signature = yield* Effect4.fromResult(Hex.decode(headers["webhook-signature"])).pipe(Effect4.mapError(() => new WebhookVerificationError({ reason: "signature" })));
|
|
490
|
+
const key = yield* Mac.key(Mac.hmacSha256, new TextEncoder().encode(Redacted.value(input.secret)));
|
|
491
|
+
const valid = yield* mac.verify(key, signature, new TextEncoder().encode(`${headers["webhook-id"]}.${timestamp}.${input.body}`));
|
|
492
|
+
if (!valid)
|
|
493
|
+
return yield* new WebhookVerificationError({ reason: "signature" });
|
|
494
|
+
const payload = yield* Schema3.decodeUnknownEffect(Schema3.fromJsonString(input.schema))(input.body).pipe(Effect4.mapError(() => new WebhookVerificationError({ reason: "payload" })));
|
|
495
|
+
const request = yield* Schema3.decodeUnknownEffect(ReceiptRequest)({
|
|
496
|
+
receiver: input.receiver,
|
|
497
|
+
eventId: headers["webhook-id"],
|
|
498
|
+
bodyHash: yield* digest.digestHex(Digest.sha256, new TextEncoder().encode(input.body))
|
|
499
|
+
});
|
|
500
|
+
return yield* sql.withTransaction(Effect4.gen(function* () {
|
|
501
|
+
const inserted = yield* sql`INSERT INTO webhook_receipts (receiver, event_id, body_hash)
|
|
502
|
+
VALUES (${request.receiver}, ${request.eventId}, ${request.bodyHash})
|
|
503
|
+
ON CONFLICT DO NOTHING RETURNING event_id`;
|
|
504
|
+
if (!inserted.length) {
|
|
505
|
+
const receipt = yield* SqlSchema.findOne({
|
|
506
|
+
Request: ReceiptRequest,
|
|
507
|
+
Result: Receipt,
|
|
508
|
+
execute: ({
|
|
509
|
+
receiver,
|
|
510
|
+
eventId
|
|
511
|
+
}) => sql`SELECT body_hash AS "bodyHash" FROM webhook_receipts
|
|
512
|
+
WHERE receiver = ${receiver} AND event_id = ${eventId}`
|
|
513
|
+
})(request);
|
|
514
|
+
if (receipt.bodyHash !== request.bodyHash)
|
|
515
|
+
return yield* new WebhookReceiptConflict({});
|
|
516
|
+
return { duplicate: true };
|
|
517
|
+
}
|
|
518
|
+
yield* input.handle(payload);
|
|
519
|
+
return { duplicate: false };
|
|
520
|
+
}));
|
|
521
|
+
});
|
|
522
|
+
return {
|
|
523
|
+
receive,
|
|
524
|
+
cleanup: () => sql`DELETE FROM webhook_receipts WHERE completed_at <= now() - interval '30 days'`.pipe(Effect4.asVoid)
|
|
525
|
+
};
|
|
526
|
+
})
|
|
527
|
+
}) {
|
|
528
|
+
static layer = Layer3.effect(this, this.make).pipe(Layer3.provide(webhookReceiverMigrationsLayer));
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// ../../src/services/webhooks/index.ts
|
|
532
|
+
var maxDeliveryAttempts = 8;
|
|
533
|
+
var retrySchedule = Schedule.min([
|
|
534
|
+
Schedule.exponential("5 seconds", 4),
|
|
535
|
+
Schedule.spaced("10 hours")
|
|
536
|
+
]);
|
|
537
|
+
var processDelivery = Effect5.fn("Webhooks.processDelivery")(function* (input) {
|
|
538
|
+
const sql = (yield* SqlClient3.SqlClient).withoutTransforms();
|
|
539
|
+
const client = yield* HttpClient2.HttpClient;
|
|
540
|
+
const row = yield* SqlSchema2.findOneOption({
|
|
541
|
+
Request: WebhookRequest,
|
|
542
|
+
Result: WebhookDelivery,
|
|
543
|
+
execute: ({
|
|
544
|
+
id,
|
|
545
|
+
organizationId
|
|
546
|
+
}) => sql`SELECT ${sql.literal(deliveryColumns)} FROM webhook_deliveries d JOIN webhooks w ON w.id = d.webhook_id
|
|
547
|
+
WHERE d.id = ${id} AND w.organization_id = ${organizationId}`
|
|
548
|
+
})(input);
|
|
549
|
+
if (Option3.isNone(row) || row.value.status !== "pending")
|
|
550
|
+
return null;
|
|
551
|
+
const delivery = row.value;
|
|
552
|
+
const now = yield* DateTime3.now;
|
|
553
|
+
const remaining = delivery.retryAt.getTime() - DateTime3.toEpochMillis(now);
|
|
554
|
+
if (remaining > 0)
|
|
555
|
+
return remaining;
|
|
556
|
+
const found = yield* SqlSchema2.findOneOption({
|
|
557
|
+
Request: WebhookRequest,
|
|
558
|
+
Result: Webhook,
|
|
559
|
+
execute: ({ organizationId, id }) => sql`SELECT ${sql.literal(webhookColumns)} FROM webhooks WHERE organization_id = ${organizationId} AND id = ${id}`
|
|
560
|
+
})({ organizationId: input.organizationId, id: delivery.webhookId });
|
|
561
|
+
if (Option3.isNone(found))
|
|
562
|
+
return null;
|
|
563
|
+
const endpoint = found.value;
|
|
564
|
+
if (!endpoint.enabled || delivery.retries >= maxDeliveryAttempts) {
|
|
565
|
+
const error = !endpoint.enabled ? "Webhook endpoint is disabled" : delivery.error ?? "Delivery attempt limit reached";
|
|
566
|
+
yield* sql`UPDATE webhook_deliveries SET status = 'failed', error = ${error}, completed_at = now(), updated_at = now() WHERE id = ${input.id}`;
|
|
567
|
+
return null;
|
|
568
|
+
}
|
|
569
|
+
const body = yield* Schema4.encodeEffect(Schema4.fromJsonString(Schema4.Json))({
|
|
570
|
+
event: delivery.event,
|
|
571
|
+
data: delivery.data
|
|
572
|
+
});
|
|
573
|
+
const timestamp = DateTime3.formatIso(now);
|
|
574
|
+
const mac = yield* Mac2.Mac.pipe(Effect5.provide(Mac2.layerWebCrypto.pipe(Layer4.provide(SecureRandom2.layerWebCrypto))));
|
|
575
|
+
const key = yield* Mac2.key(Mac2.hmacSha256, new TextEncoder().encode(endpoint.secret));
|
|
576
|
+
const signature = Hex2.encode(yield* mac.sign(key, new TextEncoder().encode(`${delivery.id}.${timestamp}.${body}`)));
|
|
577
|
+
const allowLoopback = yield* WebhookAllowLoopback;
|
|
578
|
+
const error = isAllowedWebhookUrlString(endpoint.url, allowLoopback) ? yield* client.execute(HttpClientRequest.post(endpoint.url).pipe(HttpClientRequest.setHeaders({
|
|
579
|
+
...endpoint.headers,
|
|
580
|
+
"Content-Type": "application/json",
|
|
581
|
+
"webhook-id": delivery.id,
|
|
582
|
+
"webhook-timestamp": timestamp,
|
|
583
|
+
"webhook-signature": signature
|
|
584
|
+
}), HttpClientRequest.bodyText(body, "application/json"))).pipe(Effect5.map((response) => response.status >= 200 && response.status < 300 ? null : `HTTP ${response.status}`), Effect5.timeout("30 seconds"), Effect5.catch((error) => Effect5.succeed(error._tag === "TimeoutError" ? "Request timed out after 30 seconds" : error.reason._tag === "TransportError" && error.reason.description === "Webhook destination is not public" ? "Webhook destination is not public" : error.reason._tag === "InvalidUrlError" ? "Invalid webhook URL" : "Webhook network request failed")), Effect5.scoped) : "Webhook destination is not public";
|
|
585
|
+
if (error === null) {
|
|
586
|
+
yield* sql`UPDATE webhook_deliveries SET status = 'success', error = NULL, completed_at = now(), updated_at = now() WHERE id = ${input.id}`;
|
|
587
|
+
return null;
|
|
588
|
+
}
|
|
589
|
+
if (delivery.retries + 1 >= maxDeliveryAttempts) {
|
|
590
|
+
yield* sql`UPDATE webhook_deliveries SET status = 'failed', error = ${error}, retries = retries + 1, completed_at = now(), updated_at = now() WHERE id = ${input.id}`;
|
|
591
|
+
return null;
|
|
592
|
+
}
|
|
593
|
+
const step = yield* Schedule.toStep(retrySchedule);
|
|
594
|
+
let duration = Duration.zero;
|
|
595
|
+
for (let attempt = 0;attempt <= delivery.retries; attempt++) {
|
|
596
|
+
const [, delay] = yield* step(DateTime3.toEpochMillis(now), undefined).pipe(Effect5.orDie);
|
|
597
|
+
duration = delay;
|
|
598
|
+
}
|
|
599
|
+
const delay = Duration.toMillis(duration);
|
|
600
|
+
yield* sql`UPDATE webhook_deliveries SET retries = retries + 1, error = ${error}, retry_at = now() + ${delay} * interval '1 millisecond', updated_at = now() WHERE id = ${input.id}`;
|
|
601
|
+
return delay;
|
|
602
|
+
});
|
|
603
|
+
var DeliverWebhookV1 = Workflow.make("KrakstackDeliverWebhookV1", {
|
|
604
|
+
payload: { organizationId: Schema4.String, id: Schema4.String },
|
|
605
|
+
success: Schema4.Void,
|
|
606
|
+
error: WebhookError,
|
|
607
|
+
idempotencyKey: ({ organizationId, id }) => `${organizationId}:${id}`
|
|
608
|
+
});
|
|
609
|
+
var workflowLayer = DeliverWebhookV1.toLayer((input) => Effect5.gen(function* () {
|
|
610
|
+
for (let step = 0;; step++) {
|
|
611
|
+
const wait = yield* Activity.make({
|
|
612
|
+
name: `DeliverWebhookAttemptV1-${step}`,
|
|
613
|
+
success: Schema4.NullOr(Schema4.Number),
|
|
614
|
+
error: WebhookError,
|
|
615
|
+
execute: processDelivery(input).pipe(Effect5.mapError(() => new WebhookError({
|
|
616
|
+
message: "Webhook delivery persistence failed"
|
|
617
|
+
})), Effect5.tapError(() => Effect5.logError("Webhook delivery persistence failed")), Effect5.retry(Schedule.spaced("5 seconds")))
|
|
618
|
+
});
|
|
619
|
+
if (wait === null)
|
|
620
|
+
return;
|
|
621
|
+
yield* DurableClock.sleep({
|
|
622
|
+
name: `WebhookRetryV1-${step}`,
|
|
623
|
+
duration: wait,
|
|
624
|
+
inMemoryThreshold: 0
|
|
625
|
+
});
|
|
626
|
+
}
|
|
627
|
+
}));
|
|
628
|
+
var dispatchPending = Effect5.gen(function* () {
|
|
629
|
+
const sql = (yield* SqlClient3.SqlClient).withoutTransforms();
|
|
630
|
+
const pending = yield* SqlSchema2.findAll({
|
|
631
|
+
Request: Schema4.Void,
|
|
632
|
+
Result: Schema4.Struct({
|
|
633
|
+
id: Schema4.String,
|
|
634
|
+
organizationId: Schema4.String
|
|
635
|
+
}).annotate({ identifier: "PendingWebhookDelivery" }),
|
|
636
|
+
execute: () => sql`SELECT d.id, w.organization_id AS "organizationId" FROM webhook_deliveries d JOIN webhooks w ON w.id = d.webhook_id
|
|
637
|
+
WHERE d.status = 'pending' AND d.retry_at <= now() ORDER BY d.retry_at LIMIT 100`
|
|
638
|
+
})();
|
|
639
|
+
yield* Effect5.forEach(pending, (input) => DeliverWebhookV1.execute(input, { discard: true }), { concurrency: 4, discard: true });
|
|
640
|
+
});
|
|
641
|
+
var dispatchLayer = Layer4.effectDiscard(Effect5.repeat(dispatchPending.pipe(Effect5.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect5.interrupt : Effect5.logError("Webhook dispatch failed"))), Schedule.spaced("5 seconds")).pipe(Effect5.forkScoped)).pipe(Layer4.provide(workflowLayer));
|
|
642
|
+
|
|
643
|
+
class Webhooks extends Context3.Service()("krakstack/webhooks/Webhooks", {
|
|
644
|
+
make: Effect5.gen(function* () {
|
|
645
|
+
const sql = (yield* SqlClient3.SqlClient).withoutTransforms();
|
|
646
|
+
const pg = yield* PgClient.PgClient;
|
|
647
|
+
const configuredPayload = webhookPayloadSchema(yield* WebhookAllowLoopback);
|
|
648
|
+
const random = yield* SecureRandom2.SecureRandom.pipe(Effect5.provide(SecureRandom2.layerWebCrypto));
|
|
649
|
+
const list = SqlSchema2.findAll({
|
|
650
|
+
Request: WebhookScope,
|
|
651
|
+
Result: Webhook,
|
|
652
|
+
execute: ({ organizationId }) => sql`SELECT ${sql.literal(webhookColumns)} FROM webhooks WHERE organization_id = ${organizationId} ORDER BY created_at, id`
|
|
653
|
+
});
|
|
654
|
+
const find = SqlSchema2.findOneOption({
|
|
655
|
+
Request: WebhookRequest,
|
|
656
|
+
Result: Webhook,
|
|
657
|
+
execute: ({ organizationId, id }) => sql`SELECT ${sql.literal(webhookColumns)} FROM webhooks WHERE organization_id = ${organizationId} AND id = ${id}`
|
|
658
|
+
});
|
|
659
|
+
const deliveries = SqlSchema2.findAll({
|
|
660
|
+
Request: WebhookRequest,
|
|
661
|
+
Result: WebhookDelivery,
|
|
662
|
+
execute: ({ organizationId, id }) => sql`SELECT ${sql.literal(deliveryColumns)} FROM webhook_deliveries d JOIN webhooks w ON w.id = d.webhook_id WHERE w.organization_id = ${organizationId} AND w.id = ${id} ORDER BY d.created_at DESC LIMIT 100`
|
|
663
|
+
});
|
|
664
|
+
const get = Effect5.fn("Webhooks.get")(function* (input) {
|
|
665
|
+
const found = yield* find(input);
|
|
666
|
+
if (Option3.isNone(found))
|
|
667
|
+
return;
|
|
668
|
+
return { ...found.value, deliveries: yield* deliveries(input) };
|
|
669
|
+
});
|
|
670
|
+
const status = sql`CASE WHEN d.status = 'pending' AND d.retries > 0 THEN 'failed' ELSE d.status END`;
|
|
671
|
+
const listDeliveries = Effect5.fn("Webhooks.listDeliveries")(function* (input) {
|
|
672
|
+
const request = yield* Schema4.decodeUnknownEffect(ListWebhookDeliveries)(input);
|
|
673
|
+
if (Option3.isNone(yield* find(request)))
|
|
674
|
+
return;
|
|
675
|
+
const columns = {
|
|
676
|
+
id: sql`d.id`,
|
|
677
|
+
event: sql`d.event`,
|
|
678
|
+
status,
|
|
679
|
+
createdAt: sql`d.created_at`,
|
|
680
|
+
completedAt: sql`d.completed_at`
|
|
681
|
+
};
|
|
682
|
+
const predicates = yield* Effect5.forEach(request.filters ?? [], (filter) => Effect5.gen(function* () {
|
|
683
|
+
const id = yield* Schema4.decodeUnknownEffect(WebhookDeliverySortId)(filter.id);
|
|
684
|
+
const column = columns[id];
|
|
685
|
+
if (filter.kind === "values")
|
|
686
|
+
return sql`AND ${sql.or(filter.values.map((value) => sql`${column} = ${value}`))}`;
|
|
687
|
+
if (filter.kind === "date")
|
|
688
|
+
return sql`${filter.from ? sql`AND ${column} >= ${filter.from}::timestamp` : sql``}
|
|
689
|
+
${filter.to ? sql`AND ${column} < ${filter.to}::timestamp + interval '1 day'` : sql``}`;
|
|
690
|
+
if (filter.kind === "text") {
|
|
691
|
+
const value = filter.value.toLowerCase();
|
|
692
|
+
if (filter.operator === "equals")
|
|
693
|
+
return sql`AND LOWER(${column}) = ${value}`;
|
|
694
|
+
const escaped = value.replace(/[\\%_]/g, "\\$&");
|
|
695
|
+
const pattern = filter.operator === "startsWith" ? `${escaped}%` : filter.operator === "endsWith" ? `%${escaped}` : `%${escaped}%`;
|
|
696
|
+
return sql`AND LOWER(${column}) LIKE ${pattern} ESCAPE ${"\\"}`;
|
|
697
|
+
}
|
|
698
|
+
return sql``;
|
|
699
|
+
}));
|
|
700
|
+
const search = request.globalFilter?.trim().toLowerCase().replace(/[\\%_]/g, "\\$&");
|
|
701
|
+
const predicate = sql`w.id = ${request.id} AND w.organization_id = ${request.organizationId}
|
|
702
|
+
${sql.join(" ", false)(predicates)}
|
|
703
|
+
${search ? sql`AND LOWER(d.id || ' ' || d.event || ' ' || ${status} || ' ' || COALESCE(d.error, '') || ' ' || d.data::text) LIKE ${`%${search}%`} ESCAPE ${"\\"}` : sql``}`;
|
|
704
|
+
const sorts = yield* Effect5.forEach(request.sort ?? [], (part) => Effect5.gen(function* () {
|
|
705
|
+
const id = yield* Schema4.decodeUnknownEffect(WebhookDeliverySortId)(part.id);
|
|
706
|
+
return sql`${columns[id]} ${sql.literal(part.direction === "desc" ? "DESC" : "ASC")} NULLS LAST`;
|
|
707
|
+
}));
|
|
708
|
+
const count = yield* SqlSchema2.findOne({
|
|
709
|
+
Request: Schema4.Void,
|
|
710
|
+
Result: Schema4.Struct({ total: Schema4.Int }).annotate({
|
|
711
|
+
identifier: "WebhookDeliveryCount"
|
|
712
|
+
}),
|
|
713
|
+
execute: () => sql`SELECT count(*)::int AS total FROM webhook_deliveries d JOIN webhooks w ON w.id = d.webhook_id WHERE ${predicate}`
|
|
714
|
+
})();
|
|
715
|
+
const data = yield* SqlSchema2.findAll({
|
|
716
|
+
Request: Schema4.Void,
|
|
717
|
+
Result: WebhookDelivery,
|
|
718
|
+
execute: () => sql`SELECT ${sql.literal(deliveryColumns)} FROM webhook_deliveries d JOIN webhooks w ON w.id = d.webhook_id
|
|
719
|
+
WHERE ${predicate} ORDER BY ${sql.join(", ", false)(sorts.length ? [...sorts, sql`d.id DESC`] : [sql`d.created_at DESC`, sql`d.id DESC`])}
|
|
720
|
+
LIMIT ${request.pageSize} OFFSET ${request.page * request.pageSize}`
|
|
721
|
+
})();
|
|
722
|
+
return {
|
|
723
|
+
data,
|
|
724
|
+
meta: {
|
|
725
|
+
page: request.page,
|
|
726
|
+
pageSize: request.pageSize,
|
|
727
|
+
total: count.total,
|
|
728
|
+
pageCount: Math.ceil(count.total / request.pageSize)
|
|
729
|
+
}
|
|
730
|
+
};
|
|
731
|
+
});
|
|
732
|
+
const statistics = Effect5.fn("Webhooks.statistics")(function* (input) {
|
|
733
|
+
const request = yield* Schema4.decodeUnknownEffect(WebhookStatisticsRequest)(input);
|
|
734
|
+
if (Option3.isNone(yield* find(request)))
|
|
735
|
+
return;
|
|
736
|
+
const totals = yield* SqlSchema2.findOne({
|
|
737
|
+
Request: WebhookRequest,
|
|
738
|
+
Result: WebhookDeliveryCounts,
|
|
739
|
+
execute: ({
|
|
740
|
+
organizationId,
|
|
741
|
+
id
|
|
742
|
+
}) => sql`SELECT count(*)::float8 AS total,
|
|
743
|
+
count(*) FILTER (WHERE d.status = 'success')::float8 AS success,
|
|
744
|
+
count(*) FILTER (WHERE ${status} = 'failed')::float8 AS failed
|
|
745
|
+
FROM webhook_deliveries d JOIN webhooks w ON w.id = d.webhook_id
|
|
746
|
+
WHERE w.id = ${id} AND w.organization_id = ${organizationId}`
|
|
747
|
+
})(request);
|
|
748
|
+
const windows = {
|
|
749
|
+
hour: { start: "day", step: "1 hour" },
|
|
750
|
+
day: { start: "month", step: "1 day" }
|
|
751
|
+
};
|
|
752
|
+
const window = windows[request.interval];
|
|
753
|
+
const buckets = yield* SqlSchema2.findAll({
|
|
754
|
+
Request: WebhookStatisticsRequest,
|
|
755
|
+
Result: WebhookDeliveryBucket,
|
|
756
|
+
execute: ({ organizationId, id, interval }) => sql`WITH bounds AS (
|
|
757
|
+
SELECT date_trunc(${window.start}, now() AT TIME ZONE 'UTC') AS start,
|
|
758
|
+
date_trunc(${interval}, now() AT TIME ZONE 'UTC') AS finish, ${window.step}::interval AS step
|
|
759
|
+
), buckets AS (
|
|
760
|
+
SELECT generate_series(start, finish, step) AS bucket, step FROM bounds
|
|
761
|
+
), scoped AS (
|
|
762
|
+
SELECT d.id, d.event, ${status} AS status, d.created_at FROM webhook_deliveries d JOIN webhooks w ON w.id = d.webhook_id
|
|
763
|
+
WHERE w.id = ${id} AND w.organization_id = ${organizationId}
|
|
764
|
+
AND d.created_at >= (SELECT min(bucket) FROM buckets)
|
|
765
|
+
), counts AS (SELECT b.bucket, d.event, count(d.id)::float8 AS total,
|
|
766
|
+
count(d.id) FILTER (WHERE d.status = 'success')::float8 AS success,
|
|
767
|
+
count(d.id) FILTER (WHERE d.status = 'failed')::float8 AS failed
|
|
768
|
+
FROM buckets b LEFT JOIN scoped d ON d.created_at >= b.bucket AND d.created_at < b.bucket + b.step
|
|
769
|
+
GROUP BY b.bucket, d.event)
|
|
770
|
+
SELECT bucket, sum(total)::float8 AS total, sum(success)::float8 AS success, sum(failed)::float8 AS failed,
|
|
771
|
+
COALESCE(jsonb_agg(jsonb_build_object('event', event, 'total', total) ORDER BY event)
|
|
772
|
+
FILTER (WHERE event IS NOT NULL), '[]'::jsonb) AS events
|
|
773
|
+
FROM counts GROUP BY bucket ORDER BY bucket`
|
|
774
|
+
})(request);
|
|
775
|
+
return { ...totals, buckets };
|
|
776
|
+
});
|
|
777
|
+
const create = Effect5.fn("Webhooks.create")(function* (input) {
|
|
778
|
+
const { organizationId } = yield* Schema4.decodeUnknownEffect(WebhookScope)(input);
|
|
779
|
+
const payload = yield* Schema4.decodeUnknownEffect(configuredPayload)(input.payload);
|
|
780
|
+
const id = yield* random.uuidV7();
|
|
781
|
+
const secret = Hex2.encode(yield* random.randomBytes(32));
|
|
782
|
+
yield* sql`INSERT INTO webhooks (id, organization_id, name, url, description, enabled, events, headers, secret)
|
|
783
|
+
VALUES (${id}, ${organizationId}, ${payload.name ?? payload.url}, ${payload.url}, ${payload.description}, ${payload.enabled},
|
|
784
|
+
${payload.events === null ? null : pg.json(payload.events)}, ${payload.customHeaders === null ? null : pg.json(payload.customHeaders)}, ${secret})`;
|
|
785
|
+
return { id };
|
|
786
|
+
});
|
|
787
|
+
const update = Effect5.fn("Webhooks.update")(function* (input) {
|
|
788
|
+
const { organizationId, id } = yield* Schema4.decodeUnknownEffect(WebhookRequest)(input);
|
|
789
|
+
const payload = yield* Schema4.decodeUnknownEffect(configuredPayload)(input.payload);
|
|
790
|
+
return yield* SqlSchema2.findOneOption({
|
|
791
|
+
Request: Schema4.Void,
|
|
792
|
+
Result: Webhook,
|
|
793
|
+
execute: () => sql`UPDATE webhooks SET name = COALESCE(${payload.name ?? null}, name), url = ${payload.url}, description = ${payload.description}, enabled = ${payload.enabled},
|
|
794
|
+
events = ${payload.events === null ? null : pg.json(payload.events)}, headers = ${payload.customHeaders === null ? null : pg.json(payload.customHeaders)}, updated_at = now()
|
|
795
|
+
WHERE organization_id = ${organizationId} AND id = ${id} RETURNING ${sql.literal(webhookColumns)}`
|
|
796
|
+
})().pipe(Effect5.map(Option3.getOrNull));
|
|
797
|
+
});
|
|
798
|
+
const remove = Effect5.fn("Webhooks.delete")(function* (input) {
|
|
799
|
+
const { organizationId, id } = yield* Schema4.decodeUnknownEffect(WebhookRequest)(input);
|
|
800
|
+
const rows = yield* sql`DELETE FROM webhooks WHERE organization_id = ${organizationId} AND id = ${id} RETURNING id`;
|
|
801
|
+
return rows.length ? { success: true } : null;
|
|
802
|
+
});
|
|
803
|
+
const publish = Effect5.fn("Webhooks.publish")(function* (input) {
|
|
804
|
+
const { organizationId, eventId, event, data } = yield* Schema4.decodeUnknownEffect(PublishWebhook)(input);
|
|
805
|
+
const inserted = yield* sql`INSERT INTO webhook_publications (organization_id, event_id, event, data)
|
|
806
|
+
VALUES (${organizationId}, ${eventId}, ${event}, ${pg.json(data)}) ON CONFLICT DO NOTHING RETURNING event_id`;
|
|
807
|
+
if (!inserted.length) {
|
|
808
|
+
const match = yield* sql`SELECT event_id FROM webhook_publications WHERE organization_id = ${organizationId}
|
|
809
|
+
AND event_id = ${eventId} AND event = ${event} AND data = ${pg.json(data)}::jsonb`;
|
|
810
|
+
if (!match.length)
|
|
811
|
+
return yield* new WebhookError({
|
|
812
|
+
message: "Webhook event id was reused with different content"
|
|
813
|
+
});
|
|
814
|
+
return;
|
|
815
|
+
}
|
|
816
|
+
const endpoints = yield* list({ organizationId });
|
|
817
|
+
for (const endpoint of endpoints) {
|
|
818
|
+
if (!endpoint.enabled || endpoint.events !== null && !endpoint.events.includes(event))
|
|
819
|
+
continue;
|
|
820
|
+
const id = yield* random.uuidV7();
|
|
821
|
+
yield* sql`INSERT INTO webhook_deliveries (id, webhook_id, event_id, event, data, status, retry_at)
|
|
822
|
+
VALUES (${id}, ${endpoint.id}, ${eventId}, ${event}, ${pg.json(data)}, 'pending', now())`;
|
|
823
|
+
}
|
|
824
|
+
}, sql.withTransaction);
|
|
825
|
+
const cleanup = Effect5.fn("Webhooks.cleanup")(function* () {
|
|
826
|
+
yield* sql`DELETE FROM webhook_deliveries WHERE completed_at <= now() - interval '7 days'`;
|
|
827
|
+
});
|
|
828
|
+
return {
|
|
829
|
+
list,
|
|
830
|
+
get,
|
|
831
|
+
listDeliveries,
|
|
832
|
+
statistics,
|
|
833
|
+
create,
|
|
834
|
+
update,
|
|
835
|
+
delete: remove,
|
|
836
|
+
publish,
|
|
837
|
+
cleanup
|
|
838
|
+
};
|
|
839
|
+
})
|
|
840
|
+
}) {
|
|
841
|
+
static layerWithoutMigrations = Layer4.effect(this, this.make).pipe(Layer4.provide(dispatchLayer));
|
|
842
|
+
static layer = this.layerWithoutMigrations.pipe(Layer4.provide(layer), Layer4.provide(webhookMigrationsLayer));
|
|
843
|
+
}
|
|
844
|
+
export {
|
|
845
|
+
DeliverWebhookV1,
|
|
846
|
+
ListWebhookDeliveries,
|
|
847
|
+
PublishWebhook,
|
|
848
|
+
Webhook,
|
|
849
|
+
WebhookAllowLoopback,
|
|
850
|
+
WebhookDeliveries,
|
|
851
|
+
WebhookDeliveriesQuery,
|
|
852
|
+
WebhookDelivery,
|
|
853
|
+
WebhookDeliveryBucket,
|
|
854
|
+
WebhookDeliveryCounts,
|
|
855
|
+
WebhookDeliverySortId,
|
|
856
|
+
WebhookError,
|
|
857
|
+
WebhookEventCount,
|
|
858
|
+
WebhookName,
|
|
859
|
+
WebhookPayload,
|
|
860
|
+
WebhookReceiptConflict,
|
|
861
|
+
WebhookRequest,
|
|
862
|
+
WebhookScope,
|
|
863
|
+
WebhookStatistics,
|
|
864
|
+
WebhookStatisticsInterval,
|
|
865
|
+
WebhookStatisticsRequest,
|
|
866
|
+
WebhookVerificationError,
|
|
867
|
+
Webhooks,
|
|
868
|
+
WebhooksReceiver,
|
|
869
|
+
deliveryColumns,
|
|
870
|
+
webhookColumns,
|
|
871
|
+
webhookPayloadSchema
|
|
872
|
+
};
|