@krak-stack/registry 0.1.60 → 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.
@@ -3,5 +3,6 @@ import { Dns } from "effect/net";
3
3
  import { HttpClient } from "effect/http";
4
4
  /** DNS preflight. Network egress rules must also prevent DNS rebinding. */
5
5
  export declare const isPublicWebhookDestination: (url: URL) => Effect.Effect<boolean, never, Dns.Dns>;
6
+ export declare const isAllowedWebhookDestination: (url: URL) => Effect.Effect<boolean, never, Dns.Dns>;
6
7
  /** Built-in fetch client with public-destination checks and no redirects. */
7
8
  export declare const layer: Layer.Layer<HttpClient.HttpClient, never, Dns.Dns>;
@@ -4,6 +4,7 @@ import { Dns, NetAddress } from "effect/net";
4
4
  import { FetchHttpClient, HttpClient, HttpClientError } from "effect/http";
5
5
 
6
6
  // ../../src/services/webhooks/url.ts
7
+ import { Context } from "effect";
7
8
  var hostname = (value) => value.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
8
9
  var isPublicIpAddress = (value) => {
9
10
  const address = hostname(value);
@@ -23,6 +24,10 @@ var isPublicWebhookUrl = (url) => {
23
24
  return false;
24
25
  return !(host.includes(":") || /^\d+(?:\.\d+){3}$/.test(host)) || isPublicIpAddress(host);
25
26
  };
27
+ var WebhookAllowLoopback = Context.Reference("Webhooks/AllowLoopback", {
28
+ defaultValue: () => false
29
+ });
30
+ var isLoopbackWebhookUrl = (url) => ["http:", "https:"].includes(url.protocol) && !url.username && !url.password && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
26
31
 
27
32
  // ../../src/services/webhooks/http-client.ts
28
33
  var isPublicWebhookDestination = Effect.fn("Webhooks.isPublicDestination")(function* (url) {
@@ -34,11 +39,17 @@ var isPublicWebhookDestination = Effect.fn("Webhooks.isPublicDestination")(funct
34
39
  const dns = yield* Dns.Dns;
35
40
  return yield* dns.lookup(hostname).pipe(Effect.map((addresses) => addresses.every((address) => isPublicIpAddress(NetAddress.formatIp(address)))), Effect.catch(() => Effect.succeed(false)));
36
41
  });
42
+ var isAllowedWebhookDestination = Effect.fn("Webhooks.isAllowedDestination")(function* (url) {
43
+ if ((yield* WebhookAllowLoopback) && isLoopbackWebhookUrl(url))
44
+ return true;
45
+ return yield* isPublicWebhookDestination(url);
46
+ });
37
47
  var layer = Layer.effect(HttpClient.HttpClient, Effect.gen(function* () {
38
48
  const client = yield* HttpClient.HttpClient;
39
49
  const dns = yield* Dns.Dns;
50
+ const allowLoopback = yield* WebhookAllowLoopback;
40
51
  return client.pipe(HttpClient.transform((response, request) => Effect.gen(function* () {
41
- if (!(yield* isPublicWebhookDestination(new URL(request.url)).pipe(Effect.provideService(Dns.Dns, dns)))) {
52
+ if (!(yield* isAllowedWebhookDestination(new URL(request.url)).pipe(Effect.provideService(Dns.Dns, dns), Effect.provideService(WebhookAllowLoopback, allowLoopback)))) {
42
53
  return yield* new HttpClientError.HttpClientError({
43
54
  reason: new HttpClientError.TransportError({
44
55
  request,
@@ -52,6 +63,7 @@ var layer = Layer.effect(HttpClient.HttpClient, Effect.gen(function* () {
52
63
  })));
53
64
  })).pipe(Layer.provide(FetchHttpClient.layer));
54
65
  export {
66
+ isAllowedWebhookDestination,
55
67
  isPublicWebhookDestination,
56
68
  layer
57
69
  };
@@ -2,8 +2,10 @@ import { Cause, Context, Effect, Layer, Schema } from "effect";
2
2
  import { HttpClient } from "effect/http";
3
3
  import { Workflow } from "effect/workflow";
4
4
  import { SqlClient } from "effect/sql";
5
+ export { WebhookAllowLoopback } from "./url.js";
5
6
  import { WebhookError, WebhookPayload } from "./schema.js";
6
7
  export * from "./schema.js";
8
+ export { WebhooksReceiver, WebhookVerificationError, WebhookReceiptConflict, } from "./receiver.js";
7
9
  export declare const DeliverWebhookV1: Workflow.Workflow<"KrakstackDeliverWebhookV1", Schema.Struct<{
8
10
  organizationId: Schema.String;
9
11
  id: Schema.String;
@@ -2,20 +2,20 @@
2
2
  import { PgClient } from "@effect/sql-pg";
3
3
  import {
4
4
  Cause,
5
- Context,
6
- DateTime as DateTime2,
5
+ Context as Context3,
6
+ DateTime as DateTime3,
7
7
  Duration,
8
- Effect as Effect4,
9
- Layer as Layer3,
10
- Option as Option2,
8
+ Effect as Effect5,
9
+ Layer as Layer4,
10
+ Option as Option3,
11
11
  Schedule,
12
- Schema as Schema3
12
+ Schema as Schema4
13
13
  } from "effect";
14
14
  import { HttpClient as HttpClient2, HttpClientRequest } from "effect/http";
15
15
  import { Activity, DurableClock, Workflow } from "effect/workflow";
16
- import { SqlClient as SqlClient2, SqlSchema } from "effect/sql";
17
- import { Mac, SecureRandom } from "effect/crypto";
18
- import { Hex } from "effect/encoding";
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
19
 
20
20
  // ../../src/services/webhooks/migrations.ts
21
21
  import { Effect, Layer } from "effect";
@@ -56,8 +56,25 @@ var migrateWebhooks = Migrator.make({})({
56
56
  table: "krakstack_webhook_migrations"
57
57
  });
58
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);
59
75
 
60
76
  // ../../src/services/webhooks/url.ts
77
+ import { Context } from "effect";
61
78
  var hostname = (value) => value.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
62
79
  var isPublicIpAddress = (value) => {
63
80
  const address = hostname(value);
@@ -84,7 +101,18 @@ var isPublicWebhookUrlString = (value) => {
84
101
  return false;
85
102
  }
86
103
  };
87
-
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);
88
116
  // ../../src/services/webhooks/http-client.ts
89
117
  import { Effect as Effect2, Layer as Layer2, Result } from "effect";
90
118
  import { Dns, NetAddress } from "effect/net";
@@ -98,11 +126,17 @@ var isPublicWebhookDestination = Effect2.fn("Webhooks.isPublicDestination")(func
98
126
  const dns = yield* Dns.Dns;
99
127
  return yield* dns.lookup(hostname).pipe(Effect2.map((addresses) => addresses.every((address) => isPublicIpAddress(NetAddress.formatIp(address)))), Effect2.catch(() => Effect2.succeed(false)));
100
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
+ });
101
134
  var layer = Layer2.effect(HttpClient.HttpClient, Effect2.gen(function* () {
102
135
  const client = yield* HttpClient.HttpClient;
103
136
  const dns = yield* Dns.Dns;
137
+ const allowLoopback = yield* WebhookAllowLoopback;
104
138
  return client.pipe(HttpClient.transform((response, request) => Effect2.gen(function* () {
105
- if (!(yield* isPublicWebhookDestination(new URL(request.url)).pipe(Effect2.provideService(Dns.Dns, dns)))) {
139
+ if (!(yield* isAllowedWebhookDestination(new URL(request.url)).pipe(Effect2.provideService(Dns.Dns, dns), Effect2.provideService(WebhookAllowLoopback, allowLoopback)))) {
106
140
  return yield* new HttpClientError.HttpClientError({
107
141
  reason: new HttpClientError.TransportError({
108
142
  request,
@@ -342,6 +376,12 @@ var WebhookPayload = Schema2.Struct({
342
376
  "webhook-signature"
343
377
  ].includes(name.toLowerCase())), { expected: "headers that do not override webhook protocol headers" }))
344
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" });
345
385
  var Webhook = Schema2.Struct({
346
386
  id: Schema2.String,
347
387
  name: Schema2.String,
@@ -399,6 +439,94 @@ class WebhookError extends Schema2.TaggedError()("WebhookError", {
399
439
  message: Schema2.String
400
440
  }) {
401
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
+ }
402
530
 
403
531
  // ../../src/services/webhooks/index.ts
404
532
  var maxDeliveryAttempts = 8;
@@ -406,10 +534,10 @@ var retrySchedule = Schedule.min([
406
534
  Schedule.exponential("5 seconds", 4),
407
535
  Schedule.spaced("10 hours")
408
536
  ]);
409
- var processDelivery = Effect4.fn("Webhooks.processDelivery")(function* (input) {
410
- const sql = (yield* SqlClient2.SqlClient).withoutTransforms();
537
+ var processDelivery = Effect5.fn("Webhooks.processDelivery")(function* (input) {
538
+ const sql = (yield* SqlClient3.SqlClient).withoutTransforms();
411
539
  const client = yield* HttpClient2.HttpClient;
412
- const row = yield* SqlSchema.findOneOption({
540
+ const row = yield* SqlSchema2.findOneOption({
413
541
  Request: WebhookRequest,
414
542
  Result: WebhookDelivery,
415
543
  execute: ({
@@ -418,19 +546,19 @@ var processDelivery = Effect4.fn("Webhooks.processDelivery")(function* (input) {
418
546
  }) => sql`SELECT ${sql.literal(deliveryColumns)} FROM webhook_deliveries d JOIN webhooks w ON w.id = d.webhook_id
419
547
  WHERE d.id = ${id} AND w.organization_id = ${organizationId}`
420
548
  })(input);
421
- if (Option2.isNone(row) || row.value.status !== "pending")
549
+ if (Option3.isNone(row) || row.value.status !== "pending")
422
550
  return null;
423
551
  const delivery = row.value;
424
- const now = yield* DateTime2.now;
425
- const remaining = delivery.retryAt.getTime() - DateTime2.toEpochMillis(now);
552
+ const now = yield* DateTime3.now;
553
+ const remaining = delivery.retryAt.getTime() - DateTime3.toEpochMillis(now);
426
554
  if (remaining > 0)
427
555
  return remaining;
428
- const found = yield* SqlSchema.findOneOption({
556
+ const found = yield* SqlSchema2.findOneOption({
429
557
  Request: WebhookRequest,
430
558
  Result: Webhook,
431
559
  execute: ({ organizationId, id }) => sql`SELECT ${sql.literal(webhookColumns)} FROM webhooks WHERE organization_id = ${organizationId} AND id = ${id}`
432
560
  })({ organizationId: input.organizationId, id: delivery.webhookId });
433
- if (Option2.isNone(found))
561
+ if (Option3.isNone(found))
434
562
  return null;
435
563
  const endpoint = found.value;
436
564
  if (!endpoint.enabled || delivery.retries >= maxDeliveryAttempts) {
@@ -438,21 +566,22 @@ var processDelivery = Effect4.fn("Webhooks.processDelivery")(function* (input) {
438
566
  yield* sql`UPDATE webhook_deliveries SET status = 'failed', error = ${error}, completed_at = now(), updated_at = now() WHERE id = ${input.id}`;
439
567
  return null;
440
568
  }
441
- const body = yield* Schema3.encodeEffect(Schema3.fromJsonString(Schema3.Json))({
569
+ const body = yield* Schema4.encodeEffect(Schema4.fromJsonString(Schema4.Json))({
442
570
  event: delivery.event,
443
571
  data: delivery.data
444
572
  });
445
- const timestamp = DateTime2.formatIso(now);
446
- const mac = yield* Mac.Mac.pipe(Effect4.provide(Mac.layerWebCrypto.pipe(Layer3.provide(SecureRandom.layerWebCrypto))));
447
- const key = yield* Mac.key(Mac.hmacSha256, new TextEncoder().encode(endpoint.secret));
448
- const signature = Hex.encode(yield* mac.sign(key, new TextEncoder().encode(`${timestamp}.${body}`)));
449
- const error = isPublicWebhookUrlString(endpoint.url) ? yield* client.execute(HttpClientRequest.post(endpoint.url).pipe(HttpClientRequest.setHeaders({
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({
450
579
  ...endpoint.headers,
451
580
  "Content-Type": "application/json",
452
581
  "webhook-id": delivery.id,
453
582
  "webhook-timestamp": timestamp,
454
583
  "webhook-signature": signature
455
- }), HttpClientRequest.bodyText(body, "application/json"))).pipe(Effect4.map((response) => response.status >= 200 && response.status < 300 ? null : `HTTP ${response.status}`), Effect4.timeout("30 seconds"), Effect4.catch((error) => Effect4.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")), Effect4.scoped) : "Webhook destination is not public";
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";
456
585
  if (error === null) {
457
586
  yield* sql`UPDATE webhook_deliveries SET status = 'success', error = NULL, completed_at = now(), updated_at = now() WHERE id = ${input.id}`;
458
587
  return null;
@@ -464,7 +593,7 @@ var processDelivery = Effect4.fn("Webhooks.processDelivery")(function* (input) {
464
593
  const step = yield* Schedule.toStep(retrySchedule);
465
594
  let duration = Duration.zero;
466
595
  for (let attempt = 0;attempt <= delivery.retries; attempt++) {
467
- const [, delay] = yield* step(DateTime2.toEpochMillis(now), undefined).pipe(Effect4.orDie);
596
+ const [, delay] = yield* step(DateTime3.toEpochMillis(now), undefined).pipe(Effect5.orDie);
468
597
  duration = delay;
469
598
  }
470
599
  const delay = Duration.toMillis(duration);
@@ -472,20 +601,20 @@ var processDelivery = Effect4.fn("Webhooks.processDelivery")(function* (input) {
472
601
  return delay;
473
602
  });
474
603
  var DeliverWebhookV1 = Workflow.make("KrakstackDeliverWebhookV1", {
475
- payload: { organizationId: Schema3.String, id: Schema3.String },
476
- success: Schema3.Void,
604
+ payload: { organizationId: Schema4.String, id: Schema4.String },
605
+ success: Schema4.Void,
477
606
  error: WebhookError,
478
607
  idempotencyKey: ({ organizationId, id }) => `${organizationId}:${id}`
479
608
  });
480
- var workflowLayer = DeliverWebhookV1.toLayer((input) => Effect4.gen(function* () {
609
+ var workflowLayer = DeliverWebhookV1.toLayer((input) => Effect5.gen(function* () {
481
610
  for (let step = 0;; step++) {
482
611
  const wait = yield* Activity.make({
483
612
  name: `DeliverWebhookAttemptV1-${step}`,
484
- success: Schema3.NullOr(Schema3.Number),
613
+ success: Schema4.NullOr(Schema4.Number),
485
614
  error: WebhookError,
486
- execute: processDelivery(input).pipe(Effect4.mapError(() => new WebhookError({
615
+ execute: processDelivery(input).pipe(Effect5.mapError(() => new WebhookError({
487
616
  message: "Webhook delivery persistence failed"
488
- })), Effect4.tapError(() => Effect4.logError("Webhook delivery persistence failed")), Effect4.retry(Schedule.spaced("5 seconds")))
617
+ })), Effect5.tapError(() => Effect5.logError("Webhook delivery persistence failed")), Effect5.retry(Schedule.spaced("5 seconds")))
489
618
  });
490
619
  if (wait === null)
491
620
  return;
@@ -496,51 +625,52 @@ var workflowLayer = DeliverWebhookV1.toLayer((input) => Effect4.gen(function* ()
496
625
  });
497
626
  }
498
627
  }));
499
- var dispatchPending = Effect4.gen(function* () {
500
- const sql = (yield* SqlClient2.SqlClient).withoutTransforms();
501
- const pending = yield* SqlSchema.findAll({
502
- Request: Schema3.Void,
503
- Result: Schema3.Struct({
504
- id: Schema3.String,
505
- organizationId: Schema3.String
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
506
635
  }).annotate({ identifier: "PendingWebhookDelivery" }),
507
636
  execute: () => sql`SELECT d.id, w.organization_id AS "organizationId" FROM webhook_deliveries d JOIN webhooks w ON w.id = d.webhook_id
508
637
  WHERE d.status = 'pending' AND d.retry_at <= now() ORDER BY d.retry_at LIMIT 100`
509
638
  })();
510
- yield* Effect4.forEach(pending, (input) => DeliverWebhookV1.execute(input, { discard: true }), { concurrency: 4, discard: true });
639
+ yield* Effect5.forEach(pending, (input) => DeliverWebhookV1.execute(input, { discard: true }), { concurrency: 4, discard: true });
511
640
  });
512
- var dispatchLayer = Layer3.effectDiscard(Effect4.repeat(dispatchPending.pipe(Effect4.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect4.interrupt : Effect4.logError("Webhook dispatch failed"))), Schedule.spaced("5 seconds")).pipe(Effect4.forkScoped)).pipe(Layer3.provide(workflowLayer));
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));
513
642
 
514
- class Webhooks extends Context.Service()("krakstack/webhooks/Webhooks", {
515
- make: Effect4.gen(function* () {
516
- const sql = (yield* SqlClient2.SqlClient).withoutTransforms();
643
+ class Webhooks extends Context3.Service()("krakstack/webhooks/Webhooks", {
644
+ make: Effect5.gen(function* () {
645
+ const sql = (yield* SqlClient3.SqlClient).withoutTransforms();
517
646
  const pg = yield* PgClient.PgClient;
518
- const random = yield* SecureRandom.SecureRandom.pipe(Effect4.provide(SecureRandom.layerWebCrypto));
519
- const list = SqlSchema.findAll({
647
+ const configuredPayload = webhookPayloadSchema(yield* WebhookAllowLoopback);
648
+ const random = yield* SecureRandom2.SecureRandom.pipe(Effect5.provide(SecureRandom2.layerWebCrypto));
649
+ const list = SqlSchema2.findAll({
520
650
  Request: WebhookScope,
521
651
  Result: Webhook,
522
652
  execute: ({ organizationId }) => sql`SELECT ${sql.literal(webhookColumns)} FROM webhooks WHERE organization_id = ${organizationId} ORDER BY created_at, id`
523
653
  });
524
- const find = SqlSchema.findOneOption({
654
+ const find = SqlSchema2.findOneOption({
525
655
  Request: WebhookRequest,
526
656
  Result: Webhook,
527
657
  execute: ({ organizationId, id }) => sql`SELECT ${sql.literal(webhookColumns)} FROM webhooks WHERE organization_id = ${organizationId} AND id = ${id}`
528
658
  });
529
- const deliveries = SqlSchema.findAll({
659
+ const deliveries = SqlSchema2.findAll({
530
660
  Request: WebhookRequest,
531
661
  Result: WebhookDelivery,
532
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`
533
663
  });
534
- const get = Effect4.fn("Webhooks.get")(function* (input) {
664
+ const get = Effect5.fn("Webhooks.get")(function* (input) {
535
665
  const found = yield* find(input);
536
- if (Option2.isNone(found))
666
+ if (Option3.isNone(found))
537
667
  return;
538
668
  return { ...found.value, deliveries: yield* deliveries(input) };
539
669
  });
540
670
  const status = sql`CASE WHEN d.status = 'pending' AND d.retries > 0 THEN 'failed' ELSE d.status END`;
541
- const listDeliveries = Effect4.fn("Webhooks.listDeliveries")(function* (input) {
542
- const request = yield* Schema3.decodeUnknownEffect(ListWebhookDeliveries)(input);
543
- if (Option2.isNone(yield* find(request)))
671
+ const listDeliveries = Effect5.fn("Webhooks.listDeliveries")(function* (input) {
672
+ const request = yield* Schema4.decodeUnknownEffect(ListWebhookDeliveries)(input);
673
+ if (Option3.isNone(yield* find(request)))
544
674
  return;
545
675
  const columns = {
546
676
  id: sql`d.id`,
@@ -549,8 +679,8 @@ class Webhooks extends Context.Service()("krakstack/webhooks/Webhooks", {
549
679
  createdAt: sql`d.created_at`,
550
680
  completedAt: sql`d.completed_at`
551
681
  };
552
- const predicates = yield* Effect4.forEach(request.filters ?? [], (filter) => Effect4.gen(function* () {
553
- const id = yield* Schema3.decodeUnknownEffect(WebhookDeliverySortId)(filter.id);
682
+ const predicates = yield* Effect5.forEach(request.filters ?? [], (filter) => Effect5.gen(function* () {
683
+ const id = yield* Schema4.decodeUnknownEffect(WebhookDeliverySortId)(filter.id);
554
684
  const column = columns[id];
555
685
  if (filter.kind === "values")
556
686
  return sql`AND ${sql.or(filter.values.map((value) => sql`${column} = ${value}`))}`;
@@ -571,19 +701,19 @@ class Webhooks extends Context.Service()("krakstack/webhooks/Webhooks", {
571
701
  const predicate = sql`w.id = ${request.id} AND w.organization_id = ${request.organizationId}
572
702
  ${sql.join(" ", false)(predicates)}
573
703
  ${search ? sql`AND LOWER(d.id || ' ' || d.event || ' ' || ${status} || ' ' || COALESCE(d.error, '') || ' ' || d.data::text) LIKE ${`%${search}%`} ESCAPE ${"\\"}` : sql``}`;
574
- const sorts = yield* Effect4.forEach(request.sort ?? [], (part) => Effect4.gen(function* () {
575
- const id = yield* Schema3.decodeUnknownEffect(WebhookDeliverySortId)(part.id);
704
+ const sorts = yield* Effect5.forEach(request.sort ?? [], (part) => Effect5.gen(function* () {
705
+ const id = yield* Schema4.decodeUnknownEffect(WebhookDeliverySortId)(part.id);
576
706
  return sql`${columns[id]} ${sql.literal(part.direction === "desc" ? "DESC" : "ASC")} NULLS LAST`;
577
707
  }));
578
- const count = yield* SqlSchema.findOne({
579
- Request: Schema3.Void,
580
- Result: Schema3.Struct({ total: Schema3.Int }).annotate({
708
+ const count = yield* SqlSchema2.findOne({
709
+ Request: Schema4.Void,
710
+ Result: Schema4.Struct({ total: Schema4.Int }).annotate({
581
711
  identifier: "WebhookDeliveryCount"
582
712
  }),
583
713
  execute: () => sql`SELECT count(*)::int AS total FROM webhook_deliveries d JOIN webhooks w ON w.id = d.webhook_id WHERE ${predicate}`
584
714
  })();
585
- const data = yield* SqlSchema.findAll({
586
- Request: Schema3.Void,
715
+ const data = yield* SqlSchema2.findAll({
716
+ Request: Schema4.Void,
587
717
  Result: WebhookDelivery,
588
718
  execute: () => sql`SELECT ${sql.literal(deliveryColumns)} FROM webhook_deliveries d JOIN webhooks w ON w.id = d.webhook_id
589
719
  WHERE ${predicate} ORDER BY ${sql.join(", ", false)(sorts.length ? [...sorts, sql`d.id DESC`] : [sql`d.created_at DESC`, sql`d.id DESC`])}
@@ -599,11 +729,11 @@ class Webhooks extends Context.Service()("krakstack/webhooks/Webhooks", {
599
729
  }
600
730
  };
601
731
  });
602
- const statistics = Effect4.fn("Webhooks.statistics")(function* (input) {
603
- const request = yield* Schema3.decodeUnknownEffect(WebhookStatisticsRequest)(input);
604
- if (Option2.isNone(yield* find(request)))
732
+ const statistics = Effect5.fn("Webhooks.statistics")(function* (input) {
733
+ const request = yield* Schema4.decodeUnknownEffect(WebhookStatisticsRequest)(input);
734
+ if (Option3.isNone(yield* find(request)))
605
735
  return;
606
- const totals = yield* SqlSchema.findOne({
736
+ const totals = yield* SqlSchema2.findOne({
607
737
  Request: WebhookRequest,
608
738
  Result: WebhookDeliveryCounts,
609
739
  execute: ({
@@ -620,7 +750,7 @@ class Webhooks extends Context.Service()("krakstack/webhooks/Webhooks", {
620
750
  day: { start: "month", step: "1 day" }
621
751
  };
622
752
  const window = windows[request.interval];
623
- const buckets = yield* SqlSchema.findAll({
753
+ const buckets = yield* SqlSchema2.findAll({
624
754
  Request: WebhookStatisticsRequest,
625
755
  Result: WebhookDeliveryBucket,
626
756
  execute: ({ organizationId, id, interval }) => sql`WITH bounds AS (
@@ -644,34 +774,34 @@ class Webhooks extends Context.Service()("krakstack/webhooks/Webhooks", {
644
774
  })(request);
645
775
  return { ...totals, buckets };
646
776
  });
647
- const create = Effect4.fn("Webhooks.create")(function* (input) {
648
- const { organizationId } = yield* Schema3.decodeUnknownEffect(WebhookScope)(input);
649
- const payload = yield* Schema3.decodeUnknownEffect(WebhookPayload)(input.payload);
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);
650
780
  const id = yield* random.uuidV7();
651
- const secret = Hex.encode(yield* random.randomBytes(32));
781
+ const secret = Hex2.encode(yield* random.randomBytes(32));
652
782
  yield* sql`INSERT INTO webhooks (id, organization_id, name, url, description, enabled, events, headers, secret)
653
783
  VALUES (${id}, ${organizationId}, ${payload.name ?? payload.url}, ${payload.url}, ${payload.description}, ${payload.enabled},
654
784
  ${payload.events === null ? null : pg.json(payload.events)}, ${payload.customHeaders === null ? null : pg.json(payload.customHeaders)}, ${secret})`;
655
785
  return { id };
656
786
  });
657
- const update = Effect4.fn("Webhooks.update")(function* (input) {
658
- const { organizationId, id } = yield* Schema3.decodeUnknownEffect(WebhookRequest)(input);
659
- const payload = yield* Schema3.decodeUnknownEffect(WebhookPayload)(input.payload);
660
- return yield* SqlSchema.findOneOption({
661
- Request: Schema3.Void,
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,
662
792
  Result: Webhook,
663
793
  execute: () => sql`UPDATE webhooks SET name = COALESCE(${payload.name ?? null}, name), url = ${payload.url}, description = ${payload.description}, enabled = ${payload.enabled},
664
794
  events = ${payload.events === null ? null : pg.json(payload.events)}, headers = ${payload.customHeaders === null ? null : pg.json(payload.customHeaders)}, updated_at = now()
665
795
  WHERE organization_id = ${organizationId} AND id = ${id} RETURNING ${sql.literal(webhookColumns)}`
666
- })().pipe(Effect4.map(Option2.getOrNull));
796
+ })().pipe(Effect5.map(Option3.getOrNull));
667
797
  });
668
- const remove = Effect4.fn("Webhooks.delete")(function* (input) {
669
- const { organizationId, id } = yield* Schema3.decodeUnknownEffect(WebhookRequest)(input);
798
+ const remove = Effect5.fn("Webhooks.delete")(function* (input) {
799
+ const { organizationId, id } = yield* Schema4.decodeUnknownEffect(WebhookRequest)(input);
670
800
  const rows = yield* sql`DELETE FROM webhooks WHERE organization_id = ${organizationId} AND id = ${id} RETURNING id`;
671
801
  return rows.length ? { success: true } : null;
672
802
  });
673
- const publish = Effect4.fn("Webhooks.publish")(function* (input) {
674
- const { organizationId, eventId, event, data } = yield* Schema3.decodeUnknownEffect(PublishWebhook)(input);
803
+ const publish = Effect5.fn("Webhooks.publish")(function* (input) {
804
+ const { organizationId, eventId, event, data } = yield* Schema4.decodeUnknownEffect(PublishWebhook)(input);
675
805
  const inserted = yield* sql`INSERT INTO webhook_publications (organization_id, event_id, event, data)
676
806
  VALUES (${organizationId}, ${eventId}, ${event}, ${pg.json(data)}) ON CONFLICT DO NOTHING RETURNING event_id`;
677
807
  if (!inserted.length) {
@@ -692,7 +822,7 @@ class Webhooks extends Context.Service()("krakstack/webhooks/Webhooks", {
692
822
  VALUES (${id}, ${endpoint.id}, ${eventId}, ${event}, ${pg.json(data)}, 'pending', now())`;
693
823
  }
694
824
  }, sql.withTransaction);
695
- const cleanup = Effect4.fn("Webhooks.cleanup")(function* () {
825
+ const cleanup = Effect5.fn("Webhooks.cleanup")(function* () {
696
826
  yield* sql`DELETE FROM webhook_deliveries WHERE completed_at <= now() - interval '7 days'`;
697
827
  });
698
828
  return {
@@ -708,14 +838,15 @@ class Webhooks extends Context.Service()("krakstack/webhooks/Webhooks", {
708
838
  };
709
839
  })
710
840
  }) {
711
- static layerWithoutMigrations = Layer3.effect(this, this.make).pipe(Layer3.provide(dispatchLayer));
712
- static layer = this.layerWithoutMigrations.pipe(Layer3.provide(layer), Layer3.provide(webhookMigrationsLayer));
841
+ static layerWithoutMigrations = Layer4.effect(this, this.make).pipe(Layer4.provide(dispatchLayer));
842
+ static layer = this.layerWithoutMigrations.pipe(Layer4.provide(layer), Layer4.provide(webhookMigrationsLayer));
713
843
  }
714
844
  export {
715
845
  DeliverWebhookV1,
716
846
  ListWebhookDeliveries,
717
847
  PublishWebhook,
718
848
  Webhook,
849
+ WebhookAllowLoopback,
719
850
  WebhookDeliveries,
720
851
  WebhookDeliveriesQuery,
721
852
  WebhookDelivery,
@@ -726,12 +857,16 @@ export {
726
857
  WebhookEventCount,
727
858
  WebhookName,
728
859
  WebhookPayload,
860
+ WebhookReceiptConflict,
729
861
  WebhookRequest,
730
862
  WebhookScope,
731
863
  WebhookStatistics,
732
864
  WebhookStatisticsInterval,
733
865
  WebhookStatisticsRequest,
866
+ WebhookVerificationError,
734
867
  Webhooks,
868
+ WebhooksReceiver,
735
869
  deliveryColumns,
736
- webhookColumns
870
+ webhookColumns,
871
+ webhookPayloadSchema
737
872
  };
@@ -3,3 +3,6 @@ import { Migrator, SqlClient } from "effect/sql";
3
3
  export declare const webhookMigrations: Migrator.Loader<never>;
4
4
  export declare const migrateWebhooks: Effect.Effect<readonly (readonly [id: number, name: string])[], Migrator.MigrationError | import("effect/sql/SqlError").SqlError, SqlClient.SqlClient>;
5
5
  export declare const webhookMigrationsLayer: Layer.Layer<never, Migrator.MigrationError | import("effect/sql/SqlError").SqlError, SqlClient.SqlClient>;
6
+ export declare const webhookReceiverMigrations: Migrator.Loader<never>;
7
+ export declare const migrateWebhookReceiver: Effect.Effect<readonly (readonly [id: number, name: string])[], Migrator.MigrationError | import("effect/sql/SqlError").SqlError, SqlClient.SqlClient>;
8
+ export declare const webhookReceiverMigrationsLayer: Layer.Layer<never, Migrator.MigrationError | import("effect/sql/SqlError").SqlError, SqlClient.SqlClient>;
@@ -37,8 +37,27 @@ var migrateWebhooks = Migrator.make({})({
37
37
  table: "krakstack_webhook_migrations"
38
38
  });
39
39
  var webhookMigrationsLayer = Layer.effectDiscard(migrateWebhooks);
40
+ var webhookReceiverMigrations = Migrator.fromRecord({
41
+ "1_webhook_receipts": Effect.gen(function* () {
42
+ const sql = yield* SqlClient.SqlClient;
43
+ yield* sql`CREATE TABLE webhook_receipts (
44
+ receiver text NOT NULL, event_id text NOT NULL, body_hash text NOT NULL,
45
+ completed_at timestamptz NOT NULL DEFAULT now(),
46
+ PRIMARY KEY (receiver, event_id)
47
+ )`;
48
+ yield* sql`CREATE INDEX webhook_receipts_completed ON webhook_receipts (completed_at)`;
49
+ })
50
+ });
51
+ var migrateWebhookReceiver = Migrator.make({})({
52
+ loader: webhookReceiverMigrations,
53
+ table: "krakstack_webhook_receiver_migrations"
54
+ });
55
+ var webhookReceiverMigrationsLayer = Layer.effectDiscard(migrateWebhookReceiver);
40
56
  export {
57
+ migrateWebhookReceiver,
41
58
  migrateWebhooks,
42
59
  webhookMigrations,
43
- webhookMigrationsLayer
60
+ webhookMigrationsLayer,
61
+ webhookReceiverMigrations,
62
+ webhookReceiverMigrationsLayer
44
63
  };