@ordinatio/scheduling 0.6.0 → 0.7.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/CHANGELOG.md +8 -0
- package/dist/index.d.mts +94 -2
- package/dist/index.d.ts +94 -2
- package/dist/index.js +244 -4
- package/dist/index.mjs +227 -4
- package/package.json +1 -1
- package/prisma/migrations/20261116000000_organization_text_settings/migration.sql +18 -0
- package/prisma/migrations/20261118000000_organization_api_keys/migration.sql +24 -0
- package/prisma/schema.prisma +33 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.7.0 (prepared 2026-11-18)
|
|
4
|
+
|
|
5
|
+
- **New: API keys, so an outside tool can act for one business.** A new table, `OrganizationApiKey` (`name`, `access`, a short `prefix`, `keyHash`, `createdByUserId`, `lastUsedAt`, `revokedAt`; migration `20261118000000_organization_api_keys`, or `20261118000000_scheduling_organization_api_keys` in the host database package; apply it before using keys). `createApiKey(db, organizationId, { name, access }, createdByUserId?)` returns `{ key, view }`: the secret (`osk_` and 43 characters) is in the result once and only its SHA-256 is stored. `access` is `READ` or `FULL`; a business may have 25 live keys (`SCHED_1601` beyond that; two requests at the same moment can pass the check together). `listApiKeys` never returns a hash, `revokeApiKey` answers whether it revoked a live key of that business, and `verifyApiKey(db, secret)` returns who a live key acts as or null (it never throws for a bad secret, and records "last used" at most every ten minutes without ever refusing a valid key if that write fails). A key whose stored access level is not `READ` or `FULL` is refused. Bad requests are `SCHED_1600` with every problem at once; a failed "last used" write is logged as `SCHED_1602`. Also exported: `validateApiKeyRequest`, `looksLikeApiKey`, `MAX_ACTIVE_API_KEYS`.
|
|
6
|
+
## 0.6.1 (prepared 2026-11-16)
|
|
7
|
+
|
|
8
|
+
- **New: a business's text-message settings.** A new table, `OrganizationTextSettings` (`provider`, `fromNumber`, `enabled`, one row per organization), and `getTextSettings`, `saveTextSettings`, `deleteTextSettings`, `validateTextSettings` and `normalizeTextNumber`. The provider is `TELNYX` or `TWILIO` (a server can offer fewer with the `providers` option); the number is cleaned up to international format; every problem is reported at once as `SCHED_1500`. No provider keys are stored: the host holds the provider accounts and looks the business's settings up to choose the adapter. Saving replaces the whole row, so leaving `enabled` out sets it back to true. **After upgrading, run the new migration** (a new empty table; nothing existing changes): `20261116000000_organization_text_settings` in this package, and `20261116000000_scheduling_organization_text_settings` in a host that copies the migrations into its own database package.
|
|
9
|
+
- **New: the sender can be told which business a notification belongs to.** `processPendingNotifications(db, sender, { organization: true })` adds `organizationId` to the sender's context for each notification whose calendar has an organization, and `adaptersToCallbacks` hands it to the adapter as `OutboundMessage.organizationId`. It is off by default, so nothing changes for a host that does not ask. It lets one text-message adapter pick a number or provider per business.
|
|
10
|
+
|
|
3
11
|
## 0.6.0 (prepared 2026-11-10)
|
|
4
12
|
|
|
5
13
|
- **Fix: the organization table now has the `settings` and `updatedAt` columns the cancellation policy needs.** `GET` and `PUT
|
package/dist/index.d.mts
CHANGED
|
@@ -11,7 +11,7 @@ import * as _prisma_client_runtime_client from '@prisma/client/runtime/client';
|
|
|
11
11
|
* interface (minus $transaction itself) so code inside transactions
|
|
12
12
|
* is fully typed without `as any` casts.
|
|
13
13
|
*/
|
|
14
|
-
type SchedulingDb = Pick<PrismaClient, 'schedulingCalendar' | 'availabilityRule' | 'appointmentType' | 'appointmentTypeCalendar' | 'appointmentCategory' | 'appointment' | 'scheduledNotification' | 'notificationTemplate' | 'servicePackage' | 'packagePurchase' | 'couponCode' | 'recurringSeries' | 'roundRobinState' | 'webhookEndpoint' | 'webhookDelivery' | 'webhookAttempt' | 'waitlistEntry' | 'routingForm' | 'dataSubjectRequest' | 'organizationBrand' | 'organization' | '$transaction' | '$executeRaw' | '$queryRaw'>;
|
|
14
|
+
type SchedulingDb = Pick<PrismaClient, 'schedulingCalendar' | 'availabilityRule' | 'appointmentType' | 'appointmentTypeCalendar' | 'appointmentCategory' | 'appointment' | 'scheduledNotification' | 'notificationTemplate' | 'servicePackage' | 'packagePurchase' | 'couponCode' | 'recurringSeries' | 'roundRobinState' | 'webhookEndpoint' | 'webhookDelivery' | 'webhookAttempt' | 'waitlistEntry' | 'routingForm' | 'dataSubjectRequest' | 'organizationBrand' | 'organizationTextSettings' | 'organizationApiKey' | 'organization' | '$transaction' | '$executeRaw' | '$queryRaw'>;
|
|
15
15
|
/**
|
|
16
16
|
* Branded subtype of SchedulingDb for transaction clients produced by withTransaction().
|
|
17
17
|
* selectCalendarForBooking() requires this type to enforce that its RoundRobinState
|
|
@@ -391,6 +391,8 @@ interface NotificationSenderContext {
|
|
|
391
391
|
trigger?: NotificationTrigger;
|
|
392
392
|
/** The organization's own sender identity, when branding is on and one is set. */
|
|
393
393
|
from?: SenderIdentity;
|
|
394
|
+
/** The organization the notification belongs to. Only set when the caller asks for it (`organization: true`). */
|
|
395
|
+
organizationId?: string;
|
|
394
396
|
}
|
|
395
397
|
/**
|
|
396
398
|
* Returned by the sender when it deliberately does not deliver the notification.
|
|
@@ -1409,6 +1411,8 @@ interface OutboundMessage {
|
|
|
1409
1411
|
trigger?: NotificationTrigger;
|
|
1410
1412
|
/** The organization's own sender identity, when it has one. An adapter that cannot send as it uses its default sender. */
|
|
1411
1413
|
from?: SenderIdentity;
|
|
1414
|
+
/** The organization this message belongs to, when the host asked for it. Lets one adapter pick a number or provider per business. */
|
|
1415
|
+
organizationId?: string;
|
|
1412
1416
|
}
|
|
1413
1417
|
type SendResult = {
|
|
1414
1418
|
status: 'SENT';
|
|
@@ -1654,6 +1658,8 @@ declare function processPendingNotifications(db: SchedulingDb, sender: Notificat
|
|
|
1654
1658
|
webhooks?: boolean;
|
|
1655
1659
|
/** Send each message with its organization's sender identity (name, address, reply-to). Off by default; needs the brand table. */
|
|
1656
1660
|
brand?: boolean;
|
|
1661
|
+
/** Tell the sender which organization each notification belongs to (`organizationId` in its context). Off by default. */
|
|
1662
|
+
organization?: boolean;
|
|
1657
1663
|
}): Promise<{
|
|
1658
1664
|
sent: number;
|
|
1659
1665
|
failed: number;
|
|
@@ -2740,4 +2746,90 @@ declare function senderIdentity(brand: BrandFields | null): SenderIdentity | nul
|
|
|
2740
2746
|
declare function brandTemplateFields(brand: BrandFields | null): Record<string, string>;
|
|
2741
2747
|
declare function toPublicBrand(brand: BrandFields): PublicBrand;
|
|
2742
2748
|
|
|
2743
|
-
|
|
2749
|
+
declare const TEXT_PROVIDERS: readonly ["TELNYX", "TWILIO"];
|
|
2750
|
+
type TextProvider = (typeof TEXT_PROVIDERS)[number];
|
|
2751
|
+
interface TextSettingsFields {
|
|
2752
|
+
provider: TextProvider;
|
|
2753
|
+
/** International format, such as +13135550100. */
|
|
2754
|
+
fromNumber: string;
|
|
2755
|
+
/** False pauses texting for the business without losing its number. */
|
|
2756
|
+
enabled: boolean;
|
|
2757
|
+
}
|
|
2758
|
+
interface TextSettingsView extends TextSettingsFields {
|
|
2759
|
+
updatedAt: Date;
|
|
2760
|
+
}
|
|
2761
|
+
interface TextSettingsProblem {
|
|
2762
|
+
path: string;
|
|
2763
|
+
message: string;
|
|
2764
|
+
}
|
|
2765
|
+
declare const TEXT_SETTINGS_FIELDS: readonly ["provider", "fromNumber", "enabled"];
|
|
2766
|
+
|
|
2767
|
+
/** International format, or null. Ten digits are read as a US number. */
|
|
2768
|
+
declare function normalizeTextNumber(raw: string): string | null;
|
|
2769
|
+
interface ValidateTextSettingsOptions {
|
|
2770
|
+
/** The providers this server has accounts for. Default: all known providers. */
|
|
2771
|
+
providers?: readonly TextProvider[];
|
|
2772
|
+
}
|
|
2773
|
+
/** The stored form of the settings, or a SCHED_1500 error listing every problem. */
|
|
2774
|
+
declare function validateTextSettings(input: unknown, options?: ValidateTextSettingsOptions): TextSettingsFields;
|
|
2775
|
+
|
|
2776
|
+
declare function getTextSettings(db: SchedulingDb, organizationId: string): Promise<TextSettingsView | null>;
|
|
2777
|
+
/** Saves the whole settings, replacing what was there. Throws SCHED_1500 listing every problem. */
|
|
2778
|
+
declare function saveTextSettings(db: SchedulingDb, organizationId: string, input: unknown, options?: ValidateTextSettingsOptions): Promise<TextSettingsView>;
|
|
2779
|
+
/** Removes the settings. True when there were some. */
|
|
2780
|
+
declare function deleteTextSettings(db: SchedulingDb, organizationId: string): Promise<boolean>;
|
|
2781
|
+
|
|
2782
|
+
/** READ may only look things up; FULL may also change them. */
|
|
2783
|
+
declare const API_KEY_ACCESS: readonly ["READ", "FULL"];
|
|
2784
|
+
type ApiKeyAccess = (typeof API_KEY_ACCESS)[number];
|
|
2785
|
+
declare const API_KEY_FIELDS: readonly ["name", "access"];
|
|
2786
|
+
declare const MAX_ACTIVE_API_KEYS = 25;
|
|
2787
|
+
declare const API_KEY_NAME_MAX = 60;
|
|
2788
|
+
interface ApiKeyFields {
|
|
2789
|
+
/** What the key is for, such as "Zapier". Shown in the list so the owner can tell keys apart. */
|
|
2790
|
+
name: string;
|
|
2791
|
+
access: ApiKeyAccess;
|
|
2792
|
+
}
|
|
2793
|
+
/** A key as listed: never the secret, only enough to recognise it. */
|
|
2794
|
+
interface ApiKeyView extends ApiKeyFields {
|
|
2795
|
+
id: string;
|
|
2796
|
+
/** The first characters of the key, so the owner can match a list entry to a key they hold. */
|
|
2797
|
+
prefix: string;
|
|
2798
|
+
createdByUserId: string | null;
|
|
2799
|
+
createdAt: Date;
|
|
2800
|
+
lastUsedAt: Date | null;
|
|
2801
|
+
revokedAt: Date | null;
|
|
2802
|
+
}
|
|
2803
|
+
/** Returned once, when a key is created. The secret cannot be read again. */
|
|
2804
|
+
interface CreatedApiKey {
|
|
2805
|
+
key: string;
|
|
2806
|
+
view: ApiKeyView;
|
|
2807
|
+
}
|
|
2808
|
+
/** Who a valid key acts as. */
|
|
2809
|
+
interface VerifiedApiKey {
|
|
2810
|
+
id: string;
|
|
2811
|
+
organizationId: string;
|
|
2812
|
+
access: ApiKeyAccess;
|
|
2813
|
+
createdByUserId: string | null;
|
|
2814
|
+
}
|
|
2815
|
+
|
|
2816
|
+
/** The cleaned-up request for a new key, or a SCHED_1600 error listing every problem. */
|
|
2817
|
+
declare function validateApiKeyRequest(input: unknown): ApiKeyFields;
|
|
2818
|
+
|
|
2819
|
+
/** True when the text has the shape of a key, so a request with some other credential is never looked up. */
|
|
2820
|
+
declare function looksLikeApiKey(text: string): boolean;
|
|
2821
|
+
|
|
2822
|
+
/**
|
|
2823
|
+
* Makes a key for the business. The secret is in the result once and cannot be read again.
|
|
2824
|
+
* Throws SCHED_1600 for a bad request and SCHED_1601 when the business already has the most keys it may have.
|
|
2825
|
+
* The limit is checked just before the key is written, so two requests at the same moment can pass it together.
|
|
2826
|
+
*/
|
|
2827
|
+
declare function createApiKey(db: SchedulingDb, organizationId: string, input: unknown, createdByUserId?: string): Promise<CreatedApiKey>;
|
|
2828
|
+
/** Every key of the business, newest first, revoked ones included. Never the secret. */
|
|
2829
|
+
declare function listApiKeys(db: SchedulingDb, organizationId: string): Promise<ApiKeyView[]>;
|
|
2830
|
+
/** Stops a key from working. True when it was active; false for an unknown, other-business or already revoked key. */
|
|
2831
|
+
declare function revokeApiKey(db: SchedulingDb, organizationId: string, id: string): Promise<boolean>;
|
|
2832
|
+
/** Who a secret acts as, or null when it is not a live key. Never throws for a bad secret. */
|
|
2833
|
+
declare function verifyApiKey(db: SchedulingDb, secret: string): Promise<VerifiedApiKey | null>;
|
|
2834
|
+
|
|
2835
|
+
export { API_KEY_ACCESS, API_KEY_FIELDS, API_KEY_NAME_MAX, type AcceptRelease, type AddTimeBlockInput, type ApiKeyAccess, type ApiKeyFields, type ApiKeyView, type AppointmentDashboardData, type AppointmentDashboardItem, type AppointmentDashboardStats, type AppointmentLocationType, type AppointmentStatus, type AppointmentWithDetails, type AssignmentStrategy, type AttemptOptions, type AuthAdapter, type AuthContext, type AvailabilityQuery, type AvailabilityResult, type AvailabilityRuleInput, BRAND_FIELDS, BlockedTargetError, type BookAppointmentInput, type BookingAnalytics, type BrandFields, type BrandProblem, type BrandView, type CalendarEvent, type CalendarEventRef, type CalendarSyncAdapter, type CalendarType, type CancelInput, type CancelRecurringScope, type CancellationFeeConfig, type CancellationFeeResult, type ChargeRequest, type ChargeResult, type Clock, type CreateAppointmentTypeInput, type CreateCalendarInput, type CreatedApiKey, DEFAULT_BACKOFF_SECONDS, DEFAULT_OFFER_MINUTES, type DashboardQuery, type DayAppointment, type DeliverOptions, type DeliverSummary, ERASED_EMAIL, ERASED_NAME, type EraseBlockers, type ErasePreview, type FreedSlot, type GroupCapacityResult, type GroupSession, type GroupSessionAttendee, type InMemoryClockControl, type InMemoryOptions, type InMemoryRecords, type IntakeFormField, type JoinWaitlistInput, LIMITS, MAX_ACTIVE_API_KEYS, MAX_ENDPOINTS_PER_ORGANIZATION, MAX_WAITING_PER_TYPE_DAY, type MarkNoShowInput, type NotificationAdapter, type NotificationChannel, type NotificationContext, type NotificationSender, type NotificationTrigger, OPERATORS_BY_TYPE, type OfferDetails, type OrgCancellationPolicy, type OutboundMessage, type ParsedSubject, type PaymentAdapter, type PaymentCheck, type PaymentContractOptions, type PaymentProcessor, type PaymentResult, type PrivacyRequestKind, type PrivacyRequestView, type PublicBrand, type PublicRoutingForm, type QuestionType, RECURRING_MAX_OCCURRENCES, LIMITS as ROUTING_LIMITS, type RecurringFrequency, type RefundOptions, type RefundResult, type RescheduleInput, type ResolvedDestination, type ResolvedSubject, type RetryConfig, type RoutingAnswers, type RoutingCondition, type RoutingDestination, type RoutingFallback, type RoutingFormDefinition, type RoutingFormInput, type RoutingFormSummary, type RoutingFormView, type RoutingOperator, type RoutingOutcome, type RoutingProblem, type RoutingQuestion, type RoutingRule, SCHEDULING_ERRORS, SIGNATURE_HEADER, type SchedulingAdapters, type SchedulingCallbacks, type SchedulingDb, SchedulingNotFoundError, SchedulingValidationError, type SendResult, type SettledBooking, type SubjectCounts, type SubjectExport, TEXT_PROVIDERS, TEXT_SETTINGS_FIELDS, type TeamAvailabilityQuery, type TeamAvailabilityResult, type TestSendResult, type TextProvider, type TextSettingsFields, type TextSettingsProblem, type TextSettingsView, type TimeSlot, type TransportRequest, USER_DAY_LIMIT, type UpdateCalendarInput, type UrlCheckOptions, type UserDayInput, type UserDayResult, type ValidateBrandOptions, type ValidateTextSettingsOptions, type VerifiedApiKey, WEBHOOK_EVENT_TYPES, WEBHOOK_TEST_EVENT, type WaitlistEntryView, type WaitlistOffer, type WebhookDeliveryView, type WebhookEndpointView, type WebhookEnvelope, type WebhookEventType, type WebhookTransport, adaptersToCallbacks, addDateOverride, addTimeBlock, appointmentWebhookData, archiveCalendar, beginWaitlistAccept, bookAppointment, brandTemplateFields, buildJitsiUrl, buildNotificationContext, buildOccurrenceStartTime, buildRecurringSlots, calculateCancellationFee, cancelAppointment, cancelPendingNotifications, checkAnswers, checkAuthContract, checkCalendarSyncContract, checkClockContract, checkNotificationContract, checkPaymentContract, checkWebhookUrl, completeWaitlistAccept, createApiKey, createAppointmentType, createCalendar, createInMemoryAdapters, createNodeTransport, createNotificationTemplate, createRoutingForm, createWebhookEndpoint, deleteBrand, deleteCalendar, deleteNotificationTemplate, deleteRoutingForm, deleteTextSettings, deleteWebhookEndpoint, deliverDueWebhooks, enqueueAppointmentWebhook, enqueueReminderSent, enqueueWebhookEvent, eraseSubject, expireWaitlistOffers, exportSubject, generateOccurrenceDates, generateWebhookSecret, getAppointment, getAppointmentDashboard, getAppointmentType, getAppointmentsForRange, getAvailableDates, getAvailableSlots, getBookingAnalytics, getBrand, getCalendar, getGroupCapacity, getGroupSessions, getNotificationTemplate, getPublicBrand, getPublicRoutingForm, getRoutingForm, getTeamAvailableSlots, getTextSettings, getUserDayAppointments, getWaitlistOffer, isPrivateAddress, isSlotAvailable, isVirtualMeeting, joinWaitlist, leaveWaitlist, listApiKeys, listAppointmentTypes, listAppointments, listAvailabilityRules, listCalendars, listNotificationTemplates, listPrivacyRequests, listRoutingForms, listWaitlist, listWebhookDeliveries, listWebhookEndpoints, localDay, localToUTC, looksLikeApiKey, markNoShow, matchingRules, normalizeTextNumber, offerFreedSlot, parseSubject, parseTimeLocal, previewErase, processPendingNotifications, queueImmediateNotification, queueStaffNotification, releaseWaitlistAccept, removeDateOverride, removeWaitlistEntry, renderTemplate, rescheduleAppointment, resolveDestination, resolveLocation, resolveSubject, retryWebhookDelivery, revokeApiKey, routeClient, saveBrand, saveTextSettings, schedError, scheduleNotifications, scopeToOrganization, selectCalendarForBooking, sendTestWebhook, senderIdentity, setWeeklyAvailability, settleBookedAccept, signWebhook, subjectHashes, testRoutingForm, toPublicBrand, tryOfferFreedSlot, updateAppointmentType, updateCalendar, updateNotificationTemplate, updateRoutingForm, validateApiKeyRequest, validateBrand, validateRoutingDestinations, validateRoutingStructure, validateTextSettings, verifyApiKey, verifyWebhookSignature, withCalendarVisibility, withOrganization };
|
package/dist/index.d.ts
CHANGED
|
@@ -11,7 +11,7 @@ import * as _prisma_client_runtime_client from '@prisma/client/runtime/client';
|
|
|
11
11
|
* interface (minus $transaction itself) so code inside transactions
|
|
12
12
|
* is fully typed without `as any` casts.
|
|
13
13
|
*/
|
|
14
|
-
type SchedulingDb = Pick<PrismaClient, 'schedulingCalendar' | 'availabilityRule' | 'appointmentType' | 'appointmentTypeCalendar' | 'appointmentCategory' | 'appointment' | 'scheduledNotification' | 'notificationTemplate' | 'servicePackage' | 'packagePurchase' | 'couponCode' | 'recurringSeries' | 'roundRobinState' | 'webhookEndpoint' | 'webhookDelivery' | 'webhookAttempt' | 'waitlistEntry' | 'routingForm' | 'dataSubjectRequest' | 'organizationBrand' | 'organization' | '$transaction' | '$executeRaw' | '$queryRaw'>;
|
|
14
|
+
type SchedulingDb = Pick<PrismaClient, 'schedulingCalendar' | 'availabilityRule' | 'appointmentType' | 'appointmentTypeCalendar' | 'appointmentCategory' | 'appointment' | 'scheduledNotification' | 'notificationTemplate' | 'servicePackage' | 'packagePurchase' | 'couponCode' | 'recurringSeries' | 'roundRobinState' | 'webhookEndpoint' | 'webhookDelivery' | 'webhookAttempt' | 'waitlistEntry' | 'routingForm' | 'dataSubjectRequest' | 'organizationBrand' | 'organizationTextSettings' | 'organizationApiKey' | 'organization' | '$transaction' | '$executeRaw' | '$queryRaw'>;
|
|
15
15
|
/**
|
|
16
16
|
* Branded subtype of SchedulingDb for transaction clients produced by withTransaction().
|
|
17
17
|
* selectCalendarForBooking() requires this type to enforce that its RoundRobinState
|
|
@@ -391,6 +391,8 @@ interface NotificationSenderContext {
|
|
|
391
391
|
trigger?: NotificationTrigger;
|
|
392
392
|
/** The organization's own sender identity, when branding is on and one is set. */
|
|
393
393
|
from?: SenderIdentity;
|
|
394
|
+
/** The organization the notification belongs to. Only set when the caller asks for it (`organization: true`). */
|
|
395
|
+
organizationId?: string;
|
|
394
396
|
}
|
|
395
397
|
/**
|
|
396
398
|
* Returned by the sender when it deliberately does not deliver the notification.
|
|
@@ -1409,6 +1411,8 @@ interface OutboundMessage {
|
|
|
1409
1411
|
trigger?: NotificationTrigger;
|
|
1410
1412
|
/** The organization's own sender identity, when it has one. An adapter that cannot send as it uses its default sender. */
|
|
1411
1413
|
from?: SenderIdentity;
|
|
1414
|
+
/** The organization this message belongs to, when the host asked for it. Lets one adapter pick a number or provider per business. */
|
|
1415
|
+
organizationId?: string;
|
|
1412
1416
|
}
|
|
1413
1417
|
type SendResult = {
|
|
1414
1418
|
status: 'SENT';
|
|
@@ -1654,6 +1658,8 @@ declare function processPendingNotifications(db: SchedulingDb, sender: Notificat
|
|
|
1654
1658
|
webhooks?: boolean;
|
|
1655
1659
|
/** Send each message with its organization's sender identity (name, address, reply-to). Off by default; needs the brand table. */
|
|
1656
1660
|
brand?: boolean;
|
|
1661
|
+
/** Tell the sender which organization each notification belongs to (`organizationId` in its context). Off by default. */
|
|
1662
|
+
organization?: boolean;
|
|
1657
1663
|
}): Promise<{
|
|
1658
1664
|
sent: number;
|
|
1659
1665
|
failed: number;
|
|
@@ -2740,4 +2746,90 @@ declare function senderIdentity(brand: BrandFields | null): SenderIdentity | nul
|
|
|
2740
2746
|
declare function brandTemplateFields(brand: BrandFields | null): Record<string, string>;
|
|
2741
2747
|
declare function toPublicBrand(brand: BrandFields): PublicBrand;
|
|
2742
2748
|
|
|
2743
|
-
|
|
2749
|
+
declare const TEXT_PROVIDERS: readonly ["TELNYX", "TWILIO"];
|
|
2750
|
+
type TextProvider = (typeof TEXT_PROVIDERS)[number];
|
|
2751
|
+
interface TextSettingsFields {
|
|
2752
|
+
provider: TextProvider;
|
|
2753
|
+
/** International format, such as +13135550100. */
|
|
2754
|
+
fromNumber: string;
|
|
2755
|
+
/** False pauses texting for the business without losing its number. */
|
|
2756
|
+
enabled: boolean;
|
|
2757
|
+
}
|
|
2758
|
+
interface TextSettingsView extends TextSettingsFields {
|
|
2759
|
+
updatedAt: Date;
|
|
2760
|
+
}
|
|
2761
|
+
interface TextSettingsProblem {
|
|
2762
|
+
path: string;
|
|
2763
|
+
message: string;
|
|
2764
|
+
}
|
|
2765
|
+
declare const TEXT_SETTINGS_FIELDS: readonly ["provider", "fromNumber", "enabled"];
|
|
2766
|
+
|
|
2767
|
+
/** International format, or null. Ten digits are read as a US number. */
|
|
2768
|
+
declare function normalizeTextNumber(raw: string): string | null;
|
|
2769
|
+
interface ValidateTextSettingsOptions {
|
|
2770
|
+
/** The providers this server has accounts for. Default: all known providers. */
|
|
2771
|
+
providers?: readonly TextProvider[];
|
|
2772
|
+
}
|
|
2773
|
+
/** The stored form of the settings, or a SCHED_1500 error listing every problem. */
|
|
2774
|
+
declare function validateTextSettings(input: unknown, options?: ValidateTextSettingsOptions): TextSettingsFields;
|
|
2775
|
+
|
|
2776
|
+
declare function getTextSettings(db: SchedulingDb, organizationId: string): Promise<TextSettingsView | null>;
|
|
2777
|
+
/** Saves the whole settings, replacing what was there. Throws SCHED_1500 listing every problem. */
|
|
2778
|
+
declare function saveTextSettings(db: SchedulingDb, organizationId: string, input: unknown, options?: ValidateTextSettingsOptions): Promise<TextSettingsView>;
|
|
2779
|
+
/** Removes the settings. True when there were some. */
|
|
2780
|
+
declare function deleteTextSettings(db: SchedulingDb, organizationId: string): Promise<boolean>;
|
|
2781
|
+
|
|
2782
|
+
/** READ may only look things up; FULL may also change them. */
|
|
2783
|
+
declare const API_KEY_ACCESS: readonly ["READ", "FULL"];
|
|
2784
|
+
type ApiKeyAccess = (typeof API_KEY_ACCESS)[number];
|
|
2785
|
+
declare const API_KEY_FIELDS: readonly ["name", "access"];
|
|
2786
|
+
declare const MAX_ACTIVE_API_KEYS = 25;
|
|
2787
|
+
declare const API_KEY_NAME_MAX = 60;
|
|
2788
|
+
interface ApiKeyFields {
|
|
2789
|
+
/** What the key is for, such as "Zapier". Shown in the list so the owner can tell keys apart. */
|
|
2790
|
+
name: string;
|
|
2791
|
+
access: ApiKeyAccess;
|
|
2792
|
+
}
|
|
2793
|
+
/** A key as listed: never the secret, only enough to recognise it. */
|
|
2794
|
+
interface ApiKeyView extends ApiKeyFields {
|
|
2795
|
+
id: string;
|
|
2796
|
+
/** The first characters of the key, so the owner can match a list entry to a key they hold. */
|
|
2797
|
+
prefix: string;
|
|
2798
|
+
createdByUserId: string | null;
|
|
2799
|
+
createdAt: Date;
|
|
2800
|
+
lastUsedAt: Date | null;
|
|
2801
|
+
revokedAt: Date | null;
|
|
2802
|
+
}
|
|
2803
|
+
/** Returned once, when a key is created. The secret cannot be read again. */
|
|
2804
|
+
interface CreatedApiKey {
|
|
2805
|
+
key: string;
|
|
2806
|
+
view: ApiKeyView;
|
|
2807
|
+
}
|
|
2808
|
+
/** Who a valid key acts as. */
|
|
2809
|
+
interface VerifiedApiKey {
|
|
2810
|
+
id: string;
|
|
2811
|
+
organizationId: string;
|
|
2812
|
+
access: ApiKeyAccess;
|
|
2813
|
+
createdByUserId: string | null;
|
|
2814
|
+
}
|
|
2815
|
+
|
|
2816
|
+
/** The cleaned-up request for a new key, or a SCHED_1600 error listing every problem. */
|
|
2817
|
+
declare function validateApiKeyRequest(input: unknown): ApiKeyFields;
|
|
2818
|
+
|
|
2819
|
+
/** True when the text has the shape of a key, so a request with some other credential is never looked up. */
|
|
2820
|
+
declare function looksLikeApiKey(text: string): boolean;
|
|
2821
|
+
|
|
2822
|
+
/**
|
|
2823
|
+
* Makes a key for the business. The secret is in the result once and cannot be read again.
|
|
2824
|
+
* Throws SCHED_1600 for a bad request and SCHED_1601 when the business already has the most keys it may have.
|
|
2825
|
+
* The limit is checked just before the key is written, so two requests at the same moment can pass it together.
|
|
2826
|
+
*/
|
|
2827
|
+
declare function createApiKey(db: SchedulingDb, organizationId: string, input: unknown, createdByUserId?: string): Promise<CreatedApiKey>;
|
|
2828
|
+
/** Every key of the business, newest first, revoked ones included. Never the secret. */
|
|
2829
|
+
declare function listApiKeys(db: SchedulingDb, organizationId: string): Promise<ApiKeyView[]>;
|
|
2830
|
+
/** Stops a key from working. True when it was active; false for an unknown, other-business or already revoked key. */
|
|
2831
|
+
declare function revokeApiKey(db: SchedulingDb, organizationId: string, id: string): Promise<boolean>;
|
|
2832
|
+
/** Who a secret acts as, or null when it is not a live key. Never throws for a bad secret. */
|
|
2833
|
+
declare function verifyApiKey(db: SchedulingDb, secret: string): Promise<VerifiedApiKey | null>;
|
|
2834
|
+
|
|
2835
|
+
export { API_KEY_ACCESS, API_KEY_FIELDS, API_KEY_NAME_MAX, type AcceptRelease, type AddTimeBlockInput, type ApiKeyAccess, type ApiKeyFields, type ApiKeyView, type AppointmentDashboardData, type AppointmentDashboardItem, type AppointmentDashboardStats, type AppointmentLocationType, type AppointmentStatus, type AppointmentWithDetails, type AssignmentStrategy, type AttemptOptions, type AuthAdapter, type AuthContext, type AvailabilityQuery, type AvailabilityResult, type AvailabilityRuleInput, BRAND_FIELDS, BlockedTargetError, type BookAppointmentInput, type BookingAnalytics, type BrandFields, type BrandProblem, type BrandView, type CalendarEvent, type CalendarEventRef, type CalendarSyncAdapter, type CalendarType, type CancelInput, type CancelRecurringScope, type CancellationFeeConfig, type CancellationFeeResult, type ChargeRequest, type ChargeResult, type Clock, type CreateAppointmentTypeInput, type CreateCalendarInput, type CreatedApiKey, DEFAULT_BACKOFF_SECONDS, DEFAULT_OFFER_MINUTES, type DashboardQuery, type DayAppointment, type DeliverOptions, type DeliverSummary, ERASED_EMAIL, ERASED_NAME, type EraseBlockers, type ErasePreview, type FreedSlot, type GroupCapacityResult, type GroupSession, type GroupSessionAttendee, type InMemoryClockControl, type InMemoryOptions, type InMemoryRecords, type IntakeFormField, type JoinWaitlistInput, LIMITS, MAX_ACTIVE_API_KEYS, MAX_ENDPOINTS_PER_ORGANIZATION, MAX_WAITING_PER_TYPE_DAY, type MarkNoShowInput, type NotificationAdapter, type NotificationChannel, type NotificationContext, type NotificationSender, type NotificationTrigger, OPERATORS_BY_TYPE, type OfferDetails, type OrgCancellationPolicy, type OutboundMessage, type ParsedSubject, type PaymentAdapter, type PaymentCheck, type PaymentContractOptions, type PaymentProcessor, type PaymentResult, type PrivacyRequestKind, type PrivacyRequestView, type PublicBrand, type PublicRoutingForm, type QuestionType, RECURRING_MAX_OCCURRENCES, LIMITS as ROUTING_LIMITS, type RecurringFrequency, type RefundOptions, type RefundResult, type RescheduleInput, type ResolvedDestination, type ResolvedSubject, type RetryConfig, type RoutingAnswers, type RoutingCondition, type RoutingDestination, type RoutingFallback, type RoutingFormDefinition, type RoutingFormInput, type RoutingFormSummary, type RoutingFormView, type RoutingOperator, type RoutingOutcome, type RoutingProblem, type RoutingQuestion, type RoutingRule, SCHEDULING_ERRORS, SIGNATURE_HEADER, type SchedulingAdapters, type SchedulingCallbacks, type SchedulingDb, SchedulingNotFoundError, SchedulingValidationError, type SendResult, type SettledBooking, type SubjectCounts, type SubjectExport, TEXT_PROVIDERS, TEXT_SETTINGS_FIELDS, type TeamAvailabilityQuery, type TeamAvailabilityResult, type TestSendResult, type TextProvider, type TextSettingsFields, type TextSettingsProblem, type TextSettingsView, type TimeSlot, type TransportRequest, USER_DAY_LIMIT, type UpdateCalendarInput, type UrlCheckOptions, type UserDayInput, type UserDayResult, type ValidateBrandOptions, type ValidateTextSettingsOptions, type VerifiedApiKey, WEBHOOK_EVENT_TYPES, WEBHOOK_TEST_EVENT, type WaitlistEntryView, type WaitlistOffer, type WebhookDeliveryView, type WebhookEndpointView, type WebhookEnvelope, type WebhookEventType, type WebhookTransport, adaptersToCallbacks, addDateOverride, addTimeBlock, appointmentWebhookData, archiveCalendar, beginWaitlistAccept, bookAppointment, brandTemplateFields, buildJitsiUrl, buildNotificationContext, buildOccurrenceStartTime, buildRecurringSlots, calculateCancellationFee, cancelAppointment, cancelPendingNotifications, checkAnswers, checkAuthContract, checkCalendarSyncContract, checkClockContract, checkNotificationContract, checkPaymentContract, checkWebhookUrl, completeWaitlistAccept, createApiKey, createAppointmentType, createCalendar, createInMemoryAdapters, createNodeTransport, createNotificationTemplate, createRoutingForm, createWebhookEndpoint, deleteBrand, deleteCalendar, deleteNotificationTemplate, deleteRoutingForm, deleteTextSettings, deleteWebhookEndpoint, deliverDueWebhooks, enqueueAppointmentWebhook, enqueueReminderSent, enqueueWebhookEvent, eraseSubject, expireWaitlistOffers, exportSubject, generateOccurrenceDates, generateWebhookSecret, getAppointment, getAppointmentDashboard, getAppointmentType, getAppointmentsForRange, getAvailableDates, getAvailableSlots, getBookingAnalytics, getBrand, getCalendar, getGroupCapacity, getGroupSessions, getNotificationTemplate, getPublicBrand, getPublicRoutingForm, getRoutingForm, getTeamAvailableSlots, getTextSettings, getUserDayAppointments, getWaitlistOffer, isPrivateAddress, isSlotAvailable, isVirtualMeeting, joinWaitlist, leaveWaitlist, listApiKeys, listAppointmentTypes, listAppointments, listAvailabilityRules, listCalendars, listNotificationTemplates, listPrivacyRequests, listRoutingForms, listWaitlist, listWebhookDeliveries, listWebhookEndpoints, localDay, localToUTC, looksLikeApiKey, markNoShow, matchingRules, normalizeTextNumber, offerFreedSlot, parseSubject, parseTimeLocal, previewErase, processPendingNotifications, queueImmediateNotification, queueStaffNotification, releaseWaitlistAccept, removeDateOverride, removeWaitlistEntry, renderTemplate, rescheduleAppointment, resolveDestination, resolveLocation, resolveSubject, retryWebhookDelivery, revokeApiKey, routeClient, saveBrand, saveTextSettings, schedError, scheduleNotifications, scopeToOrganization, selectCalendarForBooking, sendTestWebhook, senderIdentity, setWeeklyAvailability, settleBookedAccept, signWebhook, subjectHashes, testRoutingForm, toPublicBrand, tryOfferFreedSlot, updateAppointmentType, updateCalendar, updateNotificationTemplate, updateRoutingForm, validateApiKeyRequest, validateBrand, validateRoutingDestinations, validateRoutingStructure, validateTextSettings, verifyApiKey, verifyWebhookSignature, withCalendarVisibility, withOrganization };
|
package/dist/index.js
CHANGED
|
@@ -30,12 +30,16 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
30
30
|
// src/index.ts
|
|
31
31
|
var index_exports = {};
|
|
32
32
|
__export(index_exports, {
|
|
33
|
+
API_KEY_ACCESS: () => API_KEY_ACCESS,
|
|
34
|
+
API_KEY_FIELDS: () => API_KEY_FIELDS,
|
|
35
|
+
API_KEY_NAME_MAX: () => API_KEY_NAME_MAX,
|
|
33
36
|
BRAND_FIELDS: () => BRAND_FIELDS,
|
|
34
37
|
BlockedTargetError: () => BlockedTargetError,
|
|
35
38
|
DEFAULT_BACKOFF_SECONDS: () => DEFAULT_BACKOFF_SECONDS,
|
|
36
39
|
DEFAULT_OFFER_MINUTES: () => DEFAULT_OFFER_MINUTES,
|
|
37
40
|
ERASED_EMAIL: () => ERASED_EMAIL,
|
|
38
41
|
ERASED_NAME: () => ERASED_NAME,
|
|
42
|
+
MAX_ACTIVE_API_KEYS: () => MAX_ACTIVE_API_KEYS,
|
|
39
43
|
MAX_ENDPOINTS_PER_ORGANIZATION: () => MAX_ENDPOINTS_PER_ORGANIZATION,
|
|
40
44
|
MAX_WAITING_PER_TYPE_DAY: () => MAX_WAITING_PER_TYPE_DAY,
|
|
41
45
|
OPERATORS_BY_TYPE: () => OPERATORS_BY_TYPE,
|
|
@@ -45,6 +49,8 @@ __export(index_exports, {
|
|
|
45
49
|
SIGNATURE_HEADER: () => SIGNATURE_HEADER,
|
|
46
50
|
SchedulingNotFoundError: () => SchedulingNotFoundError,
|
|
47
51
|
SchedulingValidationError: () => SchedulingValidationError,
|
|
52
|
+
TEXT_PROVIDERS: () => TEXT_PROVIDERS,
|
|
53
|
+
TEXT_SETTINGS_FIELDS: () => TEXT_SETTINGS_FIELDS,
|
|
48
54
|
USER_DAY_LIMIT: () => USER_DAY_LIMIT,
|
|
49
55
|
WEBHOOK_EVENT_TYPES: () => WEBHOOK_EVENT_TYPES,
|
|
50
56
|
WEBHOOK_TEST_EVENT: () => WEBHOOK_TEST_EVENT,
|
|
@@ -71,6 +77,7 @@ __export(index_exports, {
|
|
|
71
77
|
checkPaymentContract: () => checkPaymentContract,
|
|
72
78
|
checkWebhookUrl: () => checkWebhookUrl,
|
|
73
79
|
completeWaitlistAccept: () => completeWaitlistAccept,
|
|
80
|
+
createApiKey: () => createApiKey,
|
|
74
81
|
createAppointmentType: () => createAppointmentType,
|
|
75
82
|
createCalendar: () => createCalendar,
|
|
76
83
|
createInMemoryAdapters: () => createInMemoryAdapters,
|
|
@@ -82,6 +89,7 @@ __export(index_exports, {
|
|
|
82
89
|
deleteCalendar: () => deleteCalendar,
|
|
83
90
|
deleteNotificationTemplate: () => deleteNotificationTemplate,
|
|
84
91
|
deleteRoutingForm: () => deleteRoutingForm,
|
|
92
|
+
deleteTextSettings: () => deleteTextSettings,
|
|
85
93
|
deleteWebhookEndpoint: () => deleteWebhookEndpoint,
|
|
86
94
|
deliverDueWebhooks: () => deliverDueWebhooks,
|
|
87
95
|
enqueueAppointmentWebhook: () => enqueueAppointmentWebhook,
|
|
@@ -108,6 +116,7 @@ __export(index_exports, {
|
|
|
108
116
|
getPublicRoutingForm: () => getPublicRoutingForm,
|
|
109
117
|
getRoutingForm: () => getRoutingForm,
|
|
110
118
|
getTeamAvailableSlots: () => getTeamAvailableSlots,
|
|
119
|
+
getTextSettings: () => getTextSettings,
|
|
111
120
|
getUserDayAppointments: () => getUserDayAppointments,
|
|
112
121
|
getWaitlistOffer: () => getWaitlistOffer,
|
|
113
122
|
isPrivateAddress: () => isPrivateAddress,
|
|
@@ -115,6 +124,7 @@ __export(index_exports, {
|
|
|
115
124
|
isVirtualMeeting: () => isVirtualMeeting,
|
|
116
125
|
joinWaitlist: () => joinWaitlist,
|
|
117
126
|
leaveWaitlist: () => leaveWaitlist,
|
|
127
|
+
listApiKeys: () => listApiKeys,
|
|
118
128
|
listAppointmentTypes: () => listAppointmentTypes,
|
|
119
129
|
listAppointments: () => listAppointments,
|
|
120
130
|
listAvailabilityRules: () => listAvailabilityRules,
|
|
@@ -127,8 +137,10 @@ __export(index_exports, {
|
|
|
127
137
|
listWebhookEndpoints: () => listWebhookEndpoints,
|
|
128
138
|
localDay: () => localDay,
|
|
129
139
|
localToUTC: () => localToUTC,
|
|
140
|
+
looksLikeApiKey: () => looksLikeApiKey,
|
|
130
141
|
markNoShow: () => markNoShow,
|
|
131
142
|
matchingRules: () => matchingRules,
|
|
143
|
+
normalizeTextNumber: () => normalizeTextNumber,
|
|
132
144
|
offerFreedSlot: () => offerFreedSlot,
|
|
133
145
|
parseSubject: () => parseSubject,
|
|
134
146
|
parseTimeLocal: () => parseTimeLocal,
|
|
@@ -145,8 +157,10 @@ __export(index_exports, {
|
|
|
145
157
|
resolveLocation: () => resolveLocation,
|
|
146
158
|
resolveSubject: () => resolveSubject,
|
|
147
159
|
retryWebhookDelivery: () => retryWebhookDelivery,
|
|
160
|
+
revokeApiKey: () => revokeApiKey,
|
|
148
161
|
routeClient: () => routeClient,
|
|
149
162
|
saveBrand: () => saveBrand,
|
|
163
|
+
saveTextSettings: () => saveTextSettings,
|
|
150
164
|
schedError: () => schedError,
|
|
151
165
|
scheduleNotifications: () => scheduleNotifications,
|
|
152
166
|
scopeToOrganization: () => scopeToOrganization,
|
|
@@ -164,9 +178,12 @@ __export(index_exports, {
|
|
|
164
178
|
updateCalendar: () => updateCalendar,
|
|
165
179
|
updateNotificationTemplate: () => updateNotificationTemplate,
|
|
166
180
|
updateRoutingForm: () => updateRoutingForm,
|
|
181
|
+
validateApiKeyRequest: () => validateApiKeyRequest,
|
|
167
182
|
validateBrand: () => validateBrand,
|
|
168
183
|
validateRoutingDestinations: () => validateRoutingDestinations,
|
|
169
184
|
validateRoutingStructure: () => validateRoutingStructure,
|
|
185
|
+
validateTextSettings: () => validateTextSettings,
|
|
186
|
+
verifyApiKey: () => verifyApiKey,
|
|
170
187
|
verifyWebhookSignature: () => verifyWebhookSignature,
|
|
171
188
|
withCalendarVisibility: () => withCalendarVisibility,
|
|
172
189
|
withOrganization: () => withOrganization
|
|
@@ -1310,6 +1327,61 @@ var BRAND_ERRORS = {
|
|
|
1310
1327
|
}
|
|
1311
1328
|
};
|
|
1312
1329
|
|
|
1330
|
+
// src/errors/registry-text-settings.ts
|
|
1331
|
+
var TEXT_SETTINGS_ERRORS = {
|
|
1332
|
+
SCHED_1500: {
|
|
1333
|
+
code: "SCHED_1500",
|
|
1334
|
+
file: "text-settings/",
|
|
1335
|
+
function: "validateTextSettings",
|
|
1336
|
+
severity: "warning",
|
|
1337
|
+
recoverable: true,
|
|
1338
|
+
description: "The text-message settings are not valid",
|
|
1339
|
+
diagnosis: [
|
|
1340
|
+
"Read the list of problems in the error context: each names the field and what is wrong",
|
|
1341
|
+
"The provider must be one the server offers; the number is a phone number such as +13135550100"
|
|
1342
|
+
]
|
|
1343
|
+
}
|
|
1344
|
+
};
|
|
1345
|
+
|
|
1346
|
+
// src/errors/registry-api-keys.ts
|
|
1347
|
+
var API_KEY_ERRORS = {
|
|
1348
|
+
SCHED_1600: {
|
|
1349
|
+
code: "SCHED_1600",
|
|
1350
|
+
file: "api-keys/",
|
|
1351
|
+
function: "validateApiKeyRequest",
|
|
1352
|
+
severity: "warning",
|
|
1353
|
+
recoverable: true,
|
|
1354
|
+
description: "The API key request is not valid",
|
|
1355
|
+
diagnosis: [
|
|
1356
|
+
"Read the list of problems in the error context: each names the field and what is wrong",
|
|
1357
|
+
"A key needs a name of at most 60 characters and an access level of READ or FULL"
|
|
1358
|
+
]
|
|
1359
|
+
},
|
|
1360
|
+
SCHED_1601: {
|
|
1361
|
+
code: "SCHED_1601",
|
|
1362
|
+
file: "api-keys/",
|
|
1363
|
+
function: "createApiKey",
|
|
1364
|
+
severity: "warning",
|
|
1365
|
+
recoverable: true,
|
|
1366
|
+
description: "The business already has the most API keys it may have",
|
|
1367
|
+
diagnosis: [
|
|
1368
|
+
"Revoke a key that is no longer used, then create the new one"
|
|
1369
|
+
]
|
|
1370
|
+
},
|
|
1371
|
+
SCHED_1602: {
|
|
1372
|
+
code: "SCHED_1602",
|
|
1373
|
+
file: "api-keys/",
|
|
1374
|
+
function: "verifyApiKey",
|
|
1375
|
+
severity: "warning",
|
|
1376
|
+
recoverable: true,
|
|
1377
|
+
description: "An API key was accepted but the time it was last used could not be recorded",
|
|
1378
|
+
diagnosis: [
|
|
1379
|
+
'The key still worked; only the "last used" time is out of date',
|
|
1380
|
+
"Check that the database is reachable and the OrganizationApiKey table has been migrated"
|
|
1381
|
+
]
|
|
1382
|
+
}
|
|
1383
|
+
};
|
|
1384
|
+
|
|
1313
1385
|
// src/errors/registry.ts
|
|
1314
1386
|
var SCHEDULING_ERRORS = {
|
|
1315
1387
|
...CALENDARS_AVAILABILITY_ERRORS,
|
|
@@ -1324,7 +1396,9 @@ var SCHEDULING_ERRORS = {
|
|
|
1324
1396
|
...WAITLIST_ERRORS,
|
|
1325
1397
|
...ROUTING_ERRORS,
|
|
1326
1398
|
...PRIVACY_ERRORS,
|
|
1327
|
-
...BRAND_ERRORS
|
|
1399
|
+
...BRAND_ERRORS,
|
|
1400
|
+
...TEXT_SETTINGS_ERRORS,
|
|
1401
|
+
...API_KEY_ERRORS
|
|
1328
1402
|
};
|
|
1329
1403
|
|
|
1330
1404
|
// src/errors/diagnostic-error.ts
|
|
@@ -2958,7 +3032,7 @@ async function processPendingNotifications(db, sender, options) {
|
|
|
2958
3032
|
if (claimed.length === 0) return { sent: 0, failed: 0, deadLettered: 0, skipped: 0 };
|
|
2959
3033
|
const pending = await db.scheduledNotification.findMany({
|
|
2960
3034
|
where: { id: { in: claimed.map((c) => c.id) } },
|
|
2961
|
-
...options?.brand ? { include: { appointment: { select: { calendar: { select: { organizationId: true } } } } } } : {}
|
|
3035
|
+
...options?.brand || options?.organization ? { include: { appointment: { select: { calendar: { select: { organizationId: true } } } } } } : {}
|
|
2962
3036
|
});
|
|
2963
3037
|
const senders = options?.brand ? await loadSenders(db, pending) : null;
|
|
2964
3038
|
let sent = 0;
|
|
@@ -2974,7 +3048,8 @@ async function processPendingNotifications(db, sender, options) {
|
|
|
2974
3048
|
notification.body,
|
|
2975
3049
|
{
|
|
2976
3050
|
trigger: notification.trigger,
|
|
2977
|
-
...senderFor(senders, notification)
|
|
3051
|
+
...senderFor(senders, notification),
|
|
3052
|
+
...options?.organization ? organizationOf(notification) : {}
|
|
2978
3053
|
}
|
|
2979
3054
|
);
|
|
2980
3055
|
if (result?.skipped) {
|
|
@@ -3040,6 +3115,10 @@ async function loadSenders(db, rows) {
|
|
|
3040
3115
|
}
|
|
3041
3116
|
return senders;
|
|
3042
3117
|
}
|
|
3118
|
+
function organizationOf(row) {
|
|
3119
|
+
const organizationId = row.appointment?.calendar?.organizationId;
|
|
3120
|
+
return organizationId ? { organizationId } : {};
|
|
3121
|
+
}
|
|
3043
3122
|
function senderFor(senders, row) {
|
|
3044
3123
|
const organizationId = row.appointment?.calendar?.organizationId;
|
|
3045
3124
|
const from = senders && organizationId ? senders.get(organizationId) : void 0;
|
|
@@ -4145,7 +4224,7 @@ function adaptersToCallbacks(adapters, passThrough = {}) {
|
|
|
4145
4224
|
return {
|
|
4146
4225
|
...passThrough,
|
|
4147
4226
|
sendNotification: async (channel, to, subject, body, context) => {
|
|
4148
|
-
const result = await adapters.notifications.send({ channel, to, subject, body, trigger: context?.trigger, ...context?.from ? { from: context.from } : {} });
|
|
4227
|
+
const result = await adapters.notifications.send({ channel, to, subject, body, trigger: context?.trigger, ...context?.from ? { from: context.from } : {}, ...context?.organizationId ? { organizationId: context.organizationId } : {} });
|
|
4149
4228
|
if (result.status === "SKIPPED") return { skipped: true, reason: result.reason };
|
|
4150
4229
|
return void 0;
|
|
4151
4230
|
},
|
|
@@ -6158,14 +6237,162 @@ async function eraseSubject(db, input) {
|
|
|
6158
6237
|
return { counts };
|
|
6159
6238
|
}, { timeout: 12e4 });
|
|
6160
6239
|
}
|
|
6240
|
+
|
|
6241
|
+
// src/text-settings/types.ts
|
|
6242
|
+
var TEXT_PROVIDERS = ["TELNYX", "TWILIO"];
|
|
6243
|
+
var TEXT_SETTINGS_FIELDS = ["provider", "fromNumber", "enabled"];
|
|
6244
|
+
|
|
6245
|
+
// src/text-settings/validate.ts
|
|
6246
|
+
function normalizeTextNumber(raw) {
|
|
6247
|
+
const digits = raw.trim().replace(/[\s().-]/g, "");
|
|
6248
|
+
if (/^\+[1-9]\d{7,14}$/.test(digits)) return digits;
|
|
6249
|
+
if (/^\d{10}$/.test(digits)) return `+1${digits}`;
|
|
6250
|
+
if (/^1\d{10}$/.test(digits)) return `+${digits}`;
|
|
6251
|
+
return null;
|
|
6252
|
+
}
|
|
6253
|
+
function validateTextSettings(input, options = {}) {
|
|
6254
|
+
const problems = [];
|
|
6255
|
+
if (typeof input !== "object" || input === null || Array.isArray(input)) {
|
|
6256
|
+
throw new SchedulingValidationError("The text-message settings are not valid", "SCHED_1500", { errors: [{ path: "", message: "Must be an object" }] });
|
|
6257
|
+
}
|
|
6258
|
+
const given = input;
|
|
6259
|
+
for (const key of Object.keys(given)) if (!TEXT_SETTINGS_FIELDS.includes(key)) problems.push({ path: key, message: "Unknown field" });
|
|
6260
|
+
const offered = options.providers ?? TEXT_PROVIDERS;
|
|
6261
|
+
let provider = TEXT_PROVIDERS[0];
|
|
6262
|
+
if (typeof given.provider !== "string" || given.provider === "") problems.push({ path: "provider", message: "Required" });
|
|
6263
|
+
else if (!TEXT_PROVIDERS.includes(given.provider) || !offered.includes(given.provider)) {
|
|
6264
|
+
problems.push({ path: "provider", message: `Must be one of: ${offered.join(", ")}` });
|
|
6265
|
+
} else provider = given.provider;
|
|
6266
|
+
let fromNumber = "";
|
|
6267
|
+
if (typeof given.fromNumber !== "string" || given.fromNumber.trim() === "") problems.push({ path: "fromNumber", message: "Required" });
|
|
6268
|
+
else {
|
|
6269
|
+
const normalized = normalizeTextNumber(given.fromNumber);
|
|
6270
|
+
if (normalized === null) problems.push({ path: "fromNumber", message: "Must be a phone number such as +13135550100" });
|
|
6271
|
+
else fromNumber = normalized;
|
|
6272
|
+
}
|
|
6273
|
+
let enabled = true;
|
|
6274
|
+
if (given.enabled !== void 0) {
|
|
6275
|
+
if (typeof given.enabled === "boolean") enabled = given.enabled;
|
|
6276
|
+
else problems.push({ path: "enabled", message: "Must be true or false" });
|
|
6277
|
+
}
|
|
6278
|
+
if (problems.length > 0) throw new SchedulingValidationError("The text-message settings are not valid", "SCHED_1500", { errors: problems });
|
|
6279
|
+
return { provider, fromNumber, enabled };
|
|
6280
|
+
}
|
|
6281
|
+
|
|
6282
|
+
// src/text-settings/crud.ts
|
|
6283
|
+
var SELECT2 = { provider: true, fromNumber: true, enabled: true, updatedAt: true };
|
|
6284
|
+
async function getTextSettings(db, organizationId) {
|
|
6285
|
+
return db.organizationTextSettings.findUnique({ where: { organizationId }, select: SELECT2 });
|
|
6286
|
+
}
|
|
6287
|
+
async function saveTextSettings(db, organizationId, input, options = {}) {
|
|
6288
|
+
const fields = validateTextSettings(input, options);
|
|
6289
|
+
return db.organizationTextSettings.upsert({
|
|
6290
|
+
where: { organizationId },
|
|
6291
|
+
create: { organizationId, ...fields },
|
|
6292
|
+
update: { ...fields },
|
|
6293
|
+
select: SELECT2
|
|
6294
|
+
});
|
|
6295
|
+
}
|
|
6296
|
+
async function deleteTextSettings(db, organizationId) {
|
|
6297
|
+
const { count } = await db.organizationTextSettings.deleteMany({ where: { organizationId } });
|
|
6298
|
+
return count > 0;
|
|
6299
|
+
}
|
|
6300
|
+
|
|
6301
|
+
// src/api-keys/types.ts
|
|
6302
|
+
var API_KEY_ACCESS = ["READ", "FULL"];
|
|
6303
|
+
var API_KEY_FIELDS = ["name", "access"];
|
|
6304
|
+
var MAX_ACTIVE_API_KEYS = 25;
|
|
6305
|
+
var API_KEY_NAME_MAX = 60;
|
|
6306
|
+
|
|
6307
|
+
// src/api-keys/validate.ts
|
|
6308
|
+
function validateApiKeyRequest(input) {
|
|
6309
|
+
const problems = [];
|
|
6310
|
+
if (typeof input !== "object" || input === null || Array.isArray(input)) {
|
|
6311
|
+
throw new SchedulingValidationError("The API key request is not valid", "SCHED_1600", { errors: [{ path: "", message: "Must be an object" }] });
|
|
6312
|
+
}
|
|
6313
|
+
const given = input;
|
|
6314
|
+
for (const key of Object.keys(given)) if (!API_KEY_FIELDS.includes(key)) problems.push({ path: key, message: "Unknown field" });
|
|
6315
|
+
let name = "";
|
|
6316
|
+
if (typeof given.name !== "string" || given.name.trim() === "") problems.push({ path: "name", message: "Required" });
|
|
6317
|
+
else if (given.name.trim().length > API_KEY_NAME_MAX) problems.push({ path: "name", message: `Must be at most ${API_KEY_NAME_MAX} characters` });
|
|
6318
|
+
else name = given.name.trim();
|
|
6319
|
+
let access = "READ";
|
|
6320
|
+
if (given.access === void 0) problems.push({ path: "access", message: "Required" });
|
|
6321
|
+
else if (typeof given.access !== "string" || !API_KEY_ACCESS.includes(given.access)) problems.push({ path: "access", message: `Must be one of: ${API_KEY_ACCESS.join(", ")}` });
|
|
6322
|
+
else access = given.access;
|
|
6323
|
+
if (problems.length > 0) throw new SchedulingValidationError("The API key request is not valid", "SCHED_1600", { errors: problems });
|
|
6324
|
+
return { name, access };
|
|
6325
|
+
}
|
|
6326
|
+
|
|
6327
|
+
// src/api-keys/secret.ts
|
|
6328
|
+
var import_node_crypto8 = require("crypto");
|
|
6329
|
+
var API_KEY_PREFIX = "osk_";
|
|
6330
|
+
var PREFIX_SHOWN = 12;
|
|
6331
|
+
function generateApiKeySecret() {
|
|
6332
|
+
return `${API_KEY_PREFIX}${(0, import_node_crypto8.randomBytes)(32).toString("base64url")}`;
|
|
6333
|
+
}
|
|
6334
|
+
function hashApiKeySecret(secret) {
|
|
6335
|
+
return (0, import_node_crypto8.createHash)("sha256").update(secret).digest("hex");
|
|
6336
|
+
}
|
|
6337
|
+
function visiblePrefix(secret) {
|
|
6338
|
+
return secret.slice(0, PREFIX_SHOWN);
|
|
6339
|
+
}
|
|
6340
|
+
function looksLikeApiKey(text2) {
|
|
6341
|
+
return /^osk_[A-Za-z0-9_-]{43}$/.test(text2);
|
|
6342
|
+
}
|
|
6343
|
+
|
|
6344
|
+
// src/api-keys/crud.ts
|
|
6345
|
+
var VIEW = { id: true, name: true, access: true, prefix: true, createdByUserId: true, createdAt: true, lastUsedAt: true, revokedAt: true };
|
|
6346
|
+
var LAST_USED_REFRESH_MS = 10 * 60 * 1e3;
|
|
6347
|
+
async function createApiKey(db, organizationId, input, createdByUserId) {
|
|
6348
|
+
const fields = validateApiKeyRequest(input);
|
|
6349
|
+
const active = await db.organizationApiKey.count({ where: { organizationId, revokedAt: null } });
|
|
6350
|
+
if (active >= MAX_ACTIVE_API_KEYS) {
|
|
6351
|
+
throw new SchedulingValidationError(`A business may have at most ${MAX_ACTIVE_API_KEYS} API keys`, "SCHED_1601", { limit: MAX_ACTIVE_API_KEYS });
|
|
6352
|
+
}
|
|
6353
|
+
const key = generateApiKeySecret();
|
|
6354
|
+
const view2 = await db.organizationApiKey.create({
|
|
6355
|
+
data: { organizationId, ...fields, prefix: visiblePrefix(key), keyHash: hashApiKeySecret(key), createdByUserId: createdByUserId ?? null },
|
|
6356
|
+
select: VIEW
|
|
6357
|
+
});
|
|
6358
|
+
return { key, view: view2 };
|
|
6359
|
+
}
|
|
6360
|
+
async function listApiKeys(db, organizationId) {
|
|
6361
|
+
return db.organizationApiKey.findMany({ where: { organizationId }, orderBy: { createdAt: "desc" }, select: VIEW });
|
|
6362
|
+
}
|
|
6363
|
+
async function revokeApiKey(db, organizationId, id) {
|
|
6364
|
+
const { count } = await db.organizationApiKey.updateMany({ where: { id, organizationId, revokedAt: null }, data: { revokedAt: /* @__PURE__ */ new Date() } });
|
|
6365
|
+
return count > 0;
|
|
6366
|
+
}
|
|
6367
|
+
async function verifyApiKey(db, secret) {
|
|
6368
|
+
if (!looksLikeApiKey(secret)) return null;
|
|
6369
|
+
const row = await db.organizationApiKey.findUnique({
|
|
6370
|
+
where: { keyHash: hashApiKeySecret(secret) },
|
|
6371
|
+
select: { id: true, organizationId: true, access: true, createdByUserId: true, revokedAt: true, lastUsedAt: true }
|
|
6372
|
+
});
|
|
6373
|
+
if (!row || row.revokedAt) return null;
|
|
6374
|
+
if (!API_KEY_ACCESS.includes(row.access)) return null;
|
|
6375
|
+
const now = Date.now();
|
|
6376
|
+
if (!row.lastUsedAt || now - row.lastUsedAt.getTime() > LAST_USED_REFRESH_MS) {
|
|
6377
|
+
await db.organizationApiKey.updateMany({ where: { id: row.id, revokedAt: null }, data: { lastUsedAt: new Date(now) } }).catch((error) => {
|
|
6378
|
+
const diagnostic = schedError("SCHED_1602", { keyId: row.id, error });
|
|
6379
|
+
console.error(`[api-keys] ${diagnostic.code}-${diagnostic.ref} could not record last use`, error);
|
|
6380
|
+
});
|
|
6381
|
+
}
|
|
6382
|
+
return { id: row.id, organizationId: row.organizationId, access: row.access, createdByUserId: row.createdByUserId };
|
|
6383
|
+
}
|
|
6161
6384
|
// Annotate the CommonJS export names for ESM import in node:
|
|
6162
6385
|
0 && (module.exports = {
|
|
6386
|
+
API_KEY_ACCESS,
|
|
6387
|
+
API_KEY_FIELDS,
|
|
6388
|
+
API_KEY_NAME_MAX,
|
|
6163
6389
|
BRAND_FIELDS,
|
|
6164
6390
|
BlockedTargetError,
|
|
6165
6391
|
DEFAULT_BACKOFF_SECONDS,
|
|
6166
6392
|
DEFAULT_OFFER_MINUTES,
|
|
6167
6393
|
ERASED_EMAIL,
|
|
6168
6394
|
ERASED_NAME,
|
|
6395
|
+
MAX_ACTIVE_API_KEYS,
|
|
6169
6396
|
MAX_ENDPOINTS_PER_ORGANIZATION,
|
|
6170
6397
|
MAX_WAITING_PER_TYPE_DAY,
|
|
6171
6398
|
OPERATORS_BY_TYPE,
|
|
@@ -6175,6 +6402,8 @@ async function eraseSubject(db, input) {
|
|
|
6175
6402
|
SIGNATURE_HEADER,
|
|
6176
6403
|
SchedulingNotFoundError,
|
|
6177
6404
|
SchedulingValidationError,
|
|
6405
|
+
TEXT_PROVIDERS,
|
|
6406
|
+
TEXT_SETTINGS_FIELDS,
|
|
6178
6407
|
USER_DAY_LIMIT,
|
|
6179
6408
|
WEBHOOK_EVENT_TYPES,
|
|
6180
6409
|
WEBHOOK_TEST_EVENT,
|
|
@@ -6201,6 +6430,7 @@ async function eraseSubject(db, input) {
|
|
|
6201
6430
|
checkPaymentContract,
|
|
6202
6431
|
checkWebhookUrl,
|
|
6203
6432
|
completeWaitlistAccept,
|
|
6433
|
+
createApiKey,
|
|
6204
6434
|
createAppointmentType,
|
|
6205
6435
|
createCalendar,
|
|
6206
6436
|
createInMemoryAdapters,
|
|
@@ -6212,6 +6442,7 @@ async function eraseSubject(db, input) {
|
|
|
6212
6442
|
deleteCalendar,
|
|
6213
6443
|
deleteNotificationTemplate,
|
|
6214
6444
|
deleteRoutingForm,
|
|
6445
|
+
deleteTextSettings,
|
|
6215
6446
|
deleteWebhookEndpoint,
|
|
6216
6447
|
deliverDueWebhooks,
|
|
6217
6448
|
enqueueAppointmentWebhook,
|
|
@@ -6238,6 +6469,7 @@ async function eraseSubject(db, input) {
|
|
|
6238
6469
|
getPublicRoutingForm,
|
|
6239
6470
|
getRoutingForm,
|
|
6240
6471
|
getTeamAvailableSlots,
|
|
6472
|
+
getTextSettings,
|
|
6241
6473
|
getUserDayAppointments,
|
|
6242
6474
|
getWaitlistOffer,
|
|
6243
6475
|
isPrivateAddress,
|
|
@@ -6245,6 +6477,7 @@ async function eraseSubject(db, input) {
|
|
|
6245
6477
|
isVirtualMeeting,
|
|
6246
6478
|
joinWaitlist,
|
|
6247
6479
|
leaveWaitlist,
|
|
6480
|
+
listApiKeys,
|
|
6248
6481
|
listAppointmentTypes,
|
|
6249
6482
|
listAppointments,
|
|
6250
6483
|
listAvailabilityRules,
|
|
@@ -6257,8 +6490,10 @@ async function eraseSubject(db, input) {
|
|
|
6257
6490
|
listWebhookEndpoints,
|
|
6258
6491
|
localDay,
|
|
6259
6492
|
localToUTC,
|
|
6493
|
+
looksLikeApiKey,
|
|
6260
6494
|
markNoShow,
|
|
6261
6495
|
matchingRules,
|
|
6496
|
+
normalizeTextNumber,
|
|
6262
6497
|
offerFreedSlot,
|
|
6263
6498
|
parseSubject,
|
|
6264
6499
|
parseTimeLocal,
|
|
@@ -6275,8 +6510,10 @@ async function eraseSubject(db, input) {
|
|
|
6275
6510
|
resolveLocation,
|
|
6276
6511
|
resolveSubject,
|
|
6277
6512
|
retryWebhookDelivery,
|
|
6513
|
+
revokeApiKey,
|
|
6278
6514
|
routeClient,
|
|
6279
6515
|
saveBrand,
|
|
6516
|
+
saveTextSettings,
|
|
6280
6517
|
schedError,
|
|
6281
6518
|
scheduleNotifications,
|
|
6282
6519
|
scopeToOrganization,
|
|
@@ -6294,9 +6531,12 @@ async function eraseSubject(db, input) {
|
|
|
6294
6531
|
updateCalendar,
|
|
6295
6532
|
updateNotificationTemplate,
|
|
6296
6533
|
updateRoutingForm,
|
|
6534
|
+
validateApiKeyRequest,
|
|
6297
6535
|
validateBrand,
|
|
6298
6536
|
validateRoutingDestinations,
|
|
6299
6537
|
validateRoutingStructure,
|
|
6538
|
+
validateTextSettings,
|
|
6539
|
+
verifyApiKey,
|
|
6300
6540
|
verifyWebhookSignature,
|
|
6301
6541
|
withCalendarVisibility,
|
|
6302
6542
|
withOrganization
|
package/dist/index.mjs
CHANGED
|
@@ -1135,6 +1135,61 @@ var BRAND_ERRORS = {
|
|
|
1135
1135
|
}
|
|
1136
1136
|
};
|
|
1137
1137
|
|
|
1138
|
+
// src/errors/registry-text-settings.ts
|
|
1139
|
+
var TEXT_SETTINGS_ERRORS = {
|
|
1140
|
+
SCHED_1500: {
|
|
1141
|
+
code: "SCHED_1500",
|
|
1142
|
+
file: "text-settings/",
|
|
1143
|
+
function: "validateTextSettings",
|
|
1144
|
+
severity: "warning",
|
|
1145
|
+
recoverable: true,
|
|
1146
|
+
description: "The text-message settings are not valid",
|
|
1147
|
+
diagnosis: [
|
|
1148
|
+
"Read the list of problems in the error context: each names the field and what is wrong",
|
|
1149
|
+
"The provider must be one the server offers; the number is a phone number such as +13135550100"
|
|
1150
|
+
]
|
|
1151
|
+
}
|
|
1152
|
+
};
|
|
1153
|
+
|
|
1154
|
+
// src/errors/registry-api-keys.ts
|
|
1155
|
+
var API_KEY_ERRORS = {
|
|
1156
|
+
SCHED_1600: {
|
|
1157
|
+
code: "SCHED_1600",
|
|
1158
|
+
file: "api-keys/",
|
|
1159
|
+
function: "validateApiKeyRequest",
|
|
1160
|
+
severity: "warning",
|
|
1161
|
+
recoverable: true,
|
|
1162
|
+
description: "The API key request is not valid",
|
|
1163
|
+
diagnosis: [
|
|
1164
|
+
"Read the list of problems in the error context: each names the field and what is wrong",
|
|
1165
|
+
"A key needs a name of at most 60 characters and an access level of READ or FULL"
|
|
1166
|
+
]
|
|
1167
|
+
},
|
|
1168
|
+
SCHED_1601: {
|
|
1169
|
+
code: "SCHED_1601",
|
|
1170
|
+
file: "api-keys/",
|
|
1171
|
+
function: "createApiKey",
|
|
1172
|
+
severity: "warning",
|
|
1173
|
+
recoverable: true,
|
|
1174
|
+
description: "The business already has the most API keys it may have",
|
|
1175
|
+
diagnosis: [
|
|
1176
|
+
"Revoke a key that is no longer used, then create the new one"
|
|
1177
|
+
]
|
|
1178
|
+
},
|
|
1179
|
+
SCHED_1602: {
|
|
1180
|
+
code: "SCHED_1602",
|
|
1181
|
+
file: "api-keys/",
|
|
1182
|
+
function: "verifyApiKey",
|
|
1183
|
+
severity: "warning",
|
|
1184
|
+
recoverable: true,
|
|
1185
|
+
description: "An API key was accepted but the time it was last used could not be recorded",
|
|
1186
|
+
diagnosis: [
|
|
1187
|
+
'The key still worked; only the "last used" time is out of date',
|
|
1188
|
+
"Check that the database is reachable and the OrganizationApiKey table has been migrated"
|
|
1189
|
+
]
|
|
1190
|
+
}
|
|
1191
|
+
};
|
|
1192
|
+
|
|
1138
1193
|
// src/errors/registry.ts
|
|
1139
1194
|
var SCHEDULING_ERRORS = {
|
|
1140
1195
|
...CALENDARS_AVAILABILITY_ERRORS,
|
|
@@ -1149,7 +1204,9 @@ var SCHEDULING_ERRORS = {
|
|
|
1149
1204
|
...WAITLIST_ERRORS,
|
|
1150
1205
|
...ROUTING_ERRORS,
|
|
1151
1206
|
...PRIVACY_ERRORS,
|
|
1152
|
-
...BRAND_ERRORS
|
|
1207
|
+
...BRAND_ERRORS,
|
|
1208
|
+
...TEXT_SETTINGS_ERRORS,
|
|
1209
|
+
...API_KEY_ERRORS
|
|
1153
1210
|
};
|
|
1154
1211
|
|
|
1155
1212
|
// src/errors/diagnostic-error.ts
|
|
@@ -2783,7 +2840,7 @@ async function processPendingNotifications(db, sender, options) {
|
|
|
2783
2840
|
if (claimed.length === 0) return { sent: 0, failed: 0, deadLettered: 0, skipped: 0 };
|
|
2784
2841
|
const pending = await db.scheduledNotification.findMany({
|
|
2785
2842
|
where: { id: { in: claimed.map((c) => c.id) } },
|
|
2786
|
-
...options?.brand ? { include: { appointment: { select: { calendar: { select: { organizationId: true } } } } } } : {}
|
|
2843
|
+
...options?.brand || options?.organization ? { include: { appointment: { select: { calendar: { select: { organizationId: true } } } } } } : {}
|
|
2787
2844
|
});
|
|
2788
2845
|
const senders = options?.brand ? await loadSenders(db, pending) : null;
|
|
2789
2846
|
let sent = 0;
|
|
@@ -2799,7 +2856,8 @@ async function processPendingNotifications(db, sender, options) {
|
|
|
2799
2856
|
notification.body,
|
|
2800
2857
|
{
|
|
2801
2858
|
trigger: notification.trigger,
|
|
2802
|
-
...senderFor(senders, notification)
|
|
2859
|
+
...senderFor(senders, notification),
|
|
2860
|
+
...options?.organization ? organizationOf(notification) : {}
|
|
2803
2861
|
}
|
|
2804
2862
|
);
|
|
2805
2863
|
if (result?.skipped) {
|
|
@@ -2865,6 +2923,10 @@ async function loadSenders(db, rows) {
|
|
|
2865
2923
|
}
|
|
2866
2924
|
return senders;
|
|
2867
2925
|
}
|
|
2926
|
+
function organizationOf(row) {
|
|
2927
|
+
const organizationId = row.appointment?.calendar?.organizationId;
|
|
2928
|
+
return organizationId ? { organizationId } : {};
|
|
2929
|
+
}
|
|
2868
2930
|
function senderFor(senders, row) {
|
|
2869
2931
|
const organizationId = row.appointment?.calendar?.organizationId;
|
|
2870
2932
|
const from = senders && organizationId ? senders.get(organizationId) : void 0;
|
|
@@ -3970,7 +4032,7 @@ function adaptersToCallbacks(adapters, passThrough = {}) {
|
|
|
3970
4032
|
return {
|
|
3971
4033
|
...passThrough,
|
|
3972
4034
|
sendNotification: async (channel, to, subject, body, context) => {
|
|
3973
|
-
const result = await adapters.notifications.send({ channel, to, subject, body, trigger: context?.trigger, ...context?.from ? { from: context.from } : {} });
|
|
4035
|
+
const result = await adapters.notifications.send({ channel, to, subject, body, trigger: context?.trigger, ...context?.from ? { from: context.from } : {}, ...context?.organizationId ? { organizationId: context.organizationId } : {} });
|
|
3974
4036
|
if (result.status === "SKIPPED") return { skipped: true, reason: result.reason };
|
|
3975
4037
|
return void 0;
|
|
3976
4038
|
},
|
|
@@ -5983,13 +6045,161 @@ async function eraseSubject(db, input) {
|
|
|
5983
6045
|
return { counts };
|
|
5984
6046
|
}, { timeout: 12e4 });
|
|
5985
6047
|
}
|
|
6048
|
+
|
|
6049
|
+
// src/text-settings/types.ts
|
|
6050
|
+
var TEXT_PROVIDERS = ["TELNYX", "TWILIO"];
|
|
6051
|
+
var TEXT_SETTINGS_FIELDS = ["provider", "fromNumber", "enabled"];
|
|
6052
|
+
|
|
6053
|
+
// src/text-settings/validate.ts
|
|
6054
|
+
function normalizeTextNumber(raw) {
|
|
6055
|
+
const digits = raw.trim().replace(/[\s().-]/g, "");
|
|
6056
|
+
if (/^\+[1-9]\d{7,14}$/.test(digits)) return digits;
|
|
6057
|
+
if (/^\d{10}$/.test(digits)) return `+1${digits}`;
|
|
6058
|
+
if (/^1\d{10}$/.test(digits)) return `+${digits}`;
|
|
6059
|
+
return null;
|
|
6060
|
+
}
|
|
6061
|
+
function validateTextSettings(input, options = {}) {
|
|
6062
|
+
const problems = [];
|
|
6063
|
+
if (typeof input !== "object" || input === null || Array.isArray(input)) {
|
|
6064
|
+
throw new SchedulingValidationError("The text-message settings are not valid", "SCHED_1500", { errors: [{ path: "", message: "Must be an object" }] });
|
|
6065
|
+
}
|
|
6066
|
+
const given = input;
|
|
6067
|
+
for (const key of Object.keys(given)) if (!TEXT_SETTINGS_FIELDS.includes(key)) problems.push({ path: key, message: "Unknown field" });
|
|
6068
|
+
const offered = options.providers ?? TEXT_PROVIDERS;
|
|
6069
|
+
let provider = TEXT_PROVIDERS[0];
|
|
6070
|
+
if (typeof given.provider !== "string" || given.provider === "") problems.push({ path: "provider", message: "Required" });
|
|
6071
|
+
else if (!TEXT_PROVIDERS.includes(given.provider) || !offered.includes(given.provider)) {
|
|
6072
|
+
problems.push({ path: "provider", message: `Must be one of: ${offered.join(", ")}` });
|
|
6073
|
+
} else provider = given.provider;
|
|
6074
|
+
let fromNumber = "";
|
|
6075
|
+
if (typeof given.fromNumber !== "string" || given.fromNumber.trim() === "") problems.push({ path: "fromNumber", message: "Required" });
|
|
6076
|
+
else {
|
|
6077
|
+
const normalized = normalizeTextNumber(given.fromNumber);
|
|
6078
|
+
if (normalized === null) problems.push({ path: "fromNumber", message: "Must be a phone number such as +13135550100" });
|
|
6079
|
+
else fromNumber = normalized;
|
|
6080
|
+
}
|
|
6081
|
+
let enabled = true;
|
|
6082
|
+
if (given.enabled !== void 0) {
|
|
6083
|
+
if (typeof given.enabled === "boolean") enabled = given.enabled;
|
|
6084
|
+
else problems.push({ path: "enabled", message: "Must be true or false" });
|
|
6085
|
+
}
|
|
6086
|
+
if (problems.length > 0) throw new SchedulingValidationError("The text-message settings are not valid", "SCHED_1500", { errors: problems });
|
|
6087
|
+
return { provider, fromNumber, enabled };
|
|
6088
|
+
}
|
|
6089
|
+
|
|
6090
|
+
// src/text-settings/crud.ts
|
|
6091
|
+
var SELECT2 = { provider: true, fromNumber: true, enabled: true, updatedAt: true };
|
|
6092
|
+
async function getTextSettings(db, organizationId) {
|
|
6093
|
+
return db.organizationTextSettings.findUnique({ where: { organizationId }, select: SELECT2 });
|
|
6094
|
+
}
|
|
6095
|
+
async function saveTextSettings(db, organizationId, input, options = {}) {
|
|
6096
|
+
const fields = validateTextSettings(input, options);
|
|
6097
|
+
return db.organizationTextSettings.upsert({
|
|
6098
|
+
where: { organizationId },
|
|
6099
|
+
create: { organizationId, ...fields },
|
|
6100
|
+
update: { ...fields },
|
|
6101
|
+
select: SELECT2
|
|
6102
|
+
});
|
|
6103
|
+
}
|
|
6104
|
+
async function deleteTextSettings(db, organizationId) {
|
|
6105
|
+
const { count } = await db.organizationTextSettings.deleteMany({ where: { organizationId } });
|
|
6106
|
+
return count > 0;
|
|
6107
|
+
}
|
|
6108
|
+
|
|
6109
|
+
// src/api-keys/types.ts
|
|
6110
|
+
var API_KEY_ACCESS = ["READ", "FULL"];
|
|
6111
|
+
var API_KEY_FIELDS = ["name", "access"];
|
|
6112
|
+
var MAX_ACTIVE_API_KEYS = 25;
|
|
6113
|
+
var API_KEY_NAME_MAX = 60;
|
|
6114
|
+
|
|
6115
|
+
// src/api-keys/validate.ts
|
|
6116
|
+
function validateApiKeyRequest(input) {
|
|
6117
|
+
const problems = [];
|
|
6118
|
+
if (typeof input !== "object" || input === null || Array.isArray(input)) {
|
|
6119
|
+
throw new SchedulingValidationError("The API key request is not valid", "SCHED_1600", { errors: [{ path: "", message: "Must be an object" }] });
|
|
6120
|
+
}
|
|
6121
|
+
const given = input;
|
|
6122
|
+
for (const key of Object.keys(given)) if (!API_KEY_FIELDS.includes(key)) problems.push({ path: key, message: "Unknown field" });
|
|
6123
|
+
let name = "";
|
|
6124
|
+
if (typeof given.name !== "string" || given.name.trim() === "") problems.push({ path: "name", message: "Required" });
|
|
6125
|
+
else if (given.name.trim().length > API_KEY_NAME_MAX) problems.push({ path: "name", message: `Must be at most ${API_KEY_NAME_MAX} characters` });
|
|
6126
|
+
else name = given.name.trim();
|
|
6127
|
+
let access = "READ";
|
|
6128
|
+
if (given.access === void 0) problems.push({ path: "access", message: "Required" });
|
|
6129
|
+
else if (typeof given.access !== "string" || !API_KEY_ACCESS.includes(given.access)) problems.push({ path: "access", message: `Must be one of: ${API_KEY_ACCESS.join(", ")}` });
|
|
6130
|
+
else access = given.access;
|
|
6131
|
+
if (problems.length > 0) throw new SchedulingValidationError("The API key request is not valid", "SCHED_1600", { errors: problems });
|
|
6132
|
+
return { name, access };
|
|
6133
|
+
}
|
|
6134
|
+
|
|
6135
|
+
// src/api-keys/secret.ts
|
|
6136
|
+
import { createHash as createHash2, randomBytes as randomBytes3 } from "crypto";
|
|
6137
|
+
var API_KEY_PREFIX = "osk_";
|
|
6138
|
+
var PREFIX_SHOWN = 12;
|
|
6139
|
+
function generateApiKeySecret() {
|
|
6140
|
+
return `${API_KEY_PREFIX}${randomBytes3(32).toString("base64url")}`;
|
|
6141
|
+
}
|
|
6142
|
+
function hashApiKeySecret(secret) {
|
|
6143
|
+
return createHash2("sha256").update(secret).digest("hex");
|
|
6144
|
+
}
|
|
6145
|
+
function visiblePrefix(secret) {
|
|
6146
|
+
return secret.slice(0, PREFIX_SHOWN);
|
|
6147
|
+
}
|
|
6148
|
+
function looksLikeApiKey(text2) {
|
|
6149
|
+
return /^osk_[A-Za-z0-9_-]{43}$/.test(text2);
|
|
6150
|
+
}
|
|
6151
|
+
|
|
6152
|
+
// src/api-keys/crud.ts
|
|
6153
|
+
var VIEW = { id: true, name: true, access: true, prefix: true, createdByUserId: true, createdAt: true, lastUsedAt: true, revokedAt: true };
|
|
6154
|
+
var LAST_USED_REFRESH_MS = 10 * 60 * 1e3;
|
|
6155
|
+
async function createApiKey(db, organizationId, input, createdByUserId) {
|
|
6156
|
+
const fields = validateApiKeyRequest(input);
|
|
6157
|
+
const active = await db.organizationApiKey.count({ where: { organizationId, revokedAt: null } });
|
|
6158
|
+
if (active >= MAX_ACTIVE_API_KEYS) {
|
|
6159
|
+
throw new SchedulingValidationError(`A business may have at most ${MAX_ACTIVE_API_KEYS} API keys`, "SCHED_1601", { limit: MAX_ACTIVE_API_KEYS });
|
|
6160
|
+
}
|
|
6161
|
+
const key = generateApiKeySecret();
|
|
6162
|
+
const view2 = await db.organizationApiKey.create({
|
|
6163
|
+
data: { organizationId, ...fields, prefix: visiblePrefix(key), keyHash: hashApiKeySecret(key), createdByUserId: createdByUserId ?? null },
|
|
6164
|
+
select: VIEW
|
|
6165
|
+
});
|
|
6166
|
+
return { key, view: view2 };
|
|
6167
|
+
}
|
|
6168
|
+
async function listApiKeys(db, organizationId) {
|
|
6169
|
+
return db.organizationApiKey.findMany({ where: { organizationId }, orderBy: { createdAt: "desc" }, select: VIEW });
|
|
6170
|
+
}
|
|
6171
|
+
async function revokeApiKey(db, organizationId, id) {
|
|
6172
|
+
const { count } = await db.organizationApiKey.updateMany({ where: { id, organizationId, revokedAt: null }, data: { revokedAt: /* @__PURE__ */ new Date() } });
|
|
6173
|
+
return count > 0;
|
|
6174
|
+
}
|
|
6175
|
+
async function verifyApiKey(db, secret) {
|
|
6176
|
+
if (!looksLikeApiKey(secret)) return null;
|
|
6177
|
+
const row = await db.organizationApiKey.findUnique({
|
|
6178
|
+
where: { keyHash: hashApiKeySecret(secret) },
|
|
6179
|
+
select: { id: true, organizationId: true, access: true, createdByUserId: true, revokedAt: true, lastUsedAt: true }
|
|
6180
|
+
});
|
|
6181
|
+
if (!row || row.revokedAt) return null;
|
|
6182
|
+
if (!API_KEY_ACCESS.includes(row.access)) return null;
|
|
6183
|
+
const now = Date.now();
|
|
6184
|
+
if (!row.lastUsedAt || now - row.lastUsedAt.getTime() > LAST_USED_REFRESH_MS) {
|
|
6185
|
+
await db.organizationApiKey.updateMany({ where: { id: row.id, revokedAt: null }, data: { lastUsedAt: new Date(now) } }).catch((error) => {
|
|
6186
|
+
const diagnostic = schedError("SCHED_1602", { keyId: row.id, error });
|
|
6187
|
+
console.error(`[api-keys] ${diagnostic.code}-${diagnostic.ref} could not record last use`, error);
|
|
6188
|
+
});
|
|
6189
|
+
}
|
|
6190
|
+
return { id: row.id, organizationId: row.organizationId, access: row.access, createdByUserId: row.createdByUserId };
|
|
6191
|
+
}
|
|
5986
6192
|
export {
|
|
6193
|
+
API_KEY_ACCESS,
|
|
6194
|
+
API_KEY_FIELDS,
|
|
6195
|
+
API_KEY_NAME_MAX,
|
|
5987
6196
|
BRAND_FIELDS,
|
|
5988
6197
|
BlockedTargetError,
|
|
5989
6198
|
DEFAULT_BACKOFF_SECONDS,
|
|
5990
6199
|
DEFAULT_OFFER_MINUTES,
|
|
5991
6200
|
ERASED_EMAIL,
|
|
5992
6201
|
ERASED_NAME,
|
|
6202
|
+
MAX_ACTIVE_API_KEYS,
|
|
5993
6203
|
MAX_ENDPOINTS_PER_ORGANIZATION,
|
|
5994
6204
|
MAX_WAITING_PER_TYPE_DAY,
|
|
5995
6205
|
OPERATORS_BY_TYPE,
|
|
@@ -5999,6 +6209,8 @@ export {
|
|
|
5999
6209
|
SIGNATURE_HEADER,
|
|
6000
6210
|
SchedulingNotFoundError,
|
|
6001
6211
|
SchedulingValidationError,
|
|
6212
|
+
TEXT_PROVIDERS,
|
|
6213
|
+
TEXT_SETTINGS_FIELDS,
|
|
6002
6214
|
USER_DAY_LIMIT,
|
|
6003
6215
|
WEBHOOK_EVENT_TYPES,
|
|
6004
6216
|
WEBHOOK_TEST_EVENT,
|
|
@@ -6025,6 +6237,7 @@ export {
|
|
|
6025
6237
|
checkPaymentContract,
|
|
6026
6238
|
checkWebhookUrl,
|
|
6027
6239
|
completeWaitlistAccept,
|
|
6240
|
+
createApiKey,
|
|
6028
6241
|
createAppointmentType,
|
|
6029
6242
|
createCalendar,
|
|
6030
6243
|
createInMemoryAdapters,
|
|
@@ -6036,6 +6249,7 @@ export {
|
|
|
6036
6249
|
deleteCalendar,
|
|
6037
6250
|
deleteNotificationTemplate,
|
|
6038
6251
|
deleteRoutingForm,
|
|
6252
|
+
deleteTextSettings,
|
|
6039
6253
|
deleteWebhookEndpoint,
|
|
6040
6254
|
deliverDueWebhooks,
|
|
6041
6255
|
enqueueAppointmentWebhook,
|
|
@@ -6062,6 +6276,7 @@ export {
|
|
|
6062
6276
|
getPublicRoutingForm,
|
|
6063
6277
|
getRoutingForm,
|
|
6064
6278
|
getTeamAvailableSlots,
|
|
6279
|
+
getTextSettings,
|
|
6065
6280
|
getUserDayAppointments,
|
|
6066
6281
|
getWaitlistOffer,
|
|
6067
6282
|
isPrivateAddress,
|
|
@@ -6069,6 +6284,7 @@ export {
|
|
|
6069
6284
|
isVirtualMeeting,
|
|
6070
6285
|
joinWaitlist,
|
|
6071
6286
|
leaveWaitlist,
|
|
6287
|
+
listApiKeys,
|
|
6072
6288
|
listAppointmentTypes,
|
|
6073
6289
|
listAppointments,
|
|
6074
6290
|
listAvailabilityRules,
|
|
@@ -6081,8 +6297,10 @@ export {
|
|
|
6081
6297
|
listWebhookEndpoints,
|
|
6082
6298
|
localDay,
|
|
6083
6299
|
localToUTC,
|
|
6300
|
+
looksLikeApiKey,
|
|
6084
6301
|
markNoShow,
|
|
6085
6302
|
matchingRules,
|
|
6303
|
+
normalizeTextNumber,
|
|
6086
6304
|
offerFreedSlot,
|
|
6087
6305
|
parseSubject,
|
|
6088
6306
|
parseTimeLocal,
|
|
@@ -6099,8 +6317,10 @@ export {
|
|
|
6099
6317
|
resolveLocation,
|
|
6100
6318
|
resolveSubject,
|
|
6101
6319
|
retryWebhookDelivery,
|
|
6320
|
+
revokeApiKey,
|
|
6102
6321
|
routeClient,
|
|
6103
6322
|
saveBrand,
|
|
6323
|
+
saveTextSettings,
|
|
6104
6324
|
schedError,
|
|
6105
6325
|
scheduleNotifications,
|
|
6106
6326
|
scopeToOrganization,
|
|
@@ -6118,9 +6338,12 @@ export {
|
|
|
6118
6338
|
updateCalendar,
|
|
6119
6339
|
updateNotificationTemplate,
|
|
6120
6340
|
updateRoutingForm,
|
|
6341
|
+
validateApiKeyRequest,
|
|
6121
6342
|
validateBrand,
|
|
6122
6343
|
validateRoutingDestinations,
|
|
6123
6344
|
validateRoutingStructure,
|
|
6345
|
+
validateTextSettings,
|
|
6346
|
+
verifyApiKey,
|
|
6124
6347
|
verifyWebhookSignature,
|
|
6125
6348
|
withCalendarVisibility,
|
|
6126
6349
|
withOrganization
|
package/package.json
CHANGED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
-- CreateTable
|
|
2
|
+
CREATE TABLE "OrganizationTextSettings" (
|
|
3
|
+
"id" TEXT NOT NULL,
|
|
4
|
+
"organizationId" TEXT NOT NULL,
|
|
5
|
+
"provider" TEXT NOT NULL,
|
|
6
|
+
"fromNumber" TEXT NOT NULL,
|
|
7
|
+
"enabled" BOOLEAN NOT NULL DEFAULT true,
|
|
8
|
+
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
9
|
+
"updatedAt" TIMESTAMP(3) NOT NULL,
|
|
10
|
+
|
|
11
|
+
CONSTRAINT "OrganizationTextSettings_pkey" PRIMARY KEY ("id")
|
|
12
|
+
);
|
|
13
|
+
|
|
14
|
+
-- CreateIndex
|
|
15
|
+
CREATE UNIQUE INDEX "OrganizationTextSettings_organizationId_key" ON "OrganizationTextSettings"("organizationId");
|
|
16
|
+
|
|
17
|
+
-- AddForeignKey
|
|
18
|
+
ALTER TABLE "OrganizationTextSettings" ADD CONSTRAINT "OrganizationTextSettings_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
-- CreateTable
|
|
2
|
+
CREATE TABLE "OrganizationApiKey" (
|
|
3
|
+
"id" TEXT NOT NULL,
|
|
4
|
+
"organizationId" TEXT NOT NULL,
|
|
5
|
+
"name" TEXT NOT NULL,
|
|
6
|
+
"access" TEXT NOT NULL,
|
|
7
|
+
"prefix" TEXT NOT NULL,
|
|
8
|
+
"keyHash" TEXT NOT NULL,
|
|
9
|
+
"createdByUserId" TEXT,
|
|
10
|
+
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
11
|
+
"lastUsedAt" TIMESTAMP(3),
|
|
12
|
+
"revokedAt" TIMESTAMP(3),
|
|
13
|
+
|
|
14
|
+
CONSTRAINT "OrganizationApiKey_pkey" PRIMARY KEY ("id")
|
|
15
|
+
);
|
|
16
|
+
|
|
17
|
+
-- CreateIndex
|
|
18
|
+
CREATE UNIQUE INDEX "OrganizationApiKey_keyHash_key" ON "OrganizationApiKey"("keyHash");
|
|
19
|
+
|
|
20
|
+
-- CreateIndex
|
|
21
|
+
CREATE INDEX "OrganizationApiKey_organizationId_idx" ON "OrganizationApiKey"("organizationId");
|
|
22
|
+
|
|
23
|
+
-- AddForeignKey
|
|
24
|
+
ALTER TABLE "OrganizationApiKey" ADD CONSTRAINT "OrganizationApiKey_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
package/prisma/schema.prisma
CHANGED
|
@@ -36,6 +36,8 @@ model Organization {
|
|
|
36
36
|
routingForms RoutingForm[]
|
|
37
37
|
dataSubjectRequests DataSubjectRequest[]
|
|
38
38
|
brand OrganizationBrand?
|
|
39
|
+
textSettings OrganizationTextSettings?
|
|
40
|
+
apiKeys OrganizationApiKey[]
|
|
39
41
|
}
|
|
40
42
|
|
|
41
43
|
// ===== BEGIN SHARED SCHEDULING MODELS (copied verbatim into the host schema by packages/database/scripts/sync-scheduling-schema.ts) =====
|
|
@@ -543,6 +545,37 @@ model OrganizationBrand {
|
|
|
543
545
|
updatedAt DateTime @updatedAt
|
|
544
546
|
}
|
|
545
547
|
|
|
548
|
+
/// Which text-message provider and sending number a business uses. No keys are stored here: the host holds the provider accounts.
|
|
549
|
+
model OrganizationTextSettings {
|
|
550
|
+
id String @id @default(cuid())
|
|
551
|
+
organizationId String @unique
|
|
552
|
+
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
|
553
|
+
provider String
|
|
554
|
+
fromNumber String
|
|
555
|
+
enabled Boolean @default(true)
|
|
556
|
+
createdAt DateTime @default(now())
|
|
557
|
+
updatedAt DateTime @updatedAt
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
/// A key that lets an outside tool act for one business. Only a hash of the secret is stored.
|
|
561
|
+
model OrganizationApiKey {
|
|
562
|
+
id String @id @default(cuid())
|
|
563
|
+
organizationId String
|
|
564
|
+
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
|
565
|
+
name String
|
|
566
|
+
/// READ or FULL.
|
|
567
|
+
access String
|
|
568
|
+
/// The start of the key, to recognise it in a list.
|
|
569
|
+
prefix String
|
|
570
|
+
keyHash String @unique
|
|
571
|
+
createdByUserId String?
|
|
572
|
+
createdAt DateTime @default(now())
|
|
573
|
+
lastUsedAt DateTime?
|
|
574
|
+
revokedAt DateTime?
|
|
575
|
+
|
|
576
|
+
@@index([organizationId])
|
|
577
|
+
}
|
|
578
|
+
|
|
546
579
|
model ServicePackage {
|
|
547
580
|
id String @id @default(cuid())
|
|
548
581
|
name String
|