@scalemule/nextjs 0.1.60 → 0.1.61

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