@thebookingkit/server 0.1.1 → 0.1.3
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/README.md +50 -0
- package/dist/adapters/email-adapter.js +2 -2
- package/dist/adapters/email-adapter.js.map +1 -1
- package/dist/adapters/job-adapter.d.ts +10 -10
- package/dist/adapters/job-adapter.d.ts.map +1 -1
- package/dist/adapters/job-adapter.js +10 -10
- package/dist/adapters/job-adapter.js.map +1 -1
- package/dist/api.d.ts +3 -3
- package/dist/api.js +5 -5
- package/dist/api.js.map +1 -1
- package/package.json +21 -2
- package/.turbo/turbo-build.log +0 -6
- package/.turbo/turbo-test.log +0 -20
- package/CHANGELOG.md +0 -9
- package/dist/__tests__/api.test.d.ts +0 -2
- package/dist/__tests__/api.test.d.ts.map +0 -1
- package/dist/__tests__/api.test.js +0 -280
- package/dist/__tests__/api.test.js.map +0 -1
- package/dist/__tests__/auth.test.d.ts +0 -2
- package/dist/__tests__/auth.test.d.ts.map +0 -1
- package/dist/__tests__/auth.test.js +0 -78
- package/dist/__tests__/auth.test.js.map +0 -1
- package/dist/__tests__/concurrent-booking.test.d.ts +0 -2
- package/dist/__tests__/concurrent-booking.test.d.ts.map +0 -1
- package/dist/__tests__/concurrent-booking.test.js +0 -111
- package/dist/__tests__/concurrent-booking.test.js.map +0 -1
- package/dist/__tests__/multi-tenancy.test.d.ts +0 -2
- package/dist/__tests__/multi-tenancy.test.d.ts.map +0 -1
- package/dist/__tests__/multi-tenancy.test.js +0 -196
- package/dist/__tests__/multi-tenancy.test.js.map +0 -1
- package/dist/__tests__/serialization-retry.test.d.ts +0 -2
- package/dist/__tests__/serialization-retry.test.d.ts.map +0 -1
- package/dist/__tests__/serialization-retry.test.js +0 -53
- package/dist/__tests__/serialization-retry.test.js.map +0 -1
- package/dist/__tests__/webhooks.test.d.ts +0 -2
- package/dist/__tests__/webhooks.test.d.ts.map +0 -1
- package/dist/__tests__/webhooks.test.js +0 -286
- package/dist/__tests__/webhooks.test.js.map +0 -1
- package/dist/__tests__/workflows.test.d.ts +0 -2
- package/dist/__tests__/workflows.test.d.ts.map +0 -1
- package/dist/__tests__/workflows.test.js +0 -299
- package/dist/__tests__/workflows.test.js.map +0 -1
- package/src/__tests__/api.test.ts +0 -354
- package/src/__tests__/auth.test.ts +0 -111
- package/src/__tests__/concurrent-booking.test.ts +0 -170
- package/src/__tests__/multi-tenancy.test.ts +0 -267
- package/src/__tests__/serialization-retry.test.ts +0 -76
- package/src/__tests__/webhooks.test.ts +0 -412
- package/src/__tests__/workflows.test.ts +0 -422
- package/src/adapters/calendar-adapter.ts +0 -49
- package/src/adapters/email-adapter.ts +0 -108
- package/src/adapters/index.ts +0 -36
- package/src/adapters/job-adapter.ts +0 -26
- package/src/adapters/payment-adapter.ts +0 -118
- package/src/adapters/sms-adapter.ts +0 -35
- package/src/adapters/storage-adapter.ts +0 -11
- package/src/api.ts +0 -446
- package/src/auth.ts +0 -146
- package/src/booking-tokens.ts +0 -61
- package/src/email-templates.ts +0 -140
- package/src/index.ts +0 -192
- package/src/multi-tenancy.ts +0 -301
- package/src/notification-jobs.ts +0 -428
- package/src/serialization-retry.ts +0 -94
- package/src/webhooks.ts +0 -378
- package/src/workflows.ts +0 -441
- package/tsconfig.json +0 -9
- package/vitest.config.ts +0 -7
|
@@ -1,118 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Abstract interface for payment processing.
|
|
3
|
-
*
|
|
4
|
-
* Default implementation: Stripe via `stripe` npm package.
|
|
5
|
-
* Alternatives: Square, PayPal, or mock for testing.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
/** Result of creating a payment intent */
|
|
9
|
-
export interface CreatePaymentIntentResult {
|
|
10
|
-
/** Stripe PaymentIntent ID (or equivalent) */
|
|
11
|
-
paymentIntentId: string;
|
|
12
|
-
/** Client secret for confirming payment on the frontend */
|
|
13
|
-
clientSecret: string;
|
|
14
|
-
/** Current status of the payment intent */
|
|
15
|
-
status: "requires_payment_method" | "requires_confirmation" | "requires_action" | "processing" | "succeeded" | "canceled";
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
/** Result of creating a setup intent for card authorization */
|
|
19
|
-
export interface CreateSetupIntentResult {
|
|
20
|
-
/** Stripe SetupIntent ID (or equivalent) */
|
|
21
|
-
setupIntentId: string;
|
|
22
|
-
/** Client secret for confirming setup on the frontend */
|
|
23
|
-
clientSecret: string;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
/** Result of capturing a held payment */
|
|
27
|
-
export interface CaptureResult {
|
|
28
|
-
/** Whether the capture was successful */
|
|
29
|
-
captured: boolean;
|
|
30
|
-
/** The payment intent ID that was captured */
|
|
31
|
-
paymentIntentId: string;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/** Result of a refund operation */
|
|
35
|
-
export interface RefundResult {
|
|
36
|
-
/** Refund ID from the payment provider */
|
|
37
|
-
refundId: string;
|
|
38
|
-
/** Amount refunded in cents */
|
|
39
|
-
amountCents: number;
|
|
40
|
-
/** Status of the refund */
|
|
41
|
-
status: "succeeded" | "pending" | "failed";
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
/** Options for creating a payment intent */
|
|
45
|
-
export interface CreatePaymentIntentOptions {
|
|
46
|
-
/** Amount in smallest currency unit (e.g., cents for USD) */
|
|
47
|
-
amountCents: number;
|
|
48
|
-
/** ISO 4217 currency code */
|
|
49
|
-
currency: string;
|
|
50
|
-
/** Connected account ID (for Stripe Connect) */
|
|
51
|
-
connectedAccountId?: string;
|
|
52
|
-
/** Whether to use manual capture (for holds) */
|
|
53
|
-
captureMethod?: "automatic" | "manual";
|
|
54
|
-
/** Metadata to attach to the payment */
|
|
55
|
-
metadata?: Record<string, string>;
|
|
56
|
-
/** Customer email for receipt */
|
|
57
|
-
customerEmail?: string;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/** Options for creating a setup intent */
|
|
61
|
-
export interface CreateSetupIntentOptions {
|
|
62
|
-
/** Connected account ID (for Stripe Connect) */
|
|
63
|
-
connectedAccountId?: string;
|
|
64
|
-
/** Customer email */
|
|
65
|
-
customerEmail?: string;
|
|
66
|
-
/** Metadata */
|
|
67
|
-
metadata?: Record<string, string>;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
/**
|
|
71
|
-
* Payment processing adapter interface.
|
|
72
|
-
*
|
|
73
|
-
* Implementations handle creating payment intents, capturing holds,
|
|
74
|
-
* processing refunds, and managing Stripe Connect onboarding.
|
|
75
|
-
*/
|
|
76
|
-
export interface PaymentAdapter {
|
|
77
|
-
/**
|
|
78
|
-
* Create a payment intent for collecting payment.
|
|
79
|
-
* Use `captureMethod: 'manual'` for no-show fee holds.
|
|
80
|
-
*/
|
|
81
|
-
createPaymentIntent(options: CreatePaymentIntentOptions): Promise<CreatePaymentIntentResult>;
|
|
82
|
-
|
|
83
|
-
/**
|
|
84
|
-
* Create a setup intent for authorizing a card without charging.
|
|
85
|
-
*/
|
|
86
|
-
createSetupIntent(options: CreateSetupIntentOptions): Promise<CreateSetupIntentResult>;
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* Capture a previously authorized (manual capture) payment intent.
|
|
90
|
-
* Used when marking a booking as no-show.
|
|
91
|
-
*/
|
|
92
|
-
capturePaymentIntent(paymentIntentId: string, amountCents?: number): Promise<CaptureResult>;
|
|
93
|
-
|
|
94
|
-
/**
|
|
95
|
-
* Cancel a payment intent (release a hold).
|
|
96
|
-
* Used when a booking completes normally and the no-show hold should be released.
|
|
97
|
-
*/
|
|
98
|
-
cancelPaymentIntent(paymentIntentId: string): Promise<void>;
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* Refund a payment intent (full or partial).
|
|
102
|
-
*/
|
|
103
|
-
refund(paymentIntentId: string, amountCents?: number): Promise<RefundResult>;
|
|
104
|
-
|
|
105
|
-
/**
|
|
106
|
-
* Generate a Stripe Connect onboarding URL for a provider.
|
|
107
|
-
* Returns the URL the provider should be redirected to.
|
|
108
|
-
*/
|
|
109
|
-
createConnectOnboardingUrl(options: {
|
|
110
|
-
returnUrl: string;
|
|
111
|
-
refreshUrl: string;
|
|
112
|
-
}): Promise<string>;
|
|
113
|
-
|
|
114
|
-
/**
|
|
115
|
-
* Disconnect a Stripe Connect account.
|
|
116
|
-
*/
|
|
117
|
-
disconnectAccount(connectedAccountId: string): Promise<void>;
|
|
118
|
-
}
|
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Abstract interface for SMS delivery.
|
|
3
|
-
*
|
|
4
|
-
* Default implementation: Twilio.
|
|
5
|
-
* Alternatives: AWS SNS, Vonage, or mock for testing.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
/** Options for sending an SMS */
|
|
9
|
-
export interface SendSmsOptions {
|
|
10
|
-
/** Recipient phone number (E.164 format) */
|
|
11
|
-
to: string;
|
|
12
|
-
/** SMS body text */
|
|
13
|
-
body: string;
|
|
14
|
-
/** Sender phone number or alphanumeric sender ID */
|
|
15
|
-
from?: string;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
/** Result of an SMS send operation */
|
|
19
|
-
export interface SmsResult {
|
|
20
|
-
/** Message ID from the SMS provider */
|
|
21
|
-
messageId: string;
|
|
22
|
-
/** Delivery status */
|
|
23
|
-
status: "queued" | "sent" | "delivered" | "failed";
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* SMS delivery adapter interface.
|
|
28
|
-
*
|
|
29
|
-
* Implementations handle sending SMS messages via a provider
|
|
30
|
-
* (e.g., Twilio, AWS SNS).
|
|
31
|
-
*/
|
|
32
|
-
export interface SmsAdapter {
|
|
33
|
-
/** Send an SMS message */
|
|
34
|
-
send(options: SendSmsOptions): Promise<SmsResult>;
|
|
35
|
-
}
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Storage/encryption adapter interface.
|
|
3
|
-
* Default implementation uses an environment variable encryption key.
|
|
4
|
-
* Swap to AWS KMS, GCP KMS, or HashiCorp Vault by implementing this interface.
|
|
5
|
-
*/
|
|
6
|
-
export interface StorageAdapter {
|
|
7
|
-
/** Encrypt a plaintext value */
|
|
8
|
-
encrypt(plaintext: string): Promise<string>;
|
|
9
|
-
/** Decrypt an encrypted value */
|
|
10
|
-
decrypt(ciphertext: string): Promise<string>;
|
|
11
|
-
}
|
package/src/api.ts
DELETED
|
@@ -1,446 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* REST API utilities for SlotKit.
|
|
3
|
-
*
|
|
4
|
-
* Provides standardized response formatting, API key management,
|
|
5
|
-
* rate limiting, pagination, and request validation helpers
|
|
6
|
-
* for Next.js API routes.
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
import { createHmac, randomBytes } from "node:crypto";
|
|
10
|
-
|
|
11
|
-
// ---------------------------------------------------------------------------
|
|
12
|
-
// Standard Response Types
|
|
13
|
-
// ---------------------------------------------------------------------------
|
|
14
|
-
|
|
15
|
-
/** Standard API error */
|
|
16
|
-
export interface ApiError {
|
|
17
|
-
code: string;
|
|
18
|
-
message: string;
|
|
19
|
-
details?: Record<string, unknown>;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
/** Standard error response envelope */
|
|
23
|
-
export interface ApiErrorResponse {
|
|
24
|
-
error: ApiError;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
/** Standard success response envelope */
|
|
28
|
-
export interface ApiSuccessResponse<T> {
|
|
29
|
-
data: T;
|
|
30
|
-
meta?: ApiMeta;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/** Pagination metadata */
|
|
34
|
-
export interface ApiMeta {
|
|
35
|
-
total?: number;
|
|
36
|
-
nextCursor?: string | null;
|
|
37
|
-
prevCursor?: string | null;
|
|
38
|
-
hasMore?: boolean;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
/** Paginated list response */
|
|
42
|
-
export interface PaginatedResponse<T> {
|
|
43
|
-
data: T[];
|
|
44
|
-
meta: {
|
|
45
|
-
nextCursor: string | null;
|
|
46
|
-
hasMore: boolean;
|
|
47
|
-
total?: number;
|
|
48
|
-
};
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
// ---------------------------------------------------------------------------
|
|
52
|
-
// Error Codes
|
|
53
|
-
// ---------------------------------------------------------------------------
|
|
54
|
-
|
|
55
|
-
/** Standard API error codes */
|
|
56
|
-
export const API_ERROR_CODES = {
|
|
57
|
-
NOT_FOUND: "NOT_FOUND",
|
|
58
|
-
UNAUTHORIZED: "UNAUTHORIZED",
|
|
59
|
-
FORBIDDEN: "FORBIDDEN",
|
|
60
|
-
VALIDATION_ERROR: "VALIDATION_ERROR",
|
|
61
|
-
CONFLICT: "CONFLICT",
|
|
62
|
-
RATE_LIMITED: "RATE_LIMITED",
|
|
63
|
-
INTERNAL_ERROR: "INTERNAL_ERROR",
|
|
64
|
-
PAYMENT_REQUIRED: "PAYMENT_REQUIRED",
|
|
65
|
-
} as const;
|
|
66
|
-
|
|
67
|
-
export type ApiErrorCode = (typeof API_ERROR_CODES)[keyof typeof API_ERROR_CODES];
|
|
68
|
-
|
|
69
|
-
// ---------------------------------------------------------------------------
|
|
70
|
-
// Response Helpers
|
|
71
|
-
// ---------------------------------------------------------------------------
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* Create a standardized API error response.
|
|
75
|
-
*
|
|
76
|
-
* @param code - Error code from API_ERROR_CODES
|
|
77
|
-
* @param message - Human-readable error message
|
|
78
|
-
* @param details - Optional additional details
|
|
79
|
-
* @returns Standardized error response object
|
|
80
|
-
*/
|
|
81
|
-
export function createErrorResponse(
|
|
82
|
-
code: ApiErrorCode | string,
|
|
83
|
-
message: string,
|
|
84
|
-
details?: Record<string, unknown>,
|
|
85
|
-
): ApiErrorResponse {
|
|
86
|
-
return {
|
|
87
|
-
error: {
|
|
88
|
-
code,
|
|
89
|
-
message,
|
|
90
|
-
...(details ? { details } : {}),
|
|
91
|
-
},
|
|
92
|
-
};
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/**
|
|
96
|
-
* Create a standardized API success response.
|
|
97
|
-
*
|
|
98
|
-
* @param data - The response data
|
|
99
|
-
* @param meta - Optional pagination metadata
|
|
100
|
-
* @returns Standardized success response object
|
|
101
|
-
*/
|
|
102
|
-
export function createSuccessResponse<T>(
|
|
103
|
-
data: T,
|
|
104
|
-
meta?: ApiMeta,
|
|
105
|
-
): ApiSuccessResponse<T> {
|
|
106
|
-
return {
|
|
107
|
-
data,
|
|
108
|
-
...(meta ? { meta } : {}),
|
|
109
|
-
};
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/**
|
|
113
|
-
* Create a paginated list response.
|
|
114
|
-
*
|
|
115
|
-
* @param items - The page of items
|
|
116
|
-
* @param nextCursor - Cursor for the next page (null if last page)
|
|
117
|
-
* @param total - Optional total count
|
|
118
|
-
* @returns Paginated response
|
|
119
|
-
*/
|
|
120
|
-
export function createPaginatedResponse<T>(
|
|
121
|
-
items: T[],
|
|
122
|
-
nextCursor: string | null,
|
|
123
|
-
total?: number,
|
|
124
|
-
): PaginatedResponse<T> {
|
|
125
|
-
return {
|
|
126
|
-
data: items,
|
|
127
|
-
meta: {
|
|
128
|
-
nextCursor,
|
|
129
|
-
hasMore: nextCursor !== null,
|
|
130
|
-
...(total !== undefined ? { total } : {}),
|
|
131
|
-
},
|
|
132
|
-
};
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
// ---------------------------------------------------------------------------
|
|
136
|
-
// API Key Management
|
|
137
|
-
// ---------------------------------------------------------------------------
|
|
138
|
-
|
|
139
|
-
/** An API key record */
|
|
140
|
-
export interface ApiKeyRecord {
|
|
141
|
-
id: string;
|
|
142
|
-
name: string;
|
|
143
|
-
keyHash: string;
|
|
144
|
-
keyPrefix: string;
|
|
145
|
-
providerId?: string;
|
|
146
|
-
teamId?: string;
|
|
147
|
-
scopes: ApiKeyScope[];
|
|
148
|
-
rateLimit: number;
|
|
149
|
-
createdAt: Date;
|
|
150
|
-
expiresAt?: Date;
|
|
151
|
-
lastUsedAt?: Date;
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
/** API key scope */
|
|
155
|
-
export type ApiKeyScope =
|
|
156
|
-
| "read:bookings"
|
|
157
|
-
| "write:bookings"
|
|
158
|
-
| "read:availability"
|
|
159
|
-
| "write:availability"
|
|
160
|
-
| "read:event-types"
|
|
161
|
-
| "write:event-types"
|
|
162
|
-
| "read:webhooks"
|
|
163
|
-
| "write:webhooks"
|
|
164
|
-
| "read:analytics"
|
|
165
|
-
| "admin";
|
|
166
|
-
|
|
167
|
-
/** Result of generating a new API key */
|
|
168
|
-
export interface GeneratedApiKey {
|
|
169
|
-
/** The full key (only shown once) */
|
|
170
|
-
key: string;
|
|
171
|
-
/** The prefix for display (e.g., "sk_live_abc123...") */
|
|
172
|
-
prefix: string;
|
|
173
|
-
/** The hash stored in the database */
|
|
174
|
-
hash: string;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
/**
|
|
178
|
-
* Generate a new API key.
|
|
179
|
-
*
|
|
180
|
-
* The full key is only returned once and should be displayed to the user.
|
|
181
|
-
* Only the hash is stored in the database.
|
|
182
|
-
*
|
|
183
|
-
* @param prefix - Key prefix (e.g., "sk_live_" or "sk_test_")
|
|
184
|
-
* @returns Generated key with hash for storage
|
|
185
|
-
*/
|
|
186
|
-
export function generateApiKey(prefix: string = "sk_live_"): GeneratedApiKey {
|
|
187
|
-
const rawKey = randomBytes(32).toString("hex");
|
|
188
|
-
const key = `${prefix}${rawKey}`;
|
|
189
|
-
const hash = hashApiKey(key);
|
|
190
|
-
const displayPrefix = key.slice(0, prefix.length + 8) + "...";
|
|
191
|
-
|
|
192
|
-
return { key, prefix: displayPrefix, hash };
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
/**
|
|
196
|
-
* Hash an API key for secure storage.
|
|
197
|
-
*
|
|
198
|
-
* Uses HMAC-SHA256 with a secret from the SLOTKIT_API_KEY_SECRET
|
|
199
|
-
* environment variable. Throws if the secret is not configured.
|
|
200
|
-
*
|
|
201
|
-
* @param key - The full API key
|
|
202
|
-
* @param secret - Optional HMAC secret (defaults to SLOTKIT_API_KEY_SECRET env var)
|
|
203
|
-
* @returns The hex-encoded hash
|
|
204
|
-
*/
|
|
205
|
-
export function hashApiKey(key: string, secret?: string): string {
|
|
206
|
-
const hmacSecret =
|
|
207
|
-
secret ?? process.env.SLOTKIT_API_KEY_SECRET;
|
|
208
|
-
if (!hmacSecret) {
|
|
209
|
-
throw new Error(
|
|
210
|
-
"SLOTKIT_API_KEY_SECRET environment variable is required for API key hashing. " +
|
|
211
|
-
"Set it to a random 32+ character string.",
|
|
212
|
-
);
|
|
213
|
-
}
|
|
214
|
-
return createHmac("sha256", hmacSecret).update(key).digest("hex");
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
/**
|
|
218
|
-
* Verify an API key against a stored hash.
|
|
219
|
-
*
|
|
220
|
-
* @param key - The key to verify
|
|
221
|
-
* @param storedHash - The hash stored in the database
|
|
222
|
-
* @returns Whether the key is valid
|
|
223
|
-
*/
|
|
224
|
-
export function verifyApiKey(key: string, storedHash: string): boolean {
|
|
225
|
-
const hash = hashApiKey(key);
|
|
226
|
-
if (hash.length !== storedHash.length) return false;
|
|
227
|
-
|
|
228
|
-
// Constant-time comparison
|
|
229
|
-
const a = Buffer.from(hash, "hex");
|
|
230
|
-
const b = Buffer.from(storedHash, "hex");
|
|
231
|
-
|
|
232
|
-
if (a.length !== b.length) return false;
|
|
233
|
-
|
|
234
|
-
let mismatch = 0;
|
|
235
|
-
for (let i = 0; i < a.length; i++) {
|
|
236
|
-
mismatch |= a[i] ^ b[i];
|
|
237
|
-
}
|
|
238
|
-
return mismatch === 0;
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
/**
|
|
242
|
-
* Check if an API key has a required scope.
|
|
243
|
-
*
|
|
244
|
-
* Admin scope grants all permissions.
|
|
245
|
-
*
|
|
246
|
-
* @param keyScopes - The scopes granted to the API key
|
|
247
|
-
* @param requiredScope - The scope to check for
|
|
248
|
-
* @returns Whether the key has the required scope
|
|
249
|
-
*/
|
|
250
|
-
export function hasScope(
|
|
251
|
-
keyScopes: ApiKeyScope[],
|
|
252
|
-
requiredScope: ApiKeyScope,
|
|
253
|
-
): boolean {
|
|
254
|
-
return keyScopes.includes("admin") || keyScopes.includes(requiredScope);
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
/**
|
|
258
|
-
* Check if an API key has expired.
|
|
259
|
-
*
|
|
260
|
-
* @param expiresAt - Optional expiry timestamp
|
|
261
|
-
* @returns Whether the key is expired
|
|
262
|
-
*/
|
|
263
|
-
export function isKeyExpired(expiresAt: Date | undefined | null): boolean {
|
|
264
|
-
if (!expiresAt) return false;
|
|
265
|
-
return expiresAt.getTime() < Date.now();
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
// ---------------------------------------------------------------------------
|
|
269
|
-
// Rate Limiting
|
|
270
|
-
// ---------------------------------------------------------------------------
|
|
271
|
-
|
|
272
|
-
/** Rate limit state for a key */
|
|
273
|
-
export interface RateLimitState {
|
|
274
|
-
count: number;
|
|
275
|
-
windowStartMs: number;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
/** Rate limit check result */
|
|
279
|
-
export interface RateLimitResult {
|
|
280
|
-
allowed: boolean;
|
|
281
|
-
remaining: number;
|
|
282
|
-
resetMs: number;
|
|
283
|
-
limit: number;
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
/**
|
|
287
|
-
* Check if a request should be allowed under rate limiting.
|
|
288
|
-
*
|
|
289
|
-
* Uses a fixed 1-minute window.
|
|
290
|
-
*
|
|
291
|
-
* @param state - Current rate limit state
|
|
292
|
-
* @param limit - Maximum requests per minute
|
|
293
|
-
* @param nowMs - Current timestamp in milliseconds
|
|
294
|
-
* @returns Rate limit check result
|
|
295
|
-
*/
|
|
296
|
-
export function checkRateLimit(
|
|
297
|
-
state: RateLimitState | null,
|
|
298
|
-
limit: number,
|
|
299
|
-
nowMs: number = Date.now(),
|
|
300
|
-
): { result: RateLimitResult; newState: RateLimitState } {
|
|
301
|
-
const windowMs = 60 * 1000; // 1 minute
|
|
302
|
-
const windowStart = nowMs - (nowMs % windowMs);
|
|
303
|
-
|
|
304
|
-
// New window or no existing state
|
|
305
|
-
if (!state || state.windowStartMs !== windowStart) {
|
|
306
|
-
return {
|
|
307
|
-
result: {
|
|
308
|
-
allowed: true,
|
|
309
|
-
remaining: limit - 1,
|
|
310
|
-
resetMs: windowStart + windowMs,
|
|
311
|
-
limit,
|
|
312
|
-
},
|
|
313
|
-
newState: { count: 1, windowStartMs: windowStart },
|
|
314
|
-
};
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
const newCount = state.count + 1;
|
|
318
|
-
const allowed = newCount <= limit;
|
|
319
|
-
|
|
320
|
-
return {
|
|
321
|
-
result: {
|
|
322
|
-
allowed,
|
|
323
|
-
remaining: Math.max(0, limit - newCount),
|
|
324
|
-
resetMs: windowStart + windowMs,
|
|
325
|
-
limit,
|
|
326
|
-
},
|
|
327
|
-
newState: { count: newCount, windowStartMs: windowStart },
|
|
328
|
-
};
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
// ---------------------------------------------------------------------------
|
|
332
|
-
// Pagination
|
|
333
|
-
// ---------------------------------------------------------------------------
|
|
334
|
-
|
|
335
|
-
/**
|
|
336
|
-
* Encode a cursor for pagination (base64 JSON).
|
|
337
|
-
*
|
|
338
|
-
* @param data - The cursor data to encode
|
|
339
|
-
* @returns Base64-encoded cursor string
|
|
340
|
-
*/
|
|
341
|
-
export function encodeCursor(data: Record<string, unknown>): string {
|
|
342
|
-
return Buffer.from(JSON.stringify(data)).toString("base64url");
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
/**
|
|
346
|
-
* Decode a pagination cursor.
|
|
347
|
-
*
|
|
348
|
-
* @param cursor - The base64-encoded cursor string
|
|
349
|
-
* @returns The decoded cursor data, or null if invalid
|
|
350
|
-
*/
|
|
351
|
-
export function decodeCursor(
|
|
352
|
-
cursor: string,
|
|
353
|
-
): Record<string, unknown> | null {
|
|
354
|
-
try {
|
|
355
|
-
const json = Buffer.from(cursor, "base64url").toString("utf-8");
|
|
356
|
-
return JSON.parse(json);
|
|
357
|
-
} catch {
|
|
358
|
-
return null;
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
// ---------------------------------------------------------------------------
|
|
363
|
-
// Request Validation
|
|
364
|
-
// ---------------------------------------------------------------------------
|
|
365
|
-
|
|
366
|
-
/** Validation error detail */
|
|
367
|
-
export interface ValidationDetail {
|
|
368
|
-
field: string;
|
|
369
|
-
message: string;
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
/** Result of input validation */
|
|
373
|
-
export interface ValidationResult {
|
|
374
|
-
valid: boolean;
|
|
375
|
-
errors: ValidationDetail[];
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
/**
|
|
379
|
-
* Validate API request parameters for slot queries.
|
|
380
|
-
*
|
|
381
|
-
* @param params - Query parameters
|
|
382
|
-
* @returns Validation result
|
|
383
|
-
*/
|
|
384
|
-
export function validateSlotQueryParams(params: {
|
|
385
|
-
providerId?: string;
|
|
386
|
-
teamId?: string;
|
|
387
|
-
eventTypeId?: string;
|
|
388
|
-
start?: string;
|
|
389
|
-
end?: string;
|
|
390
|
-
timezone?: string;
|
|
391
|
-
}): ValidationResult {
|
|
392
|
-
const errors: ValidationDetail[] = [];
|
|
393
|
-
|
|
394
|
-
if (!params.providerId && !params.teamId) {
|
|
395
|
-
errors.push({
|
|
396
|
-
field: "providerId",
|
|
397
|
-
message: "Either providerId or teamId is required",
|
|
398
|
-
});
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
if (!params.start) {
|
|
402
|
-
errors.push({ field: "start", message: "start date is required" });
|
|
403
|
-
} else if (isNaN(Date.parse(params.start))) {
|
|
404
|
-
errors.push({
|
|
405
|
-
field: "start",
|
|
406
|
-
message: `Invalid date: "${params.start}"`,
|
|
407
|
-
});
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
if (!params.end) {
|
|
411
|
-
errors.push({ field: "end", message: "end date is required" });
|
|
412
|
-
} else if (isNaN(Date.parse(params.end))) {
|
|
413
|
-
errors.push({ field: "end", message: `Invalid date: "${params.end}"` });
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
if (params.start && params.end) {
|
|
417
|
-
const start = new Date(params.start);
|
|
418
|
-
const end = new Date(params.end);
|
|
419
|
-
if (!isNaN(start.getTime()) && !isNaN(end.getTime()) && end <= start) {
|
|
420
|
-
errors.push({ field: "end", message: "end must be after start" });
|
|
421
|
-
}
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
return { valid: errors.length === 0, errors };
|
|
425
|
-
}
|
|
426
|
-
|
|
427
|
-
/**
|
|
428
|
-
* Parse and validate a sort parameter.
|
|
429
|
-
*
|
|
430
|
-
* @param sortParam - Sort string (e.g., "-createdAt" or "startsAt")
|
|
431
|
-
* @param allowedFields - Fields that can be sorted by
|
|
432
|
-
* @returns Parsed sort field and direction
|
|
433
|
-
*/
|
|
434
|
-
export function parseSortParam(
|
|
435
|
-
sortParam: string | undefined,
|
|
436
|
-
allowedFields: string[],
|
|
437
|
-
): { field: string; direction: "asc" | "desc" } | null {
|
|
438
|
-
if (!sortParam) return null;
|
|
439
|
-
|
|
440
|
-
const descending = sortParam.startsWith("-");
|
|
441
|
-
const field = descending ? sortParam.slice(1) : sortParam;
|
|
442
|
-
|
|
443
|
-
if (!allowedFields.includes(field)) return null;
|
|
444
|
-
|
|
445
|
-
return { field, direction: descending ? "desc" : "asc" };
|
|
446
|
-
}
|