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