@scalemule/nextjs 0.1.61 → 0.1.63

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.
Files changed (41) hide show
  1. package/dist/audio.css +857 -0
  2. package/dist/audio.d.mts +334 -0
  3. package/dist/audio.d.ts +334 -0
  4. package/dist/audio.js +2178 -0
  5. package/dist/audio.mjs +2156 -0
  6. package/dist/client.d.mts +240 -0
  7. package/dist/client.d.ts +240 -0
  8. package/dist/client.js +938 -0
  9. package/dist/client.mjs +935 -0
  10. package/dist/index-CEi5Nd4L.d.mts +980 -0
  11. package/dist/index-CEi5Nd4L.d.ts +980 -0
  12. package/dist/index.d.mts +1354 -0
  13. package/dist/index.d.ts +1354 -0
  14. package/dist/index.js +6070 -0
  15. package/dist/index.mjs +6006 -0
  16. package/dist/ledvery-CxPzZpxP.d.mts +44 -0
  17. package/dist/ledvery-CxPzZpxP.d.ts +44 -0
  18. package/dist/listening-hub.global.js +1 -0
  19. package/dist/server/auth.d.mts +43 -0
  20. package/dist/server/auth.d.ts +43 -0
  21. package/dist/server/auth.js +2015 -0
  22. package/dist/server/auth.mjs +2009 -0
  23. package/dist/server/index.d.mts +1303 -0
  24. package/dist/server/index.d.ts +1303 -0
  25. package/dist/server/index.js +3660 -0
  26. package/dist/server/index.mjs +3581 -0
  27. package/dist/server/ledvery.d.mts +1 -0
  28. package/dist/server/ledvery.d.ts +1 -0
  29. package/dist/server/ledvery.js +336 -0
  30. package/dist/server/ledvery.mjs +333 -0
  31. package/dist/server/webhook-handler.d.mts +4 -0
  32. package/dist/server/webhook-handler.d.ts +4 -0
  33. package/dist/server/webhook-handler.js +60 -0
  34. package/dist/server/webhook-handler.mjs +58 -0
  35. package/dist/testing.d.mts +109 -0
  36. package/dist/testing.d.ts +109 -0
  37. package/dist/testing.js +144 -0
  38. package/dist/testing.mjs +138 -0
  39. package/dist/webhook-handler-CJm0sIZG.d.mts +856 -0
  40. package/dist/webhook-handler-CnQe9hm5.d.ts +856 -0
  41. package/package.json +2 -2
@@ -0,0 +1,3581 @@
1
+ import { exposureEvent, experimentVariant } from '@scalemule/sdk';
2
+ import { createMoneyClient } from '@scalemule/money';
3
+ import { cookies, headers } from 'next/headers';
4
+ import { NextResponse } from 'next/server';
5
+ import { LedveryClient } from '@scalemule/ledvery';
6
+ import { createHmac, timingSafeEqual } from 'crypto';
7
+ import { FlagClient } from '@scalemule/sdk/flags/server';
8
+
9
+ // src/server/client.ts
10
+
11
+ // src/types/index.ts
12
+ var ScaleMuleApiError = class extends Error {
13
+ constructor(error2, status) {
14
+ super(error2.message);
15
+ this.name = "ScaleMuleApiError";
16
+ this.code = error2.code;
17
+ this.field = error2.field;
18
+ this.status = status;
19
+ this.requestId = error2.requestId;
20
+ this.traceId = error2.traceId;
21
+ this.problem = error2.problem;
22
+ }
23
+ };
24
+
25
+ // src/url-privacy.ts
26
+ function withoutAuthSecrets(value) {
27
+ if (!value) return value;
28
+ try {
29
+ const absolute = /^[a-z][a-z0-9+.-]*:/i.test(value);
30
+ const protocolRelative = value.startsWith("//");
31
+ const url = new URL(value, "https://relative.invalid");
32
+ if (!["http:", "https:"].includes(url.protocol)) return void 0;
33
+ let changed = false;
34
+ for (const name of [...url.searchParams.keys()]) {
35
+ if (/^(token|code|state|password|new_password|access_token|refresh_token|id_token|api_key|client_secret|challenge_token|challenge_code)$/i.test(name)) {
36
+ url.searchParams.delete(name);
37
+ changed = true;
38
+ }
39
+ }
40
+ if (url.hash) {
41
+ url.hash = "";
42
+ changed = true;
43
+ }
44
+ if (!changed) return value;
45
+ if (absolute) return url.toString();
46
+ if (protocolRelative) return url.toString().replace(/^https:/, "");
47
+ return value.split(/[?#]/, 1)[0] + url.search;
48
+ } catch {
49
+ return void 0;
50
+ }
51
+ }
52
+
53
+ // src/server/context.ts
54
+ function validateIP(ip) {
55
+ if (!ip) return void 0;
56
+ const trimmed = ip.trim();
57
+ if (!trimmed) return void 0;
58
+ const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
59
+ const ipv6Regex = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^::(?:[0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4}$|^(?:[0-9a-fA-F]{1,4}:){1,7}:$|^(?:[0-9a-fA-F]{1,4}:){0,6}::(?:[0-9a-fA-F]{1,4}:){0,5}[0-9a-fA-F]{1,4}$/;
60
+ const ipv4MappedRegex = /^::ffff:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/i;
61
+ if (ipv4Regex.test(trimmed) || ipv6Regex.test(trimmed) || ipv4MappedRegex.test(trimmed)) {
62
+ return trimmed;
63
+ }
64
+ return void 0;
65
+ }
66
+ function extractClientContext(request, options = {}) {
67
+ const headers3 = request.headers;
68
+ let ip;
69
+ ip = validateIP(headers3.get("x-real-ip"));
70
+ const cfConnectingIp = headers3.get("cf-connecting-ip");
71
+ if (!ip && cfConnectingIp) {
72
+ ip = validateIP(cfConnectingIp);
73
+ }
74
+ if (!ip) {
75
+ const doConnectingIp = headers3.get("do-connecting-ip");
76
+ if (doConnectingIp) {
77
+ ip = validateIP(doConnectingIp);
78
+ }
79
+ }
80
+ if (!ip) {
81
+ const realIp = headers3.get("x-real-ip");
82
+ if (realIp) {
83
+ ip = validateIP(realIp);
84
+ }
85
+ }
86
+ if (!ip) {
87
+ const forwardedFor = headers3.get("x-forwarded-for");
88
+ if (forwardedFor) {
89
+ const firstIp = forwardedFor.split(",")[0]?.trim();
90
+ ip = validateIP(firstIp);
91
+ }
92
+ }
93
+ if (!ip) {
94
+ const vercelForwarded = headers3.get("x-vercel-forwarded-for");
95
+ if (vercelForwarded) {
96
+ const firstIp = vercelForwarded.split(",")[0]?.trim();
97
+ ip = validateIP(firstIp);
98
+ }
99
+ }
100
+ if (!ip) {
101
+ const trueClientIp = headers3.get("true-client-ip");
102
+ if (trueClientIp) {
103
+ ip = validateIP(trueClientIp);
104
+ }
105
+ }
106
+ if (!ip && request.ip) {
107
+ ip = validateIP(request.ip);
108
+ }
109
+ if (options.trustedIpHeader) {
110
+ const value = headers3.get(options.trustedIpHeader);
111
+ const hop = options.trustedIpHeader === "x-forwarded-for" ? value?.split(",").at(-1)?.trim() : value;
112
+ ip = validateIP(hop);
113
+ }
114
+ const userAgent = headers3.get("user-agent") || void 0;
115
+ const deviceFingerprint = headers3.get("x-device-fingerprint") || void 0;
116
+ const referrer = withoutAuthSecrets(headers3.get("referer") || void 0);
117
+ const anonymousId = headers3.get("x-anonymous-id") || void 0;
118
+ return {
119
+ ip,
120
+ userAgent,
121
+ deviceFingerprint,
122
+ referrer,
123
+ anonymousId
124
+ };
125
+ }
126
+ function extractClientContextFromReq(req) {
127
+ const headers3 = req.headers;
128
+ const getHeader = (name) => {
129
+ const value = headers3[name.toLowerCase()];
130
+ if (Array.isArray(value)) {
131
+ return value[0];
132
+ }
133
+ return value;
134
+ };
135
+ let ip;
136
+ ip = validateIP(getHeader("x-real-ip"));
137
+ const cfConnectingIp = getHeader("cf-connecting-ip");
138
+ if (!ip && cfConnectingIp) {
139
+ ip = validateIP(cfConnectingIp);
140
+ }
141
+ if (!ip) {
142
+ const doConnectingIp = getHeader("do-connecting-ip");
143
+ if (doConnectingIp) {
144
+ ip = validateIP(doConnectingIp);
145
+ }
146
+ }
147
+ if (!ip) {
148
+ const realIp = getHeader("x-real-ip");
149
+ if (realIp) {
150
+ ip = validateIP(realIp);
151
+ }
152
+ }
153
+ if (!ip) {
154
+ const forwardedFor = getHeader("x-forwarded-for");
155
+ if (forwardedFor) {
156
+ const firstIp = forwardedFor.split(",")[0]?.trim();
157
+ ip = validateIP(firstIp);
158
+ }
159
+ }
160
+ if (!ip) {
161
+ const vercelForwarded = getHeader("x-vercel-forwarded-for");
162
+ if (vercelForwarded) {
163
+ const firstIp = vercelForwarded.split(",")[0]?.trim();
164
+ ip = validateIP(firstIp);
165
+ }
166
+ }
167
+ if (!ip) {
168
+ const trueClientIp = getHeader("true-client-ip");
169
+ if (trueClientIp) {
170
+ ip = validateIP(trueClientIp);
171
+ }
172
+ }
173
+ if (!ip && req.socket?.remoteAddress) {
174
+ ip = validateIP(req.socket.remoteAddress);
175
+ }
176
+ const userAgent = getHeader("user-agent");
177
+ const deviceFingerprint = getHeader("x-device-fingerprint");
178
+ const referrer = withoutAuthSecrets(getHeader("referer"));
179
+ const anonymousId = getHeader("x-anonymous-id");
180
+ return {
181
+ ip,
182
+ userAgent,
183
+ deviceFingerprint,
184
+ referrer,
185
+ anonymousId
186
+ };
187
+ }
188
+ function buildClientContextHeaders(context) {
189
+ const headers3 = {};
190
+ if (!context) {
191
+ return headers3;
192
+ }
193
+ if (context.ip) {
194
+ headers3["x-sm-forwarded-client-ip"] = context.ip;
195
+ headers3["X-Client-IP"] = context.ip;
196
+ }
197
+ if (context.userAgent) {
198
+ headers3["X-Client-User-Agent"] = context.userAgent;
199
+ }
200
+ if (context.deviceFingerprint) {
201
+ headers3["X-Client-Device-Fingerprint"] = context.deviceFingerprint;
202
+ }
203
+ if (context.referrer) {
204
+ headers3["X-Client-Referrer"] = context.referrer;
205
+ }
206
+ if (context.anonymousId) {
207
+ headers3["x-anonymous-id"] = context.anonymousId;
208
+ }
209
+ return headers3;
210
+ }
211
+ function buildFlagContext(clientContext, extraContext = {}) {
212
+ const context = { ...extraContext };
213
+ if (clientContext?.ip && context.ip_address === void 0) {
214
+ context.ip_address = clientContext.ip;
215
+ }
216
+ return context;
217
+ }
218
+
219
+ // src/error-context.ts
220
+ function withErrorContext(error2, responseData, headers3) {
221
+ const enriched = { ...error2 };
222
+ const meta = responseData?.meta;
223
+ const requestId = meta?.request_id ?? headers3?.get("x-request-id") ?? void 0;
224
+ if (requestId !== void 0 && enriched.requestId === void 0) {
225
+ enriched.requestId = requestId;
226
+ }
227
+ const traceId = meta?.trace_id;
228
+ if (traceId !== void 0 && enriched.traceId === void 0) {
229
+ enriched.traceId = traceId;
230
+ }
231
+ const rawError = responseData?.error;
232
+ if (rawError !== null && typeof rawError === "object" && enriched.problem === void 0) {
233
+ enriched.problem = rawError;
234
+ }
235
+ return enriched;
236
+ }
237
+
238
+ // src/server/client.ts
239
+ var GATEWAY_URLS = {
240
+ dev: "https://api-dev.scalemule.com",
241
+ prod: "https://api.scalemule.com"
242
+ };
243
+ function resolveGatewayUrl(config) {
244
+ if (config.gatewayUrl) return config.gatewayUrl;
245
+ if (process.env.SCALEMULE_API_URL) return process.env.SCALEMULE_API_URL;
246
+ if (process.env.SCALEMULE_GATEWAY_URL) return process.env.SCALEMULE_GATEWAY_URL;
247
+ return GATEWAY_URLS[config.environment || "prod"];
248
+ }
249
+ var ScaleMuleServer = class {
250
+ constructor(config) {
251
+ // ==========================================================================
252
+ // Auth Methods
253
+ // ==========================================================================
254
+ this.auth = {
255
+ /** Issue a 60-second, single-use transfer code after a server OAuth callback. */
256
+ createSessionHandoff: async (sessionToken, audience) => {
257
+ return this.request("POST", "/v1/auth/session-handoff", { sessionToken, body: { session_token: sessionToken, audience } });
258
+ },
259
+ /** Exchange only on the server; write the returned session into an HTTP-only cookie. */
260
+ exchangeSessionHandoff: async (code, audience) => {
261
+ return this.request("POST", "/v1/auth/session-handoff/exchange", { body: { code, audience } });
262
+ },
263
+ /**
264
+ * Register a new user
265
+ */
266
+ register: async (data, options) => {
267
+ return this.request("POST", "/v1/auth/register", { body: data, clientContext: options?.clientContext });
268
+ },
269
+ /**
270
+ * Login user - returns session token (store in HTTP-only cookie)
271
+ */
272
+ sendMfaCode: async (pending_token, method, options) => {
273
+ return this.request("POST", "/v1/auth/mfa/send-code", { body: { pending_token, method }, clientContext: options?.clientContext });
274
+ },
275
+ completeMfa: async (pending_token, code, method, options) => {
276
+ return this.request("POST", "/v1/auth/mfa/verify", { body: { pending_token, code, method }, clientContext: options?.clientContext });
277
+ },
278
+ login: async (data, options) => {
279
+ return this.request("POST", "/v1/auth/login", { body: data, clientContext: options?.clientContext });
280
+ },
281
+ /**
282
+ * Logout user
283
+ */
284
+ logout: async (sessionToken, options) => {
285
+ return this.request("POST", "/v1/auth/logout", {
286
+ sessionToken,
287
+ body: { session_token: sessionToken },
288
+ onTokenRotated: options?.onTokenRotated
289
+ });
290
+ },
291
+ /**
292
+ * Get current user from session token
293
+ */
294
+ me: async (sessionToken, options) => {
295
+ return this.request("GET", "/v1/auth/me", {
296
+ sessionToken,
297
+ onTokenRotated: options?.onTokenRotated
298
+ });
299
+ },
300
+ /**
301
+ * Refresh session token
302
+ */
303
+ refresh: async (sessionToken, options) => {
304
+ return this.request("POST", "/v1/auth/refresh", {
305
+ sessionToken,
306
+ // The auth service reads the token to rotate from the body, not the
307
+ // Authorization header; without it every refresh is rejected.
308
+ body: { session_token: sessionToken },
309
+ clientContext: options?.clientContext,
310
+ isAutoRefresh: options?.isAutoRefresh,
311
+ onTokenRotated: options?.onTokenRotated
312
+ });
313
+ },
314
+ /**
315
+ * Request password reset email
316
+ */
317
+ forgotPassword: async (email, options) => {
318
+ return this.request("POST", "/v1/auth/forgot-password", { body: { email }, clientContext: options?.clientContext });
319
+ },
320
+ /**
321
+ * Reset password with token
322
+ */
323
+ resetPassword: async (token, newPassword, options) => {
324
+ return this.request("POST", "/v1/auth/reset-password", {
325
+ body: { token, new_password: newPassword },
326
+ clientContext: options?.clientContext
327
+ });
328
+ },
329
+ /**
330
+ * Verify email with token
331
+ */
332
+ verifyEmail: async (token) => {
333
+ return this.request("POST", "/v1/auth/verify-email", { body: { token } });
334
+ },
335
+ /**
336
+ * Resend verification email.
337
+ * Can be called with a session token (authenticated) or email (unauthenticated).
338
+ */
339
+ resendVerification: async (sessionTokenOrEmail, options) => {
340
+ if (options?.email) {
341
+ return this.request("POST", "/v1/auth/resend-verification", {
342
+ sessionToken: sessionTokenOrEmail,
343
+ body: { email: options.email },
344
+ onTokenRotated: options?.onTokenRotated
345
+ });
346
+ }
347
+ if (sessionTokenOrEmail.includes("@")) {
348
+ return this.request("POST", "/v1/auth/resend-verification", {
349
+ body: { email: sessionTokenOrEmail }
350
+ });
351
+ }
352
+ return this.request("POST", "/v1/auth/resend-verification", {
353
+ sessionToken: sessionTokenOrEmail,
354
+ onTokenRotated: options?.onTokenRotated
355
+ });
356
+ }
357
+ };
358
+ // ==========================================================================
359
+ // User/Profile Methods
360
+ // ==========================================================================
361
+ this.user = {
362
+ /**
363
+ * Update user profile
364
+ */
365
+ update: async (sessionToken, data, options) => {
366
+ return this.request("PATCH", "/v1/auth/profile", {
367
+ sessionToken,
368
+ body: data,
369
+ onTokenRotated: options?.onTokenRotated
370
+ });
371
+ },
372
+ /**
373
+ * Change password
374
+ */
375
+ changePassword: async (sessionToken, currentPassword, newPassword, options) => {
376
+ return this.request("POST", "/v1/auth/change-password", {
377
+ sessionToken,
378
+ body: { current_password: currentPassword, new_password: newPassword },
379
+ onTokenRotated: options?.onTokenRotated
380
+ });
381
+ },
382
+ /**
383
+ * Change email
384
+ */
385
+ changeEmail: async (sessionToken, newEmail, password, options) => {
386
+ return this.request("POST", "/v1/auth/change-email", {
387
+ sessionToken,
388
+ body: { new_email: newEmail, password },
389
+ onTokenRotated: options?.onTokenRotated
390
+ });
391
+ },
392
+ /**
393
+ * Delete account
394
+ */
395
+ deleteAccount: async (sessionToken, password, options) => {
396
+ return this.request("DELETE", "/v1/auth/me", {
397
+ sessionToken,
398
+ body: { password },
399
+ onTokenRotated: options?.onTokenRotated
400
+ });
401
+ }
402
+ };
403
+ // ==========================================================================
404
+ // Storage/Content Methods
405
+ // ==========================================================================
406
+ // ==========================================================================
407
+ // Secrets Methods (Tenant Vault)
408
+ // ==========================================================================
409
+ this.secrets = {
410
+ /**
411
+ * Get a secret from the tenant vault
412
+ *
413
+ * @example
414
+ * ```typescript
415
+ * const result = await scalemule.secrets.get('ANONYMOUS_USER_SALT')
416
+ * if (result.success) {
417
+ * console.log('Salt:', result.data.value)
418
+ * }
419
+ * ```
420
+ */
421
+ get: async (key) => {
422
+ return this.request("GET", `/v1/vault/secrets/${encodeURIComponent(key)}`);
423
+ },
424
+ /**
425
+ * Set a secret in the tenant vault
426
+ *
427
+ * @example
428
+ * ```typescript
429
+ * await scalemule.secrets.set('ANONYMOUS_USER_SALT', 'my-secret-salt')
430
+ * ```
431
+ */
432
+ set: async (key, value) => {
433
+ return this.request("PUT", `/v1/vault/secrets/${encodeURIComponent(key)}`, {
434
+ body: { value }
435
+ });
436
+ },
437
+ /**
438
+ * Delete a secret from the tenant vault
439
+ */
440
+ delete: async (key) => {
441
+ return this.request("DELETE", `/v1/vault/secrets/${encodeURIComponent(key)}`);
442
+ },
443
+ /**
444
+ * List all secrets in the tenant vault
445
+ */
446
+ list: async () => {
447
+ return this.request("GET", "/v1/vault/secrets");
448
+ },
449
+ /**
450
+ * Get secret version history
451
+ */
452
+ versions: async (key) => {
453
+ return this.request(
454
+ "GET",
455
+ `/v1/vault/versions/${encodeURIComponent(key)}`
456
+ );
457
+ },
458
+ /**
459
+ * Rollback to a specific version
460
+ */
461
+ rollback: async (key, version) => {
462
+ return this.request(
463
+ "POST",
464
+ `/v1/vault/actions/rollback/${encodeURIComponent(key)}`,
465
+ { body: { version } }
466
+ );
467
+ },
468
+ /**
469
+ * Rotate a secret (copy current version as new version)
470
+ */
471
+ rotate: async (key, newValue) => {
472
+ return this.request(
473
+ "POST",
474
+ `/v1/vault/actions/rotate/${encodeURIComponent(key)}`,
475
+ { body: { value: newValue } }
476
+ );
477
+ }
478
+ };
479
+ // ==========================================================================
480
+ // Bundle Methods (Structured Secrets with Inheritance)
481
+ // ==========================================================================
482
+ this.bundles = {
483
+ /**
484
+ * Get a bundle (structured secret like database credentials)
485
+ *
486
+ * @param key - Bundle key (e.g., 'database/prod')
487
+ * @param resolve - Whether to resolve inheritance (default: true)
488
+ *
489
+ * @example
490
+ * ```typescript
491
+ * const result = await scalemule.bundles.get('database/prod')
492
+ * if (result.success) {
493
+ * console.log('DB Host:', result.data.data.host)
494
+ * }
495
+ * ```
496
+ */
497
+ get: async (key, resolve = true) => {
498
+ const params = new URLSearchParams({ resolve: resolve.toString() });
499
+ return this.request(
500
+ "GET",
501
+ `/v1/vault/bundles/${encodeURIComponent(key)}?${params}`
502
+ );
503
+ },
504
+ /**
505
+ * Set a bundle (structured secret)
506
+ *
507
+ * @param key - Bundle key
508
+ * @param type - Bundle type: 'mysql', 'postgres', 'redis', 's3', 'oauth', 'smtp', 'generic'
509
+ * @param data - Bundle data (structure depends on type)
510
+ * @param inheritsFrom - Optional parent bundle key for inheritance
511
+ *
512
+ * @example
513
+ * ```typescript
514
+ * // Create a MySQL bundle
515
+ * await scalemule.bundles.set('database/prod', 'mysql', {
516
+ * host: 'db.example.com',
517
+ * port: 3306,
518
+ * username: 'app',
519
+ * password: 'secret',
520
+ * database: 'myapp'
521
+ * })
522
+ *
523
+ * // Create a bundle that inherits from another
524
+ * await scalemule.bundles.set('database/staging', 'mysql', {
525
+ * host: 'staging-db.example.com', // Override just the host
526
+ * }, 'database/prod')
527
+ * ```
528
+ */
529
+ set: async (key, type, data, inheritsFrom) => {
530
+ return this.request(
531
+ "PUT",
532
+ `/v1/vault/bundles/${encodeURIComponent(key)}`,
533
+ {
534
+ body: {
535
+ type,
536
+ value: data,
537
+ inherits_from: inheritsFrom
538
+ }
539
+ }
540
+ );
541
+ },
542
+ /**
543
+ * Delete a bundle
544
+ */
545
+ delete: async (key) => {
546
+ return this.request("DELETE", `/v1/vault/bundles/${encodeURIComponent(key)}`);
547
+ },
548
+ /**
549
+ * List all bundles
550
+ */
551
+ list: async () => {
552
+ return this.request(
553
+ "GET",
554
+ "/v1/vault/bundles"
555
+ );
556
+ },
557
+ /**
558
+ * Get connection URL for a database bundle
559
+ *
560
+ * @example
561
+ * ```typescript
562
+ * const result = await scalemule.bundles.connectionUrl('database/prod')
563
+ * if (result.success) {
564
+ * const client = mysql.createConnection(result.data.url)
565
+ * }
566
+ * ```
567
+ */
568
+ connectionUrl: async (key) => {
569
+ return this.request(
570
+ "GET",
571
+ `/v1/vault/bundles/${encodeURIComponent(key)}?connection_url=true`
572
+ );
573
+ }
574
+ };
575
+ // ==========================================================================
576
+ // Vault Audit Methods
577
+ // ==========================================================================
578
+ this.vaultAudit = {
579
+ /**
580
+ * Query audit logs for your tenant's vault operations
581
+ *
582
+ * @example
583
+ * ```typescript
584
+ * const result = await scalemule.vaultAudit.query({
585
+ * action: 'read',
586
+ * path: 'database/*',
587
+ * since: '2026-01-01'
588
+ * })
589
+ * ```
590
+ */
591
+ query: async (options) => {
592
+ const params = new URLSearchParams();
593
+ if (options?.action) params.set("action", options.action);
594
+ if (options?.path) params.set("path", options.path);
595
+ if (options?.since) params.set("since", options.since);
596
+ if (options?.until) params.set("until", options.until);
597
+ if (options?.limit) params.set("limit", options.limit.toString());
598
+ const queryStr = params.toString();
599
+ return this.request("GET", `/v1/vault/audit${queryStr ? `?${queryStr}` : ""}`);
600
+ }
601
+ };
602
+ this.storage = {
603
+ /**
604
+ * List user's files
605
+ */
606
+ list: async (userId, params) => {
607
+ const query = new URLSearchParams();
608
+ if (params?.content_type) query.set("content_type", params.content_type);
609
+ if (params?.search) query.set("search", params.search);
610
+ if (params?.limit) query.set("limit", params.limit.toString());
611
+ if (params?.offset) query.set("offset", params.offset.toString());
612
+ const queryStr = query.toString();
613
+ const path = `/v1/storage/my-files${queryStr ? `?${queryStr}` : ""}`;
614
+ return this.request("GET", path, { userId });
615
+ },
616
+ /**
617
+ * Get file info
618
+ */
619
+ get: async (fileId) => {
620
+ return this.request("GET", `/v1/storage/files/${fileId}/info`);
621
+ },
622
+ /**
623
+ * Delete file
624
+ */
625
+ delete: async (userId, fileId) => {
626
+ return this.request("DELETE", `/v1/storage/files/${fileId}`, { userId });
627
+ },
628
+ /**
629
+ * Upload file (from server - use FormData)
630
+ *
631
+ * @param userId - The user ID who owns this file
632
+ * @param file - File data to upload
633
+ * @param options - Upload options
634
+ * @param options.clientContext - End user context to forward (IP, user agent, etc.)
635
+ *
636
+ * @example
637
+ * ```typescript
638
+ * // Forward end user context for proper attribution
639
+ * const result = await scalemule.storage.upload(
640
+ * userId,
641
+ * { buffer, filename, contentType },
642
+ * { clientContext: extractClientContext(request) }
643
+ * )
644
+ * ```
645
+ */
646
+ upload: async (userId, file, options) => {
647
+ const formData = new FormData();
648
+ const blob = new Blob([file.buffer], { type: file.contentType });
649
+ formData.append("file", blob, file.filename);
650
+ formData.append("sm_user_id", userId);
651
+ const url = `${this.gatewayUrl}/v1/storage/upload`;
652
+ const headers3 = {
653
+ "x-api-key": this.apiKey,
654
+ "x-user-id": userId,
655
+ ...buildClientContextHeaders(options?.clientContext)
656
+ };
657
+ if (this.debug && options?.clientContext) {
658
+ console.log(`[ScaleMule Server] Upload with client context: IP=${options.clientContext.ip}`);
659
+ }
660
+ try {
661
+ const response = await fetch(url, {
662
+ method: "POST",
663
+ headers: headers3,
664
+ body: formData
665
+ });
666
+ const text = await response.text();
667
+ let responseData = null;
668
+ try {
669
+ responseData = text ? JSON.parse(text) : null;
670
+ } catch {
671
+ }
672
+ if (!response.ok) {
673
+ throw new ScaleMuleApiError(
674
+ withErrorContext(
675
+ responseData?.error || { code: "UPLOAD_FAILED", message: text || "Upload failed" },
676
+ responseData,
677
+ response.headers
678
+ )
679
+ );
680
+ }
681
+ const data = responseData?.data !== void 0 ? responseData.data : responseData;
682
+ return data;
683
+ } catch (err) {
684
+ if (err instanceof ScaleMuleApiError) {
685
+ throw err;
686
+ }
687
+ throw new ScaleMuleApiError({
688
+ code: "UPLOAD_ERROR",
689
+ message: err instanceof Error ? err.message : "Upload failed"
690
+ });
691
+ }
692
+ }
693
+ };
694
+ // ==========================================================================
695
+ // Analytics Methods
696
+ // ==========================================================================
697
+ // ==========================================================================
698
+ // Webhooks Methods
699
+ // ==========================================================================
700
+ this.webhooks = {
701
+ /**
702
+ * Create a new webhook subscription
703
+ *
704
+ * @example
705
+ * ```typescript
706
+ * const result = await scalemule.webhooks.create({
707
+ * webhook_name: 'Video Status Webhook',
708
+ * url: 'https://myapp.com/api/webhooks/scalemule',
709
+ * events: ['video.ready', 'video.failed']
710
+ * })
711
+ *
712
+ * // Store the secret for signature verification
713
+ * console.log('Webhook secret:', result.secret)
714
+ * ```
715
+ */
716
+ create: async (data) => {
717
+ return this.request(
718
+ "POST",
719
+ "/v1/webhooks",
720
+ { body: data }
721
+ );
722
+ },
723
+ /**
724
+ * List all webhook subscriptions
725
+ */
726
+ list: async () => {
727
+ return this.request("GET", "/v1/webhooks");
728
+ },
729
+ /**
730
+ * Delete a webhook subscription
731
+ */
732
+ delete: async (id) => {
733
+ return this.request("DELETE", `/v1/webhooks/${id}`);
734
+ },
735
+ /**
736
+ * Update a webhook subscription
737
+ */
738
+ update: async (id, data) => {
739
+ return this.request(
740
+ "PATCH",
741
+ `/v1/webhooks/${id}`,
742
+ { body: data }
743
+ );
744
+ },
745
+ /**
746
+ * Get available webhook event types
747
+ */
748
+ eventTypes: async () => {
749
+ return this.request("GET", "/v1/webhooks/events");
750
+ }
751
+ };
752
+ // ==========================================================================
753
+ // Analytics Methods
754
+ // ==========================================================================
755
+ this.analytics = {
756
+ /**
757
+ * Track an analytics event
758
+ *
759
+ * IMPORTANT: When calling from server-side code (API routes), always pass
760
+ * clientContext to ensure the real end user's IP is recorded, not the server's IP.
761
+ *
762
+ * @example
763
+ * ```typescript
764
+ * // In an API route
765
+ * import { extractClientContext, createServerClient } from '@scalemule/nextjs/server'
766
+ *
767
+ * export async function POST(request: NextRequest) {
768
+ * const clientContext = extractClientContext(request)
769
+ * const scalemule = createServerClient()
770
+ *
771
+ * await scalemule.analytics.trackEvent({
772
+ * event_name: 'button_clicked',
773
+ * properties: { button_id: 'signup' }
774
+ * }, { clientContext })
775
+ * }
776
+ * ```
777
+ */
778
+ trackEvent: async (event, options) => {
779
+ return this.request("POST", "/v1/analytics/v2/events", {
780
+ body: event,
781
+ clientContext: options?.clientContext
782
+ });
783
+ },
784
+ /**
785
+ * Track that a visitor saw an experiment variant (once per visitor and flag). The event carries
786
+ * `properties.experiments` so the analytics experiment report attributes it.
787
+ */
788
+ trackExposure: async (flagKey, variant, data, options) => {
789
+ const event = exposureEvent(flagKey, variant);
790
+ return this.request("POST", "/v1/analytics/v2/events", {
791
+ body: { ...event, ...data ?? {} },
792
+ clientContext: options?.clientContext
793
+ });
794
+ },
795
+ /**
796
+ * Track a page view
797
+ *
798
+ * @example
799
+ * ```typescript
800
+ * await scalemule.analytics.trackPageView({
801
+ * page_url: 'https://example.com/products',
802
+ * page_title: 'Products',
803
+ * referrer: 'https://google.com'
804
+ * }, { clientContext })
805
+ * ```
806
+ */
807
+ trackPageView: async (data, options) => {
808
+ return this.request("POST", "/v1/analytics/v2/events", {
809
+ body: {
810
+ event_name: "page_viewed",
811
+ event_category: "navigation",
812
+ page_url: data.page_url,
813
+ properties: {
814
+ page_title: data.page_title,
815
+ referrer: data.referrer
816
+ },
817
+ session_id: data.session_id,
818
+ user_id: data.user_id
819
+ },
820
+ clientContext: options?.clientContext
821
+ });
822
+ },
823
+ /**
824
+ * Track multiple events in a batch (max 100)
825
+ *
826
+ * @example
827
+ * ```typescript
828
+ * await scalemule.analytics.trackBatch([
829
+ * { event_name: 'item_viewed', properties: { item_id: '123' } },
830
+ * { event_name: 'item_added_to_cart', properties: { item_id: '123' } }
831
+ * ], { clientContext })
832
+ * ```
833
+ */
834
+ trackBatch: async (events, options) => {
835
+ return this.request("POST", "/v1/analytics/v2/events/batch", {
836
+ body: { events },
837
+ clientContext: options?.clientContext
838
+ });
839
+ }
840
+ };
841
+ this.flags = {
842
+ /**
843
+ * Assign a visitor to an experiment (a flag with weighted variants). Pass a stable identifier
844
+ * (`session_id` or `user_id`) so the assignment is sticky. Attach the returned assignment to
845
+ * every analytics event as `properties.experiments` and track one `experiment_exposed` with
846
+ * `analytics.trackExposure` when the variant is shown.
847
+ *
848
+ * @example
849
+ * ```typescript
850
+ * const { variant } = await scalemule.flags.experiment('front_page_layout', { session_id: visitorId })
851
+ * ```
852
+ */
853
+ experiment: async (flagKey, context = {}, environment = "prod", options) => {
854
+ const evaluation = await this.flags.evaluate(flagKey, context, environment, options);
855
+ return { flag_key: flagKey, variant: experimentVariant(evaluation), evaluation };
856
+ },
857
+ evaluate: async (flagKey, context = {}, environment = "prod", options) => {
858
+ return this.request("POST", "/v1/flags/evaluate", {
859
+ body: {
860
+ flag_key: flagKey,
861
+ environment,
862
+ context
863
+ },
864
+ clientContext: options?.clientContext
865
+ });
866
+ },
867
+ evaluateBatch: async (flagKeys, context = {}, environment = "prod", options) => {
868
+ return this.request("POST", "/v1/flags/evaluate/batch", {
869
+ body: {
870
+ flag_keys: flagKeys,
871
+ environment,
872
+ context
873
+ },
874
+ clientContext: options?.clientContext
875
+ });
876
+ },
877
+ evaluateAll: async (context = {}, environment = "prod", options) => {
878
+ return this.request("POST", "/v1/flags/evaluate/all", {
879
+ body: {
880
+ environment,
881
+ context
882
+ },
883
+ clientContext: options?.clientContext
884
+ });
885
+ }
886
+ };
887
+ this.apiKey = config.apiKey;
888
+ this.gatewayUrl = resolveGatewayUrl(config);
889
+ this.debug = config.debug || false;
890
+ this.onRefreshStart = config.onRefreshStart;
891
+ this.onRefreshEnd = config.onRefreshEnd;
892
+ this.onAutoRefreshFailed = config.onAutoRefreshFailed;
893
+ this.money = createMoneyClient({
894
+ apiKey: this.apiKey,
895
+ gatewayUrl: this.gatewayUrl,
896
+ fetch: globalThis.fetch.bind(globalThis)
897
+ });
898
+ }
899
+ moneyWithSession(sessionToken) {
900
+ return this.money.withAccessToken(sessionToken);
901
+ }
902
+ /**
903
+ * Make a request to the ScaleMule API
904
+ *
905
+ * @param method - HTTP method
906
+ * @param path - API path (e.g., /v1/auth/login)
907
+ * @param options - Request options
908
+ * @param options.body - Request body (will be JSON stringified)
909
+ * @param options.userId - User ID (passed through for storage operations)
910
+ * @param options.sessionToken - Session token sent as Authorization: Bearer header
911
+ * @param options.clientContext - End user context to forward (IP, user agent, etc.)
912
+ */
913
+ async request(method, path, options = {}) {
914
+ const url = `${this.gatewayUrl}${path}`;
915
+ const headers3 = {
916
+ "x-api-key": this.apiKey,
917
+ "Content-Type": "application/json",
918
+ // Forward client context headers if provided
919
+ ...buildClientContextHeaders(options.clientContext)
920
+ };
921
+ if (options.sessionToken) {
922
+ headers3["Authorization"] = `Bearer ${options.sessionToken}`;
923
+ }
924
+ if (this.debug) {
925
+ console.log(`[ScaleMule Server] ${method} ${path}`);
926
+ if (options.clientContext) {
927
+ console.log(`[ScaleMule Server] Client context: IP=${options.clientContext.ip}, UA=${options.clientContext.userAgent?.substring(0, 50)}...`);
928
+ }
929
+ }
930
+ try {
931
+ const response = await fetch(url, {
932
+ method,
933
+ headers: headers3,
934
+ body: options.body ? JSON.stringify(options.body) : void 0
935
+ });
936
+ const rotated = response.headers.get("x-rotated-session-token");
937
+ if (rotated && options.onTokenRotated) {
938
+ options.onTokenRotated(rotated);
939
+ }
940
+ const text = await response.text();
941
+ let responseData = null;
942
+ try {
943
+ responseData = text ? JSON.parse(text) : null;
944
+ } catch {
945
+ }
946
+ if (!response.ok || responseData?.success === false) {
947
+ const baseError = responseData?.error || {
948
+ code: `HTTP_${response.status}`,
949
+ message: responseData?.message || text || response.statusText
950
+ };
951
+ const error2 = withErrorContext(baseError, responseData, response.headers);
952
+ if (response.status === 401 && options.sessionToken && !options.isAutoRefresh) {
953
+ if (this.debug) console.log("[ScaleMule Server] 401 received, attempting auto-refresh...");
954
+ try {
955
+ this.onRefreshStart?.();
956
+ const refreshData = await this.auth.refresh(options.sessionToken, {
957
+ clientContext: options.clientContext,
958
+ isAutoRefresh: true
959
+ // Prevent infinite loops
960
+ });
961
+ const newToken = refreshData.session_token;
962
+ if (this.debug) console.log("[ScaleMule Server] Auto-refresh succeeded, retrying original request...");
963
+ options.onTokenRotated?.(newToken);
964
+ return this.request(method, path, {
965
+ ...options,
966
+ sessionToken: newToken,
967
+ isAutoRefresh: true
968
+ // Don't refresh again on this retry
969
+ });
970
+ } catch (refreshErr) {
971
+ if (this.debug) console.error("[ScaleMule Server] Auto-refresh failed:", refreshErr);
972
+ const refreshApiError = refreshErr instanceof ScaleMuleApiError ? { code: refreshErr.code, message: refreshErr.message } : { code: "REFRESH_FAILED", message: "Auto-refresh failed" };
973
+ this.onAutoRefreshFailed?.(refreshApiError);
974
+ throw new ScaleMuleApiError(error2, response.status);
975
+ } finally {
976
+ this.onRefreshEnd?.();
977
+ }
978
+ }
979
+ throw new ScaleMuleApiError(error2, response.status);
980
+ }
981
+ const data = responseData?.data !== void 0 ? responseData.data : responseData;
982
+ return data;
983
+ } catch (err) {
984
+ if (err instanceof ScaleMuleApiError) {
985
+ throw err;
986
+ }
987
+ throw new ScaleMuleApiError({
988
+ code: "SERVER_ERROR",
989
+ message: err instanceof Error ? err.message : "Request failed"
990
+ });
991
+ }
992
+ }
993
+ };
994
+ function createServerClient(config) {
995
+ const apiKey = config?.apiKey || process.env.SCALEMULE_API_KEY;
996
+ if (!apiKey) {
997
+ throw new Error(
998
+ "ScaleMule API key is required. Set SCALEMULE_API_KEY environment variable or pass apiKey in config."
999
+ );
1000
+ }
1001
+ const environment = config?.environment || process.env.SCALEMULE_ENV || "prod";
1002
+ return new ScaleMuleServer({
1003
+ apiKey,
1004
+ environment,
1005
+ gatewayUrl: config?.gatewayUrl,
1006
+ debug: config?.debug || process.env.SCALEMULE_DEBUG === "true"
1007
+ });
1008
+ }
1009
+ var SESSION_COOKIE_NAME = "sm_session";
1010
+ var USER_ID_COOKIE_NAME = "sm_user_id";
1011
+ var KNOWN_ACCOUNTS_COOKIE_NAME = "sm_known_accounts";
1012
+ ({
1013
+ secure: process.env.NODE_ENV === "production"});
1014
+ function createCookieHeader(name, value, options = {}) {
1015
+ const maxAge = options.maxAge ?? 7 * 24 * 60 * 60;
1016
+ const secure = options.secure ?? process.env.NODE_ENV === "production";
1017
+ const sameSite = options.sameSite ?? "lax";
1018
+ const path = options.path ?? "/";
1019
+ let cookie = `${name}=${encodeURIComponent(value)}; Path=${path}; Max-Age=${maxAge}; HttpOnly; SameSite=${sameSite}`;
1020
+ if (secure || options.partitioned) {
1021
+ cookie += "; Secure";
1022
+ }
1023
+ if (options.partitioned) cookie += "; Partitioned";
1024
+ if (options.domain) {
1025
+ cookie += `; Domain=${options.domain}`;
1026
+ }
1027
+ return cookie;
1028
+ }
1029
+ function createClearCookieHeader(name, options = {}) {
1030
+ const path = options.path ?? "/";
1031
+ const secure = options.secure ?? process.env.NODE_ENV === "production";
1032
+ const sameSite = options.sameSite ?? "lax";
1033
+ let cookie = `${name}=; Path=${path}; Max-Age=0; HttpOnly; SameSite=${sameSite}`;
1034
+ if (secure || options.partitioned) {
1035
+ cookie += "; Secure";
1036
+ }
1037
+ if (options.partitioned) cookie += "; Partitioned";
1038
+ if (options.domain) {
1039
+ cookie += `; Domain=${options.domain}`;
1040
+ }
1041
+ return cookie;
1042
+ }
1043
+ function withSession(loginResponse, responseBody, options = {}) {
1044
+ const headers3 = new Headers();
1045
+ headers3.set("Content-Type", "application/json");
1046
+ if (options.partitioned) {
1047
+ headers3.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, { ...options, partitioned: false }));
1048
+ headers3.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, { ...options, partitioned: false }));
1049
+ }
1050
+ headers3.append(
1051
+ "Set-Cookie",
1052
+ createCookieHeader(SESSION_COOKIE_NAME, loginResponse.session_token, options)
1053
+ );
1054
+ headers3.append(
1055
+ "Set-Cookie",
1056
+ createCookieHeader(USER_ID_COOKIE_NAME, loginResponse.user.id, options)
1057
+ );
1058
+ return new Response(JSON.stringify({ success: true, data: responseBody }), {
1059
+ status: 200,
1060
+ headers: headers3
1061
+ });
1062
+ }
1063
+ function withRefreshedSession(sessionToken, userId, responseBody, options = {}) {
1064
+ const headers3 = new Headers();
1065
+ headers3.set("Content-Type", "application/json");
1066
+ if (options.partitioned) {
1067
+ headers3.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, { ...options, partitioned: false }));
1068
+ headers3.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, { ...options, partitioned: false }));
1069
+ }
1070
+ headers3.append(
1071
+ "Set-Cookie",
1072
+ createCookieHeader(SESSION_COOKIE_NAME, sessionToken, options)
1073
+ );
1074
+ headers3.append(
1075
+ "Set-Cookie",
1076
+ createCookieHeader(USER_ID_COOKIE_NAME, userId, options)
1077
+ );
1078
+ return new Response(JSON.stringify({ success: true, data: responseBody }), {
1079
+ status: 200,
1080
+ headers: headers3
1081
+ });
1082
+ }
1083
+ function clearSession(responseBody, options = {}, status = 200) {
1084
+ const headers3 = new Headers();
1085
+ headers3.set("Content-Type", "application/json");
1086
+ appendClearSessionCookies(headers3, options);
1087
+ return new Response(JSON.stringify({ success: status < 300, data: responseBody }), {
1088
+ status,
1089
+ headers: headers3
1090
+ });
1091
+ }
1092
+ function appendClearSessionCookies(headers3, options) {
1093
+ if (options.partitioned) {
1094
+ headers3.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, { ...options, partitioned: false }));
1095
+ headers3.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, { ...options, partitioned: false }));
1096
+ }
1097
+ headers3.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, options));
1098
+ headers3.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, options));
1099
+ }
1100
+ function clearSessionWithError(error2, options = {}, status = 401) {
1101
+ const headers3 = new Headers();
1102
+ headers3.set("Content-Type", "application/json");
1103
+ appendClearSessionCookies(headers3, options);
1104
+ return new Response(JSON.stringify({ success: false, error: error2 }), {
1105
+ status,
1106
+ headers: headers3
1107
+ });
1108
+ }
1109
+ async function getSession(options = {}) {
1110
+ const cookieStore = await cookies();
1111
+ const sessionCookie = cookieStore.get(SESSION_COOKIE_NAME);
1112
+ const userIdCookie = cookieStore.get(USER_ID_COOKIE_NAME);
1113
+ if (sessionCookie?.value && userIdCookie?.value) {
1114
+ return {
1115
+ sessionToken: sessionCookie.value,
1116
+ userId: userIdCookie.value,
1117
+ expiresAt: /* @__PURE__ */ new Date()
1118
+ // Note: actual expiry is managed by ScaleMule backend
1119
+ };
1120
+ }
1121
+ if (options.allowBearer === false) return null;
1122
+ const headerStore = await headers();
1123
+ return sessionFromAuthHeaders(
1124
+ headerStore.get("authorization"),
1125
+ headerStore.get("x-sm-user-id")
1126
+ );
1127
+ }
1128
+ function sessionFromAuthHeaders(authorization, userId) {
1129
+ if (!authorization || !userId) return null;
1130
+ const match = /^Bearer\s+(.+)$/i.exec(authorization.trim());
1131
+ const token = match?.[1]?.trim();
1132
+ if (!token) return null;
1133
+ return {
1134
+ sessionToken: token,
1135
+ userId,
1136
+ expiresAt: /* @__PURE__ */ new Date()
1137
+ };
1138
+ }
1139
+ function getSessionFromRequest(request) {
1140
+ const cookieHeader = request.headers.get("cookie");
1141
+ if (cookieHeader) {
1142
+ const cookies4 = Object.fromEntries(
1143
+ cookieHeader.split(";").map((c) => {
1144
+ const [key, ...rest] = c.trim().split("=");
1145
+ return [key, decodeURIComponent(rest.join("="))];
1146
+ })
1147
+ );
1148
+ const sessionToken = cookies4[SESSION_COOKIE_NAME];
1149
+ const userId = cookies4[USER_ID_COOKIE_NAME];
1150
+ if (sessionToken && userId) {
1151
+ return {
1152
+ sessionToken,
1153
+ userId,
1154
+ expiresAt: /* @__PURE__ */ new Date()
1155
+ };
1156
+ }
1157
+ }
1158
+ return sessionFromAuthHeaders(
1159
+ request.headers.get("authorization"),
1160
+ request.headers.get("x-sm-user-id")
1161
+ );
1162
+ }
1163
+ var MAX_KNOWN_ACCOUNTS = 10;
1164
+ function maskEmail(email) {
1165
+ const [local, domain] = email.split("@");
1166
+ if (!domain) return "***@***.***";
1167
+ const tldDot = domain.lastIndexOf(".");
1168
+ const tld = tldDot > 0 ? domain.slice(tldDot) : "";
1169
+ const domainBase = tldDot > 0 ? domain.slice(0, tldDot) : domain;
1170
+ return `${local[0] || "*"}***@${domainBase[0] || "*"}***${tld}`;
1171
+ }
1172
+ function stableColorIndex(userId) {
1173
+ let hash = 0;
1174
+ for (let i = 0; i < userId.length; i++) {
1175
+ hash = (hash << 5) - hash + userId.charCodeAt(i) | 0;
1176
+ }
1177
+ return Math.abs(hash) % 8;
1178
+ }
1179
+ function applyPrivacyToEntry(entry, privacy) {
1180
+ switch (privacy) {
1181
+ case "full":
1182
+ return entry;
1183
+ case "masked":
1184
+ return {
1185
+ userId: entry.userId,
1186
+ email: entry.email ? maskEmail(entry.email) : void 0,
1187
+ fullName: entry.fullName ? `${entry.fullName[0].toUpperCase()}.` : void 0,
1188
+ provider: entry.provider,
1189
+ lastActiveAt: entry.lastActiveAt,
1190
+ colorIndex: stableColorIndex(entry.userId)
1191
+ };
1192
+ case "minimal":
1193
+ return {
1194
+ userId: entry.userId,
1195
+ provider: entry.provider,
1196
+ lastActiveAt: entry.lastActiveAt,
1197
+ displayLabel: "Account",
1198
+ colorIndex: stableColorIndex(entry.userId)
1199
+ };
1200
+ }
1201
+ }
1202
+ function appendKnownAccountCookie(headers3, account, existingCookie, options = {}, privacy) {
1203
+ let accounts = {};
1204
+ if (existingCookie) {
1205
+ try {
1206
+ accounts = JSON.parse(decodeURIComponent(existingCookie));
1207
+ } catch {
1208
+ }
1209
+ }
1210
+ const effectivePrivacy = privacy || "full";
1211
+ for (const [userId, entry] of Object.entries(accounts)) {
1212
+ accounts[userId] = applyPrivacyToEntry(entry, effectivePrivacy);
1213
+ }
1214
+ accounts[account.userId] = applyPrivacyToEntry(account, effectivePrivacy);
1215
+ const entries = Object.entries(accounts);
1216
+ if (entries.length > MAX_KNOWN_ACCOUNTS) {
1217
+ entries.sort((a, b) => new Date(b[1].lastActiveAt).getTime() - new Date(a[1].lastActiveAt).getTime());
1218
+ accounts = Object.fromEntries(entries.slice(0, MAX_KNOWN_ACCOUNTS));
1219
+ }
1220
+ const maxAge = 365 * 24 * 60 * 60;
1221
+ const secure = options.secure ?? process.env.NODE_ENV === "production";
1222
+ const sameSite = options.sameSite ?? "lax";
1223
+ const path = options.path ?? "/";
1224
+ let cookie = `${KNOWN_ACCOUNTS_COOKIE_NAME}=${encodeURIComponent(JSON.stringify(accounts))}; Path=${path}; Max-Age=${maxAge}; SameSite=${sameSite}`;
1225
+ if (secure) {
1226
+ cookie += "; Secure";
1227
+ }
1228
+ if (options.domain) {
1229
+ cookie += `; Domain=${options.domain}`;
1230
+ }
1231
+ headers3.append("Set-Cookie", cookie);
1232
+ }
1233
+ function removeKnownAccountFromCookie(headers3, userId, existingCookie, options = {}) {
1234
+ let accounts = {};
1235
+ if (existingCookie) {
1236
+ try {
1237
+ accounts = JSON.parse(decodeURIComponent(existingCookie));
1238
+ } catch {
1239
+ }
1240
+ }
1241
+ delete accounts[userId];
1242
+ const maxAge = 365 * 24 * 60 * 60;
1243
+ const secure = options.secure ?? process.env.NODE_ENV === "production";
1244
+ const sameSite = options.sameSite ?? "lax";
1245
+ const path = options.path ?? "/";
1246
+ let cookie = `${KNOWN_ACCOUNTS_COOKIE_NAME}=${encodeURIComponent(JSON.stringify(accounts))}; Path=${path}; Max-Age=${maxAge}; SameSite=${sameSite}`;
1247
+ if (secure) {
1248
+ cookie += "; Secure";
1249
+ }
1250
+ if (options.domain) {
1251
+ cookie += `; Domain=${options.domain}`;
1252
+ }
1253
+ headers3.append("Set-Cookie", cookie);
1254
+ }
1255
+ function clearKnownAccountsCookie(headers3, options = {}) {
1256
+ const path = options.path ?? "/";
1257
+ let cookie = `${KNOWN_ACCOUNTS_COOKIE_NAME}=; Path=${path}; Max-Age=0`;
1258
+ if (options.domain) {
1259
+ cookie += `; Domain=${options.domain}`;
1260
+ }
1261
+ headers3.append("Set-Cookie", cookie);
1262
+ }
1263
+ function getKnownAccountsFromRequest(request) {
1264
+ const cookieHeader = request.headers.get("cookie");
1265
+ if (!cookieHeader) return [];
1266
+ const cookies4 = Object.fromEntries(
1267
+ cookieHeader.split(";").map((c) => {
1268
+ const [key, ...rest] = c.trim().split("=");
1269
+ return [key, decodeURIComponent(rest.join("="))];
1270
+ })
1271
+ );
1272
+ const raw = cookies4[KNOWN_ACCOUNTS_COOKIE_NAME];
1273
+ if (!raw) return [];
1274
+ try {
1275
+ const accounts = JSON.parse(raw);
1276
+ return Object.values(accounts);
1277
+ } catch {
1278
+ return [];
1279
+ }
1280
+ }
1281
+ function getKnownAccountsCookieRaw(request) {
1282
+ const cookieHeader = request.headers.get("cookie");
1283
+ if (!cookieHeader) return null;
1284
+ const cookies4 = Object.fromEntries(
1285
+ cookieHeader.split(";").map((c) => {
1286
+ const [key, ...rest] = c.trim().split("=");
1287
+ return [key, decodeURIComponent(rest.join("="))];
1288
+ })
1289
+ );
1290
+ return cookies4[KNOWN_ACCOUNTS_COOKIE_NAME] || null;
1291
+ }
1292
+ function normalizeKnownAccountsCookie(request, privacy, options = {}) {
1293
+ if (!privacy || privacy === "full") return null;
1294
+ const raw = getKnownAccountsCookieRaw(request);
1295
+ if (!raw) return null;
1296
+ let accounts = {};
1297
+ try {
1298
+ accounts = JSON.parse(raw);
1299
+ } catch {
1300
+ return null;
1301
+ }
1302
+ let changed = false;
1303
+ for (const [userId, entry] of Object.entries(accounts)) {
1304
+ const normalized = applyPrivacyToEntry(entry, privacy);
1305
+ if (JSON.stringify(normalized) !== JSON.stringify(entry)) {
1306
+ accounts[userId] = normalized;
1307
+ changed = true;
1308
+ }
1309
+ }
1310
+ if (!changed) return null;
1311
+ const maxAge = 365 * 24 * 60 * 60;
1312
+ const secure = options.secure ?? process.env.NODE_ENV === "production";
1313
+ const sameSite = options.sameSite ?? "lax";
1314
+ const path = options.path ?? "/";
1315
+ let cookie = `${KNOWN_ACCOUNTS_COOKIE_NAME}=${encodeURIComponent(JSON.stringify(accounts))}; Path=${path}; Max-Age=${maxAge}; SameSite=${sameSite}`;
1316
+ if (secure) cookie += "; Secure";
1317
+ if (options.domain) cookie += `; Domain=${options.domain}`;
1318
+ return cookie;
1319
+ }
1320
+ async function requireSession() {
1321
+ const session = await getSession();
1322
+ if (!session) {
1323
+ throw new Response(
1324
+ JSON.stringify({
1325
+ success: false,
1326
+ error: { code: "UNAUTHORIZED", message: "Authentication required" }
1327
+ }),
1328
+ {
1329
+ status: 401,
1330
+ headers: { "Content-Type": "application/json" }
1331
+ }
1332
+ );
1333
+ }
1334
+ return session;
1335
+ }
1336
+
1337
+ // src/server/timing.ts
1338
+ function constantTimeEqual(a, b) {
1339
+ const maxLength = Math.max(a.length, b.length);
1340
+ let mismatch = a.length ^ b.length;
1341
+ for (let i = 0; i < maxLength; i++) {
1342
+ const aCode = i < a.length ? a.charCodeAt(i) : 0;
1343
+ const bCode = i < b.length ? b.charCodeAt(i) : 0;
1344
+ mismatch |= aCode ^ bCode;
1345
+ }
1346
+ return mismatch === 0;
1347
+ }
1348
+
1349
+ // src/server/csrf.ts
1350
+ var CSRF_COOKIE_NAME = "sm_csrf";
1351
+ var CSRF_HEADER_NAME = "x-csrf-token";
1352
+ function generateCSRFToken() {
1353
+ const array = new Uint8Array(32);
1354
+ crypto.getRandomValues(array);
1355
+ return Array.from(array, (byte) => byte.toString(16).padStart(2, "0")).join("");
1356
+ }
1357
+ function withCSRFToken(response, token) {
1358
+ const csrfToken = token || generateCSRFToken();
1359
+ response.cookies.set(CSRF_COOKIE_NAME, csrfToken, {
1360
+ httpOnly: false,
1361
+ // Must be readable by JavaScript to include in requests
1362
+ secure: process.env.NODE_ENV === "production",
1363
+ sameSite: "strict",
1364
+ path: "/",
1365
+ maxAge: 60 * 60 * 24
1366
+ // 24 hours
1367
+ });
1368
+ return response;
1369
+ }
1370
+ function validateCSRFToken(request) {
1371
+ const cookieToken = request.cookies.get(CSRF_COOKIE_NAME)?.value;
1372
+ if (!cookieToken) {
1373
+ return "Missing CSRF cookie";
1374
+ }
1375
+ const headerToken = request.headers.get(CSRF_HEADER_NAME);
1376
+ if (!headerToken) {
1377
+ return "Missing CSRF token header";
1378
+ }
1379
+ if (!constantTimeEqual(cookieToken, headerToken)) {
1380
+ return "CSRF token mismatch";
1381
+ }
1382
+ return void 0;
1383
+ }
1384
+ async function validateCSRFTokenAsync(request, body) {
1385
+ const cookieToken = request.cookies.get(CSRF_COOKIE_NAME)?.value;
1386
+ if (!cookieToken) {
1387
+ return "Missing CSRF cookie";
1388
+ }
1389
+ let requestToken = request.headers.get(CSRF_HEADER_NAME);
1390
+ if (!requestToken && body) {
1391
+ requestToken = body.csrf_token ?? body._csrf ?? null;
1392
+ }
1393
+ if (!requestToken) {
1394
+ return "Missing CSRF token";
1395
+ }
1396
+ if (!constantTimeEqual(cookieToken, requestToken)) {
1397
+ return "CSRF token mismatch";
1398
+ }
1399
+ return void 0;
1400
+ }
1401
+ function withCSRFProtection(handler) {
1402
+ return async (request) => {
1403
+ if (["POST", "PUT", "PATCH", "DELETE"].includes(request.method)) {
1404
+ const error2 = validateCSRFToken(request);
1405
+ if (error2) {
1406
+ return NextResponse.json(
1407
+ { error: "CSRF validation failed", message: error2 },
1408
+ { status: 403 }
1409
+ );
1410
+ }
1411
+ }
1412
+ return handler(request);
1413
+ };
1414
+ }
1415
+ async function getCSRFToken() {
1416
+ const cookieStore = await cookies();
1417
+ let token = cookieStore.get(CSRF_COOKIE_NAME)?.value;
1418
+ if (!token) {
1419
+ token = generateCSRFToken();
1420
+ }
1421
+ return token;
1422
+ }
1423
+
1424
+ // src/server/browser-proxy.ts
1425
+ function error(code, status) {
1426
+ return Response.json({ success: false, error: { code, message: code === "UNAUTHORIZED" ? "Authentication required" : "Request not permitted" } }, { status, headers: { "Cache-Control": "no-store" } });
1427
+ }
1428
+ function isSameOriginRequest(request) {
1429
+ const origin = request.headers.get("origin");
1430
+ const site = request.headers.get("sec-fetch-site");
1431
+ if (site) return site === "same-origin" || site === "none";
1432
+ const url = new URL(request.url);
1433
+ const host = request.headers.get("host") || url.host;
1434
+ if (origin) {
1435
+ try {
1436
+ const source = new URL(origin);
1437
+ if (!["http:", "https:"].includes(source.protocol) || source.host !== host) return false;
1438
+ } catch {
1439
+ return false;
1440
+ }
1441
+ }
1442
+ return true;
1443
+ }
1444
+ var SERVICES = /* @__PURE__ */ new Set(["storage", "photo", "video", "audio", "media", "tts", "social", "chat", "realtime", "money", "billing", "flags", "notifications", "search", "presence", "conference", "gallop", "data", "forms", "preferences", "feedback", "referrals"]);
1445
+ var AUTH_ROUTES = /* @__PURE__ */ new Set([
1446
+ "GET me",
1447
+ "GET mfa/status",
1448
+ "GET oauth/providers",
1449
+ "PATCH profile",
1450
+ "POST change-password",
1451
+ "POST change-email",
1452
+ "POST delete-account",
1453
+ "POST export-data",
1454
+ "POST mfa/setup",
1455
+ "POST mfa/verify",
1456
+ "POST mfa/disable",
1457
+ "POST mfa/backup-codes",
1458
+ "POST oauth/start",
1459
+ "POST oauth/callback"
1460
+ ]);
1461
+ var PUBLIC_AUTH_ROUTES = /* @__PURE__ */ new Set(["POST oauth/start", "POST oauth/callback"]);
1462
+ var PUBLIC_DATA_ROUTES = /* @__PURE__ */ new Set(["POST flags/evaluate", "POST flags/evaluate/all", "POST flags/evaluate/batch", "GET feedback/widget-config", "POST feedback/submit"]);
1463
+ var MAX_BODY_BYTES = 25 * 1024 * 1024;
1464
+ async function boundedBody(request) {
1465
+ if (request.method === "GET" || request.method === "HEAD" || !request.body) return void 0;
1466
+ const reader = request.body.getReader();
1467
+ const chunks = [];
1468
+ let size = 0;
1469
+ try {
1470
+ while (true) {
1471
+ const part = await reader.read();
1472
+ if (part.done) break;
1473
+ size += part.value.byteLength;
1474
+ if (size > MAX_BODY_BYTES) {
1475
+ await reader.cancel();
1476
+ throw new Error("BODY_TOO_LARGE");
1477
+ }
1478
+ chunks.push(part.value);
1479
+ }
1480
+ } finally {
1481
+ reader.releaseLock();
1482
+ }
1483
+ const bytes = new Uint8Array(size);
1484
+ let offset = 0;
1485
+ for (const chunk of chunks) {
1486
+ bytes.set(chunk, offset);
1487
+ offset += chunk.byteLength;
1488
+ }
1489
+ return bytes;
1490
+ }
1491
+ async function browserProxy(request, path, config) {
1492
+ if (!isSameOriginRequest(request)) return error("CSRF_ERROR", 403);
1493
+ const key = config.publishableKey || process.env.NEXT_PUBLIC_SCALEMULE_PUBLISHABLE_KEY;
1494
+ if (!key?.startsWith("sm_pb_")) return error("BROWSER_KEY_NOT_CONFIGURED", 503);
1495
+ if (request.headers.get("x-api-key") !== key) return error("CSRF_ERROR", 403);
1496
+ const authOperation = `${request.method} ${path.slice(2).join("/")}`;
1497
+ const authRoute = path[1] === "auth" && (AUTH_ROUTES.has(authOperation) || request.method === "DELETE" && path[2] === "oauth" && path[3] === "providers" && path.length === 5);
1498
+ if (path[0] !== "v1" || !(SERVICES.has(path[1]) || authRoute) || path.some((part) => !part || part === "." || part === ".." || /[\\/%\u0000-\u001f]/.test(part))) return error("NOT_FOUND", 404);
1499
+ const session = await getSession({ allowBearer: false });
1500
+ if (!session && !(authRoute && PUBLIC_AUTH_ROUTES.has(authOperation)) && !PUBLIC_DATA_ROUTES.has(`${request.method} ${path.slice(1).join("/")}`)) return error("UNAUTHORIZED", 401);
1501
+ const gateway = resolveGatewayUrl({ ...config.client, gatewayUrl: config.browserGatewayUrl || process.env.NEXT_PUBLIC_SCALEMULE_GATEWAY_URL || config.client?.gatewayUrl });
1502
+ const target = new URL(`${gateway.replace(/\/$/, "")}/${path.map(encodeURIComponent).join("/")}`);
1503
+ target.search = new URL(request.url).search;
1504
+ const headers3 = new Headers({ "x-api-key": key });
1505
+ if (session) headers3.set("Authorization", `Bearer ${session.sessionToken}`);
1506
+ for (const name of ["x-anonymous-id", "origin", "content-type", "accept", "user-agent", "range", "if-none-match", "x-idempotency-key", "x-sm-workspace-id"]) {
1507
+ const value = request.headers.get(name);
1508
+ if (value) headers3.set(name, value);
1509
+ }
1510
+ try {
1511
+ const body = await boundedBody(request);
1512
+ const upstream = await fetch(target, { method: request.method, headers: headers3, body, redirect: "error", cache: "no-store", signal: AbortSignal.timeout(6e4) });
1513
+ const outputHeaders = new Headers({ "Cache-Control": "no-store", "Vary": "Cookie" });
1514
+ for (const name of ["content-type", "content-disposition", "content-range", "accept-ranges", "etag", "retry-after", "x-request-id"]) {
1515
+ const value = upstream.headers.get(name);
1516
+ if (value) outputHeaders.set(name, value);
1517
+ }
1518
+ const rotated = upstream.headers.get("x-rotated-session-token");
1519
+ if (rotated && session) {
1520
+ const refreshed = withRefreshedSession(rotated, session.userId, {}, config.cookies);
1521
+ for (const cookie of refreshed.headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
1522
+ }
1523
+ if ([204, 205, 304].includes(upstream.status)) {
1524
+ if (authOperation === "POST delete-account" && upstream.ok) {
1525
+ for (const cookie of clearSession({}, config.cookies).headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
1526
+ }
1527
+ return new Response(null, { status: upstream.status, headers: outputHeaders });
1528
+ }
1529
+ if (authRoute) {
1530
+ const payload = await upstream.json();
1531
+ const data = payload?.data || payload;
1532
+ if (authOperation === "POST delete-account" && upstream.ok && payload.success !== false) {
1533
+ for (const cookie of clearSession({}, config.cookies).headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
1534
+ }
1535
+ const token = data?.session_token;
1536
+ if (typeof token === "string" && data?.user?.id && upstream.ok && payload.success !== false) {
1537
+ const established = withSession({ session_token: token, user: data.user }, {}, config.cookies);
1538
+ for (const cookie of established.headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
1539
+ data.authenticated = true;
1540
+ }
1541
+ if (data && typeof data === "object") {
1542
+ delete data.session_token;
1543
+ delete data.sessionToken;
1544
+ delete data.refresh_token;
1545
+ delete data.access_token;
1546
+ }
1547
+ return Response.json(payload, { status: upstream.status, headers: outputHeaders });
1548
+ }
1549
+ return new Response(upstream.body, { status: upstream.status, headers: outputHeaders });
1550
+ } catch (err) {
1551
+ if (err instanceof Error && err.message === "BODY_TOO_LARGE") return error("BODY_TOO_LARGE", 413);
1552
+ console.error("[ScaleMule] Browser proxy upstream request failed");
1553
+ return error("UPSTREAM_UNAVAILABLE", 502);
1554
+ }
1555
+ }
1556
+
1557
+ // src/session-errors.ts
1558
+ var SESSION_ENDED_CODES = /* @__PURE__ */ new Set([
1559
+ "UNAUTHORIZED",
1560
+ "INVALID_SESSION",
1561
+ "SESSION_EXPIRED",
1562
+ "SESSION_IDLE_EXPIRED",
1563
+ "SESSION_ABSOLUTE_EXPIRED",
1564
+ "SESSION_REVOKED",
1565
+ "TOKEN_EXPIRED",
1566
+ "TOKEN_INVALID"
1567
+ ]);
1568
+ function isSessionEndedError(error2) {
1569
+ if (!error2 || typeof error2 !== "object") return false;
1570
+ const { status, code } = error2;
1571
+ if (status === 401) return true;
1572
+ return typeof code === "string" && SESSION_ENDED_CODES.has(code);
1573
+ }
1574
+
1575
+ // src/server/routes.ts
1576
+ function errorResponse(code, message, status) {
1577
+ return new Response(
1578
+ JSON.stringify({ success: false, error: { code, message } }),
1579
+ { status, headers: { "Content-Type": "application/json" } }
1580
+ );
1581
+ }
1582
+ function successResponse(data, status = 200) {
1583
+ return new Response(
1584
+ JSON.stringify({ success: true, data }),
1585
+ { status, headers: { "Content-Type": "application/json" } }
1586
+ );
1587
+ }
1588
+ function createAuthRoutes(config = {}) {
1589
+ const sm = createServerClient(config.client);
1590
+ const cookieOptions = config.cookies || {};
1591
+ const sessionData = (user, token) => ({
1592
+ user,
1593
+ userId: user.id,
1594
+ authenticated: true,
1595
+ ...config.sessionMode === "bearer" ? { sessionToken: token } : {}
1596
+ });
1597
+ const POST = async (request, context) => {
1598
+ if (config.csrf) {
1599
+ const csrfError = validateCSRFToken(request);
1600
+ if (csrfError) {
1601
+ return errorResponse("CSRF_ERROR", "CSRF validation failed", 403);
1602
+ }
1603
+ }
1604
+ const params = await context?.params;
1605
+ const path = params?.scalemule?.join("/") || "";
1606
+ try {
1607
+ const body = await request.json().catch(() => ({}));
1608
+ const clientContext = extractClientContext(request, config.clientContext);
1609
+ switch (path) {
1610
+ // ==================== Register ====================
1611
+ case "register": {
1612
+ const { email, password, full_name, username, phone, publication_code, website, company, hp_field } = body;
1613
+ if (!email || !password) {
1614
+ return errorResponse("VALIDATION_ERROR", "Email and password required", 400);
1615
+ }
1616
+ const honeypotVal = publication_code || website || company || hp_field;
1617
+ if (typeof honeypotVal === "string" && honeypotVal.trim().length > 0) {
1618
+ return successResponse(
1619
+ {
1620
+ user: {
1621
+ id: "01000000-0000-7000-8000-000000000000",
1622
+ email,
1623
+ full_name: full_name ?? null
1624
+ },
1625
+ message: "Registration successful"
1626
+ },
1627
+ 201
1628
+ );
1629
+ }
1630
+ let registeredUser;
1631
+ try {
1632
+ registeredUser = await sm.auth.register({ email, password, full_name, username, phone }, { clientContext });
1633
+ } catch (err) {
1634
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1635
+ return errorResponse(
1636
+ apiErr?.code || "REGISTER_FAILED",
1637
+ apiErr?.message || "Registration failed",
1638
+ 400
1639
+ );
1640
+ }
1641
+ if (config.onRegister) {
1642
+ await config.onRegister({ id: registeredUser.id, email: registeredUser.email });
1643
+ }
1644
+ let loginData;
1645
+ try {
1646
+ loginData = await sm.auth.login({ email, password }, { clientContext });
1647
+ } catch {
1648
+ return successResponse({ user: registeredUser, authenticated: false, message: "Registration successful" }, 201);
1649
+ }
1650
+ const registerResponse = withSession(loginData, sessionData(registeredUser, loginData.session_token), cookieOptions);
1651
+ if (config.enableAccountSwitcher) {
1652
+ const existingKnown = getKnownAccountsCookieRaw(request);
1653
+ appendKnownAccountCookie(
1654
+ registerResponse.headers,
1655
+ {
1656
+ userId: registeredUser.id,
1657
+ email: registeredUser.email,
1658
+ fullName: registeredUser.full_name ?? void 0,
1659
+ avatarUrl: registeredUser.avatar_url ?? void 0,
1660
+ provider: "email",
1661
+ lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
1662
+ },
1663
+ existingKnown,
1664
+ cookieOptions,
1665
+ config.accountSwitcherPrivacy
1666
+ );
1667
+ }
1668
+ return registerResponse;
1669
+ }
1670
+ case "handoff/exchange": {
1671
+ if (!config.handoffAudience) return errorResponse("HANDOFF_DISABLED", "Session transfer is not configured", 404);
1672
+ if (typeof body.code !== "string" || !body.code || body.code.length > 256) return errorResponse("INVALID_HANDOFF", "Invalid sign-in transfer", 400);
1673
+ const result = await sm.auth.exchangeSessionHandoff(body.code, config.handoffAudience);
1674
+ return withRefreshedSession(result.session_token, result.user_id, { authenticated: true, userId: result.user_id }, cookieOptions);
1675
+ }
1676
+ case "mfa/send-code": {
1677
+ const { pending_token, method } = body;
1678
+ if (!pending_token || !["email", "sms"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token and method required", 400);
1679
+ return successResponse(await sm.auth.sendMfaCode(pending_token, method, { clientContext }));
1680
+ }
1681
+ case "mfa/verify": {
1682
+ const { pending_token, code, method } = body;
1683
+ if (!pending_token || !code || !["totp", "email", "sms", "backup_code"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token, code, and valid method required", 400);
1684
+ const result = await sm.auth.completeMfa(pending_token, code, method, { clientContext });
1685
+ if (!result.session_token || !result.user) return errorResponse("MFA_FAILED", "Unable to complete sign-in", 400);
1686
+ await config.onLogin?.({ id: result.user.id, email: result.user.email });
1687
+ const response = withSession(result, sessionData(result.user, result.session_token), cookieOptions);
1688
+ if (config.enableAccountSwitcher) {
1689
+ appendKnownAccountCookie(response.headers, {
1690
+ userId: result.user.id,
1691
+ email: result.user.email,
1692
+ fullName: result.user.full_name ?? void 0,
1693
+ avatarUrl: result.user.avatar_url ?? void 0,
1694
+ provider: "email",
1695
+ lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
1696
+ }, getKnownAccountsCookieRaw(request), cookieOptions, config.accountSwitcherPrivacy);
1697
+ }
1698
+ return response;
1699
+ }
1700
+ // ==================== Login ====================
1701
+ case "login": {
1702
+ const { email, password, remember_me, device_fingerprint, challenge_token, challenge_code } = body;
1703
+ if (!email || !password) {
1704
+ return errorResponse("VALIDATION_ERROR", "Email and password required", 400);
1705
+ }
1706
+ let loginData;
1707
+ try {
1708
+ loginData = await sm.auth.login({ email, password, remember_me, device_fingerprint, challenge_token, challenge_code }, { clientContext });
1709
+ } catch (err) {
1710
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1711
+ const errorCode = apiErr?.code || "LOGIN_FAILED";
1712
+ let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 403 : 400;
1713
+ if (errorCode === "CHALLENGE_RATE_LIMITED") status = 429;
1714
+ if (errorCode === "INVALID_CREDENTIALS" || errorCode === "UNAUTHORIZED") status = 401;
1715
+ if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED"].includes(errorCode)) {
1716
+ status = 403;
1717
+ }
1718
+ return errorResponse(
1719
+ errorCode,
1720
+ apiErr?.message || "Login failed",
1721
+ status
1722
+ );
1723
+ }
1724
+ if (config.onLogin) {
1725
+ await config.onLogin({
1726
+ id: loginData.user.id,
1727
+ email: loginData.user.email
1728
+ });
1729
+ }
1730
+ const loginResponse = withSession(loginData, sessionData(loginData.user, loginData.session_token), cookieOptions);
1731
+ if (config.enableAccountSwitcher) {
1732
+ const existingKnown = getKnownAccountsCookieRaw(request);
1733
+ appendKnownAccountCookie(
1734
+ loginResponse.headers,
1735
+ {
1736
+ userId: loginData.user.id,
1737
+ email: loginData.user.email,
1738
+ fullName: loginData.user.full_name ?? void 0,
1739
+ avatarUrl: loginData.user.avatar_url ?? void 0,
1740
+ provider: "email",
1741
+ lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
1742
+ },
1743
+ existingKnown,
1744
+ cookieOptions,
1745
+ config.accountSwitcherPrivacy
1746
+ );
1747
+ }
1748
+ return loginResponse;
1749
+ }
1750
+ // ==================== Logout ====================
1751
+ case "logout": {
1752
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1753
+ let rotated = null;
1754
+ if (session) {
1755
+ try {
1756
+ await sm.auth.logout(session.sessionToken, {
1757
+ onTokenRotated: (newToken) => {
1758
+ rotated = newToken;
1759
+ }
1760
+ });
1761
+ } catch {
1762
+ }
1763
+ }
1764
+ if (config.onLogout) {
1765
+ await config.onLogout();
1766
+ }
1767
+ return clearSession({ message: "Logged out successfully" }, cookieOptions);
1768
+ }
1769
+ // ==================== Forgot Password ====================
1770
+ case "forgot-password": {
1771
+ const { email } = body;
1772
+ if (!email) {
1773
+ return errorResponse("VALIDATION_ERROR", "Email required", 400);
1774
+ }
1775
+ const result = await sm.auth.forgotPassword(email, { clientContext });
1776
+ return successResponse({ message: "If an account exists, a reset email has been sent" });
1777
+ }
1778
+ // ==================== Reset Password ====================
1779
+ case "reset-password": {
1780
+ const { token, new_password } = body;
1781
+ if (!token || !new_password) {
1782
+ return errorResponse("VALIDATION_ERROR", "Token and new password required", 400);
1783
+ }
1784
+ try {
1785
+ await sm.auth.resetPassword(token, new_password, { clientContext });
1786
+ } catch (err) {
1787
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1788
+ return errorResponse(
1789
+ apiErr?.code || "RESET_FAILED",
1790
+ apiErr?.message || "Password reset failed",
1791
+ 400
1792
+ );
1793
+ }
1794
+ return clearSession({ message: "Password reset successful" }, cookieOptions);
1795
+ }
1796
+ // ==================== Verify Email ====================
1797
+ case "verify-email": {
1798
+ const { token } = body;
1799
+ if (!token) {
1800
+ return errorResponse("VALIDATION_ERROR", "Token required", 400);
1801
+ }
1802
+ let verifyData;
1803
+ try {
1804
+ verifyData = await sm.auth.verifyEmail(token);
1805
+ } catch (err) {
1806
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1807
+ return errorResponse(
1808
+ apiErr?.code || "VERIFY_FAILED",
1809
+ apiErr?.message || "Email verification failed",
1810
+ 400
1811
+ );
1812
+ }
1813
+ if (verifyData?.session_token && verifyData?.user) {
1814
+ return withSession(
1815
+ { session_token: verifyData.session_token, user: verifyData.user },
1816
+ { message: "Email verified successfully", verified: true, ...sessionData(verifyData.user, verifyData.session_token) },
1817
+ cookieOptions
1818
+ );
1819
+ }
1820
+ return successResponse({ message: "Email verified successfully" });
1821
+ }
1822
+ // ==================== Resend Verification ====================
1823
+ // Supports both authenticated (session-based) and unauthenticated (email-based) resend
1824
+ case "resend-verification": {
1825
+ const { email } = body;
1826
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1827
+ let rotated = null;
1828
+ if (email) {
1829
+ try {
1830
+ await sm.auth.resendVerification(email);
1831
+ } catch (err) {
1832
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1833
+ return errorResponse(
1834
+ apiErr?.code || "RESEND_FAILED",
1835
+ apiErr?.message || "Failed to resend verification",
1836
+ apiErr?.code === "RATE_LIMITED" ? 429 : 400
1837
+ );
1838
+ }
1839
+ return successResponse({ message: "Verification email sent" });
1840
+ }
1841
+ if (!session) {
1842
+ return errorResponse("UNAUTHORIZED", "Email or session required", 401);
1843
+ }
1844
+ try {
1845
+ await sm.auth.resendVerification(session.sessionToken, {
1846
+ onTokenRotated: (newToken) => {
1847
+ rotated = newToken;
1848
+ }
1849
+ });
1850
+ } catch (err) {
1851
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1852
+ return errorResponse(
1853
+ apiErr?.code || "RESEND_FAILED",
1854
+ apiErr?.message || "Failed to resend verification",
1855
+ 400
1856
+ );
1857
+ }
1858
+ if (rotated) {
1859
+ return withRefreshedSession(
1860
+ rotated,
1861
+ session.userId,
1862
+ { success: true, data: { message: "Verification email sent" } },
1863
+ cookieOptions
1864
+ );
1865
+ }
1866
+ return successResponse({ message: "Verification email sent" });
1867
+ }
1868
+ // ==================== Refresh Session ====================
1869
+ case "refresh": {
1870
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1871
+ if (!session) {
1872
+ return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1873
+ }
1874
+ let refreshData;
1875
+ try {
1876
+ refreshData = await sm.auth.refresh(session.sessionToken);
1877
+ } catch (err) {
1878
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1879
+ if (isSessionEndedError(apiErr)) {
1880
+ return clearSessionWithError(
1881
+ { code: apiErr?.code || "SESSION_EXPIRED", message: apiErr?.message || "Session expired" },
1882
+ cookieOptions
1883
+ );
1884
+ }
1885
+ return errorResponse(
1886
+ apiErr?.code || "REFRESH_FAILED",
1887
+ apiErr?.message || "Session refresh failed",
1888
+ apiErr?.status && apiErr.status >= 400 ? apiErr.status : 503
1889
+ );
1890
+ }
1891
+ return withRefreshedSession(
1892
+ refreshData.session_token,
1893
+ session.userId,
1894
+ { message: "Session refreshed", ...config.sessionMode === "bearer" ? { sessionToken: refreshData.session_token, userId: session.userId } : {} },
1895
+ cookieOptions
1896
+ );
1897
+ }
1898
+ // ==================== Change Password ====================
1899
+ case "change-password": {
1900
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1901
+ if (!session) {
1902
+ return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1903
+ }
1904
+ const { current_password, new_password } = body;
1905
+ if (!current_password || !new_password) {
1906
+ return errorResponse("VALIDATION_ERROR", "Current and new password required", 400);
1907
+ }
1908
+ let rotated = null;
1909
+ try {
1910
+ await sm.user.changePassword(
1911
+ session.sessionToken,
1912
+ current_password,
1913
+ new_password,
1914
+ {
1915
+ onTokenRotated: (newToken) => {
1916
+ rotated = newToken;
1917
+ }
1918
+ }
1919
+ );
1920
+ } catch (err) {
1921
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1922
+ return errorResponse(
1923
+ apiErr?.code || "CHANGE_FAILED",
1924
+ apiErr?.message || "Failed to change password",
1925
+ 400
1926
+ );
1927
+ }
1928
+ if (rotated) {
1929
+ return withRefreshedSession(
1930
+ rotated,
1931
+ session.userId,
1932
+ { success: true, data: { message: "Password changed successfully" } },
1933
+ cookieOptions
1934
+ );
1935
+ }
1936
+ return successResponse({ message: "Password changed successfully" });
1937
+ }
1938
+ // ==================== Switch Account ====================
1939
+ // Clears the active session so the user can re-authenticate as a different account.
1940
+ // The known accounts cookie is preserved — only the session cookie is cleared.
1941
+ case "switch-account": {
1942
+ if (!config.enableAccountSwitcher) {
1943
+ return errorResponse("NOT_FOUND", "Account switcher not enabled", 404);
1944
+ }
1945
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1946
+ if (session) {
1947
+ try {
1948
+ await sm.auth.logout(session.sessionToken);
1949
+ } catch {
1950
+ }
1951
+ }
1952
+ const switchResponse = clearSession({ message: "Session cleared for account switch" }, cookieOptions);
1953
+ const knownAccounts = getKnownAccountsFromRequest(request);
1954
+ return new Response(
1955
+ JSON.stringify({ success: true, data: { message: "Session cleared for account switch", knownAccounts } }),
1956
+ { status: 200, headers: switchResponse.headers }
1957
+ );
1958
+ }
1959
+ // ==================== Forget Account ====================
1960
+ // Remove a specific account from the known accounts cookie.
1961
+ case "forget-account": {
1962
+ if (!config.enableAccountSwitcher) {
1963
+ return errorResponse("NOT_FOUND", "Account switcher not enabled", 404);
1964
+ }
1965
+ const { user_id } = body;
1966
+ if (!user_id) {
1967
+ return errorResponse("VALIDATION_ERROR", "user_id required", 400);
1968
+ }
1969
+ const headers3 = new Headers();
1970
+ headers3.set("Content-Type", "application/json");
1971
+ const existingKnown = getKnownAccountsCookieRaw(request);
1972
+ removeKnownAccountFromCookie(headers3, user_id, existingKnown, cookieOptions);
1973
+ return new Response(
1974
+ JSON.stringify({ success: true, data: { message: "Account forgotten" } }),
1975
+ { status: 200, headers: headers3 }
1976
+ );
1977
+ }
1978
+ // ==================== Forget All Accounts ====================
1979
+ case "forget-all-accounts": {
1980
+ if (!config.enableAccountSwitcher) {
1981
+ return errorResponse("NOT_FOUND", "Account switcher not enabled", 404);
1982
+ }
1983
+ const headers3 = new Headers();
1984
+ headers3.set("Content-Type", "application/json");
1985
+ clearKnownAccountsCookie(headers3, cookieOptions);
1986
+ return new Response(
1987
+ JSON.stringify({ success: true, data: { message: "All accounts forgotten" } }),
1988
+ { status: 200, headers: headers3 }
1989
+ );
1990
+ }
1991
+ default:
1992
+ return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
1993
+ }
1994
+ } catch (err) {
1995
+ if (path === "handoff/exchange" && err instanceof ScaleMuleApiError) {
1996
+ return errorResponse(err.code, err.message, err.code === "HANDOFF_UNAVAILABLE" ? 503 : 401);
1997
+ }
1998
+ if (path.startsWith("mfa/") && err instanceof ScaleMuleApiError) {
1999
+ const status = ["CHALLENGE_RATE_LIMITED", "MFA_RATE_LIMITED", "MFA_MAX_ATTEMPTS"].includes(err.code) ? 429 : 400;
2000
+ return errorResponse(err.code, err.message, status);
2001
+ }
2002
+ console.error("[ScaleMule Auth] Error:", err);
2003
+ return errorResponse("SERVER_ERROR", "Internal server error", 500);
2004
+ }
2005
+ };
2006
+ const GET = async (request, context) => {
2007
+ const params = await context?.params;
2008
+ const path = params?.scalemule?.join("/") || "";
2009
+ try {
2010
+ switch (path) {
2011
+ // ==================== Get Current User ====================
2012
+ case "me": {
2013
+ const normCookie = config.enableAccountSwitcher ? normalizeKnownAccountsCookie(request, config.accountSwitcherPrivacy, cookieOptions) : null;
2014
+ const withNorm = (resp) => {
2015
+ if (normCookie) resp.headers.append("Set-Cookie", normCookie);
2016
+ return resp;
2017
+ };
2018
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
2019
+ if (!session) {
2020
+ return withNorm(errorResponse("UNAUTHORIZED", "Authentication required", 401));
2021
+ }
2022
+ let userData;
2023
+ let rotated = null;
2024
+ try {
2025
+ userData = await sm.auth.me(session.sessionToken, {
2026
+ onTokenRotated: (newToken) => {
2027
+ rotated = newToken;
2028
+ }
2029
+ });
2030
+ } catch {
2031
+ return withNorm(clearSession(
2032
+ { error: { code: "SESSION_EXPIRED", message: "Session expired" } },
2033
+ cookieOptions
2034
+ ));
2035
+ }
2036
+ if (rotated) {
2037
+ return withNorm(withRefreshedSession(
2038
+ rotated,
2039
+ session.userId,
2040
+ sessionData(userData, rotated),
2041
+ cookieOptions
2042
+ ));
2043
+ }
2044
+ return withNorm(successResponse(sessionData(userData, session.sessionToken)));
2045
+ }
2046
+ // ==================== Get Session Status ====================
2047
+ case "session": {
2048
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
2049
+ return successResponse({
2050
+ authenticated: !!session,
2051
+ userId: session?.userId || null
2052
+ });
2053
+ }
2054
+ // ==================== Get Known Accounts ====================
2055
+ case "known-accounts": {
2056
+ if (!config.enableAccountSwitcher) {
2057
+ return errorResponse("NOT_FOUND", "Account switcher not enabled", 404);
2058
+ }
2059
+ const knownAccounts = getKnownAccountsFromRequest(request);
2060
+ return successResponse({ knownAccounts });
2061
+ }
2062
+ default:
2063
+ return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
2064
+ }
2065
+ } catch (err) {
2066
+ console.error("[ScaleMule Auth] Error:", err);
2067
+ return errorResponse("SERVER_ERROR", "Internal server error", 500);
2068
+ }
2069
+ };
2070
+ const DELETE = async (request, context) => {
2071
+ const params = await context?.params;
2072
+ const path = params?.scalemule?.join("/") || "";
2073
+ try {
2074
+ switch (path) {
2075
+ // ==================== Delete Account ====================
2076
+ case "me":
2077
+ case "account": {
2078
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
2079
+ if (!session) {
2080
+ return errorResponse("UNAUTHORIZED", "Authentication required", 401);
2081
+ }
2082
+ const body = await request.json().catch(() => ({}));
2083
+ const { password } = body;
2084
+ if (!password) {
2085
+ return errorResponse("VALIDATION_ERROR", "Password required", 400);
2086
+ }
2087
+ try {
2088
+ await sm.user.deleteAccount(session.sessionToken, password);
2089
+ } catch (err) {
2090
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
2091
+ return errorResponse(
2092
+ apiErr?.code || "DELETE_FAILED",
2093
+ apiErr?.message || "Failed to delete account",
2094
+ 400
2095
+ );
2096
+ }
2097
+ return clearSession({ message: "Account deleted successfully" }, cookieOptions);
2098
+ }
2099
+ default:
2100
+ return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
2101
+ }
2102
+ } catch (err) {
2103
+ console.error("[ScaleMule Auth] Error:", err);
2104
+ return errorResponse("SERVER_ERROR", "Internal server error", 500);
2105
+ }
2106
+ };
2107
+ const PATCH = async (request, context) => {
2108
+ const params = await context?.params;
2109
+ const path = params?.scalemule?.join("/") || "";
2110
+ try {
2111
+ switch (path) {
2112
+ // ==================== Update Profile ====================
2113
+ case "me":
2114
+ case "profile": {
2115
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
2116
+ if (!session) {
2117
+ return errorResponse("UNAUTHORIZED", "Authentication required", 401);
2118
+ }
2119
+ const body = await request.json().catch(() => ({}));
2120
+ const { full_name, avatar_url } = body;
2121
+ let updatedUser;
2122
+ let rotated = null;
2123
+ try {
2124
+ updatedUser = await sm.user.update(session.sessionToken, { full_name, avatar_url }, {
2125
+ onTokenRotated: (newToken) => {
2126
+ rotated = newToken;
2127
+ }
2128
+ });
2129
+ } catch (err) {
2130
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
2131
+ return errorResponse(
2132
+ apiErr?.code || "UPDATE_FAILED",
2133
+ apiErr?.message || "Failed to update profile",
2134
+ 400
2135
+ );
2136
+ }
2137
+ if (rotated) {
2138
+ return withRefreshedSession(
2139
+ rotated,
2140
+ session.userId,
2141
+ { success: true, data: { user: updatedUser } },
2142
+ cookieOptions
2143
+ );
2144
+ }
2145
+ return successResponse({ user: updatedUser });
2146
+ }
2147
+ default:
2148
+ return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
2149
+ }
2150
+ } catch (err) {
2151
+ console.error("[ScaleMule Auth] Error:", err);
2152
+ return errorResponse("SERVER_ERROR", "Internal server error", 500);
2153
+ }
2154
+ };
2155
+ const wrap = (handler) => async (request, context) => {
2156
+ const params = await context.params;
2157
+ const path = params.scalemule || [];
2158
+ let response;
2159
+ if (path[0] === "client") {
2160
+ response = await browserProxy(request, path.slice(1), config);
2161
+ } else if (!["GET", "HEAD"].includes(request.method) && (!isSameOriginRequest(request) || !request.headers.get("content-type")?.toLowerCase().startsWith("application/json"))) {
2162
+ response = errorResponse("CSRF_ERROR", "Same-origin JSON request required", 403);
2163
+ } else {
2164
+ response = await handler(request, context);
2165
+ }
2166
+ response.headers.set("Cache-Control", "no-store");
2167
+ response.headers.set("Vary", "Cookie");
2168
+ return response;
2169
+ };
2170
+ return { GET: wrap(GET), POST: wrap(POST), DELETE: wrap(DELETE), PATCH: wrap(PATCH), PUT: wrap(async () => errorResponse("NOT_FOUND", "Unknown endpoint", 404)) };
2171
+ }
2172
+ function getPrimaryTrackingContextSource(body) {
2173
+ if (Array.isArray(body.events)) {
2174
+ const firstEvent = body.events.find((event) => event && typeof event === "object" && !Array.isArray(event));
2175
+ if (firstEvent && typeof firstEvent === "object" && !Array.isArray(firstEvent)) {
2176
+ return firstEvent;
2177
+ }
2178
+ }
2179
+ return body;
2180
+ }
2181
+ function buildDefaultTrackingGateContext(args) {
2182
+ const source = getPrimaryTrackingContextSource(args.body);
2183
+ const extraContext = {};
2184
+ for (const key of ["user_id", "anonymous_id", "session_id", "event_name", "page_url"]) {
2185
+ const value = source[key];
2186
+ if (typeof value === "string" && value.trim()) {
2187
+ extraContext[key] = value;
2188
+ }
2189
+ }
2190
+ return buildFlagContext(args.clientContext, extraContext);
2191
+ }
2192
+ function createAnalyticsRoutes(config = {}) {
2193
+ const sm = createServerClient(config.client);
2194
+ const shouldSuppressTracking = async (body, clientContext, request) => {
2195
+ const gate = config.trackingGate;
2196
+ if (!gate) {
2197
+ return false;
2198
+ }
2199
+ try {
2200
+ const contextBuilder = gate.buildContext || ((args) => buildDefaultTrackingGateContext(args));
2201
+ const evaluation = await sm.flags.evaluate(
2202
+ gate.flagKey,
2203
+ contextBuilder({ body, clientContext, request }) || {},
2204
+ gate.environment || "prod",
2205
+ { clientContext }
2206
+ );
2207
+ return evaluation?.value === false;
2208
+ } catch (err) {
2209
+ if (gate.failOpen === false) {
2210
+ console.warn(`[ScaleMule Analytics] Tracking gate blocked "${gate.flagKey}" after evaluation failure`, err);
2211
+ return true;
2212
+ }
2213
+ return false;
2214
+ }
2215
+ };
2216
+ const handleTrackEvent = async (body, clientContext) => {
2217
+ const {
2218
+ event_name,
2219
+ event_category,
2220
+ properties,
2221
+ user_id,
2222
+ session_id,
2223
+ anonymous_id,
2224
+ session_duration_seconds,
2225
+ page_url,
2226
+ page_title,
2227
+ referrer,
2228
+ landing_page,
2229
+ device_type,
2230
+ device_brand,
2231
+ device_model,
2232
+ browser,
2233
+ browser_version,
2234
+ os,
2235
+ os_version,
2236
+ screen_resolution,
2237
+ viewport_size,
2238
+ utm_source,
2239
+ utm_medium,
2240
+ utm_campaign,
2241
+ utm_term,
2242
+ utm_content,
2243
+ client_timestamp,
2244
+ timestamp
2245
+ // Legacy field
2246
+ } = body;
2247
+ if (!event_name) {
2248
+ return errorResponse("VALIDATION_ERROR", "event_name is required", 400);
2249
+ }
2250
+ let trackResult;
2251
+ try {
2252
+ trackResult = await sm.analytics.trackEvent(
2253
+ {
2254
+ event_name,
2255
+ event_category,
2256
+ properties,
2257
+ user_id,
2258
+ session_id,
2259
+ anonymous_id,
2260
+ session_duration_seconds,
2261
+ page_url,
2262
+ page_title,
2263
+ referrer,
2264
+ landing_page,
2265
+ device_type,
2266
+ device_brand,
2267
+ device_model,
2268
+ browser,
2269
+ browser_version,
2270
+ os,
2271
+ os_version,
2272
+ screen_resolution,
2273
+ viewport_size,
2274
+ utm_source,
2275
+ utm_medium,
2276
+ utm_campaign,
2277
+ utm_term,
2278
+ utm_content,
2279
+ client_timestamp: client_timestamp || timestamp
2280
+ },
2281
+ { clientContext }
2282
+ );
2283
+ } catch (err) {
2284
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
2285
+ return errorResponse(
2286
+ apiErr?.code || "TRACK_FAILED",
2287
+ apiErr?.message || "Failed to track event",
2288
+ 400
2289
+ );
2290
+ }
2291
+ if (config.onEvent) {
2292
+ await config.onEvent({ event_name, session_id: trackResult?.session_id });
2293
+ }
2294
+ return successResponse({ tracked: trackResult?.tracked || 1, session_id: trackResult?.session_id });
2295
+ };
2296
+ const POST = async (request, context) => {
2297
+ try {
2298
+ const rawBody = await request.json().catch(() => ({}));
2299
+ const body = rawBody && typeof rawBody === "object" && !Array.isArray(rawBody) ? rawBody : {};
2300
+ const clientContext = extractClientContext(request);
2301
+ if (await shouldSuppressTracking(body, clientContext, request)) {
2302
+ return successResponse({ tracked: 0, suppressed: true }, 202);
2303
+ }
2304
+ if (config.simpleProxy) {
2305
+ return handleTrackEvent(body, clientContext);
2306
+ }
2307
+ const params = await context?.params;
2308
+ const path = params?.scalemule?.join("/") || "";
2309
+ switch (path) {
2310
+ // ==================== Track Single Event ====================
2311
+ case "event":
2312
+ case "events":
2313
+ case "": {
2314
+ return handleTrackEvent(body, clientContext);
2315
+ }
2316
+ // ==================== Track Batch Events ====================
2317
+ case "batch": {
2318
+ const { events } = body;
2319
+ if (!Array.isArray(events) || events.length === 0) {
2320
+ return errorResponse("VALIDATION_ERROR", "events array is required", 400);
2321
+ }
2322
+ if (events.length > 100) {
2323
+ return errorResponse("VALIDATION_ERROR", "Maximum 100 events per batch", 400);
2324
+ }
2325
+ let batchResult;
2326
+ try {
2327
+ batchResult = await sm.analytics.trackBatch(events, { clientContext });
2328
+ } catch (err) {
2329
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
2330
+ return errorResponse(
2331
+ apiErr?.code || "BATCH_FAILED",
2332
+ apiErr?.message || "Failed to track events",
2333
+ 400
2334
+ );
2335
+ }
2336
+ return successResponse({ tracked: batchResult?.tracked || events.length });
2337
+ }
2338
+ // ==================== Track Page View ====================
2339
+ case "page-view":
2340
+ case "pageview": {
2341
+ const { page_url, page_title, referrer, session_id, user_id } = body;
2342
+ if (!page_url) {
2343
+ return errorResponse("VALIDATION_ERROR", "page_url is required", 400);
2344
+ }
2345
+ let pageViewResult;
2346
+ try {
2347
+ pageViewResult = await sm.analytics.trackPageView(
2348
+ {
2349
+ page_url,
2350
+ page_title,
2351
+ referrer,
2352
+ session_id,
2353
+ user_id
2354
+ },
2355
+ { clientContext }
2356
+ );
2357
+ } catch (err) {
2358
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
2359
+ return errorResponse(
2360
+ apiErr?.code || "TRACK_FAILED",
2361
+ apiErr?.message || "Failed to track page view",
2362
+ 400
2363
+ );
2364
+ }
2365
+ if (config.onEvent) {
2366
+ await config.onEvent({ event_name: "page_viewed", session_id: pageViewResult?.session_id });
2367
+ }
2368
+ return successResponse({ tracked: pageViewResult?.tracked || 1, session_id: pageViewResult?.session_id });
2369
+ }
2370
+ default:
2371
+ return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
2372
+ }
2373
+ } catch (err) {
2374
+ console.error("[ScaleMule Analytics] Error:", err);
2375
+ return successResponse({ tracked: 0 });
2376
+ }
2377
+ };
2378
+ return { POST };
2379
+ }
2380
+
2381
+ // src/server/ledvery-cookies.ts
2382
+ var SM_LEDVERY_STATE_COOKIE = "sm_ledvery_state";
2383
+ var SM_LEDVERY_PKCE_VERIFIER_COOKIE = "sm_ledvery_pkce_verifier";
2384
+ var SM_LEDVERY_NONCE_COOKIE = "sm_ledvery_nonce";
2385
+ var SM_LEDVERY_ID_TOKEN_COOKIE = "sm_ledvery_id_token";
2386
+ var SM_LEDVERY_ACCESS_TOKEN_COOKIE = "sm_ledvery_access_token";
2387
+ var FLOW_COOKIE_MAX_AGE = 60 * 10;
2388
+ var SESSION_COOKIE_MAX_AGE = 60 * 60;
2389
+ function flowCookieOptions() {
2390
+ return {
2391
+ httpOnly: true,
2392
+ secure: process.env.NODE_ENV === "production",
2393
+ sameSite: "lax",
2394
+ path: "/",
2395
+ maxAge: FLOW_COOKIE_MAX_AGE
2396
+ };
2397
+ }
2398
+ function sessionCookieOptions(maxAge) {
2399
+ return {
2400
+ httpOnly: true,
2401
+ secure: process.env.NODE_ENV === "production",
2402
+ sameSite: "lax",
2403
+ path: "/",
2404
+ maxAge: maxAge ? Math.min(maxAge, SESSION_COOKIE_MAX_AGE) : SESSION_COOKIE_MAX_AGE
2405
+ };
2406
+ }
2407
+ function setLedveryFlowCookies(response, params) {
2408
+ const opts = flowCookieOptions();
2409
+ setCookie(response, SM_LEDVERY_STATE_COOKIE, params.state, opts);
2410
+ setCookie(response, SM_LEDVERY_PKCE_VERIFIER_COOKIE, params.codeVerifier, opts);
2411
+ setCookie(response, SM_LEDVERY_NONCE_COOKIE, params.nonce, opts);
2412
+ }
2413
+ function validateAndConsumeLedveryFlowCookies(request, callbackState) {
2414
+ const cookieState = getCookie(request, SM_LEDVERY_STATE_COOKIE);
2415
+ const codeVerifier = getCookie(request, SM_LEDVERY_PKCE_VERIFIER_COOKIE);
2416
+ const nonce = getCookie(request, SM_LEDVERY_NONCE_COOKIE);
2417
+ if (!cookieState) return "Missing Ledvery state cookie - session may have expired";
2418
+ if (!callbackState) return "Missing state parameter in callback";
2419
+ if (!constantTimeEqual(cookieState, callbackState)) return "Ledvery state mismatch - possible CSRF attack";
2420
+ if (!codeVerifier) return "Missing PKCE verifier cookie";
2421
+ if (!nonce) return "Missing nonce cookie";
2422
+ return { codeVerifier, nonce };
2423
+ }
2424
+ function setLedverySession(response, session, opts) {
2425
+ const cookieOpts = sessionCookieOptions(opts?.cookies?.maxAge);
2426
+ if (opts?.cookies?.domain) cookieOpts.domain = opts.cookies.domain;
2427
+ if (opts?.cookies?.path) cookieOpts.path = opts.cookies.path;
2428
+ if (opts?.cookies?.sameSite) cookieOpts.sameSite = opts.cookies.sameSite;
2429
+ if (opts?.cookies?.secure !== void 0) cookieOpts.secure = opts.cookies.secure;
2430
+ const sessionPayload = JSON.stringify({
2431
+ idToken: session.idToken,
2432
+ claims: session.claims,
2433
+ expiresAt: session.expiresAt
2434
+ });
2435
+ setCookie(response, SM_LEDVERY_ID_TOKEN_COOKIE, sessionPayload, cookieOpts);
2436
+ if (opts?.storeAccessToken && session.accessToken) {
2437
+ setCookie(response, SM_LEDVERY_ACCESS_TOKEN_COOKIE, session.accessToken, cookieOpts);
2438
+ }
2439
+ }
2440
+ function getLedverySession(request) {
2441
+ const raw = getCookie(request, SM_LEDVERY_ID_TOKEN_COOKIE);
2442
+ if (!raw) return null;
2443
+ try {
2444
+ const parsed = JSON.parse(raw);
2445
+ return {
2446
+ idToken: parsed.idToken || "",
2447
+ claims: parsed.claims,
2448
+ expiresAt: parsed.expiresAt
2449
+ };
2450
+ } catch {
2451
+ return null;
2452
+ }
2453
+ }
2454
+ function clearLedverySession(response) {
2455
+ deleteCookie(response, SM_LEDVERY_ID_TOKEN_COOKIE);
2456
+ deleteCookie(response, SM_LEDVERY_ACCESS_TOKEN_COOKIE);
2457
+ }
2458
+ function clearLedveryFlowCookies(response) {
2459
+ deleteCookie(response, SM_LEDVERY_STATE_COOKIE);
2460
+ deleteCookie(response, SM_LEDVERY_PKCE_VERIFIER_COOKIE);
2461
+ deleteCookie(response, SM_LEDVERY_NONCE_COOKIE);
2462
+ }
2463
+ function getCookie(request, name) {
2464
+ const header = request.headers.get("cookie") || "";
2465
+ const match = header.match(new RegExp(`(?:^|;\\s*)${name}=([^;]*)`));
2466
+ return match ? decodeURIComponent(match[1]) : void 0;
2467
+ }
2468
+ function setCookie(response, name, value, opts) {
2469
+ const parts = [
2470
+ `${name}=${encodeURIComponent(value)}`,
2471
+ `Path=${opts.path}`,
2472
+ `Max-Age=${opts.maxAge}`,
2473
+ `SameSite=${opts.sameSite.charAt(0).toUpperCase() + opts.sameSite.slice(1)}`
2474
+ ];
2475
+ if (opts.httpOnly) parts.push("HttpOnly");
2476
+ if (opts.secure) parts.push("Secure");
2477
+ if (opts.domain) parts.push(`Domain=${opts.domain}`);
2478
+ response.headers.append("Set-Cookie", parts.join("; "));
2479
+ }
2480
+ function deleteCookie(response, name) {
2481
+ response.headers.append("Set-Cookie", `${name}=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax`);
2482
+ }
2483
+
2484
+ // src/server/redirect.ts
2485
+ function normalizeOrigin(origin) {
2486
+ try {
2487
+ const u = new URL(origin);
2488
+ return `${u.protocol}//${u.host}`.toLowerCase();
2489
+ } catch {
2490
+ return null;
2491
+ }
2492
+ }
2493
+ function isSafeSchemeRelative(input) {
2494
+ return !(input.startsWith("//") || input.startsWith("\\"));
2495
+ }
2496
+ function validateSafeRedirect(input, opts = {}) {
2497
+ const defaultPath = opts.defaultPath ?? "/";
2498
+ if (!input || typeof input !== "string") return defaultPath;
2499
+ const trimmed = input.trim();
2500
+ if (!trimmed) return defaultPath;
2501
+ if (!isSafeSchemeRelative(trimmed)) return defaultPath;
2502
+ const colon = trimmed.indexOf(":");
2503
+ if (colon > 0 && colon < 15) {
2504
+ const scheme = trimmed.slice(0, colon).toLowerCase();
2505
+ if (/^[a-z][a-z0-9+.-]*$/.test(scheme) && scheme !== "http" && scheme !== "https") {
2506
+ return defaultPath;
2507
+ }
2508
+ }
2509
+ if (trimmed.startsWith("/")) {
2510
+ if (trimmed.length > 1 && trimmed[1] === "\\") return defaultPath;
2511
+ return trimmed;
2512
+ }
2513
+ const allowed = (opts.allowedOrigins ?? []).map(normalizeOrigin).filter((o) => o !== null);
2514
+ try {
2515
+ const parsed = new URL(trimmed);
2516
+ const origin = `${parsed.protocol}//${parsed.host}`.toLowerCase();
2517
+ if (!allowed.includes(origin)) return defaultPath;
2518
+ if (opts.stripSameOriginHost !== false) {
2519
+ return `${parsed.pathname}${parsed.search}${parsed.hash}` || "/";
2520
+ }
2521
+ return trimmed;
2522
+ } catch {
2523
+ return defaultPath;
2524
+ }
2525
+ }
2526
+ function isSafeRedirect(input, opts = {}) {
2527
+ if (!input || typeof input !== "string") return false;
2528
+ const defaultPath = `__unsafe_sentinel_${Math.random()}`;
2529
+ const resolved = validateSafeRedirect(input, { ...opts, defaultPath });
2530
+ return resolved !== defaultPath;
2531
+ }
2532
+
2533
+ // src/server/ledvery.ts
2534
+ function createLedveryRoutes(config) {
2535
+ const client = new LedveryClient({
2536
+ issuer: config.issuer,
2537
+ clientId: config.clientId,
2538
+ clientSecret: config.clientSecret,
2539
+ redirectUri: config.redirectUri,
2540
+ fetch: config.fetch
2541
+ });
2542
+ const postLoginRedirect = config.postLoginRedirect || "/";
2543
+ const postLogoutRedirect = config.postLogoutRedirect || "/";
2544
+ const defaultScope = config.defaultScope || "openid email profile";
2545
+ async function handleLogin(request) {
2546
+ const url = new URL(request.url);
2547
+ const returnTo = url.searchParams.get("returnTo");
2548
+ const validatedReturnTo = validateSafeRedirect(returnTo, { defaultPath: postLoginRedirect });
2549
+ const authResult = await client.createAuthorizationUrl({
2550
+ scope: defaultScope
2551
+ });
2552
+ const response = new Response(null, {
2553
+ status: 302,
2554
+ headers: { Location: authResult.url }
2555
+ });
2556
+ setLedveryFlowCookies(response, {
2557
+ state: authResult.state,
2558
+ codeVerifier: authResult.codeVerifier,
2559
+ nonce: authResult.nonce
2560
+ });
2561
+ if (validatedReturnTo !== postLoginRedirect) {
2562
+ response.headers.append(
2563
+ "Set-Cookie",
2564
+ `sm_ledvery_return_to=${encodeURIComponent(validatedReturnTo)}; Path=/; Max-Age=600; HttpOnly; SameSite=Lax${process.env.NODE_ENV === "production" ? "; Secure" : ""}`
2565
+ );
2566
+ }
2567
+ return response;
2568
+ }
2569
+ async function handleCallback(request) {
2570
+ const url = new URL(request.url);
2571
+ const code = url.searchParams.get("code");
2572
+ const callbackState = url.searchParams.get("state");
2573
+ if (!code) {
2574
+ const error2 = url.searchParams.get("error");
2575
+ const errorDesc = url.searchParams.get("error_description");
2576
+ return new Response(
2577
+ JSON.stringify({ error: error2 || "missing_code", message: errorDesc || "No authorization code in callback" }),
2578
+ { status: 403, headers: { "Content-Type": "application/json" } }
2579
+ );
2580
+ }
2581
+ const flowResult = validateAndConsumeLedveryFlowCookies(request, callbackState);
2582
+ if (typeof flowResult === "string") {
2583
+ return new Response(
2584
+ JSON.stringify({ error: "state_mismatch", message: flowResult }),
2585
+ { status: 403, headers: { "Content-Type": "application/json" } }
2586
+ );
2587
+ }
2588
+ let session;
2589
+ try {
2590
+ session = await client.exchangeCode({
2591
+ code,
2592
+ codeVerifier: flowResult.codeVerifier,
2593
+ receivedState: callbackState,
2594
+ expectedState: getCookieValue(request, "sm_ledvery_state"),
2595
+ expectedNonce: flowResult.nonce
2596
+ });
2597
+ } catch (err) {
2598
+ return new Response(
2599
+ JSON.stringify({ error: "code_exchange_failed", message: err instanceof Error ? err.message : "Code exchange failed" }),
2600
+ { status: 403, headers: { "Content-Type": "application/json" } }
2601
+ );
2602
+ }
2603
+ const returnTo = getCookieValue(request, "sm_ledvery_return_to");
2604
+ const redirectTo = validateSafeRedirect(returnTo, { defaultPath: postLoginRedirect });
2605
+ const response = new Response(null, {
2606
+ status: 302,
2607
+ headers: { Location: redirectTo }
2608
+ });
2609
+ setLedverySession(response, {
2610
+ idToken: session.idToken,
2611
+ accessToken: session.accessToken,
2612
+ claims: session.claims,
2613
+ expiresAt: session.expiresAt.toISOString()
2614
+ }, {
2615
+ storeAccessToken: config.storeAccessToken,
2616
+ cookies: config.cookies
2617
+ });
2618
+ clearLedveryFlowCookies(response);
2619
+ response.headers.append("Set-Cookie", "sm_ledvery_return_to=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax");
2620
+ return response;
2621
+ }
2622
+ function handleSession(request) {
2623
+ const session = getLedverySession(request);
2624
+ if (!session) {
2625
+ return new Response(JSON.stringify({ session: null }), {
2626
+ status: 200,
2627
+ headers: { "Content-Type": "application/json" }
2628
+ });
2629
+ }
2630
+ const expiresAt = new Date(session.expiresAt);
2631
+ if (expiresAt <= /* @__PURE__ */ new Date()) {
2632
+ return new Response(JSON.stringify({ session: null }), {
2633
+ status: 200,
2634
+ headers: { "Content-Type": "application/json" }
2635
+ });
2636
+ }
2637
+ return new Response(
2638
+ JSON.stringify({
2639
+ session: {
2640
+ sub: session.claims.sub,
2641
+ email: session.claims.email,
2642
+ email_verified: session.claims.email_verified,
2643
+ name: session.claims.name,
2644
+ idp: session.claims.idp,
2645
+ expiresAt: session.expiresAt
2646
+ }
2647
+ }),
2648
+ { status: 200, headers: { "Content-Type": "application/json" } }
2649
+ );
2650
+ }
2651
+ function handleLogout(request) {
2652
+ const session = getLedverySession(request);
2653
+ const idToken = session?.idToken;
2654
+ if (config.gatewayUrl) {
2655
+ let rpLogoutUrl = `${config.gatewayUrl}/v1/auth/oauth/ledvery/logout?post_logout_redirect_uri=${encodeURIComponent(postLogoutRedirect)}`;
2656
+ if (idToken) {
2657
+ rpLogoutUrl += `&id_token_hint=${encodeURIComponent(idToken)}`;
2658
+ }
2659
+ const response2 = new Response(null, {
2660
+ status: 302,
2661
+ headers: { Location: rpLogoutUrl }
2662
+ });
2663
+ clearLedverySession(response2);
2664
+ return response2;
2665
+ }
2666
+ const response = new Response(null, {
2667
+ status: 302,
2668
+ headers: { Location: postLogoutRedirect }
2669
+ });
2670
+ clearLedverySession(response);
2671
+ return response;
2672
+ }
2673
+ async function handler(request, context) {
2674
+ const params = await context.params;
2675
+ const action = params.action?.[0] || "";
2676
+ switch (action) {
2677
+ case "login":
2678
+ return handleLogin(request);
2679
+ case "callback":
2680
+ return handleCallback(request);
2681
+ case "session":
2682
+ return handleSession(request);
2683
+ case "logout":
2684
+ return handleLogout(request);
2685
+ default:
2686
+ return new Response(
2687
+ JSON.stringify({ error: "not_found", message: `Unknown Ledvery route: ${action}` }),
2688
+ { status: 404, headers: { "Content-Type": "application/json" } }
2689
+ );
2690
+ }
2691
+ }
2692
+ return {
2693
+ GET: handler,
2694
+ POST: handler
2695
+ };
2696
+ }
2697
+ function getCookieValue(request, name) {
2698
+ const header = request.headers.get("cookie") || "";
2699
+ const match = header.match(new RegExp(`(?:^|;\\s*)${name}=([^;]*)`));
2700
+ return match ? decodeURIComponent(match[1]) : void 0;
2701
+ }
2702
+
2703
+ // src/server/push.ts
2704
+ function errorResponse2(code, message, status) {
2705
+ return new Response(
2706
+ JSON.stringify({ success: false, error: { code, message } }),
2707
+ { status, headers: { "Content-Type": "application/json" } }
2708
+ );
2709
+ }
2710
+ function successResponse2(data, status = 200) {
2711
+ return new Response(
2712
+ JSON.stringify({ success: true, data }),
2713
+ { status, headers: { "Content-Type": "application/json" } }
2714
+ );
2715
+ }
2716
+ function createPushRoutes(config) {
2717
+ const { apiKey, gatewayUrl, csrf = true } = config;
2718
+ async function proxyToGateway(request, method, subPath) {
2719
+ const targetUrl = `${gatewayUrl}/v1/communication/push/${subPath}`;
2720
+ const headers3 = {
2721
+ "x-api-key": apiKey
2722
+ };
2723
+ const session = getSessionFromRequest(request);
2724
+ if (session?.sessionToken) {
2725
+ headers3["Authorization"] = `Bearer ${session.sessionToken}`;
2726
+ }
2727
+ const clientContext = extractClientContext(
2728
+ request
2729
+ );
2730
+ const contextHeaders = buildClientContextHeaders(clientContext);
2731
+ Object.assign(headers3, contextHeaders);
2732
+ const workspaceId = request.headers.get("x-sm-workspace-id");
2733
+ if (workspaceId) {
2734
+ headers3["x-sm-workspace-id"] = workspaceId;
2735
+ }
2736
+ const fetchOptions = {
2737
+ method,
2738
+ headers: headers3
2739
+ };
2740
+ if (method !== "GET" && method !== "DELETE") {
2741
+ try {
2742
+ const body = await request.text();
2743
+ if (body) {
2744
+ headers3["Content-Type"] = "application/json";
2745
+ fetchOptions.body = body;
2746
+ }
2747
+ } catch {
2748
+ }
2749
+ }
2750
+ const response = await fetch(targetUrl, fetchOptions);
2751
+ if (response.status === 204) {
2752
+ return successResponse2(null);
2753
+ }
2754
+ const contentType = response.headers.get("content-type") || "";
2755
+ if (contentType.includes("application/json")) {
2756
+ const json = await response.json();
2757
+ if (response.ok) {
2758
+ return new Response(JSON.stringify(json), {
2759
+ status: response.status,
2760
+ headers: { "Content-Type": "application/json" }
2761
+ });
2762
+ } else {
2763
+ const errMsg = json?.error?.message || json?.message || "Request failed";
2764
+ const errCode = json?.error?.code || json?.code || "PUSH_ERROR";
2765
+ return errorResponse2(errCode, errMsg, response.status);
2766
+ }
2767
+ }
2768
+ const text = await response.text();
2769
+ if (response.ok) {
2770
+ return successResponse2(text);
2771
+ }
2772
+ return errorResponse2("PUSH_ERROR", text || "Request failed", response.status);
2773
+ }
2774
+ function extractSubPath(params) {
2775
+ return (params.action || []).join("/");
2776
+ }
2777
+ const GET = async (request, context) => {
2778
+ try {
2779
+ const params = await context?.params;
2780
+ const subPath = extractSubPath(params || {});
2781
+ return proxyToGateway(request, "GET", subPath);
2782
+ } catch (e) {
2783
+ return errorResponse2("INTERNAL_ERROR", String(e), 500);
2784
+ }
2785
+ };
2786
+ const POST = async (request, context) => {
2787
+ if (csrf) {
2788
+ const csrfError = validateCSRFToken(request);
2789
+ if (csrfError) {
2790
+ return errorResponse2("CSRF_ERROR", "CSRF validation failed", 403);
2791
+ }
2792
+ }
2793
+ try {
2794
+ const params = await context?.params;
2795
+ const subPath = extractSubPath(params || {});
2796
+ return proxyToGateway(request, "POST", subPath);
2797
+ } catch (e) {
2798
+ return errorResponse2("INTERNAL_ERROR", String(e), 500);
2799
+ }
2800
+ };
2801
+ const PUT = async (request, context) => {
2802
+ if (csrf) {
2803
+ const csrfError = validateCSRFToken(request);
2804
+ if (csrfError) {
2805
+ return errorResponse2("CSRF_ERROR", "CSRF validation failed", 403);
2806
+ }
2807
+ }
2808
+ try {
2809
+ const params = await context?.params;
2810
+ const subPath = extractSubPath(params || {});
2811
+ return proxyToGateway(request, "PUT", subPath);
2812
+ } catch (e) {
2813
+ return errorResponse2("INTERNAL_ERROR", String(e), 500);
2814
+ }
2815
+ };
2816
+ const DELETE = async (request, context) => {
2817
+ if (csrf) {
2818
+ const csrfError = validateCSRFToken(request);
2819
+ if (csrfError) {
2820
+ return errorResponse2("CSRF_ERROR", "CSRF validation failed", 403);
2821
+ }
2822
+ }
2823
+ try {
2824
+ const params = await context?.params;
2825
+ const subPath = extractSubPath(params || {});
2826
+ return proxyToGateway(request, "DELETE", subPath);
2827
+ } catch (e) {
2828
+ return errorResponse2("INTERNAL_ERROR", String(e), 500);
2829
+ }
2830
+ };
2831
+ return { GET, POST, PUT, DELETE };
2832
+ }
2833
+
2834
+ // src/server/notifications.ts
2835
+ function createNotificationRoutes(config) {
2836
+ const { apiKey, gatewayUrl } = config;
2837
+ async function proxyToGateway(request, method, subPath) {
2838
+ const targetUrl = `${gatewayUrl}/v1/notifications/${subPath}`;
2839
+ const headers3 = {
2840
+ "x-api-key": apiKey,
2841
+ "Content-Type": "application/json"
2842
+ };
2843
+ const session = getSessionFromRequest(request);
2844
+ if (session?.sessionToken) {
2845
+ headers3["Authorization"] = `Bearer ${session.sessionToken}`;
2846
+ }
2847
+ const clientContext = extractClientContext(
2848
+ request
2849
+ );
2850
+ const contextHeaders = buildClientContextHeaders(clientContext);
2851
+ Object.assign(headers3, contextHeaders);
2852
+ const workspaceId = request.headers.get("x-sm-workspace-id");
2853
+ if (workspaceId) {
2854
+ headers3["x-sm-workspace-id"] = workspaceId;
2855
+ }
2856
+ const fetchOptions = {
2857
+ method,
2858
+ headers: headers3
2859
+ };
2860
+ if (method === "PATCH") {
2861
+ try {
2862
+ const body = await request.text();
2863
+ if (body) {
2864
+ fetchOptions.body = body;
2865
+ }
2866
+ } catch {
2867
+ }
2868
+ }
2869
+ let targetUrlWithQuery = targetUrl;
2870
+ if (method === "GET") {
2871
+ const url = new URL(request.url);
2872
+ if (url.search) {
2873
+ targetUrlWithQuery = `${targetUrl}${url.search}`;
2874
+ }
2875
+ }
2876
+ const response = await fetch(targetUrlWithQuery, fetchOptions);
2877
+ const responseBody = await response.text();
2878
+ return new Response(responseBody, {
2879
+ status: response.status,
2880
+ headers: { "Content-Type": "application/json" }
2881
+ });
2882
+ }
2883
+ const GET = async (request, context) => {
2884
+ const params = await context.params;
2885
+ const subPath = params.action?.join("/") || "";
2886
+ return proxyToGateway(request, "GET", subPath);
2887
+ };
2888
+ const PATCH = async (request, context) => {
2889
+ const params = await context.params;
2890
+ const subPath = params.action?.join("/") || "";
2891
+ return proxyToGateway(request, "PATCH", subPath);
2892
+ };
2893
+ const DELETE = async (request, context) => {
2894
+ const params = await context.params;
2895
+ const subPath = params.action?.join("/") || "";
2896
+ return proxyToGateway(request, "DELETE", subPath);
2897
+ };
2898
+ return { GET, PATCH, DELETE };
2899
+ }
2900
+
2901
+ // src/server/errors.ts
2902
+ var ScaleMuleError = class extends Error {
2903
+ constructor(code, message, status = 400, details, requestId) {
2904
+ super(message);
2905
+ this.code = code;
2906
+ this.status = status;
2907
+ this.details = details;
2908
+ this.requestId = requestId;
2909
+ this.name = "ScaleMuleError";
2910
+ }
2911
+ };
2912
+ var CODE_TO_STATUS = {
2913
+ // Auth (401)
2914
+ unauthorized: 401,
2915
+ invalid_credentials: 401,
2916
+ session_expired: 401,
2917
+ token_expired: 401,
2918
+ token_invalid: 401,
2919
+ // Forbidden (403)
2920
+ forbidden: 403,
2921
+ email_not_verified: 403,
2922
+ phone_not_verified: 403,
2923
+ account_locked: 403,
2924
+ account_disabled: 403,
2925
+ mfa_required: 403,
2926
+ csrf_error: 403,
2927
+ origin_not_allowed: 403,
2928
+ // Not found (404)
2929
+ not_found: 404,
2930
+ // Conflict (409)
2931
+ conflict: 409,
2932
+ email_taken: 409,
2933
+ // Rate limiting (429)
2934
+ rate_limited: 429,
2935
+ quota_exceeded: 429,
2936
+ // Validation (400)
2937
+ validation_error: 400,
2938
+ weak_password: 400,
2939
+ invalid_email: 400,
2940
+ invalid_otp: 400,
2941
+ otp_expired: 400,
2942
+ // Server (500)
2943
+ internal_error: 500,
2944
+ // Network — SDK-generated (502/504)
2945
+ network_error: 502,
2946
+ timeout: 504
2947
+ };
2948
+ function errorCodeToStatus(code) {
2949
+ return CODE_TO_STATUS[code.toLowerCase()] || 400;
2950
+ }
2951
+ function unwrap(result) {
2952
+ if (result !== null && result !== void 0 && typeof result === "object" && ("success" in result || "error" in result) && "data" in result) {
2953
+ const envelope = result;
2954
+ if (envelope.error || envelope.success === false) {
2955
+ const err = envelope.error;
2956
+ const code = err?.code || "UNKNOWN_ERROR";
2957
+ const status = err?.status || errorCodeToStatus(code);
2958
+ throw new ScaleMuleError(
2959
+ code,
2960
+ err?.message || "An error occurred",
2961
+ status,
2962
+ err?.details,
2963
+ err?.requestId ?? envelope.meta?.request_id
2964
+ );
2965
+ }
2966
+ return envelope.data;
2967
+ }
2968
+ return result;
2969
+ }
2970
+
2971
+ // src/server/handler.ts
2972
+ function apiHandler(handler, options) {
2973
+ return async (request, routeContext) => {
2974
+ try {
2975
+ if (options?.csrf) {
2976
+ const csrfError = validateCSRFToken(request);
2977
+ if (csrfError) {
2978
+ throw new ScaleMuleError("CSRF_ERROR", csrfError, 403);
2979
+ }
2980
+ }
2981
+ let session;
2982
+ if (options?.auth) {
2983
+ session = await requireSession();
2984
+ }
2985
+ const rawParams = routeContext?.params ? await routeContext.params : {};
2986
+ const params = {};
2987
+ for (const [key, val] of Object.entries(rawParams)) {
2988
+ params[key] = Array.isArray(val) ? val.join("/") : val;
2989
+ }
2990
+ const context = {
2991
+ params,
2992
+ searchParams: request.nextUrl.searchParams,
2993
+ session
2994
+ };
2995
+ const result = await handler(request, context);
2996
+ if (result instanceof Response) return result;
2997
+ if (result !== void 0) {
2998
+ return Response.json({ success: true, data: result }, { status: 200 });
2999
+ }
3000
+ return new Response(null, { status: 204 });
3001
+ } catch (error2) {
3002
+ if (error2 instanceof ScaleMuleError) {
3003
+ if (options?.onError) {
3004
+ const custom = options.onError(error2);
3005
+ if (custom) return custom;
3006
+ }
3007
+ const safeMessage = error2.status >= 500 ? "An unexpected error occurred" : error2.message;
3008
+ if (error2.status >= 500) {
3009
+ console.error("Internal API error:", error2.message);
3010
+ }
3011
+ return Response.json(
3012
+ {
3013
+ success: false,
3014
+ error: { code: error2.code, message: safeMessage },
3015
+ ...error2.requestId ? { meta: { request_id: error2.requestId } } : {}
3016
+ },
3017
+ { status: error2.status }
3018
+ );
3019
+ }
3020
+ if (error2 instanceof Response) return error2;
3021
+ console.error("Unhandled API error:", error2);
3022
+ return Response.json(
3023
+ { success: false, error: { code: "INTERNAL_ERROR", message: "An unexpected error occurred" } },
3024
+ { status: 500 }
3025
+ );
3026
+ }
3027
+ };
3028
+ }
3029
+ function verifyWebhookSignature(payload, signature, secret) {
3030
+ if (!signature.startsWith("sha256=")) {
3031
+ return false;
3032
+ }
3033
+ const providedSig = signature.slice(7);
3034
+ const expectedSig = createHmac("sha256", secret).update(payload).digest("hex");
3035
+ try {
3036
+ return timingSafeEqual(
3037
+ Buffer.from(providedSig, "hex"),
3038
+ Buffer.from(expectedSig, "hex")
3039
+ );
3040
+ } catch {
3041
+ return false;
3042
+ }
3043
+ }
3044
+ function parseWebhookEvent(payload) {
3045
+ return JSON.parse(payload);
3046
+ }
3047
+ async function registerVideoWebhook(url, options) {
3048
+ const sm = createServerClient(options?.clientConfig);
3049
+ const result = await sm.webhooks.create({
3050
+ webhook_name: options?.name || "Video Status Webhook",
3051
+ url,
3052
+ events: options?.events || ["video.ready", "video.failed"]
3053
+ });
3054
+ return {
3055
+ id: result.id,
3056
+ secret: result.secret
3057
+ };
3058
+ }
3059
+ function createWebhookRoutes(config = {}) {
3060
+ const POST = async (request) => {
3061
+ const signature = request.headers.get("x-webhook-signature");
3062
+ const body = await request.text();
3063
+ if (config.secret) {
3064
+ if (!signature || !verifyWebhookSignature(body, signature, config.secret)) {
3065
+ return new Response(JSON.stringify({ error: "Invalid signature" }), {
3066
+ status: 401,
3067
+ headers: { "Content-Type": "application/json" }
3068
+ });
3069
+ }
3070
+ }
3071
+ try {
3072
+ const event = parseWebhookEvent(body);
3073
+ switch (event.event) {
3074
+ case "video.ready":
3075
+ if (config.onVideoReady) {
3076
+ await config.onVideoReady(event.data);
3077
+ }
3078
+ break;
3079
+ case "video.failed":
3080
+ if (config.onVideoFailed) {
3081
+ await config.onVideoFailed(event.data);
3082
+ }
3083
+ break;
3084
+ case "video.uploaded":
3085
+ if (config.onVideoUploaded) {
3086
+ await config.onVideoUploaded(event.data);
3087
+ }
3088
+ break;
3089
+ case "video.transcoded":
3090
+ if (config.onVideoTranscoded) {
3091
+ await config.onVideoTranscoded(event.data);
3092
+ }
3093
+ break;
3094
+ }
3095
+ if (config.onEvent) {
3096
+ await config.onEvent(event);
3097
+ }
3098
+ return new Response(JSON.stringify({ received: true }), {
3099
+ status: 200,
3100
+ headers: { "Content-Type": "application/json" }
3101
+ });
3102
+ } catch (error2) {
3103
+ console.error("Webhook handler error:", error2);
3104
+ return new Response(JSON.stringify({ error: "Handler failed" }), {
3105
+ status: 500,
3106
+ headers: { "Content-Type": "application/json" }
3107
+ });
3108
+ }
3109
+ };
3110
+ return { POST };
3111
+ }
3112
+
3113
+ // src/server/webhook-handler.ts
3114
+ function createWebhookHandler(config = {}) {
3115
+ return async (request) => {
3116
+ const signature = request.headers.get("x-webhook-signature");
3117
+ const body = await request.text();
3118
+ if (config.secret) {
3119
+ if (!signature || !verifyWebhookSignature(body, signature, config.secret)) {
3120
+ return new Response(JSON.stringify({ error: "Invalid signature" }), {
3121
+ status: 401,
3122
+ headers: { "Content-Type": "application/json" }
3123
+ });
3124
+ }
3125
+ }
3126
+ try {
3127
+ const event = parseWebhookEvent(body);
3128
+ if (config.onEvent && event.event && config.onEvent[event.event]) {
3129
+ await config.onEvent[event.event](event);
3130
+ }
3131
+ return new Response(JSON.stringify({ received: true }), {
3132
+ status: 200,
3133
+ headers: { "Content-Type": "application/json" }
3134
+ });
3135
+ } catch (error2) {
3136
+ return new Response(JSON.stringify({ error: "Webhook processing failed" }), {
3137
+ status: 500,
3138
+ headers: { "Content-Type": "application/json" }
3139
+ });
3140
+ }
3141
+ };
3142
+ }
3143
+ var _clients = /* @__PURE__ */ new Map();
3144
+ var _initPromises = /* @__PURE__ */ new Map();
3145
+ var _serverClient = null;
3146
+ function getServerClient() {
3147
+ if (!_serverClient) {
3148
+ _serverClient = createServerClient();
3149
+ }
3150
+ return _serverClient;
3151
+ }
3152
+ var GATEWAY_URLS2 = {
3153
+ dev: "https://api-dev.scalemule.com",
3154
+ prod: "https://api.scalemule.com"
3155
+ };
3156
+ function resolveGatewayUrl2() {
3157
+ if (process.env.SCALEMULE_API_URL) return process.env.SCALEMULE_API_URL;
3158
+ const env = process.env.SCALEMULE_ENV || "prod";
3159
+ return GATEWAY_URLS2[env] || GATEWAY_URLS2.prod;
3160
+ }
3161
+ async function getFlagClient(environment) {
3162
+ const apiKey = process.env.SCALEMULE_API_KEY;
3163
+ const gatewayUrl = resolveGatewayUrl2();
3164
+ const key = `${environment}:${gatewayUrl}`;
3165
+ const existing = _clients.get(key);
3166
+ if (existing) return existing;
3167
+ const pending = _initPromises.get(key);
3168
+ if (pending) return pending;
3169
+ const promise = (async () => {
3170
+ const client = new FlagClient({ apiKey, environment, gatewayUrl });
3171
+ await Promise.race([
3172
+ client.init(),
3173
+ new Promise(
3174
+ (_, reject) => setTimeout(() => reject(new Error("FlagClient init timeout")), 3e3)
3175
+ )
3176
+ ]);
3177
+ _clients.set(key, client);
3178
+ return client;
3179
+ })();
3180
+ _initPromises.set(key, promise);
3181
+ try {
3182
+ return await promise;
3183
+ } catch (e) {
3184
+ _initPromises.delete(key);
3185
+ throw e;
3186
+ }
3187
+ }
3188
+ var _shutdownRegistered = false;
3189
+ function ensureShutdownHook() {
3190
+ if (_shutdownRegistered) return;
3191
+ _shutdownRegistered = true;
3192
+ if (typeof process !== "undefined" && typeof process.once === "function") {
3193
+ process.once("SIGTERM", async () => {
3194
+ const shutdowns = Array.from(_clients.values()).map((c) => c.shutdown());
3195
+ await Promise.allSettled(shutdowns);
3196
+ });
3197
+ }
3198
+ }
3199
+ function extractClientIp(hdrs) {
3200
+ const realIp = hdrs.get("x-real-ip") || hdrs.get("x-real-client-ip");
3201
+ const forwardedFor = hdrs.get("x-forwarded-for");
3202
+ return realIp || (forwardedFor ? forwardedFor.split(",")[0].trim() : void 0);
3203
+ }
3204
+ async function getBootstrapFlags(flagKeys, environment = "prod", extraContext = {}, cacheTtlMs = 0) {
3205
+ try {
3206
+ const client = await getFlagClient(environment);
3207
+ ensureShutdownHook();
3208
+ const hdrs = await headers();
3209
+ const clientIp = extractClientIp(hdrs);
3210
+ const context = { ...extraContext };
3211
+ if (clientIp) context.ip_address = clientIp;
3212
+ return client.evaluateBatch(flagKeys, context);
3213
+ } catch {
3214
+ try {
3215
+ const hdrs = await headers();
3216
+ const clientIp = extractClientIp(hdrs);
3217
+ const context = { ...extraContext };
3218
+ if (clientIp) context.ip_address = clientIp;
3219
+ const result = await getServerClient().flags.evaluateBatch(flagKeys, context, environment);
3220
+ return result || {};
3221
+ } catch {
3222
+ return {};
3223
+ }
3224
+ }
3225
+ }
3226
+ function globToRegex(pattern) {
3227
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
3228
+ return new RegExp(`^${escaped}$`);
3229
+ }
3230
+ function matchesPattern(pathname, patterns) {
3231
+ return patterns.some((pattern) => {
3232
+ if (pattern === pathname) return true;
3233
+ if (pattern.includes("*") || pattern.includes("?")) {
3234
+ return globToRegex(pattern).test(pathname);
3235
+ }
3236
+ if (pathname.startsWith(pattern + "/")) return true;
3237
+ return false;
3238
+ });
3239
+ }
3240
+ function createAuthMiddleware(config = {}) {
3241
+ const {
3242
+ protectedRoutes = [],
3243
+ publicRoutes = [],
3244
+ authOnlyPublic = [],
3245
+ redirectTo = "/login",
3246
+ redirectAuthenticated,
3247
+ skipValidation = false,
3248
+ onUnauthorized
3249
+ } = config;
3250
+ return async function middleware(request) {
3251
+ const { pathname } = request.nextUrl;
3252
+ if (pathname.startsWith("/api/auth")) {
3253
+ return NextResponse.next();
3254
+ }
3255
+ if (publicRoutes.length > 0 && matchesPattern(pathname, publicRoutes)) {
3256
+ if (redirectAuthenticated && authOnlyPublic.length > 0 && matchesPattern(pathname, authOnlyPublic)) {
3257
+ const session2 = getSessionFromRequest(request);
3258
+ if (session2) {
3259
+ return NextResponse.redirect(new URL(redirectAuthenticated, request.url));
3260
+ }
3261
+ }
3262
+ return NextResponse.next();
3263
+ }
3264
+ const requiresAuth = protectedRoutes.length === 0 || matchesPattern(pathname, protectedRoutes);
3265
+ if (!requiresAuth) {
3266
+ return NextResponse.next();
3267
+ }
3268
+ const session = getSessionFromRequest(request);
3269
+ if (!session) {
3270
+ if (onUnauthorized) {
3271
+ return onUnauthorized(request);
3272
+ }
3273
+ const redirectUrl = new URL(redirectTo, request.url);
3274
+ redirectUrl.searchParams.set("callbackUrl", pathname);
3275
+ return NextResponse.redirect(redirectUrl);
3276
+ }
3277
+ if (!skipValidation) {
3278
+ try {
3279
+ const sm = createServerClient();
3280
+ await sm.auth.me(session.sessionToken);
3281
+ } catch (error2) {
3282
+ console.error("[ScaleMule Middleware] Session validation failed, blocking request:", error2);
3283
+ const response = NextResponse.redirect(new URL(redirectTo, request.url));
3284
+ response.cookies.delete(SESSION_COOKIE_NAME);
3285
+ response.cookies.delete(USER_ID_COOKIE_NAME);
3286
+ return response;
3287
+ }
3288
+ }
3289
+ return NextResponse.next();
3290
+ };
3291
+ }
3292
+ function withAuth(config = {}) {
3293
+ const { redirectTo = "/login", onUnauthorized } = config;
3294
+ return function middleware(request) {
3295
+ const session = getSessionFromRequest(request);
3296
+ if (!session) {
3297
+ if (onUnauthorized) {
3298
+ return onUnauthorized(request);
3299
+ }
3300
+ const redirectUrl = new URL(redirectTo, request.url);
3301
+ redirectUrl.searchParams.set("callbackUrl", request.nextUrl.pathname);
3302
+ return NextResponse.redirect(redirectUrl);
3303
+ }
3304
+ return NextResponse.next();
3305
+ };
3306
+ }
3307
+ var OAUTH_STATE_COOKIE_NAME = "sm_oauth_state";
3308
+ function setOAuthState(response, state) {
3309
+ response.cookies.set(OAUTH_STATE_COOKIE_NAME, state, {
3310
+ httpOnly: true,
3311
+ secure: process.env.NODE_ENV === "production",
3312
+ sameSite: "lax",
3313
+ // Lax allows the cookie to be sent on OAuth redirects
3314
+ path: "/",
3315
+ maxAge: 60 * 10
3316
+ // 10 minutes - OAuth flows should complete quickly
3317
+ });
3318
+ return response;
3319
+ }
3320
+ function validateOAuthState(request, callbackState) {
3321
+ const cookieState = request.cookies.get(OAUTH_STATE_COOKIE_NAME)?.value;
3322
+ if (!cookieState) {
3323
+ return "Missing OAuth state cookie - session may have expired";
3324
+ }
3325
+ if (!callbackState) {
3326
+ return "Missing OAuth state in callback";
3327
+ }
3328
+ if (!constantTimeEqual(cookieState, callbackState)) {
3329
+ return "OAuth state mismatch - possible CSRF attack";
3330
+ }
3331
+ return void 0;
3332
+ }
3333
+ async function validateOAuthStateAsync(callbackState) {
3334
+ const cookieStore = await cookies();
3335
+ const cookieState = cookieStore.get(OAUTH_STATE_COOKIE_NAME)?.value;
3336
+ if (!cookieState) {
3337
+ return "Missing OAuth state cookie - session may have expired";
3338
+ }
3339
+ if (!callbackState) {
3340
+ return "Missing OAuth state in callback";
3341
+ }
3342
+ if (!constantTimeEqual(cookieState, callbackState)) {
3343
+ return "OAuth state mismatch - possible CSRF attack";
3344
+ }
3345
+ return void 0;
3346
+ }
3347
+ function clearOAuthState(response) {
3348
+ response.cookies.delete(OAUTH_STATE_COOKIE_NAME);
3349
+ return response;
3350
+ }
3351
+
3352
+ // src/server/secrets.ts
3353
+ var DEFAULT_CACHE_TTL_MS = 5 * 60 * 1e3;
3354
+ var secretsCache = {};
3355
+ var globalConfig = {};
3356
+ function configureSecrets(config) {
3357
+ globalConfig = { ...globalConfig, ...config };
3358
+ }
3359
+ async function getAppSecret(key) {
3360
+ const cacheTtl = globalConfig.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
3361
+ const noCache = globalConfig.noCache ?? false;
3362
+ if (!noCache) {
3363
+ const cached = secretsCache[key];
3364
+ if (cached && Date.now() - cached.cachedAt < cacheTtl) {
3365
+ return cached.value;
3366
+ }
3367
+ }
3368
+ try {
3369
+ const client = createServerClient();
3370
+ const result = await client.secrets.get(key);
3371
+ if (!noCache && result) {
3372
+ secretsCache[key] = {
3373
+ value: result.value,
3374
+ version: result.version,
3375
+ cachedAt: Date.now()
3376
+ };
3377
+ }
3378
+ return result?.value;
3379
+ } catch (error2) {
3380
+ if (error2 instanceof ScaleMuleApiError && error2.code === "SECRET_NOT_FOUND") {
3381
+ return void 0;
3382
+ }
3383
+ console.error(`[ScaleMule Secrets] Error fetching ${key}:`, error2);
3384
+ return void 0;
3385
+ }
3386
+ }
3387
+ async function requireAppSecret(key) {
3388
+ const value = await getAppSecret(key);
3389
+ if (value === void 0) {
3390
+ throw new Error(
3391
+ `Required secret '${key}' not found in ScaleMule vault. Configure it in the ScaleMule dashboard or use the SDK: scalemule.secrets.set('${key}', value)`
3392
+ );
3393
+ }
3394
+ return value;
3395
+ }
3396
+ async function getAppSecretOrDefault(key, fallback) {
3397
+ const value = await getAppSecret(key);
3398
+ return value ?? fallback;
3399
+ }
3400
+ function invalidateSecretCache(key) {
3401
+ if (key) {
3402
+ delete secretsCache[key];
3403
+ } else {
3404
+ Object.keys(secretsCache).forEach((k) => delete secretsCache[k]);
3405
+ }
3406
+ }
3407
+ async function prefetchSecrets(keys) {
3408
+ await Promise.all(keys.map((key) => getAppSecret(key)));
3409
+ }
3410
+
3411
+ // src/server/bundles.ts
3412
+ var DEFAULT_CACHE_TTL_MS2 = 5 * 60 * 1e3;
3413
+ var bundlesCache = {};
3414
+ var globalConfig2 = {};
3415
+ function configureBundles(config) {
3416
+ globalConfig2 = { ...globalConfig2, ...config };
3417
+ }
3418
+ async function getBundle(key, resolve = true) {
3419
+ const cacheTtl = globalConfig2.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS2;
3420
+ const noCache = globalConfig2.noCache ?? false;
3421
+ if (!noCache) {
3422
+ const cached = bundlesCache[key];
3423
+ if (cached && Date.now() - cached.cachedAt < cacheTtl) {
3424
+ return cached.data;
3425
+ }
3426
+ }
3427
+ try {
3428
+ const client = createServerClient();
3429
+ const result = await client.bundles.get(key, resolve);
3430
+ if (!noCache && result) {
3431
+ bundlesCache[key] = {
3432
+ type: result.type,
3433
+ data: result.data,
3434
+ version: result.version,
3435
+ inheritsFrom: result.inherits_from,
3436
+ cachedAt: Date.now()
3437
+ };
3438
+ }
3439
+ return result?.data;
3440
+ } catch (error2) {
3441
+ if (error2 instanceof ScaleMuleApiError && error2.code === "BUNDLE_NOT_FOUND") {
3442
+ return void 0;
3443
+ }
3444
+ console.error(`[ScaleMule Bundles] Error fetching ${key}:`, error2);
3445
+ return void 0;
3446
+ }
3447
+ }
3448
+ async function requireBundle(key, resolve = true) {
3449
+ const value = await getBundle(key, resolve);
3450
+ if (value === void 0) {
3451
+ throw new Error(
3452
+ `Required bundle '${key}' not found in ScaleMule vault. Configure it in the ScaleMule dashboard`
3453
+ );
3454
+ }
3455
+ return value;
3456
+ }
3457
+ async function getMySqlBundle(key) {
3458
+ const bundle = await getBundle(key);
3459
+ if (!bundle) return void 0;
3460
+ const { host, port, username, password, database, ssl_mode } = bundle;
3461
+ const encodedPassword = encodeURIComponent(password);
3462
+ let connectionUrl = `mysql://${username}:${encodedPassword}@${host}:${port}/${database}`;
3463
+ if (ssl_mode) {
3464
+ connectionUrl += `?ssl_mode=${ssl_mode}`;
3465
+ }
3466
+ return { ...bundle, connectionUrl };
3467
+ }
3468
+ async function getPostgresBundle(key) {
3469
+ const bundle = await getBundle(key);
3470
+ if (!bundle) return void 0;
3471
+ const { host, port, username, password, database, ssl_mode } = bundle;
3472
+ const encodedPassword = encodeURIComponent(password);
3473
+ let connectionUrl = `postgresql://${username}:${encodedPassword}@${host}:${port}/${database}`;
3474
+ if (ssl_mode) {
3475
+ connectionUrl += `?sslmode=${ssl_mode}`;
3476
+ }
3477
+ return { ...bundle, connectionUrl };
3478
+ }
3479
+ async function getRedisBundle(key) {
3480
+ const bundle = await getBundle(key);
3481
+ if (!bundle) return void 0;
3482
+ const { host, port, password, database, ssl } = bundle;
3483
+ let connectionUrl = ssl ? "rediss://" : "redis://";
3484
+ if (password) {
3485
+ connectionUrl += `:${encodeURIComponent(password)}@`;
3486
+ }
3487
+ connectionUrl += `${host}:${port}`;
3488
+ if (database !== void 0) {
3489
+ connectionUrl += `/${database}`;
3490
+ }
3491
+ return { ...bundle, connectionUrl };
3492
+ }
3493
+ async function getS3Bundle(key) {
3494
+ return getBundle(key);
3495
+ }
3496
+ async function getOAuthBundle(key) {
3497
+ return getBundle(key);
3498
+ }
3499
+ async function getSmtpBundle(key) {
3500
+ return getBundle(key);
3501
+ }
3502
+ function invalidateBundleCache(key) {
3503
+ if (key) {
3504
+ delete bundlesCache[key];
3505
+ } else {
3506
+ Object.keys(bundlesCache).forEach((k) => delete bundlesCache[k]);
3507
+ }
3508
+ }
3509
+ async function prefetchBundles(keys) {
3510
+ await Promise.all(keys.map((key) => getBundle(key)));
3511
+ }
3512
+
3513
+ // src/server/security-headers.ts
3514
+ var DEFAULT_PERMISSIONS_POLICY = {
3515
+ // Conference track features — allow self-origin only.
3516
+ camera: "self",
3517
+ microphone: "self",
3518
+ "display-capture": "self",
3519
+ // Deny-by-default for features the SDK never uses.
3520
+ geolocation: "()",
3521
+ payment: "()",
3522
+ "publickey-credentials-get": "self",
3523
+ usb: "()",
3524
+ serial: "()",
3525
+ bluetooth: "()"
3526
+ };
3527
+ function formatPermissionsDirective(feature, value) {
3528
+ if (value === "*") return `${feature}=*`;
3529
+ if (value === "()" || Array.isArray(value) && value.length === 0) {
3530
+ return `${feature}=()`;
3531
+ }
3532
+ if (value === "self") return `${feature}=(self)`;
3533
+ const origins = value;
3534
+ const parts = origins.map((o) => o === "self" ? "self" : `"${o}"`);
3535
+ return `${feature}=(${parts.join(" ")})`;
3536
+ }
3537
+ function buildSecurityHeaders(opts = {}) {
3538
+ const headers3 = [];
3539
+ const includeHsts = opts.includeHsts ?? true;
3540
+ const hstsMaxAge = opts.hstsMaxAgeSeconds ?? 31536e3;
3541
+ if (includeHsts && hstsMaxAge > 0) {
3542
+ const parts = [`max-age=${hstsMaxAge}`];
3543
+ if (opts.hstsIncludeSubDomains ?? true) parts.push("includeSubDomains");
3544
+ if (opts.hstsPreload ?? false) parts.push("preload");
3545
+ headers3.push({
3546
+ key: "Strict-Transport-Security",
3547
+ value: parts.join("; ")
3548
+ });
3549
+ }
3550
+ const frameOptions = opts.frameOptions === void 0 ? "DENY" : opts.frameOptions;
3551
+ if (frameOptions !== null) {
3552
+ headers3.push({ key: "X-Frame-Options", value: frameOptions });
3553
+ }
3554
+ const contentTypeOptions = opts.contentTypeOptions === void 0 ? "nosniff" : opts.contentTypeOptions;
3555
+ if (contentTypeOptions !== null) {
3556
+ headers3.push({ key: "X-Content-Type-Options", value: contentTypeOptions });
3557
+ }
3558
+ headers3.push({
3559
+ key: "Referrer-Policy",
3560
+ value: opts.referrerPolicy ?? "strict-origin-when-cross-origin"
3561
+ });
3562
+ const xss = opts.xssProtection === void 0 ? "0" : opts.xssProtection;
3563
+ if (xss !== null) {
3564
+ headers3.push({ key: "X-XSS-Protection", value: xss });
3565
+ }
3566
+ const permissions = opts.permissionsPolicy === void 0 ? DEFAULT_PERMISSIONS_POLICY : opts.permissionsPolicy;
3567
+ if (permissions !== null) {
3568
+ const directives = Object.entries(permissions).map(([feature, value]) => formatPermissionsDirective(feature, value)).join(", ");
3569
+ headers3.push({ key: "Permissions-Policy", value: directives });
3570
+ }
3571
+ if (opts.extraHeaders?.length) {
3572
+ const byKey = new Map(headers3.map((h) => [h.key.toLowerCase(), h]));
3573
+ for (const extra of opts.extraHeaders) {
3574
+ byKey.set(extra.key.toLowerCase(), extra);
3575
+ }
3576
+ return Array.from(byKey.values());
3577
+ }
3578
+ return headers3;
3579
+ }
3580
+
3581
+ export { CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, KNOWN_ACCOUNTS_COOKIE_NAME, OAUTH_STATE_COOKIE_NAME, SESSION_COOKIE_NAME, SM_LEDVERY_ACCESS_TOKEN_COOKIE, SM_LEDVERY_ID_TOKEN_COOKIE, SM_LEDVERY_NONCE_COOKIE, SM_LEDVERY_PKCE_VERIFIER_COOKIE, SM_LEDVERY_STATE_COOKIE, ScaleMuleError, ScaleMuleServer, USER_ID_COOKIE_NAME, apiHandler, appendKnownAccountCookie, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearKnownAccountsCookie, clearOAuthState, clearSession, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createLedveryRoutes, createNotificationRoutes, createPushRoutes, createServerClient, createWebhookHandler, createWebhookRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getKnownAccountsCookieRaw, getKnownAccountsFromRequest, getLedverySession, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSession, getSessionFromRequest, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, normalizeKnownAccountsCookie, parseWebhookEvent, prefetchBundles, prefetchSecrets, registerVideoWebhook, removeKnownAccountFromCookie, requireAppSecret, requireBundle, requireSession, resolveGatewayUrl, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, verifyWebhookSignature, withAuth, withCSRFProtection, withCSRFToken, withSession };