@ordinatio/scheduling 0.2.0 → 0.3.0

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/dist/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,19 +17,34 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
21
31
  var index_exports = {};
22
32
  __export(index_exports, {
33
+ BlockedTargetError: () => BlockedTargetError,
34
+ DEFAULT_BACKOFF_SECONDS: () => DEFAULT_BACKOFF_SECONDS,
35
+ MAX_ENDPOINTS_PER_ORGANIZATION: () => MAX_ENDPOINTS_PER_ORGANIZATION,
23
36
  RECURRING_MAX_OCCURRENCES: () => RECURRING_MAX_OCCURRENCES,
24
37
  SCHEDULING_ERRORS: () => SCHEDULING_ERRORS,
38
+ SIGNATURE_HEADER: () => SIGNATURE_HEADER,
25
39
  SchedulingNotFoundError: () => SchedulingNotFoundError,
26
40
  SchedulingValidationError: () => SchedulingValidationError,
27
41
  USER_DAY_LIMIT: () => USER_DAY_LIMIT,
42
+ WEBHOOK_EVENT_TYPES: () => WEBHOOK_EVENT_TYPES,
43
+ WEBHOOK_TEST_EVENT: () => WEBHOOK_TEST_EVENT,
28
44
  adaptersToCallbacks: () => adaptersToCallbacks,
29
45
  addDateOverride: () => addDateOverride,
30
46
  addTimeBlock: () => addTimeBlock,
47
+ appointmentWebhookData: () => appointmentWebhookData,
31
48
  archiveCalendar: () => archiveCalendar,
32
49
  bookAppointment: () => bookAppointment,
33
50
  buildJitsiUrl: () => buildJitsiUrl,
@@ -42,13 +59,22 @@ __export(index_exports, {
42
59
  checkClockContract: () => checkClockContract,
43
60
  checkNotificationContract: () => checkNotificationContract,
44
61
  checkPaymentContract: () => checkPaymentContract,
62
+ checkWebhookUrl: () => checkWebhookUrl,
45
63
  createAppointmentType: () => createAppointmentType,
46
64
  createCalendar: () => createCalendar,
47
65
  createInMemoryAdapters: () => createInMemoryAdapters,
66
+ createNodeTransport: () => createNodeTransport,
48
67
  createNotificationTemplate: () => createNotificationTemplate,
68
+ createWebhookEndpoint: () => createWebhookEndpoint,
49
69
  deleteCalendar: () => deleteCalendar,
50
70
  deleteNotificationTemplate: () => deleteNotificationTemplate,
71
+ deleteWebhookEndpoint: () => deleteWebhookEndpoint,
72
+ deliverDueWebhooks: () => deliverDueWebhooks,
73
+ enqueueAppointmentWebhook: () => enqueueAppointmentWebhook,
74
+ enqueueReminderSent: () => enqueueReminderSent,
75
+ enqueueWebhookEvent: () => enqueueWebhookEvent,
51
76
  generateOccurrenceDates: () => generateOccurrenceDates,
77
+ generateWebhookSecret: () => generateWebhookSecret,
52
78
  getAppointment: () => getAppointment,
53
79
  getAppointmentDashboard: () => getAppointmentDashboard,
54
80
  getAppointmentType: () => getAppointmentType,
@@ -62,6 +88,7 @@ __export(index_exports, {
62
88
  getNotificationTemplate: () => getNotificationTemplate,
63
89
  getTeamAvailableSlots: () => getTeamAvailableSlots,
64
90
  getUserDayAppointments: () => getUserDayAppointments,
91
+ isPrivateAddress: () => isPrivateAddress,
65
92
  isSlotAvailable: () => isSlotAvailable,
66
93
  isVirtualMeeting: () => isVirtualMeeting,
67
94
  listAppointmentTypes: () => listAppointmentTypes,
@@ -69,6 +96,8 @@ __export(index_exports, {
69
96
  listAvailabilityRules: () => listAvailabilityRules,
70
97
  listCalendars: () => listCalendars,
71
98
  listNotificationTemplates: () => listNotificationTemplates,
99
+ listWebhookDeliveries: () => listWebhookDeliveries,
100
+ listWebhookEndpoints: () => listWebhookEndpoints,
72
101
  localToUTC: () => localToUTC,
73
102
  markNoShow: () => markNoShow,
74
103
  parseTimeLocal: () => parseTimeLocal,
@@ -79,13 +108,17 @@ __export(index_exports, {
79
108
  renderTemplate: () => renderTemplate,
80
109
  rescheduleAppointment: () => rescheduleAppointment,
81
110
  resolveLocation: () => resolveLocation,
111
+ retryWebhookDelivery: () => retryWebhookDelivery,
82
112
  schedError: () => schedError,
83
113
  scheduleNotifications: () => scheduleNotifications,
84
114
  selectCalendarForBooking: () => selectCalendarForBooking,
115
+ sendTestWebhook: () => sendTestWebhook,
85
116
  setWeeklyAvailability: () => setWeeklyAvailability,
117
+ signWebhook: () => signWebhook,
86
118
  updateAppointmentType: () => updateAppointmentType,
87
119
  updateCalendar: () => updateCalendar,
88
120
  updateNotificationTemplate: () => updateNotificationTemplate,
121
+ verifyWebhookSignature: () => verifyWebhookSignature,
89
122
  withCalendarVisibility: () => withCalendarVisibility
90
123
  });
91
124
  module.exports = __toCommonJS(index_exports);
@@ -994,6 +1027,92 @@ var GROUP_SCOPE_ERRORS = {
994
1027
  }
995
1028
  };
996
1029
 
1030
+ // src/errors/registry-webhooks.ts
1031
+ var WEBHOOK_ERRORS = {
1032
+ SCHED_1000: {
1033
+ code: "SCHED_1000",
1034
+ file: "webhooks/endpoints.ts",
1035
+ function: "createWebhookEndpoint",
1036
+ severity: "warning",
1037
+ recoverable: true,
1038
+ description: "The webhook address is not allowed",
1039
+ diagnosis: [
1040
+ "The address must be a full https:// address with no user name or password",
1041
+ "Addresses that point at this machine or a private network are refused",
1042
+ "For local development only, the host can allow insecure targets"
1043
+ ]
1044
+ },
1045
+ SCHED_1001: {
1046
+ code: "SCHED_1001",
1047
+ file: "webhooks/endpoints.ts",
1048
+ function: "createWebhookEndpoint",
1049
+ severity: "warning",
1050
+ recoverable: true,
1051
+ description: "The webhook event list is empty or names an event that does not exist",
1052
+ diagnosis: [
1053
+ 'Send at least one event name, or "*" for every event',
1054
+ "Valid names: appointment.booked, appointment.rescheduled, appointment.cancelled, appointment.no_show, reminder.sent"
1055
+ ]
1056
+ },
1057
+ SCHED_1002: {
1058
+ code: "SCHED_1002",
1059
+ file: "webhooks/endpoints.ts",
1060
+ function: "createWebhookEndpoint",
1061
+ severity: "warning",
1062
+ recoverable: true,
1063
+ description: "The organization already has the maximum number of webhook endpoints",
1064
+ diagnosis: ["Remove an endpoint that is no longer used, then add the new one"]
1065
+ },
1066
+ SCHED_1003: {
1067
+ code: "SCHED_1003",
1068
+ file: "webhooks/endpoints.ts",
1069
+ function: "webhook endpoint lookup",
1070
+ severity: "warning",
1071
+ recoverable: true,
1072
+ description: "Webhook endpoint not found for this organization",
1073
+ diagnosis: [
1074
+ "Check the endpoint id",
1075
+ "The endpoint may belong to another organization or may have been removed"
1076
+ ]
1077
+ },
1078
+ SCHED_1004: {
1079
+ code: "SCHED_1004",
1080
+ file: "webhooks/deliveries.ts",
1081
+ function: "retryWebhookDelivery",
1082
+ severity: "warning",
1083
+ recoverable: true,
1084
+ description: "Webhook delivery not found, or it is not in the dead-letter list",
1085
+ diagnosis: [
1086
+ "Only a delivery that ran out of tries can be retried by hand",
1087
+ "A delivery still waiting for its next try will be sent on its own"
1088
+ ]
1089
+ },
1090
+ SCHED_1005: {
1091
+ code: "SCHED_1005",
1092
+ file: "webhooks/attempt.ts",
1093
+ function: "attemptDelivery",
1094
+ severity: "warning",
1095
+ recoverable: false,
1096
+ description: "The webhook was not sent because its target is not allowed",
1097
+ diagnosis: [
1098
+ "The address, or the address its name resolves to, is on a private or local network",
1099
+ "Remove the endpoint and add one that points at a public address"
1100
+ ]
1101
+ },
1102
+ SCHED_1006: {
1103
+ code: "SCHED_1006",
1104
+ file: "webhooks/enqueue.ts",
1105
+ function: "enqueueWebhookEvent",
1106
+ severity: "error",
1107
+ recoverable: true,
1108
+ description: "A webhook event could not be queued; the booking itself was saved",
1109
+ diagnosis: [
1110
+ "Check that the webhook tables exist (run the package migrations)",
1111
+ "Check the database connection"
1112
+ ]
1113
+ }
1114
+ };
1115
+
997
1116
  // src/errors/registry.ts
998
1117
  var SCHEDULING_ERRORS = {
999
1118
  ...CALENDARS_AVAILABILITY_ERRORS,
@@ -1003,7 +1122,8 @@ var SCHEDULING_ERRORS = {
1003
1122
  ...NOTIFICATION_MANAGE_ERRORS,
1004
1123
  ...RECURRING_MISC_ERRORS,
1005
1124
  ...PUBLIC_DIRECTORY_ERRORS,
1006
- ...GROUP_SCOPE_ERRORS
1125
+ ...GROUP_SCOPE_ERRORS,
1126
+ ...WEBHOOK_ERRORS
1007
1127
  };
1008
1128
 
1009
1129
  // src/errors/diagnostic-error.ts
@@ -2260,6 +2380,126 @@ function buildNotificationContext(appointment, baseUrl) {
2260
2380
  // src/notifications/process-pending-notifications.ts
2261
2381
  var import_crypto = require("crypto");
2262
2382
  var import_client6 = require("@prisma/client");
2383
+
2384
+ // src/webhooks/events.ts
2385
+ var import_node_crypto = require("crypto");
2386
+ var WEBHOOK_EVENT_TYPES = [
2387
+ "appointment.booked",
2388
+ "appointment.rescheduled",
2389
+ "appointment.cancelled",
2390
+ "appointment.no_show",
2391
+ "reminder.sent"
2392
+ ];
2393
+ var WEBHOOK_TEST_EVENT = "webhook.test";
2394
+ var ALL_EVENTS = "*";
2395
+ function isWebhookEventType(value) {
2396
+ return typeof value === "string" && WEBHOOK_EVENT_TYPES.includes(value);
2397
+ }
2398
+ function normalizeEventTypes(input) {
2399
+ if (!Array.isArray(input) || input.length === 0) return null;
2400
+ if (input.includes(ALL_EVENTS)) return input.length === 1 ? [ALL_EVENTS] : null;
2401
+ if (!input.every(isWebhookEventType)) return null;
2402
+ return [...new Set(input)];
2403
+ }
2404
+ function buildEnvelope(args) {
2405
+ return {
2406
+ id: args.eventId ?? `evt_${(0, import_node_crypto.randomUUID)()}`,
2407
+ type: args.type,
2408
+ createdAt: args.now.toISOString(),
2409
+ organizationId: args.organizationId,
2410
+ data: args.data
2411
+ };
2412
+ }
2413
+
2414
+ // src/webhooks/enqueue.ts
2415
+ async function appointmentWebhookData(db, organizationId, appointmentId) {
2416
+ const row = await db.appointment.findUnique({
2417
+ where: { id: appointmentId },
2418
+ select: {
2419
+ id: true,
2420
+ status: true,
2421
+ startTime: true,
2422
+ endTime: true,
2423
+ duration: true,
2424
+ timezone: true,
2425
+ clientName: true,
2426
+ clientEmail: true,
2427
+ clientPhone: true,
2428
+ clientId: true,
2429
+ cancelledAt: true,
2430
+ cancelledBy: true,
2431
+ cancelReason: true,
2432
+ rescheduledFrom: true,
2433
+ rescheduleCount: true,
2434
+ calendarId: true,
2435
+ typeId: true,
2436
+ calendar: { select: { name: true, organizationId: true } },
2437
+ type: { select: { name: true } }
2438
+ }
2439
+ });
2440
+ if (!row || row.calendar.organizationId !== null && row.calendar.organizationId !== organizationId) {
2441
+ return { appointment: { id: appointmentId } };
2442
+ }
2443
+ const { calendar, type, ...rest } = row;
2444
+ return { appointment: { ...rest, calendarName: calendar.name, typeName: type.name } };
2445
+ }
2446
+ async function enqueueWebhookEvent(db, input) {
2447
+ const now = input.now ?? /* @__PURE__ */ new Date();
2448
+ const endpoints = await db.webhookEndpoint.findMany({
2449
+ where: {
2450
+ organizationId: input.organizationId,
2451
+ isActive: true,
2452
+ OR: [{ eventTypes: { has: input.type } }, { eventTypes: { has: ALL_EVENTS } }]
2453
+ },
2454
+ select: { id: true }
2455
+ });
2456
+ if (endpoints.length === 0) return { queued: 0 };
2457
+ const envelope = buildEnvelope({ organizationId: input.organizationId, type: input.type, data: input.data, eventId: input.eventId, now });
2458
+ const body = JSON.stringify(envelope);
2459
+ const created = await db.webhookDelivery.createMany({
2460
+ data: endpoints.map((endpoint) => ({
2461
+ organizationId: input.organizationId,
2462
+ endpointId: endpoint.id,
2463
+ eventId: envelope.id,
2464
+ eventType: input.type,
2465
+ body,
2466
+ nextAttemptAt: now
2467
+ })),
2468
+ skipDuplicates: true
2469
+ });
2470
+ return { queued: created.count };
2471
+ }
2472
+ async function enqueueAppointmentWebhook(db, input) {
2473
+ try {
2474
+ const data = { ...await appointmentWebhookData(db, input.organizationId, input.appointmentId), ...input.extra };
2475
+ await enqueueWebhookEvent(db, { organizationId: input.organizationId, type: input.type, data, eventId: input.eventId });
2476
+ } catch (error) {
2477
+ const diagnostic = schedError("SCHED_1006", { organizationId: input.organizationId, type: input.type, appointmentId: input.appointmentId, error });
2478
+ console.error(`[webhooks] ${diagnostic.ref} could not queue ${input.type}:`, error);
2479
+ }
2480
+ }
2481
+ async function enqueueReminderSent(db, notification) {
2482
+ try {
2483
+ const appointment = await db.appointment.findUnique({
2484
+ where: { id: notification.appointmentId },
2485
+ select: { calendar: { select: { organizationId: true } } }
2486
+ });
2487
+ const organizationId = appointment?.calendar.organizationId;
2488
+ if (!organizationId) return;
2489
+ await enqueueAppointmentWebhook(db, {
2490
+ organizationId,
2491
+ type: "reminder.sent",
2492
+ appointmentId: notification.appointmentId,
2493
+ extra: { reminder: { channel: notification.channel, trigger: notification.trigger } },
2494
+ eventId: `reminder_${notification.id}`
2495
+ });
2496
+ } catch (error) {
2497
+ const diagnostic = schedError("SCHED_1006", { appointmentId: notification.appointmentId, error });
2498
+ console.error(`[webhooks] ${diagnostic.ref} could not queue reminder.sent:`, error);
2499
+ }
2500
+ }
2501
+
2502
+ // src/notifications/process-pending-notifications.ts
2263
2503
  async function processPendingNotifications(db, sender, options) {
2264
2504
  const batchSize = options?.batchSize ?? 20;
2265
2505
  const maxRetries = options?.retry?.maxRetries ?? 3;
@@ -2326,6 +2566,9 @@ async function processPendingNotifications(db, sender, options) {
2326
2566
  data: { status: "SENT", sentAt: /* @__PURE__ */ new Date() }
2327
2567
  });
2328
2568
  sent++;
2569
+ if (options?.webhooks && notification.trigger.startsWith("REMINDER_")) {
2570
+ await enqueueReminderSent(db, notification);
2571
+ }
2329
2572
  }
2330
2573
  } catch (error) {
2331
2574
  const errorMsg = error instanceof Error ? error.message : "Unknown error";
@@ -3119,6 +3362,7 @@ var DASHBOARD_INCLUDE = {
3119
3362
  calendar: { select: { name: true, staffName: true } }
3120
3363
  };
3121
3364
  var PAGE_SIZE = 20;
3365
+ var UPCOMING_LIMIT = 50;
3122
3366
  var DEFAULT_DASHBOARD_TIMEZONE = "America/Detroit";
3123
3367
  function preciseDayEnd(truncatedEnd) {
3124
3368
  return new Date(truncatedEnd.getTime() + 59e3);
@@ -3169,7 +3413,9 @@ async function getAppointmentDashboard(db, query = {}) {
3169
3413
  weekTotal,
3170
3414
  weekCancelled,
3171
3415
  historyAppointments,
3172
- historyTotal
3416
+ historyTotal,
3417
+ upcomingAppointments,
3418
+ upcomingTotal
3173
3419
  ] = await Promise.all([
3174
3420
  db.appointment.findMany({
3175
3421
  where: withCalendarVisibility({
@@ -3206,12 +3452,29 @@ async function getAppointmentDashboard(db, query = {}) {
3206
3452
  skip: (page - 1) * pageSize,
3207
3453
  take: pageSize
3208
3454
  }),
3209
- db.appointment.count({ where: scopedHistoryWhere })
3455
+ db.appointment.count({ where: scopedHistoryWhere }),
3456
+ db.appointment.findMany({
3457
+ where: withCalendarVisibility({
3458
+ startTime: { gt: weekEnd },
3459
+ status: { not: "CANCELLED" }
3460
+ }, visibleCalendarIds),
3461
+ include: DASHBOARD_INCLUDE,
3462
+ orderBy: { startTime: "asc" },
3463
+ take: UPCOMING_LIMIT
3464
+ }),
3465
+ db.appointment.count({
3466
+ where: withCalendarVisibility({
3467
+ startTime: { gt: weekEnd },
3468
+ status: { not: "CANCELLED" }
3469
+ }, visibleCalendarIds)
3470
+ })
3210
3471
  ]);
3211
3472
  return {
3212
3473
  today: todayAppointments.map(mapToDashboardItem),
3213
3474
  week: weekAppointments.map(mapToDashboardItem),
3214
3475
  history: historyAppointments.map(mapToDashboardItem),
3476
+ upcoming: upcomingAppointments.map(mapToDashboardItem),
3477
+ upcomingTotal,
3215
3478
  stats: {
3216
3479
  todayTotal,
3217
3480
  todayConfirmed: todayTotal - todayCancelled,
@@ -3868,16 +4131,413 @@ async function getTeamAvailableSlots(db, query, _getSlots = getAvailableSlots) {
3868
4131
  timezone: query.timezone ?? firstResult?.timezone ?? "UTC"
3869
4132
  };
3870
4133
  }
4134
+
4135
+ // src/webhooks/signature.ts
4136
+ var import_node_crypto2 = require("crypto");
4137
+ var SIGNATURE_HEADER = "x-scheduling-signature";
4138
+ function generateWebhookSecret() {
4139
+ return `whsec_${(0, import_node_crypto2.randomBytes)(32).toString("base64url")}`;
4140
+ }
4141
+ function mac(secret, timestamp, body) {
4142
+ return (0, import_node_crypto2.createHmac)("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
4143
+ }
4144
+ function signWebhook(args) {
4145
+ const timestamp = Math.floor(args.now.getTime() / 1e3);
4146
+ return `t=${timestamp},v1=${mac(args.secret, timestamp, args.body)}`;
4147
+ }
4148
+ function verifyWebhookSignature(args) {
4149
+ if (!args.header) return false;
4150
+ let timestamp = null;
4151
+ const candidates = [];
4152
+ for (const part of args.header.split(",")) {
4153
+ const [key, value] = part.trim().split("=");
4154
+ if (key === "t" && /^\d{1,12}$/.test(value ?? "")) timestamp = Number(value);
4155
+ if (key === "v1" && value) candidates.push(value);
4156
+ }
4157
+ if (timestamp === null || candidates.length === 0) return false;
4158
+ const tolerance = args.toleranceSeconds ?? 300;
4159
+ const nowSeconds = Math.floor((args.now ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
4160
+ if (Math.abs(nowSeconds - timestamp) > tolerance) return false;
4161
+ const expected = Buffer.from(mac(args.secret, timestamp, args.body), "hex");
4162
+ return candidates.some((candidate) => {
4163
+ const given = Buffer.from(candidate, "hex");
4164
+ return given.length === expected.length && (0, import_node_crypto2.timingSafeEqual)(given, expected);
4165
+ });
4166
+ }
4167
+
4168
+ // src/webhooks/url-policy.ts
4169
+ var import_node_net = require("net");
4170
+ function v4Parts(ip) {
4171
+ return ip.split(".").map(Number);
4172
+ }
4173
+ function isPrivateV4(ip) {
4174
+ const [a, b, c] = v4Parts(ip);
4175
+ 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 && c === 0 || a === 192 && b === 168 || a === 198 && (b === 18 || b === 19) || a >= 224;
4176
+ }
4177
+ function v6Groups(ip) {
4178
+ let text = ip.toLowerCase().replace(/^\[|\]$/g, "").split("%")[0];
4179
+ const tail = /(\d+\.\d+\.\d+\.\d+)$/.exec(text);
4180
+ if (tail) {
4181
+ const [a, b, c, d] = v4Parts(tail[1]);
4182
+ text = text.slice(0, -tail[1].length) + (a << 8 | b).toString(16) + ":" + (c << 8 | d).toString(16);
4183
+ }
4184
+ const halves = text.split("::");
4185
+ if (halves.length > 2) return null;
4186
+ const head = halves[0] ? halves[0].split(":") : [];
4187
+ const rest = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
4188
+ const missing = 8 - head.length - rest.length;
4189
+ if (halves.length === 1 ? missing !== 0 : missing < 1) return null;
4190
+ const groups = [...head, ...Array(halves.length === 2 ? missing : 0).fill("0"), ...rest].map((g) => parseInt(g, 16));
4191
+ return groups.length === 8 && groups.every((g) => Number.isInteger(g) && g >= 0 && g <= 65535) ? groups : null;
4192
+ }
4193
+ function isPrivateV6(ip) {
4194
+ const g = v6Groups(ip);
4195
+ if (!g) return true;
4196
+ const allZeroUpTo = (n) => g.slice(0, n).every((x) => x === 0);
4197
+ if (allZeroUpTo(7) && g[7] <= 1) return true;
4198
+ if (allZeroUpTo(5) && g[5] === 65535) return isPrivateV4(`${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`);
4199
+ if (allZeroUpTo(6)) return isPrivateV4(`${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`);
4200
+ if (g[0] === 100 && g[1] === 65435) return isPrivateV4(`${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`);
4201
+ return (g[0] & 65024) === 64512 || (g[0] & 65472) === 65152 || (g[0] & 65280) === 65280;
4202
+ }
4203
+ function isPrivateAddress(ip) {
4204
+ const bare = ip.replace(/^\[|\]$/g, "");
4205
+ const kind = (0, import_node_net.isIP)(bare);
4206
+ if (kind === 4) return isPrivateV4(bare);
4207
+ if (kind === 6) return isPrivateV6(bare);
4208
+ return true;
4209
+ }
4210
+ var LOCAL_NAME = /(^|\.)(localhost|local|internal|localdomain|home\.arpa)$/;
4211
+ function checkWebhookUrl(raw, options = {}) {
4212
+ let url;
4213
+ try {
4214
+ url = new URL(raw);
4215
+ } catch {
4216
+ return { ok: false, reason: "The address is not a valid web address" };
4217
+ }
4218
+ const insecure = options.allowInsecureTargets === true;
4219
+ if (url.protocol !== "https:" && !(insecure && url.protocol === "http:")) {
4220
+ return { ok: false, reason: "The address must start with https://" };
4221
+ }
4222
+ if (url.username || url.password) {
4223
+ return { ok: false, reason: "The address must not contain a user name or password" };
4224
+ }
4225
+ if (!insecure) {
4226
+ const host = url.hostname.replace(/^\[|\]$/g, "").replace(/\.$/, "");
4227
+ if (LOCAL_NAME.test(host.toLowerCase()) || (0, import_node_net.isIP)(host) !== 0 && isPrivateAddress(host)) {
4228
+ return { ok: false, reason: "The address points at a private or local network" };
4229
+ }
4230
+ if (!host.includes(".") && (0, import_node_net.isIP)(host) === 0) {
4231
+ return { ok: false, reason: "The address must be a public name with a domain" };
4232
+ }
4233
+ }
4234
+ return { ok: true, url };
4235
+ }
4236
+
4237
+ // src/webhooks/transport.ts
4238
+ var import_node_dns = __toESM(require("dns"));
4239
+ var import_node_http = __toESM(require("http"));
4240
+ var import_node_https = __toESM(require("https"));
4241
+ var BlockedTargetError = class extends Error {
4242
+ constructor(hostname) {
4243
+ super(`Refused to connect to ${hostname}: it resolves to a private or local address`);
4244
+ this.name = "BlockedTargetError";
4245
+ }
4246
+ };
4247
+ function guardedLookup(allowPrivate) {
4248
+ return (hostname, options, callback) => {
4249
+ import_node_dns.default.lookup(hostname, { ...options, all: true }, (error, addresses) => {
4250
+ if (error) return callback(error, "", 0);
4251
+ const list = addresses;
4252
+ if (list.length === 0) return callback(Object.assign(new Error(`No address for ${hostname}`), { code: "ENOTFOUND" }), "", 0);
4253
+ if (!allowPrivate && list.some((a) => isPrivateAddress(a.address))) return callback(new BlockedTargetError(hostname), "", 0);
4254
+ if (options.all) return callback(null, list);
4255
+ callback(null, list[0].address, list[0].family);
4256
+ });
4257
+ };
4258
+ }
4259
+ function createNodeTransport(options = {}) {
4260
+ const allowPrivate = options.allowInsecureTargets === true;
4261
+ return ({ url, headers, body, timeoutMs }) => new Promise((resolve, reject) => {
4262
+ const client = url.protocol === "https:" ? import_node_https.default : import_node_http.default;
4263
+ let settled = false;
4264
+ const finish = (action) => {
4265
+ if (settled) return;
4266
+ settled = true;
4267
+ clearTimeout(timer);
4268
+ action();
4269
+ };
4270
+ const request = client.request(
4271
+ url,
4272
+ {
4273
+ method: "POST",
4274
+ headers: { ...headers, "content-length": String(Buffer.byteLength(body)) },
4275
+ lookup: guardedLookup(allowPrivate),
4276
+ agent: false
4277
+ },
4278
+ (response) => {
4279
+ const status = response.statusCode ?? 0;
4280
+ response.destroy();
4281
+ finish(() => resolve({ status }));
4282
+ }
4283
+ );
4284
+ const timer = setTimeout(() => {
4285
+ request.destroy(new Error(`Timed out after ${timeoutMs} ms`));
4286
+ }, timeoutMs);
4287
+ request.on("error", (error) => finish(() => reject(error)));
4288
+ request.end(body);
4289
+ });
4290
+ }
4291
+
4292
+ // src/webhooks/endpoints.ts
4293
+ var MAX_ENDPOINTS_PER_ORGANIZATION = 20;
4294
+ var VIEW_FIELDS = { id: true, url: true, description: true, eventTypes: true, isActive: true, createdAt: true };
4295
+ async function createWebhookEndpoint(db, input, options = {}) {
4296
+ const checked = checkWebhookUrl(input.url, options);
4297
+ if (!checked.ok) throw new SchedulingValidationError(checked.reason, "SCHED_1000", { url: input.url });
4298
+ const eventTypes = normalizeEventTypes(input.eventTypes);
4299
+ if (!eventTypes) throw new SchedulingValidationError("Choose at least one valid event, or *", "SCHED_1001");
4300
+ const existing = await db.webhookEndpoint.count({ where: { organizationId: input.organizationId } });
4301
+ if (existing >= MAX_ENDPOINTS_PER_ORGANIZATION) {
4302
+ throw new SchedulingValidationError(
4303
+ `An organization can have at most ${MAX_ENDPOINTS_PER_ORGANIZATION} webhook endpoints`,
4304
+ "SCHED_1002",
4305
+ { organizationId: input.organizationId }
4306
+ );
4307
+ }
4308
+ const secret = generateWebhookSecret();
4309
+ const endpoint = await db.webhookEndpoint.create({
4310
+ data: {
4311
+ organizationId: input.organizationId,
4312
+ url: checked.url.toString(),
4313
+ description: input.description?.trim() || null,
4314
+ eventTypes,
4315
+ secret
4316
+ },
4317
+ select: VIEW_FIELDS
4318
+ });
4319
+ return { endpoint, secret };
4320
+ }
4321
+ async function listWebhookEndpoints(db, organizationId) {
4322
+ return db.webhookEndpoint.findMany({ where: { organizationId }, orderBy: { createdAt: "desc" }, select: VIEW_FIELDS });
4323
+ }
4324
+ async function deleteWebhookEndpoint(db, organizationId, endpointId) {
4325
+ const removed = await db.webhookEndpoint.deleteMany({ where: { id: endpointId, organizationId } });
4326
+ if (removed.count === 0) throw new SchedulingNotFoundError("Webhook endpoint not found", "SCHED_1003", { endpointId });
4327
+ }
4328
+
4329
+ // src/webhooks/deliver.ts
4330
+ var import_node_crypto3 = require("crypto");
4331
+ var import_client8 = require("@prisma/client");
4332
+
4333
+ // src/webhooks/attempt.ts
4334
+ var DEFAULT_BACKOFF_SECONDS = [60, 300, 1800, 7200, 21600];
4335
+ var MAX_ERROR_LENGTH = 300;
4336
+ function describe(error) {
4337
+ const code = error.code;
4338
+ const message = error instanceof Error ? error.message : String(error);
4339
+ return (code && !message.includes(code) ? `${code}: ${message}` : message).slice(0, MAX_ERROR_LENGTH);
4340
+ }
4341
+ async function attemptDelivery(db, delivery, workerId, options = {}) {
4342
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
4343
+ const backoff = options.backoffSeconds ?? DEFAULT_BACKOFF_SECONDS;
4344
+ const maxAttempts = options.maxAttempts ?? backoff.length + 1;
4345
+ const transport = options.transport ?? createNodeTransport({ allowInsecureTargets: options.allowInsecureTargets });
4346
+ const attemptNumber = delivery.attempts + 1;
4347
+ const startedAt = now();
4348
+ let statusCode = null;
4349
+ let error = null;
4350
+ let retryable = true;
4351
+ const target = checkWebhookUrl(delivery.endpoint.url, { allowInsecureTargets: options.allowInsecureTargets });
4352
+ if (!delivery.endpoint.isActive) {
4353
+ error = "The endpoint is switched off";
4354
+ retryable = false;
4355
+ } else if (!target.ok) {
4356
+ error = `${schedError("SCHED_1005", { endpointId: delivery.endpoint.id }).ref}: ${target.reason}`;
4357
+ retryable = false;
4358
+ } else {
4359
+ try {
4360
+ const response = await transport({
4361
+ url: target.url,
4362
+ timeoutMs: options.timeoutMs ?? 1e4,
4363
+ body: delivery.body,
4364
+ headers: {
4365
+ "content-type": "application/json",
4366
+ "user-agent": "scheduling-webhooks/1",
4367
+ "x-scheduling-event": delivery.eventType,
4368
+ "x-scheduling-delivery": delivery.id,
4369
+ [SIGNATURE_HEADER]: signWebhook({ secret: delivery.endpoint.secret, body: delivery.body, now: startedAt })
4370
+ }
4371
+ });
4372
+ statusCode = response.status;
4373
+ if (response.status < 200 || response.status >= 300) error = `The receiver answered HTTP ${response.status}`;
4374
+ } catch (caught) {
4375
+ error = describe(caught);
4376
+ retryable = caught.name !== "BlockedTargetError";
4377
+ }
4378
+ }
4379
+ const finishedAt = now();
4380
+ const succeeded = error === null;
4381
+ const exhausted = !retryable || attemptNumber >= maxAttempts;
4382
+ const outcome = succeeded ? "SUCCEEDED" : exhausted ? "DEAD_LETTER" : "RETRY";
4383
+ const updated = await db.webhookDelivery.updateMany({
4384
+ where: { id: delivery.id, organizationId: delivery.organizationId, status: "PROCESSING", processingId: workerId },
4385
+ data: {
4386
+ status: outcome === "SUCCEEDED" ? "SUCCEEDED" : outcome === "DEAD_LETTER" ? "DEAD_LETTER" : "PENDING",
4387
+ attempts: attemptNumber,
4388
+ lastStatusCode: statusCode,
4389
+ lastError: error,
4390
+ deliveredAt: succeeded ? finishedAt : null,
4391
+ nextAttemptAt: outcome === "RETRY" ? new Date(finishedAt.getTime() + backoff[Math.min(attemptNumber - 1, backoff.length - 1)] * 1e3) : void 0,
4392
+ processingId: null,
4393
+ claimedAt: null
4394
+ }
4395
+ });
4396
+ if (updated.count === 0) return { outcome: "LOST_CLAIM", statusCode, error };
4397
+ await db.webhookAttempt.create({
4398
+ data: { deliveryId: delivery.id, attemptNumber, statusCode, error, durationMs: Math.max(0, finishedAt.getTime() - startedAt.getTime()) }
4399
+ });
4400
+ return { outcome, statusCode, error };
4401
+ }
4402
+
4403
+ // src/webhooks/deliver.ts
4404
+ async function deliverDueWebhooks(db, options = {}) {
4405
+ const now = (options.now ?? (() => /* @__PURE__ */ new Date()))();
4406
+ const batchSize = Math.max(1, Math.min(200, Math.floor(options.batchSize ?? 20)));
4407
+ const concurrency = Math.max(1, Math.floor(options.concurrency ?? 5));
4408
+ const workerId = options.workerId ?? (0, import_node_crypto3.randomUUID)();
4409
+ const staleBefore = new Date(now.getTime() - (options.staleClaimMs ?? 5 * 6e4));
4410
+ const claimed = await db.$queryRaw`
4411
+ WITH candidates AS (
4412
+ SELECT id FROM "WebhookDelivery"
4413
+ WHERE (status = 'PENDING' AND "nextAttemptAt" <= ${now})
4414
+ OR (status = 'PROCESSING' AND "claimedAt" < ${staleBefore})
4415
+ ORDER BY "nextAttemptAt" ASC
4416
+ LIMIT ${import_client8.Prisma.raw(String(batchSize))}
4417
+ FOR UPDATE SKIP LOCKED
4418
+ )
4419
+ UPDATE "WebhookDelivery" d
4420
+ SET status = 'PROCESSING', "processingId" = ${workerId}, "claimedAt" = ${now}
4421
+ FROM candidates
4422
+ WHERE d.id = candidates.id
4423
+ RETURNING d.id
4424
+ `;
4425
+ const summary = { succeeded: 0, retried: 0, deadLettered: 0, lostClaim: 0 };
4426
+ if (claimed.length === 0) return summary;
4427
+ const rows = await db.webhookDelivery.findMany({
4428
+ where: { id: { in: claimed.map((c) => c.id) }, processingId: workerId },
4429
+ select: {
4430
+ id: true,
4431
+ organizationId: true,
4432
+ eventId: true,
4433
+ eventType: true,
4434
+ body: true,
4435
+ attempts: true,
4436
+ endpoint: { select: { id: true, url: true, secret: true, isActive: true } }
4437
+ }
4438
+ });
4439
+ for (let i = 0; i < rows.length; i += concurrency) {
4440
+ const results = await Promise.all(rows.slice(i, i + concurrency).map((row) => attemptDelivery(db, row, workerId, options)));
4441
+ for (const { outcome } of results) {
4442
+ if (outcome === "SUCCEEDED") summary.succeeded++;
4443
+ else if (outcome === "RETRY") summary.retried++;
4444
+ else if (outcome === "DEAD_LETTER") summary.deadLettered++;
4445
+ else summary.lostClaim++;
4446
+ }
4447
+ }
4448
+ return summary;
4449
+ }
4450
+
4451
+ // src/webhooks/test-send.ts
4452
+ var import_node_crypto4 = require("crypto");
4453
+ async function sendTestWebhook(db, input, options = {}) {
4454
+ const endpoint = await db.webhookEndpoint.findFirst({
4455
+ where: { id: input.endpointId, organizationId: input.organizationId },
4456
+ select: { id: true, url: true, secret: true, isActive: true }
4457
+ });
4458
+ if (!endpoint) throw new SchedulingNotFoundError("Webhook endpoint not found", "SCHED_1003", { endpointId: input.endpointId });
4459
+ const now = (options.now ?? (() => /* @__PURE__ */ new Date()))();
4460
+ const workerId = (0, import_node_crypto4.randomUUID)();
4461
+ const envelope = buildEnvelope({
4462
+ organizationId: input.organizationId,
4463
+ type: WEBHOOK_TEST_EVENT,
4464
+ data: { message: "This is a test event from your scheduling system." },
4465
+ now
4466
+ });
4467
+ const created = await db.webhookDelivery.create({
4468
+ data: {
4469
+ organizationId: input.organizationId,
4470
+ endpointId: endpoint.id,
4471
+ eventId: envelope.id,
4472
+ eventType: WEBHOOK_TEST_EVENT,
4473
+ body: JSON.stringify(envelope),
4474
+ status: "PROCESSING",
4475
+ processingId: workerId,
4476
+ claimedAt: now,
4477
+ nextAttemptAt: now
4478
+ },
4479
+ select: { id: true, organizationId: true, eventId: true, eventType: true, body: true, attempts: true }
4480
+ });
4481
+ const result = await attemptDelivery(db, { ...created, endpoint }, workerId, { ...options, maxAttempts: 1 });
4482
+ return { deliveryId: created.id, ok: result.outcome === "SUCCEEDED", statusCode: result.statusCode, error: result.error };
4483
+ }
4484
+
4485
+ // src/webhooks/deliveries.ts
4486
+ async function listWebhookDeliveries(db, input) {
4487
+ const where = {
4488
+ organizationId: input.organizationId,
4489
+ ...input.endpointId ? { endpointId: input.endpointId } : {},
4490
+ ...input.status ? { status: input.status } : {}
4491
+ };
4492
+ const [deliveries, total] = await Promise.all([
4493
+ db.webhookDelivery.findMany({
4494
+ where,
4495
+ orderBy: { createdAt: "desc" },
4496
+ take: Math.min(input.limit ?? 50, 200),
4497
+ skip: input.offset ?? 0,
4498
+ select: {
4499
+ id: true,
4500
+ endpointId: true,
4501
+ eventId: true,
4502
+ eventType: true,
4503
+ status: true,
4504
+ attempts: true,
4505
+ nextAttemptAt: true,
4506
+ lastStatusCode: true,
4507
+ lastError: true,
4508
+ deliveredAt: true,
4509
+ createdAt: true,
4510
+ attemptLog: { orderBy: { attemptNumber: "desc" }, take: 10, select: { attemptNumber: true, statusCode: true, error: true, durationMs: true, createdAt: true } }
4511
+ }
4512
+ }),
4513
+ db.webhookDelivery.count({ where })
4514
+ ]);
4515
+ return { deliveries, total };
4516
+ }
4517
+ async function retryWebhookDelivery(db, organizationId, deliveryId, now = /* @__PURE__ */ new Date()) {
4518
+ const updated = await db.webhookDelivery.updateMany({
4519
+ where: { id: deliveryId, organizationId, status: "DEAD_LETTER" },
4520
+ data: { status: "PENDING", attempts: 0, nextAttemptAt: now, processingId: null, claimedAt: null }
4521
+ });
4522
+ if (updated.count === 0) throw new SchedulingNotFoundError("Delivery not found or not in the dead-letter list", "SCHED_1004", { deliveryId });
4523
+ }
3871
4524
  // Annotate the CommonJS export names for ESM import in node:
3872
4525
  0 && (module.exports = {
4526
+ BlockedTargetError,
4527
+ DEFAULT_BACKOFF_SECONDS,
4528
+ MAX_ENDPOINTS_PER_ORGANIZATION,
3873
4529
  RECURRING_MAX_OCCURRENCES,
3874
4530
  SCHEDULING_ERRORS,
4531
+ SIGNATURE_HEADER,
3875
4532
  SchedulingNotFoundError,
3876
4533
  SchedulingValidationError,
3877
4534
  USER_DAY_LIMIT,
4535
+ WEBHOOK_EVENT_TYPES,
4536
+ WEBHOOK_TEST_EVENT,
3878
4537
  adaptersToCallbacks,
3879
4538
  addDateOverride,
3880
4539
  addTimeBlock,
4540
+ appointmentWebhookData,
3881
4541
  archiveCalendar,
3882
4542
  bookAppointment,
3883
4543
  buildJitsiUrl,
@@ -3892,13 +4552,22 @@ async function getTeamAvailableSlots(db, query, _getSlots = getAvailableSlots) {
3892
4552
  checkClockContract,
3893
4553
  checkNotificationContract,
3894
4554
  checkPaymentContract,
4555
+ checkWebhookUrl,
3895
4556
  createAppointmentType,
3896
4557
  createCalendar,
3897
4558
  createInMemoryAdapters,
4559
+ createNodeTransport,
3898
4560
  createNotificationTemplate,
4561
+ createWebhookEndpoint,
3899
4562
  deleteCalendar,
3900
4563
  deleteNotificationTemplate,
4564
+ deleteWebhookEndpoint,
4565
+ deliverDueWebhooks,
4566
+ enqueueAppointmentWebhook,
4567
+ enqueueReminderSent,
4568
+ enqueueWebhookEvent,
3901
4569
  generateOccurrenceDates,
4570
+ generateWebhookSecret,
3902
4571
  getAppointment,
3903
4572
  getAppointmentDashboard,
3904
4573
  getAppointmentType,
@@ -3912,6 +4581,7 @@ async function getTeamAvailableSlots(db, query, _getSlots = getAvailableSlots) {
3912
4581
  getNotificationTemplate,
3913
4582
  getTeamAvailableSlots,
3914
4583
  getUserDayAppointments,
4584
+ isPrivateAddress,
3915
4585
  isSlotAvailable,
3916
4586
  isVirtualMeeting,
3917
4587
  listAppointmentTypes,
@@ -3919,6 +4589,8 @@ async function getTeamAvailableSlots(db, query, _getSlots = getAvailableSlots) {
3919
4589
  listAvailabilityRules,
3920
4590
  listCalendars,
3921
4591
  listNotificationTemplates,
4592
+ listWebhookDeliveries,
4593
+ listWebhookEndpoints,
3922
4594
  localToUTC,
3923
4595
  markNoShow,
3924
4596
  parseTimeLocal,
@@ -3929,12 +4601,16 @@ async function getTeamAvailableSlots(db, query, _getSlots = getAvailableSlots) {
3929
4601
  renderTemplate,
3930
4602
  rescheduleAppointment,
3931
4603
  resolveLocation,
4604
+ retryWebhookDelivery,
3932
4605
  schedError,
3933
4606
  scheduleNotifications,
3934
4607
  selectCalendarForBooking,
4608
+ sendTestWebhook,
3935
4609
  setWeeklyAvailability,
4610
+ signWebhook,
3936
4611
  updateAppointmentType,
3937
4612
  updateCalendar,
3938
4613
  updateNotificationTemplate,
4614
+ verifyWebhookSignature,
3939
4615
  withCalendarVisibility
3940
4616
  });