@ordinatio/scheduling-api 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import {
2
+ ApiKeySchema,
2
3
  BookingPageConfigSchema,
3
4
  BookingPageThemeSchema,
4
5
  BrandSchema,
@@ -38,7 +39,7 @@ import {
38
39
  UpdatePackagePurchaseSchema,
39
40
  UpdateRoutingFormSchema,
40
41
  UpdateServicePackageSchema
41
- } from "./chunk-IW6AN5WE.mjs";
42
+ } from "./chunk-X5BVCLX6.mjs";
42
43
 
43
44
  // src/create-api.ts
44
45
  import * as engine from "@ordinatio/scheduling";
@@ -54,6 +55,82 @@ function defaultCorsHeaders() {
54
55
  };
55
56
  }
56
57
 
58
+ // src/api-keys/api-key-host.ts
59
+ import { verifyApiKey } from "@ordinatio/scheduling";
60
+
61
+ // src/staff/simple-staff.ts
62
+ var DEFAULT_ADMIN_ROLES = ["OWNER", "ADMIN", "MANAGER"];
63
+ function createStaffContext(input) {
64
+ const adminRoles = (input.adminRoles ?? DEFAULT_ADMIN_ROLES).map((role) => role.toUpperCase());
65
+ const { db, organizationId } = input;
66
+ return {
67
+ userId: input.userId,
68
+ organizationId,
69
+ role: input.role,
70
+ isAdmin: adminRoles.includes(input.role.toUpperCase()),
71
+ schedulingEnabled: input.schedulingEnabled ?? true,
72
+ db,
73
+ visibleCalendars: async () => null,
74
+ visibleCalendarIds: async () => void 0,
75
+ canSeeCalendar: async (calendarId) => Boolean(await db.schedulingCalendar.findFirst({ where: { id: calendarId, organizationId }, select: { id: true } })),
76
+ canSeeAppointment: async (appointmentId) => Boolean(await db.appointment.findFirst({ where: { id: appointmentId, calendar: { organizationId } }, select: { id: true } })),
77
+ // The package has no client table, so there is no preference to read.
78
+ preferredLocationOf: async () => null
79
+ };
80
+ }
81
+ var BEARER = /^bearer\s+(\S+)$/i;
82
+ function createBearerStaffResolver(input) {
83
+ return {
84
+ async resolve(request) {
85
+ const token = BEARER.exec(request.headers.get("authorization") ?? "")?.[1];
86
+ if (!token) return null;
87
+ const person = await input.authenticate(token, request);
88
+ if (!person) return null;
89
+ return createStaffContext({
90
+ ...person,
91
+ db: await input.db(person),
92
+ adminRoles: input.adminRoles,
93
+ schedulingEnabled: input.schedulingEnabled ? await input.schedulingEnabled(person) : void 0
94
+ });
95
+ }
96
+ };
97
+ }
98
+
99
+ // src/api-keys/api-key-host.ts
100
+ var API_KEY_ROLE_PREFIX = "API_KEY_";
101
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
102
+ function bearerKeyOf(request) {
103
+ const header = request.headers.get("authorization");
104
+ if (!header) return null;
105
+ const match = /^[Bb][Ee][Aa][Rr][Ee][Rr]\s+(osk_\S+)$/.exec(header.trim());
106
+ return match ? match[1] : null;
107
+ }
108
+ function contextOf(key, db, schedulingEnabled) {
109
+ return createStaffContext({
110
+ // The key, not the person who made it, is what the rate limit counts.
111
+ userId: `api-key:${key.id}`,
112
+ organizationId: key.organizationId,
113
+ role: `${API_KEY_ROLE_PREFIX}${key.access}`,
114
+ adminRoles: [`${API_KEY_ROLE_PREFIX}READ`, `${API_KEY_ROLE_PREFIX}FULL`],
115
+ schedulingEnabled,
116
+ db
117
+ });
118
+ }
119
+ async function hostForRequest(host, request, route) {
120
+ if (route.public || !host.apiKeys) return host;
121
+ const secret = bearerKeyOf(request);
122
+ if (secret === null) return host;
123
+ const db = await host.apiKeys.db();
124
+ const key = await verifyApiKey(db, secret);
125
+ if (!key) return Response.json({ error: "Unauthorized" }, { status: 401 });
126
+ if (route.personOnly) return Response.json({ error: "This needs a person signed in at a browser, not an API key" }, { status: 403 });
127
+ if (key.access === "READ" && !SAFE_METHODS.has(request.method.toUpperCase())) {
128
+ return Response.json({ error: "This API key is read-only" }, { status: 403 });
129
+ }
130
+ const context = contextOf(key, db, await host.schedulingEnabledFor(key.organizationId));
131
+ return { ...host, staff: { resolve: async () => context } };
132
+ }
133
+
57
134
  // src/availability/memory-availability-cache.ts
58
135
  var TTL_MS = 6e4;
59
136
  var DEFAULT_MAX_ENTRIES = 2e3;
@@ -2473,16 +2550,16 @@ async function attemptLegRefund(payments, paymentIntentId, idempotencyKeySuffix,
2473
2550
  return failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay, { error: result.error, message: result.error ?? result.code ?? "no reason given", requestId: result.requestId });
2474
2551
  }
2475
2552
  }
2476
- function failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay, failure4) {
2477
- const diagnostic = schedError14(errorCode, { error: failure4.error, appointmentId, paymentIntentId });
2553
+ function failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay, failure5) {
2554
+ const diagnostic = schedError14(errorCode, { error: failure5.error, appointmentId, paymentIntentId });
2478
2555
  console.error(
2479
2556
  `[resolve-refund] ${logLabel} refund failed${retriedAfterReplay ? " (after a fresh-key re-attempt)" : ""} \u2014 manual refund may be required:`,
2480
2557
  diagnostic.ref,
2481
2558
  appointmentId,
2482
2559
  paymentIntentId,
2483
- `requestId=${failure4.requestId}`,
2560
+ `requestId=${failure5.requestId}`,
2484
2561
  `idempotencyKey=${idempotencyKey}`,
2485
- failure4.message
2562
+ failure5.message
2486
2563
  );
2487
2564
  return { succeeded: false, amountCents: null };
2488
2565
  }
@@ -6654,21 +6731,75 @@ async function deleteBrandRoute(request, { host }) {
6654
6731
  }
6655
6732
  }
6656
6733
 
6657
- // src/handlers/admin-text-settings.ts
6658
- import { deleteTextSettings, getTextSettings, saveTextSettings, SchedulingValidationError as SchedulingValidationError12 } from "@ordinatio/scheduling";
6659
- var NOT_ENABLED4 = { error: "Text-message settings are not enabled on this server" };
6734
+ // src/handlers/admin-api-keys.ts
6735
+ import { createApiKey, listApiKeys, revokeApiKey, SchedulingValidationError as SchedulingValidationError12 } from "@ordinatio/scheduling";
6736
+ var NOT_ENABLED4 = { error: "API keys are not enabled on this server" };
6660
6737
  function failure3(error, fallback) {
6661
6738
  if (error instanceof SchedulingValidationError12) {
6662
6739
  const details = error.context.errors;
6663
6740
  return Response.json({ error: error.message, code: error.code, ref: getErrorRef(error), ...details ? { details } : {} }, { status: 400 });
6664
6741
  }
6742
+ console.error("[api-keys]", error);
6743
+ return Response.json({ error: fallback }, { status: 500 });
6744
+ }
6745
+ async function requireKeyAdmin(host, request, options) {
6746
+ const staff = await requireAdminStaff(host, request, options);
6747
+ if (staff instanceof Response) return staff;
6748
+ if (!host.apiKeys) return Response.json(NOT_ENABLED4, { status: 501 });
6749
+ if (staff.role.startsWith(API_KEY_ROLE_PREFIX)) return Response.json({ error: "API keys are managed by a signed-in person, not with an API key" }, { status: 403 });
6750
+ return staff;
6751
+ }
6752
+ async function listApiKeysRoute(request, { host }) {
6753
+ try {
6754
+ const staff = await requireKeyAdmin(host, request, { action: "admin-api-keys-list", tier: "GENERAL" });
6755
+ if (staff instanceof Response) return staff;
6756
+ return Response.json({ keys: await listApiKeys(staff.db, staff.organizationId) });
6757
+ } catch (error) {
6758
+ return failure3(error, "Failed to list the API keys");
6759
+ }
6760
+ }
6761
+ async function createApiKeyRoute(request, { host }) {
6762
+ try {
6763
+ const staff = await requireKeyAdmin(host, request, { action: "admin-api-keys-create", tier: "SETTINGS" });
6764
+ if (staff instanceof Response) return staff;
6765
+ const validation = await parseBody(request, ApiKeySchema);
6766
+ if (!validation.success) return validation.response;
6767
+ const { key, view } = await createApiKey(staff.db, staff.organizationId, validation.data, staff.userId);
6768
+ await host.activity.log(staff.db, { action: "scheduling.api_key_created", description: `made the API key "${view.name}"`, metadata: { keyId: view.id, access: view.access } }).catch((error) => {
6769
+ console.error("[api-keys] could not record the new key in the activity log", error);
6770
+ });
6771
+ return Response.json({ key, apiKey: view }, { status: 201, headers: { "Cache-Control": "no-store" } });
6772
+ } catch (error) {
6773
+ return failure3(error, "Failed to make the API key");
6774
+ }
6775
+ }
6776
+ async function revokeApiKeyRoute(request, { host, params }) {
6777
+ try {
6778
+ const staff = await requireKeyAdmin(host, request, { action: "admin-api-keys-revoke", tier: "DELETE" });
6779
+ if (staff instanceof Response) return staff;
6780
+ const revoked = await revokeApiKey(staff.db, staff.organizationId, params.id);
6781
+ if (revoked) await host.activity.log(staff.db, { action: "scheduling.api_key_revoked", description: "revoked an API key", metadata: { keyId: params.id } });
6782
+ return Response.json({ revoked });
6783
+ } catch (error) {
6784
+ return failure3(error, "Failed to revoke the API key");
6785
+ }
6786
+ }
6787
+
6788
+ // src/handlers/admin-text-settings.ts
6789
+ import { deleteTextSettings, getTextSettings, saveTextSettings, SchedulingValidationError as SchedulingValidationError13 } from "@ordinatio/scheduling";
6790
+ var NOT_ENABLED5 = { error: "Text-message settings are not enabled on this server" };
6791
+ function failure4(error, fallback) {
6792
+ if (error instanceof SchedulingValidationError13) {
6793
+ const details = error.context.errors;
6794
+ return Response.json({ error: error.message, code: error.code, ref: getErrorRef(error), ...details ? { details } : {} }, { status: 400 });
6795
+ }
6665
6796
  console.error("[text-settings]", error);
6666
6797
  return Response.json({ error: fallback }, { status: 500 });
6667
6798
  }
6668
6799
  async function requireTextAdmin(host, request, options) {
6669
6800
  const staff = await requireAdminStaff(host, request, options);
6670
6801
  if (staff instanceof Response) return staff;
6671
- if (!host.textMessages) return Response.json(NOT_ENABLED4, { status: 501 });
6802
+ if (!host.textMessages) return Response.json(NOT_ENABLED5, { status: 501 });
6672
6803
  return staff;
6673
6804
  }
6674
6805
  async function getTextSettingsRoute(request, { host }) {
@@ -6677,7 +6808,7 @@ async function getTextSettingsRoute(request, { host }) {
6677
6808
  if (staff instanceof Response) return staff;
6678
6809
  return Response.json({ settings: await getTextSettings(staff.db, staff.organizationId), providers: host.textMessages?.providers ?? ["TELNYX", "TWILIO"] });
6679
6810
  } catch (error) {
6680
- return failure3(error, "Failed to read the text-message settings");
6811
+ return failure4(error, "Failed to read the text-message settings");
6681
6812
  }
6682
6813
  }
6683
6814
  async function saveTextSettingsRoute(request, { host }) {
@@ -6694,7 +6825,7 @@ async function saveTextSettingsRoute(request, { host }) {
6694
6825
  });
6695
6826
  return Response.json({ settings });
6696
6827
  } catch (error) {
6697
- return failure3(error, "Failed to save the text-message settings");
6828
+ return failure4(error, "Failed to save the text-message settings");
6698
6829
  }
6699
6830
  }
6700
6831
  async function deleteTextSettingsRoute(request, { host }) {
@@ -6705,7 +6836,7 @@ async function deleteTextSettingsRoute(request, { host }) {
6705
6836
  if (removed) await host.activity.log(staff.db, { action: "scheduling.text_settings_removed", description: "removed the text-message settings", metadata: {} });
6706
6837
  return Response.json({ removed });
6707
6838
  } catch (error) {
6708
- return failure3(error, "Failed to remove the text-message settings");
6839
+ return failure4(error, "Failed to remove the text-message settings");
6709
6840
  }
6710
6841
  }
6711
6842
 
@@ -6781,11 +6912,11 @@ async function checkSendingDomainRoute(request, { host }) {
6781
6912
  import { eraseSubject, exportSubject, listPrivacyRequests, previewErase } from "@ordinatio/scheduling";
6782
6913
 
6783
6914
  // src/privacy/privacy-http.ts
6784
- import { SchedulingValidationError as SchedulingValidationError13 } from "@ordinatio/scheduling";
6785
- var NOT_ENABLED5 = { error: "Data export and erasure are not enabled on this server" };
6915
+ import { SchedulingValidationError as SchedulingValidationError14 } from "@ordinatio/scheduling";
6916
+ var NOT_ENABLED6 = { error: "Data export and erasure are not enabled on this server" };
6786
6917
  var STATUS_BY_CODE3 = { SCHED_1300: 400, SCHED_1301: 409 };
6787
6918
  function privacyErrorResponse(error, fallback) {
6788
- if (error instanceof SchedulingValidationError13) {
6919
+ if (error instanceof SchedulingValidationError14) {
6789
6920
  return Response.json(
6790
6921
  { error: error.message, code: error.code, ref: getErrorRef(error), details: error.context },
6791
6922
  { status: STATUS_BY_CODE3[error.code] ?? 400 }
@@ -6797,7 +6928,7 @@ function privacyErrorResponse(error, fallback) {
6797
6928
  async function requirePrivacyAdmin(host, request, options) {
6798
6929
  const staff = await requireAdminStaff(host, request, options);
6799
6930
  if (staff instanceof Response) return staff;
6800
- if (!host.privacy) return Response.json(NOT_ENABLED5, { status: 501 });
6931
+ if (!host.privacy) return Response.json(NOT_ENABLED6, { status: 501 });
6801
6932
  return staff;
6802
6933
  }
6803
6934
 
@@ -7720,6 +7851,9 @@ var ROUTES = [
7720
7851
  { method: "GET", path: "/admin/text-settings", public: false, handler: getTextSettingsRoute },
7721
7852
  { method: "PUT", path: "/admin/text-settings", public: false, handler: saveTextSettingsRoute },
7722
7853
  { method: "DELETE", path: "/admin/text-settings", public: false, handler: deleteTextSettingsRoute },
7854
+ { method: "GET", path: "/admin/api-keys", public: false, handler: listApiKeysRoute },
7855
+ { method: "POST", path: "/admin/api-keys", public: false, handler: createApiKeyRoute },
7856
+ { method: "DELETE", path: "/admin/api-keys/[id]", public: false, handler: revokeApiKeyRoute },
7723
7857
  { method: "GET", path: "/admin/brand/sending-domain", public: false, handler: checkSendingDomainRoute },
7724
7858
  { method: "POST", path: "/admin/privacy/export", public: false, handler: exportPrivacyRoute },
7725
7859
  { method: "POST", path: "/admin/privacy/erase", public: false, handler: erasePrivacyRoute },
@@ -7754,11 +7888,11 @@ var ROUTES = [
7754
7888
  { method: "POST", path: "/appointments/[id]/followup", public: false, handler: sendFollowup },
7755
7889
  { method: "POST", path: "/appointments/[id]/remind", public: false, handler: sendReminder },
7756
7890
  { method: "POST", path: "/appointments/[id]/cancel", public: false, handler: cancelByStaff },
7757
- { method: "GET", path: "/calendars/connect-google", public: false, handler: startGoogleConnection },
7758
- { method: "POST", path: "/calendars/connect-google", public: false, handler: setGoogleCalendar },
7759
- { method: "GET", path: "/calendars/connect-google/callback", public: false, handler: finishGoogleConnection },
7760
- { method: "GET", path: "/calendars/connect-outlook", public: false, handler: startOutlookConnection },
7761
- { method: "GET", path: "/calendars/connect-outlook/callback", public: false, handler: finishOutlookConnection },
7891
+ { method: "GET", path: "/calendars/connect-google", public: false, personOnly: true, handler: startGoogleConnection },
7892
+ { method: "POST", path: "/calendars/connect-google", public: false, personOnly: true, handler: setGoogleCalendar },
7893
+ { method: "GET", path: "/calendars/connect-google/callback", public: false, personOnly: true, handler: finishGoogleConnection },
7894
+ { method: "GET", path: "/calendars/connect-outlook", public: false, personOnly: true, handler: startOutlookConnection },
7895
+ { method: "GET", path: "/calendars/connect-outlook/callback", public: false, personOnly: true, handler: finishOutlookConnection },
7762
7896
  { method: "POST", path: "/appointments/[id]/cancel-sync", public: false, handler: cancelFromCalendarSync },
7763
7897
  { method: "POST", path: "/appointments/[id]/approve", public: false, handler: approveOrReject },
7764
7898
  { method: "POST", path: "/appointments/[id]/reschedule", public: false, handler: rescheduleByStaff },
@@ -7816,6 +7950,7 @@ function createSchedulingApi(config) {
7816
7950
  privacy: config.host.privacy ?? null,
7817
7951
  brand: config.host.brand ?? null,
7818
7952
  textMessages: config.host.textMessages ?? null,
7953
+ apiKeys: config.host.apiKeys ?? null,
7819
7954
  icalUidDomain: config.host.icalUidDomain?.bind(config.host) ?? (() => null),
7820
7955
  calendarSync: config.host.calendarSync ?? { upsertEvent: async () => ({}), removeEvent: async () => void 0 },
7821
7956
  activity: config.host.activity ?? { log: async () => void 0, isOpen: async () => false, resolve: async () => void 0 },
@@ -7843,6 +7978,14 @@ function createSchedulingApi(config) {
7843
7978
  cors: config.host.cors?.bind(config.host) ?? defaultCorsHeaders
7844
7979
  };
7845
7980
  host.events = withWebhooks(withWaitlist(config.host.events ?? { emit: async () => void 0 }, host), host);
7981
+ async function hostForRoute(route, request) {
7982
+ try {
7983
+ return await hostForRequest(host, request, route);
7984
+ } catch (error) {
7985
+ console.error("[scheduling-api] could not check the API key:", error);
7986
+ return Response.json({ error: "Internal error" }, { status: 500 });
7987
+ }
7988
+ }
7846
7989
  async function handle(request) {
7847
7990
  const { pathname } = new URL(request.url);
7848
7991
  if (pathname !== basePath && !pathname.startsWith(`${basePath}/`)) return notFound();
@@ -7860,7 +8003,9 @@ function createSchedulingApi(config) {
7860
8003
  return Response.json({ error: "Method not allowed" }, { status: 405, headers: { Allow: allowed.join(", ") } });
7861
8004
  }
7862
8005
  try {
7863
- return await hit.route.handler(request, { host, params: hit.params });
8006
+ const runHost = await hostForRoute(hit.route, request);
8007
+ if (runHost instanceof Response) return runHost;
8008
+ return await hit.route.handler(request, { host: runHost, params: hit.params });
7864
8009
  } catch (error) {
7865
8010
  console.error("[scheduling-api] unhandled error:", error);
7866
8011
  return Response.json({ error: "Internal error" }, { status: 500 });
@@ -7871,7 +8016,9 @@ function createSchedulingApi(config) {
7871
8016
  if (!route) throw new Error(`No route ${method} ${path}`);
7872
8017
  return async (request, context) => {
7873
8018
  const params = await context?.params ?? {};
7874
- return route.handler(request, { host, params });
8019
+ const runHost = await hostForRoute(route, request);
8020
+ if (runHost instanceof Response) return runHost;
8021
+ return route.handler(request, { host: runHost, params });
7875
8022
  };
7876
8023
  }
7877
8024
  return { routes, handle, handler };
@@ -8627,44 +8774,6 @@ function createOutlookCalendarSync(config, hooks) {
8627
8774
  };
8628
8775
  }
8629
8776
 
8630
- // src/staff/simple-staff.ts
8631
- var DEFAULT_ADMIN_ROLES = ["OWNER", "ADMIN", "MANAGER"];
8632
- function createStaffContext(input) {
8633
- const adminRoles = (input.adminRoles ?? DEFAULT_ADMIN_ROLES).map((role) => role.toUpperCase());
8634
- const { db, organizationId } = input;
8635
- return {
8636
- userId: input.userId,
8637
- organizationId,
8638
- role: input.role,
8639
- isAdmin: adminRoles.includes(input.role.toUpperCase()),
8640
- schedulingEnabled: input.schedulingEnabled ?? true,
8641
- db,
8642
- visibleCalendars: async () => null,
8643
- visibleCalendarIds: async () => void 0,
8644
- canSeeCalendar: async (calendarId) => Boolean(await db.schedulingCalendar.findFirst({ where: { id: calendarId, organizationId }, select: { id: true } })),
8645
- canSeeAppointment: async (appointmentId) => Boolean(await db.appointment.findFirst({ where: { id: appointmentId, calendar: { organizationId } }, select: { id: true } })),
8646
- // The package has no client table, so there is no preference to read.
8647
- preferredLocationOf: async () => null
8648
- };
8649
- }
8650
- var BEARER = /^bearer\s+(\S+)$/i;
8651
- function createBearerStaffResolver(input) {
8652
- return {
8653
- async resolve(request) {
8654
- const token = BEARER.exec(request.headers.get("authorization") ?? "")?.[1];
8655
- if (!token) return null;
8656
- const person = await input.authenticate(token, request);
8657
- if (!person) return null;
8658
- return createStaffContext({
8659
- ...person,
8660
- db: await input.db(person),
8661
- adminRoles: input.adminRoles,
8662
- schedulingEnabled: input.schedulingEnabled ? await input.schedulingEnabled(person) : void 0
8663
- });
8664
- }
8665
- };
8666
- }
8667
-
8668
8777
  // src/staff/staff-scope.ts
8669
8778
  function isCalendarVisibleInScope(calendarUserId, scope) {
8670
8779
  if (calendarUserId === null) return true;
@@ -8779,6 +8888,7 @@ function createNodeListener(api, options) {
8779
8888
  }
8780
8889
  export {
8781
8890
  ALL_REFUND_STATUSES,
8891
+ ApiKeySchema,
8782
8892
  BALANCE_APPOINTMENT_SELECT,
8783
8893
  BALANCE_BLOCKED_APPOINTMENT_STATUS,
8784
8894
  BALANCE_REQUIRED_PAYMENT_STATUS,
@@ -8833,6 +8943,7 @@ export {
8833
8943
  UpdateServicePackageSchema,
8834
8944
  assertStripeTestKey,
8835
8945
  attemptLegRefund,
8946
+ bearerKeyOf,
8836
8947
  calendarVisibilityFilter,
8837
8948
  canSeeAppointmentInScope,
8838
8949
  canSeeCalendarInScope,
@@ -313,6 +313,17 @@ interface TextMessageSettings {
313
313
  /** The providers this server has accounts for. Default: Telnyx and Twilio. */
314
314
  providers?: readonly TextProvider[];
315
315
  }
316
+ /**
317
+ * Switches API keys on: a request with `Authorization: Bearer <key>` acts as that key's organization. A host that supplies
318
+ * none has them off, and the routes answer 501.
319
+ */
320
+ interface ApiKeySettings {
321
+ /**
322
+ * The database that holds the API key table, asked before the request's organization is known. It must be the same
323
+ * database the signed-in staff's `db` points at, because the key routes make keys through that one.
324
+ */
325
+ db(): Promise<SchedulingDb>;
326
+ }
316
327
  /** Switches data export and erasure on. A host that supplies none has them off: the routes answer 501. */
317
328
  type PrivacySettings = Record<string, never>;
318
329
  interface SchedulingHost {
@@ -375,6 +386,10 @@ interface SchedulingHost {
375
386
  * Turns on per-organization text-message settings. Needs the text-settings table. Default: off, so the routes answer 501.
376
387
  */
377
388
  textMessages?: TextMessageSettings | null;
389
+ /**
390
+ * Turns on API keys for outside tools. Needs the API key table. Default: off, so a Bearer key is ignored and the key routes answer 501.
391
+ */
392
+ apiKeys?: ApiKeySettings | null;
378
393
  /** The domain used after the "@" in calendar-file event ids. Keep it unchanged once calendars have subscribed. Default: ordinatio-scheduling. */
379
394
  icalUidDomain?(): string | null | undefined;
380
395
  /** Records what happened in the activity feed. Default: nothing is recorded. */
@@ -439,7 +454,9 @@ interface Route {
439
454
  path: string;
440
455
  /** A public route is called from other websites, so it also answers a CORS preflight. */
441
456
  public: boolean;
457
+ /** Needs a person at a browser (a consent screen, a cookie): a request made with an API key is refused with 403, whatever the key's access. */
458
+ personOnly?: boolean;
442
459
  handler: RouteHandler;
443
460
  }
444
461
 
445
- export { type AvailabilityCache as A, type BalancePaymentControl as B, type CacheOptions as C, type DnsResolver as D, type RouteHandler as E, type RoutingFormSettings as F, type StaffDirectory as G, type HttpMethod as H, type InternalAccess as I, type WebhookSettings as J, type WorkerCommands as K, checkSendingDomain as L, normalizeSendingDomain as M, type NoShowPolicy as N, type PublicBookingResolver as P, type Route as R, type SchedulingHost as S, type WaitlistSettings as W, type RateLimitTier as a, type SchedulingCache as b, type PublicOrganizationResolver as c, type SendingDomainCheck as d, type SendingDomainRecord as e, type SendingDomainRecords as f, type StaffResolver as g, type StaffContext as h, type ActivityEntry as i, type ActivityLog as j, type AppointmentEventSink as k, type BookingClientResolver as l, type BookingPolicy as m, type BrandSettings as n, type CalendarConnectOutcome as o, type CalendarConnector as p, type CalendarConnectors as q, type CalendarVisibility as r, type PrivacySettings as s, type PublicBookingContext as t, type PublicBookingKind as u, type PublicOrganization as v, type RecordCheck as w, type RecordStatus as x, type ResolvedHost as y, type RouteContext as z };
462
+ export { type AvailabilityCache as A, type BalancePaymentControl as B, type CacheOptions as C, type DnsResolver as D, type RouteContext as E, type RouteHandler as F, type RoutingFormSettings as G, type HttpMethod as H, type InternalAccess as I, type StaffDirectory as J, type WebhookSettings as K, type WorkerCommands as L, checkSendingDomain as M, type NoShowPolicy as N, normalizeSendingDomain as O, type PublicBookingResolver as P, type Route as R, type SchedulingHost as S, type WaitlistSettings as W, type RateLimitTier as a, type SchedulingCache as b, type PublicOrganizationResolver as c, type SendingDomainCheck as d, type SendingDomainRecord as e, type SendingDomainRecords as f, type StaffResolver as g, type StaffContext as h, type ActivityEntry as i, type ActivityLog as j, type ApiKeySettings as k, type AppointmentEventSink as l, type BookingClientResolver as m, type BookingPolicy as n, type BrandSettings as o, type CalendarConnectOutcome as p, type CalendarConnector as q, type CalendarConnectors as r, type CalendarVisibility as s, type PrivacySettings as t, type PublicBookingContext as u, type PublicBookingKind as v, type PublicOrganization as w, type RecordCheck as x, type RecordStatus as y, type ResolvedHost as z };
@@ -313,6 +313,17 @@ interface TextMessageSettings {
313
313
  /** The providers this server has accounts for. Default: Telnyx and Twilio. */
314
314
  providers?: readonly TextProvider[];
315
315
  }
316
+ /**
317
+ * Switches API keys on: a request with `Authorization: Bearer <key>` acts as that key's organization. A host that supplies
318
+ * none has them off, and the routes answer 501.
319
+ */
320
+ interface ApiKeySettings {
321
+ /**
322
+ * The database that holds the API key table, asked before the request's organization is known. It must be the same
323
+ * database the signed-in staff's `db` points at, because the key routes make keys through that one.
324
+ */
325
+ db(): Promise<SchedulingDb>;
326
+ }
316
327
  /** Switches data export and erasure on. A host that supplies none has them off: the routes answer 501. */
317
328
  type PrivacySettings = Record<string, never>;
318
329
  interface SchedulingHost {
@@ -375,6 +386,10 @@ interface SchedulingHost {
375
386
  * Turns on per-organization text-message settings. Needs the text-settings table. Default: off, so the routes answer 501.
376
387
  */
377
388
  textMessages?: TextMessageSettings | null;
389
+ /**
390
+ * Turns on API keys for outside tools. Needs the API key table. Default: off, so a Bearer key is ignored and the key routes answer 501.
391
+ */
392
+ apiKeys?: ApiKeySettings | null;
378
393
  /** The domain used after the "@" in calendar-file event ids. Keep it unchanged once calendars have subscribed. Default: ordinatio-scheduling. */
379
394
  icalUidDomain?(): string | null | undefined;
380
395
  /** Records what happened in the activity feed. Default: nothing is recorded. */
@@ -439,7 +454,9 @@ interface Route {
439
454
  path: string;
440
455
  /** A public route is called from other websites, so it also answers a CORS preflight. */
441
456
  public: boolean;
457
+ /** Needs a person at a browser (a consent screen, a cookie): a request made with an API key is refused with 403, whatever the key's access. */
458
+ personOnly?: boolean;
442
459
  handler: RouteHandler;
443
460
  }
444
461
 
445
- export { type AvailabilityCache as A, type BalancePaymentControl as B, type CacheOptions as C, type DnsResolver as D, type RouteHandler as E, type RoutingFormSettings as F, type StaffDirectory as G, type HttpMethod as H, type InternalAccess as I, type WebhookSettings as J, type WorkerCommands as K, checkSendingDomain as L, normalizeSendingDomain as M, type NoShowPolicy as N, type PublicBookingResolver as P, type Route as R, type SchedulingHost as S, type WaitlistSettings as W, type RateLimitTier as a, type SchedulingCache as b, type PublicOrganizationResolver as c, type SendingDomainCheck as d, type SendingDomainRecord as e, type SendingDomainRecords as f, type StaffResolver as g, type StaffContext as h, type ActivityEntry as i, type ActivityLog as j, type AppointmentEventSink as k, type BookingClientResolver as l, type BookingPolicy as m, type BrandSettings as n, type CalendarConnectOutcome as o, type CalendarConnector as p, type CalendarConnectors as q, type CalendarVisibility as r, type PrivacySettings as s, type PublicBookingContext as t, type PublicBookingKind as u, type PublicOrganization as v, type RecordCheck as w, type RecordStatus as x, type ResolvedHost as y, type RouteContext as z };
462
+ export { type AvailabilityCache as A, type BalancePaymentControl as B, type CacheOptions as C, type DnsResolver as D, type RouteContext as E, type RouteHandler as F, type RoutingFormSettings as G, type HttpMethod as H, type InternalAccess as I, type StaffDirectory as J, type WebhookSettings as K, type WorkerCommands as L, checkSendingDomain as M, type NoShowPolicy as N, normalizeSendingDomain as O, type PublicBookingResolver as P, type Route as R, type SchedulingHost as S, type WaitlistSettings as W, type RateLimitTier as a, type SchedulingCache as b, type PublicOrganizationResolver as c, type SendingDomainCheck as d, type SendingDomainRecord as e, type SendingDomainRecords as f, type StaffResolver as g, type StaffContext as h, type ActivityEntry as i, type ActivityLog as j, type ApiKeySettings as k, type AppointmentEventSink as l, type BookingClientResolver as m, type BookingPolicy as n, type BrandSettings as o, type CalendarConnectOutcome as p, type CalendarConnector as q, type CalendarConnectors as r, type CalendarVisibility as s, type PrivacySettings as t, type PublicBookingContext as u, type PublicBookingKind as v, type PublicOrganization as w, type RecordCheck as x, type RecordStatus as y, type ResolvedHost as z };
@@ -521,4 +521,9 @@ declare const TextSettingsSchema: z.ZodObject<{
521
521
  enabled: z.ZodOptional<z.ZodBoolean>;
522
522
  }, z.core.$strict>;
523
523
 
524
- export { type BookingPageConfig, BookingPageConfigSchema, type BookingPageTheme, BookingPageThemeSchema, BrandSchema, CancelRecurringScopeSchema, type CancelRecurringSeriesInput, CancelRecurringSeriesSchema, type CreateAppointmentCategoryInput, CreateAppointmentCategorySchema, type CreateAppointmentTypeInput, CreateAppointmentTypeSchema, type CreateAvailabilityRuleInput, CreateAvailabilityRuleSchema, type CreateCalendarInput, CreateCalendarSchema, type CreateCouponCodeInput, CreateCouponCodeSchema, type CreateNotificationTemplateInput, CreateNotificationTemplateSchema, type CreatePackagePurchaseInput, CreatePackagePurchaseSchema, type CreateRecurringSeriesInput, CreateRecurringSeriesSchema, type CreateRoutingFormInput, CreateRoutingFormSchema, type CreateServicePackageInput, CreateServicePackageSchema, type CreateWebhookEndpointInput, CreateWebhookEndpointSchema, DEFAULT_CANCELLATION_POLICY, IntakeFormFieldSchema, type NoShowPrevention, type NoShowPreventionAction, NoShowPreventionActionSchema, NotificationChannelSchema, NotificationTriggerSchema, type OrgCancellationPolicy, OrgCancellationPolicySchema, PrivacyEraseSchema, PrivacySubjectSchema, RecurringFrequencySchema, RouteClientSchema, SLOT_GRANULARITY_DEFAULT, SLOT_GRANULARITY_OPTIONS, type SlotGranularityMinutes, TestRoutingFormSchema, TextSettingsSchema, type UpdateAppointmentCategoryInput, UpdateAppointmentCategorySchema, type UpdateAppointmentTypeInput, UpdateAppointmentTypeSchema, type UpdateBookingPageInput, UpdateBookingPageSchema, type UpdateCalendarInput, UpdateCalendarSchema, type UpdateCouponCodeInput, UpdateCouponCodeSchema, type UpdateNotificationTemplateInput, UpdateNotificationTemplateSchema, type UpdatePackagePurchaseInput, UpdatePackagePurchaseSchema, type UpdateRoutingFormInput, UpdateRoutingFormSchema, type UpdateServicePackageInput, UpdateServicePackageSchema };
524
+ declare const ApiKeySchema: z.ZodObject<{
525
+ name: z.ZodString;
526
+ access: z.ZodString;
527
+ }, z.core.$strict>;
528
+
529
+ export { ApiKeySchema, type BookingPageConfig, BookingPageConfigSchema, type BookingPageTheme, BookingPageThemeSchema, BrandSchema, CancelRecurringScopeSchema, type CancelRecurringSeriesInput, CancelRecurringSeriesSchema, type CreateAppointmentCategoryInput, CreateAppointmentCategorySchema, type CreateAppointmentTypeInput, CreateAppointmentTypeSchema, type CreateAvailabilityRuleInput, CreateAvailabilityRuleSchema, type CreateCalendarInput, CreateCalendarSchema, type CreateCouponCodeInput, CreateCouponCodeSchema, type CreateNotificationTemplateInput, CreateNotificationTemplateSchema, type CreatePackagePurchaseInput, CreatePackagePurchaseSchema, type CreateRecurringSeriesInput, CreateRecurringSeriesSchema, type CreateRoutingFormInput, CreateRoutingFormSchema, type CreateServicePackageInput, CreateServicePackageSchema, type CreateWebhookEndpointInput, CreateWebhookEndpointSchema, DEFAULT_CANCELLATION_POLICY, IntakeFormFieldSchema, type NoShowPrevention, type NoShowPreventionAction, NoShowPreventionActionSchema, NotificationChannelSchema, NotificationTriggerSchema, type OrgCancellationPolicy, OrgCancellationPolicySchema, PrivacyEraseSchema, PrivacySubjectSchema, RecurringFrequencySchema, RouteClientSchema, SLOT_GRANULARITY_DEFAULT, SLOT_GRANULARITY_OPTIONS, type SlotGranularityMinutes, TestRoutingFormSchema, TextSettingsSchema, type UpdateAppointmentCategoryInput, UpdateAppointmentCategorySchema, type UpdateAppointmentTypeInput, UpdateAppointmentTypeSchema, type UpdateBookingPageInput, UpdateBookingPageSchema, type UpdateCalendarInput, UpdateCalendarSchema, type UpdateCouponCodeInput, UpdateCouponCodeSchema, type UpdateNotificationTemplateInput, UpdateNotificationTemplateSchema, type UpdatePackagePurchaseInput, UpdatePackagePurchaseSchema, type UpdateRoutingFormInput, UpdateRoutingFormSchema, type UpdateServicePackageInput, UpdateServicePackageSchema };
@@ -521,4 +521,9 @@ declare const TextSettingsSchema: z.ZodObject<{
521
521
  enabled: z.ZodOptional<z.ZodBoolean>;
522
522
  }, z.core.$strict>;
523
523
 
524
- export { type BookingPageConfig, BookingPageConfigSchema, type BookingPageTheme, BookingPageThemeSchema, BrandSchema, CancelRecurringScopeSchema, type CancelRecurringSeriesInput, CancelRecurringSeriesSchema, type CreateAppointmentCategoryInput, CreateAppointmentCategorySchema, type CreateAppointmentTypeInput, CreateAppointmentTypeSchema, type CreateAvailabilityRuleInput, CreateAvailabilityRuleSchema, type CreateCalendarInput, CreateCalendarSchema, type CreateCouponCodeInput, CreateCouponCodeSchema, type CreateNotificationTemplateInput, CreateNotificationTemplateSchema, type CreatePackagePurchaseInput, CreatePackagePurchaseSchema, type CreateRecurringSeriesInput, CreateRecurringSeriesSchema, type CreateRoutingFormInput, CreateRoutingFormSchema, type CreateServicePackageInput, CreateServicePackageSchema, type CreateWebhookEndpointInput, CreateWebhookEndpointSchema, DEFAULT_CANCELLATION_POLICY, IntakeFormFieldSchema, type NoShowPrevention, type NoShowPreventionAction, NoShowPreventionActionSchema, NotificationChannelSchema, NotificationTriggerSchema, type OrgCancellationPolicy, OrgCancellationPolicySchema, PrivacyEraseSchema, PrivacySubjectSchema, RecurringFrequencySchema, RouteClientSchema, SLOT_GRANULARITY_DEFAULT, SLOT_GRANULARITY_OPTIONS, type SlotGranularityMinutes, TestRoutingFormSchema, TextSettingsSchema, type UpdateAppointmentCategoryInput, UpdateAppointmentCategorySchema, type UpdateAppointmentTypeInput, UpdateAppointmentTypeSchema, type UpdateBookingPageInput, UpdateBookingPageSchema, type UpdateCalendarInput, UpdateCalendarSchema, type UpdateCouponCodeInput, UpdateCouponCodeSchema, type UpdateNotificationTemplateInput, UpdateNotificationTemplateSchema, type UpdatePackagePurchaseInput, UpdatePackagePurchaseSchema, type UpdateRoutingFormInput, UpdateRoutingFormSchema, type UpdateServicePackageInput, UpdateServicePackageSchema };
524
+ declare const ApiKeySchema: z.ZodObject<{
525
+ name: z.ZodString;
526
+ access: z.ZodString;
527
+ }, z.core.$strict>;
528
+
529
+ export { ApiKeySchema, type BookingPageConfig, BookingPageConfigSchema, type BookingPageTheme, BookingPageThemeSchema, BrandSchema, CancelRecurringScopeSchema, type CancelRecurringSeriesInput, CancelRecurringSeriesSchema, type CreateAppointmentCategoryInput, CreateAppointmentCategorySchema, type CreateAppointmentTypeInput, CreateAppointmentTypeSchema, type CreateAvailabilityRuleInput, CreateAvailabilityRuleSchema, type CreateCalendarInput, CreateCalendarSchema, type CreateCouponCodeInput, CreateCouponCodeSchema, type CreateNotificationTemplateInput, CreateNotificationTemplateSchema, type CreatePackagePurchaseInput, CreatePackagePurchaseSchema, type CreateRecurringSeriesInput, CreateRecurringSeriesSchema, type CreateRoutingFormInput, CreateRoutingFormSchema, type CreateServicePackageInput, CreateServicePackageSchema, type CreateWebhookEndpointInput, CreateWebhookEndpointSchema, DEFAULT_CANCELLATION_POLICY, IntakeFormFieldSchema, type NoShowPrevention, type NoShowPreventionAction, NoShowPreventionActionSchema, NotificationChannelSchema, NotificationTriggerSchema, type OrgCancellationPolicy, OrgCancellationPolicySchema, PrivacyEraseSchema, PrivacySubjectSchema, RecurringFrequencySchema, RouteClientSchema, SLOT_GRANULARITY_DEFAULT, SLOT_GRANULARITY_OPTIONS, type SlotGranularityMinutes, TestRoutingFormSchema, TextSettingsSchema, type UpdateAppointmentCategoryInput, UpdateAppointmentCategorySchema, type UpdateAppointmentTypeInput, UpdateAppointmentTypeSchema, type UpdateBookingPageInput, UpdateBookingPageSchema, type UpdateCalendarInput, UpdateCalendarSchema, type UpdateCouponCodeInput, UpdateCouponCodeSchema, type UpdateNotificationTemplateInput, UpdateNotificationTemplateSchema, type UpdatePackagePurchaseInput, UpdatePackagePurchaseSchema, type UpdateRoutingFormInput, UpdateRoutingFormSchema, type UpdateServicePackageInput, UpdateServicePackageSchema };
@@ -20,6 +20,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/schemas/index.ts
21
21
  var schemas_exports = {};
22
22
  __export(schemas_exports, {
23
+ ApiKeySchema: () => ApiKeySchema,
23
24
  BookingPageConfigSchema: () => BookingPageConfigSchema,
24
25
  BookingPageThemeSchema: () => BookingPageThemeSchema,
25
26
  BrandSchema: () => BrandSchema,
@@ -500,8 +501,16 @@ var TextSettingsSchema = import_zod9.z.object({
500
501
  fromNumber: import_zod9.z.string().max(40),
501
502
  enabled: import_zod9.z.boolean().optional()
502
503
  }).strict();
504
+
505
+ // src/schemas/api-key.schema.ts
506
+ var import_zod10 = require("zod");
507
+ var ApiKeySchema = import_zod10.z.object({
508
+ name: import_zod10.z.string().max(200),
509
+ access: import_zod10.z.string().max(20)
510
+ }).strict();
503
511
  // Annotate the CommonJS export names for ESM import in node:
504
512
  0 && (module.exports = {
513
+ ApiKeySchema,
505
514
  BookingPageConfigSchema,
506
515
  BookingPageThemeSchema,
507
516
  BrandSchema,
@@ -1,4 +1,5 @@
1
1
  import {
2
+ ApiKeySchema,
2
3
  BookingPageConfigSchema,
3
4
  BookingPageThemeSchema,
4
5
  BrandSchema,
@@ -38,8 +39,9 @@ import {
38
39
  UpdatePackagePurchaseSchema,
39
40
  UpdateRoutingFormSchema,
40
41
  UpdateServicePackageSchema
41
- } from "../chunk-IW6AN5WE.mjs";
42
+ } from "../chunk-X5BVCLX6.mjs";
42
43
  export {
44
+ ApiKeySchema,
43
45
  BookingPageConfigSchema,
44
46
  BookingPageThemeSchema,
45
47
  BrandSchema,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ordinatio/scheduling-api",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "license": "MIT",
5
5
  "description": "HTTP API for @ordinatio/scheduling. Every handler takes a Request and returns a Response.",
6
6
  "main": "./dist/index.js",
@@ -11,7 +11,7 @@
11
11
  "sanitize-html": "^2.16.0"
12
12
  },
13
13
  "peerDependencies": {
14
- "@ordinatio/scheduling": "^0.6.1"
14
+ "@ordinatio/scheduling": "^0.7.0"
15
15
  },
16
16
  "devDependencies": {
17
17
  "@types/sanitize-html": "^2.13.0",
@@ -19,7 +19,7 @@
19
19
  "tsup": "^8.0.0",
20
20
  "typescript": "5",
21
21
  "vitest": "4.0.18",
22
- "@ordinatio/scheduling": "0.6.1"
22
+ "@ordinatio/scheduling": "0.7.0"
23
23
  },
24
24
  "engines": {
25
25
  "node": ">=22.0.0"