@ordinatio/scheduling 0.6.1 → 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 CHANGED
@@ -1,5 +1,8 @@
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`.
3
6
  ## 0.6.1 (prepared 2026-11-16)
4
7
 
5
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.
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' | 'organizationTextSettings' | '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
@@ -2779,4 +2779,57 @@ declare function saveTextSettings(db: SchedulingDb, organizationId: string, inpu
2779
2779
  /** Removes the settings. True when there were some. */
2780
2780
  declare function deleteTextSettings(db: SchedulingDb, organizationId: string): Promise<boolean>;
2781
2781
 
2782
- export { type AcceptRelease, type AddTimeBlockInput, 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, 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_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, 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, 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, listAppointmentTypes, listAppointments, listAvailabilityRules, listCalendars, listNotificationTemplates, listPrivacyRequests, listRoutingForms, listWaitlist, listWebhookDeliveries, listWebhookEndpoints, localDay, localToUTC, markNoShow, matchingRules, normalizeTextNumber, offerFreedSlot, parseSubject, parseTimeLocal, previewErase, processPendingNotifications, queueImmediateNotification, queueStaffNotification, releaseWaitlistAccept, removeDateOverride, removeWaitlistEntry, renderTemplate, rescheduleAppointment, resolveDestination, resolveLocation, resolveSubject, retryWebhookDelivery, routeClient, saveBrand, saveTextSettings, schedError, scheduleNotifications, scopeToOrganization, selectCalendarForBooking, sendTestWebhook, senderIdentity, setWeeklyAvailability, settleBookedAccept, signWebhook, subjectHashes, testRoutingForm, toPublicBrand, tryOfferFreedSlot, updateAppointmentType, updateCalendar, updateNotificationTemplate, updateRoutingForm, validateBrand, validateRoutingDestinations, validateRoutingStructure, validateTextSettings, verifyWebhookSignature, withCalendarVisibility, withOrganization };
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' | 'organizationTextSettings' | '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
@@ -2779,4 +2779,57 @@ declare function saveTextSettings(db: SchedulingDb, organizationId: string, inpu
2779
2779
  /** Removes the settings. True when there were some. */
2780
2780
  declare function deleteTextSettings(db: SchedulingDb, organizationId: string): Promise<boolean>;
2781
2781
 
2782
- export { type AcceptRelease, type AddTimeBlockInput, 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, 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_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, 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, 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, listAppointmentTypes, listAppointments, listAvailabilityRules, listCalendars, listNotificationTemplates, listPrivacyRequests, listRoutingForms, listWaitlist, listWebhookDeliveries, listWebhookEndpoints, localDay, localToUTC, markNoShow, matchingRules, normalizeTextNumber, offerFreedSlot, parseSubject, parseTimeLocal, previewErase, processPendingNotifications, queueImmediateNotification, queueStaffNotification, releaseWaitlistAccept, removeDateOverride, removeWaitlistEntry, renderTemplate, rescheduleAppointment, resolveDestination, resolveLocation, resolveSubject, retryWebhookDelivery, routeClient, saveBrand, saveTextSettings, schedError, scheduleNotifications, scopeToOrganization, selectCalendarForBooking, sendTestWebhook, senderIdentity, setWeeklyAvailability, settleBookedAccept, signWebhook, subjectHashes, testRoutingForm, toPublicBrand, tryOfferFreedSlot, updateAppointmentType, updateCalendar, updateNotificationTemplate, updateRoutingForm, validateBrand, validateRoutingDestinations, validateRoutingStructure, validateTextSettings, verifyWebhookSignature, withCalendarVisibility, withOrganization };
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,
@@ -73,6 +77,7 @@ __export(index_exports, {
73
77
  checkPaymentContract: () => checkPaymentContract,
74
78
  checkWebhookUrl: () => checkWebhookUrl,
75
79
  completeWaitlistAccept: () => completeWaitlistAccept,
80
+ createApiKey: () => createApiKey,
76
81
  createAppointmentType: () => createAppointmentType,
77
82
  createCalendar: () => createCalendar,
78
83
  createInMemoryAdapters: () => createInMemoryAdapters,
@@ -119,6 +124,7 @@ __export(index_exports, {
119
124
  isVirtualMeeting: () => isVirtualMeeting,
120
125
  joinWaitlist: () => joinWaitlist,
121
126
  leaveWaitlist: () => leaveWaitlist,
127
+ listApiKeys: () => listApiKeys,
122
128
  listAppointmentTypes: () => listAppointmentTypes,
123
129
  listAppointments: () => listAppointments,
124
130
  listAvailabilityRules: () => listAvailabilityRules,
@@ -131,6 +137,7 @@ __export(index_exports, {
131
137
  listWebhookEndpoints: () => listWebhookEndpoints,
132
138
  localDay: () => localDay,
133
139
  localToUTC: () => localToUTC,
140
+ looksLikeApiKey: () => looksLikeApiKey,
134
141
  markNoShow: () => markNoShow,
135
142
  matchingRules: () => matchingRules,
136
143
  normalizeTextNumber: () => normalizeTextNumber,
@@ -150,6 +157,7 @@ __export(index_exports, {
150
157
  resolveLocation: () => resolveLocation,
151
158
  resolveSubject: () => resolveSubject,
152
159
  retryWebhookDelivery: () => retryWebhookDelivery,
160
+ revokeApiKey: () => revokeApiKey,
153
161
  routeClient: () => routeClient,
154
162
  saveBrand: () => saveBrand,
155
163
  saveTextSettings: () => saveTextSettings,
@@ -170,10 +178,12 @@ __export(index_exports, {
170
178
  updateCalendar: () => updateCalendar,
171
179
  updateNotificationTemplate: () => updateNotificationTemplate,
172
180
  updateRoutingForm: () => updateRoutingForm,
181
+ validateApiKeyRequest: () => validateApiKeyRequest,
173
182
  validateBrand: () => validateBrand,
174
183
  validateRoutingDestinations: () => validateRoutingDestinations,
175
184
  validateRoutingStructure: () => validateRoutingStructure,
176
185
  validateTextSettings: () => validateTextSettings,
186
+ verifyApiKey: () => verifyApiKey,
177
187
  verifyWebhookSignature: () => verifyWebhookSignature,
178
188
  withCalendarVisibility: () => withCalendarVisibility,
179
189
  withOrganization: () => withOrganization
@@ -1333,6 +1343,45 @@ var TEXT_SETTINGS_ERRORS = {
1333
1343
  }
1334
1344
  };
1335
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
+
1336
1385
  // src/errors/registry.ts
1337
1386
  var SCHEDULING_ERRORS = {
1338
1387
  ...CALENDARS_AVAILABILITY_ERRORS,
@@ -1348,7 +1397,8 @@ var SCHEDULING_ERRORS = {
1348
1397
  ...ROUTING_ERRORS,
1349
1398
  ...PRIVACY_ERRORS,
1350
1399
  ...BRAND_ERRORS,
1351
- ...TEXT_SETTINGS_ERRORS
1400
+ ...TEXT_SETTINGS_ERRORS,
1401
+ ...API_KEY_ERRORS
1352
1402
  };
1353
1403
 
1354
1404
  // src/errors/diagnostic-error.ts
@@ -6247,14 +6297,102 @@ async function deleteTextSettings(db, organizationId) {
6247
6297
  const { count } = await db.organizationTextSettings.deleteMany({ where: { organizationId } });
6248
6298
  return count > 0;
6249
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
+ }
6250
6384
  // Annotate the CommonJS export names for ESM import in node:
6251
6385
  0 && (module.exports = {
6386
+ API_KEY_ACCESS,
6387
+ API_KEY_FIELDS,
6388
+ API_KEY_NAME_MAX,
6252
6389
  BRAND_FIELDS,
6253
6390
  BlockedTargetError,
6254
6391
  DEFAULT_BACKOFF_SECONDS,
6255
6392
  DEFAULT_OFFER_MINUTES,
6256
6393
  ERASED_EMAIL,
6257
6394
  ERASED_NAME,
6395
+ MAX_ACTIVE_API_KEYS,
6258
6396
  MAX_ENDPOINTS_PER_ORGANIZATION,
6259
6397
  MAX_WAITING_PER_TYPE_DAY,
6260
6398
  OPERATORS_BY_TYPE,
@@ -6292,6 +6430,7 @@ async function deleteTextSettings(db, organizationId) {
6292
6430
  checkPaymentContract,
6293
6431
  checkWebhookUrl,
6294
6432
  completeWaitlistAccept,
6433
+ createApiKey,
6295
6434
  createAppointmentType,
6296
6435
  createCalendar,
6297
6436
  createInMemoryAdapters,
@@ -6338,6 +6477,7 @@ async function deleteTextSettings(db, organizationId) {
6338
6477
  isVirtualMeeting,
6339
6478
  joinWaitlist,
6340
6479
  leaveWaitlist,
6480
+ listApiKeys,
6341
6481
  listAppointmentTypes,
6342
6482
  listAppointments,
6343
6483
  listAvailabilityRules,
@@ -6350,6 +6490,7 @@ async function deleteTextSettings(db, organizationId) {
6350
6490
  listWebhookEndpoints,
6351
6491
  localDay,
6352
6492
  localToUTC,
6493
+ looksLikeApiKey,
6353
6494
  markNoShow,
6354
6495
  matchingRules,
6355
6496
  normalizeTextNumber,
@@ -6369,6 +6510,7 @@ async function deleteTextSettings(db, organizationId) {
6369
6510
  resolveLocation,
6370
6511
  resolveSubject,
6371
6512
  retryWebhookDelivery,
6513
+ revokeApiKey,
6372
6514
  routeClient,
6373
6515
  saveBrand,
6374
6516
  saveTextSettings,
@@ -6389,10 +6531,12 @@ async function deleteTextSettings(db, organizationId) {
6389
6531
  updateCalendar,
6390
6532
  updateNotificationTemplate,
6391
6533
  updateRoutingForm,
6534
+ validateApiKeyRequest,
6392
6535
  validateBrand,
6393
6536
  validateRoutingDestinations,
6394
6537
  validateRoutingStructure,
6395
6538
  validateTextSettings,
6539
+ verifyApiKey,
6396
6540
  verifyWebhookSignature,
6397
6541
  withCalendarVisibility,
6398
6542
  withOrganization
package/dist/index.mjs CHANGED
@@ -1151,6 +1151,45 @@ var TEXT_SETTINGS_ERRORS = {
1151
1151
  }
1152
1152
  };
1153
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
+
1154
1193
  // src/errors/registry.ts
1155
1194
  var SCHEDULING_ERRORS = {
1156
1195
  ...CALENDARS_AVAILABILITY_ERRORS,
@@ -1166,7 +1205,8 @@ var SCHEDULING_ERRORS = {
1166
1205
  ...ROUTING_ERRORS,
1167
1206
  ...PRIVACY_ERRORS,
1168
1207
  ...BRAND_ERRORS,
1169
- ...TEXT_SETTINGS_ERRORS
1208
+ ...TEXT_SETTINGS_ERRORS,
1209
+ ...API_KEY_ERRORS
1170
1210
  };
1171
1211
 
1172
1212
  // src/errors/diagnostic-error.ts
@@ -6065,13 +6105,101 @@ async function deleteTextSettings(db, organizationId) {
6065
6105
  const { count } = await db.organizationTextSettings.deleteMany({ where: { organizationId } });
6066
6106
  return count > 0;
6067
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
+ }
6068
6192
  export {
6193
+ API_KEY_ACCESS,
6194
+ API_KEY_FIELDS,
6195
+ API_KEY_NAME_MAX,
6069
6196
  BRAND_FIELDS,
6070
6197
  BlockedTargetError,
6071
6198
  DEFAULT_BACKOFF_SECONDS,
6072
6199
  DEFAULT_OFFER_MINUTES,
6073
6200
  ERASED_EMAIL,
6074
6201
  ERASED_NAME,
6202
+ MAX_ACTIVE_API_KEYS,
6075
6203
  MAX_ENDPOINTS_PER_ORGANIZATION,
6076
6204
  MAX_WAITING_PER_TYPE_DAY,
6077
6205
  OPERATORS_BY_TYPE,
@@ -6109,6 +6237,7 @@ export {
6109
6237
  checkPaymentContract,
6110
6238
  checkWebhookUrl,
6111
6239
  completeWaitlistAccept,
6240
+ createApiKey,
6112
6241
  createAppointmentType,
6113
6242
  createCalendar,
6114
6243
  createInMemoryAdapters,
@@ -6155,6 +6284,7 @@ export {
6155
6284
  isVirtualMeeting,
6156
6285
  joinWaitlist,
6157
6286
  leaveWaitlist,
6287
+ listApiKeys,
6158
6288
  listAppointmentTypes,
6159
6289
  listAppointments,
6160
6290
  listAvailabilityRules,
@@ -6167,6 +6297,7 @@ export {
6167
6297
  listWebhookEndpoints,
6168
6298
  localDay,
6169
6299
  localToUTC,
6300
+ looksLikeApiKey,
6170
6301
  markNoShow,
6171
6302
  matchingRules,
6172
6303
  normalizeTextNumber,
@@ -6186,6 +6317,7 @@ export {
6186
6317
  resolveLocation,
6187
6318
  resolveSubject,
6188
6319
  retryWebhookDelivery,
6320
+ revokeApiKey,
6189
6321
  routeClient,
6190
6322
  saveBrand,
6191
6323
  saveTextSettings,
@@ -6206,10 +6338,12 @@ export {
6206
6338
  updateCalendar,
6207
6339
  updateNotificationTemplate,
6208
6340
  updateRoutingForm,
6341
+ validateApiKeyRequest,
6209
6342
  validateBrand,
6210
6343
  validateRoutingDestinations,
6211
6344
  validateRoutingStructure,
6212
6345
  validateTextSettings,
6346
+ verifyApiKey,
6213
6347
  verifyWebhookSignature,
6214
6348
  withCalendarVisibility,
6215
6349
  withOrganization
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ordinatio/scheduling",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "license": "MIT",
5
5
  "description": "Scheduling engine for appointment-based businesses. API-first, no iframes.",
6
6
  "main": "./dist/index.js",
@@ -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;
@@ -37,6 +37,7 @@ model Organization {
37
37
  dataSubjectRequests DataSubjectRequest[]
38
38
  brand OrganizationBrand?
39
39
  textSettings OrganizationTextSettings?
40
+ apiKeys OrganizationApiKey[]
40
41
  }
41
42
 
42
43
  // ===== BEGIN SHARED SCHEDULING MODELS (copied verbatim into the host schema by packages/database/scripts/sync-scheduling-schema.ts) =====
@@ -556,6 +557,25 @@ model OrganizationTextSettings {
556
557
  updatedAt DateTime @updatedAt
557
558
  }
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
+
559
579
  model ServicePackage {
560
580
  id String @id @default(cuid())
561
581
  name String