@scalemule/nextjs 0.1.61 → 0.1.63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/audio.css +857 -0
  2. package/dist/audio.d.mts +334 -0
  3. package/dist/audio.d.ts +334 -0
  4. package/dist/audio.js +2178 -0
  5. package/dist/audio.mjs +2156 -0
  6. package/dist/client.d.mts +240 -0
  7. package/dist/client.d.ts +240 -0
  8. package/dist/client.js +938 -0
  9. package/dist/client.mjs +935 -0
  10. package/dist/index-CEi5Nd4L.d.mts +980 -0
  11. package/dist/index-CEi5Nd4L.d.ts +980 -0
  12. package/dist/index.d.mts +1354 -0
  13. package/dist/index.d.ts +1354 -0
  14. package/dist/index.js +6070 -0
  15. package/dist/index.mjs +6006 -0
  16. package/dist/ledvery-CxPzZpxP.d.mts +44 -0
  17. package/dist/ledvery-CxPzZpxP.d.ts +44 -0
  18. package/dist/listening-hub.global.js +1 -0
  19. package/dist/server/auth.d.mts +43 -0
  20. package/dist/server/auth.d.ts +43 -0
  21. package/dist/server/auth.js +2015 -0
  22. package/dist/server/auth.mjs +2009 -0
  23. package/dist/server/index.d.mts +1303 -0
  24. package/dist/server/index.d.ts +1303 -0
  25. package/dist/server/index.js +3660 -0
  26. package/dist/server/index.mjs +3581 -0
  27. package/dist/server/ledvery.d.mts +1 -0
  28. package/dist/server/ledvery.d.ts +1 -0
  29. package/dist/server/ledvery.js +336 -0
  30. package/dist/server/ledvery.mjs +333 -0
  31. package/dist/server/webhook-handler.d.mts +4 -0
  32. package/dist/server/webhook-handler.d.ts +4 -0
  33. package/dist/server/webhook-handler.js +60 -0
  34. package/dist/server/webhook-handler.mjs +58 -0
  35. package/dist/testing.d.mts +109 -0
  36. package/dist/testing.d.ts +109 -0
  37. package/dist/testing.js +144 -0
  38. package/dist/testing.mjs +138 -0
  39. package/dist/webhook-handler-CJm0sIZG.d.mts +856 -0
  40. package/dist/webhook-handler-CnQe9hm5.d.ts +856 -0
  41. package/package.json +2 -2
@@ -0,0 +1,2015 @@
1
+ 'use strict';
2
+
3
+ var sdk = require('@scalemule/sdk');
4
+ var money = require('@scalemule/money');
5
+ var headers = require('next/headers');
6
+ require('next/server');
7
+
8
+ // src/types/index.ts
9
+ var ScaleMuleApiError = class extends Error {
10
+ constructor(error2, status) {
11
+ super(error2.message);
12
+ this.name = "ScaleMuleApiError";
13
+ this.code = error2.code;
14
+ this.field = error2.field;
15
+ this.status = status;
16
+ this.requestId = error2.requestId;
17
+ this.traceId = error2.traceId;
18
+ this.problem = error2.problem;
19
+ }
20
+ };
21
+
22
+ // src/url-privacy.ts
23
+ function withoutAuthSecrets(value) {
24
+ if (!value) return value;
25
+ try {
26
+ const absolute = /^[a-z][a-z0-9+.-]*:/i.test(value);
27
+ const protocolRelative = value.startsWith("//");
28
+ const url = new URL(value, "https://relative.invalid");
29
+ if (!["http:", "https:"].includes(url.protocol)) return void 0;
30
+ let changed = false;
31
+ for (const name of [...url.searchParams.keys()]) {
32
+ if (/^(token|code|state|password|new_password|access_token|refresh_token|id_token|api_key|client_secret|challenge_token|challenge_code)$/i.test(name)) {
33
+ url.searchParams.delete(name);
34
+ changed = true;
35
+ }
36
+ }
37
+ if (url.hash) {
38
+ url.hash = "";
39
+ changed = true;
40
+ }
41
+ if (!changed) return value;
42
+ if (absolute) return url.toString();
43
+ if (protocolRelative) return url.toString().replace(/^https:/, "");
44
+ return value.split(/[?#]/, 1)[0] + url.search;
45
+ } catch {
46
+ return void 0;
47
+ }
48
+ }
49
+
50
+ // src/server/context.ts
51
+ function validateIP(ip) {
52
+ if (!ip) return void 0;
53
+ const trimmed = ip.trim();
54
+ if (!trimmed) return void 0;
55
+ 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]?)$/;
56
+ 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}$/;
57
+ 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;
58
+ if (ipv4Regex.test(trimmed) || ipv6Regex.test(trimmed) || ipv4MappedRegex.test(trimmed)) {
59
+ return trimmed;
60
+ }
61
+ return void 0;
62
+ }
63
+ function extractClientContext(request, options = {}) {
64
+ const headers2 = request.headers;
65
+ let ip;
66
+ ip = validateIP(headers2.get("x-real-ip"));
67
+ const cfConnectingIp = headers2.get("cf-connecting-ip");
68
+ if (!ip && cfConnectingIp) {
69
+ ip = validateIP(cfConnectingIp);
70
+ }
71
+ if (!ip) {
72
+ const doConnectingIp = headers2.get("do-connecting-ip");
73
+ if (doConnectingIp) {
74
+ ip = validateIP(doConnectingIp);
75
+ }
76
+ }
77
+ if (!ip) {
78
+ const realIp = headers2.get("x-real-ip");
79
+ if (realIp) {
80
+ ip = validateIP(realIp);
81
+ }
82
+ }
83
+ if (!ip) {
84
+ const forwardedFor = headers2.get("x-forwarded-for");
85
+ if (forwardedFor) {
86
+ const firstIp = forwardedFor.split(",")[0]?.trim();
87
+ ip = validateIP(firstIp);
88
+ }
89
+ }
90
+ if (!ip) {
91
+ const vercelForwarded = headers2.get("x-vercel-forwarded-for");
92
+ if (vercelForwarded) {
93
+ const firstIp = vercelForwarded.split(",")[0]?.trim();
94
+ ip = validateIP(firstIp);
95
+ }
96
+ }
97
+ if (!ip) {
98
+ const trueClientIp = headers2.get("true-client-ip");
99
+ if (trueClientIp) {
100
+ ip = validateIP(trueClientIp);
101
+ }
102
+ }
103
+ if (!ip && request.ip) {
104
+ ip = validateIP(request.ip);
105
+ }
106
+ if (options.trustedIpHeader) {
107
+ const value = headers2.get(options.trustedIpHeader);
108
+ const hop = options.trustedIpHeader === "x-forwarded-for" ? value?.split(",").at(-1)?.trim() : value;
109
+ ip = validateIP(hop);
110
+ }
111
+ const userAgent = headers2.get("user-agent") || void 0;
112
+ const deviceFingerprint = headers2.get("x-device-fingerprint") || void 0;
113
+ const referrer = withoutAuthSecrets(headers2.get("referer") || void 0);
114
+ const anonymousId = headers2.get("x-anonymous-id") || void 0;
115
+ return {
116
+ ip,
117
+ userAgent,
118
+ deviceFingerprint,
119
+ referrer,
120
+ anonymousId
121
+ };
122
+ }
123
+ function buildClientContextHeaders(context) {
124
+ const headers2 = {};
125
+ if (!context) {
126
+ return headers2;
127
+ }
128
+ if (context.ip) {
129
+ headers2["x-sm-forwarded-client-ip"] = context.ip;
130
+ headers2["X-Client-IP"] = context.ip;
131
+ }
132
+ if (context.userAgent) {
133
+ headers2["X-Client-User-Agent"] = context.userAgent;
134
+ }
135
+ if (context.deviceFingerprint) {
136
+ headers2["X-Client-Device-Fingerprint"] = context.deviceFingerprint;
137
+ }
138
+ if (context.referrer) {
139
+ headers2["X-Client-Referrer"] = context.referrer;
140
+ }
141
+ if (context.anonymousId) {
142
+ headers2["x-anonymous-id"] = context.anonymousId;
143
+ }
144
+ return headers2;
145
+ }
146
+
147
+ // src/error-context.ts
148
+ function withErrorContext(error2, responseData, headers2) {
149
+ const enriched = { ...error2 };
150
+ const meta = responseData?.meta;
151
+ const requestId = meta?.request_id ?? headers2?.get("x-request-id") ?? void 0;
152
+ if (requestId !== void 0 && enriched.requestId === void 0) {
153
+ enriched.requestId = requestId;
154
+ }
155
+ const traceId = meta?.trace_id;
156
+ if (traceId !== void 0 && enriched.traceId === void 0) {
157
+ enriched.traceId = traceId;
158
+ }
159
+ const rawError = responseData?.error;
160
+ if (rawError !== null && typeof rawError === "object" && enriched.problem === void 0) {
161
+ enriched.problem = rawError;
162
+ }
163
+ return enriched;
164
+ }
165
+
166
+ // src/server/client.ts
167
+ var GATEWAY_URLS = {
168
+ dev: "https://api-dev.scalemule.com",
169
+ prod: "https://api.scalemule.com"
170
+ };
171
+ function resolveGatewayUrl(config) {
172
+ if (config.gatewayUrl) return config.gatewayUrl;
173
+ if (process.env.SCALEMULE_API_URL) return process.env.SCALEMULE_API_URL;
174
+ if (process.env.SCALEMULE_GATEWAY_URL) return process.env.SCALEMULE_GATEWAY_URL;
175
+ return GATEWAY_URLS[config.environment || "prod"];
176
+ }
177
+ var ScaleMuleServer = class {
178
+ constructor(config) {
179
+ // ==========================================================================
180
+ // Auth Methods
181
+ // ==========================================================================
182
+ this.auth = {
183
+ /** Issue a 60-second, single-use transfer code after a server OAuth callback. */
184
+ createSessionHandoff: async (sessionToken, audience) => {
185
+ return this.request("POST", "/v1/auth/session-handoff", { sessionToken, body: { session_token: sessionToken, audience } });
186
+ },
187
+ /** Exchange only on the server; write the returned session into an HTTP-only cookie. */
188
+ exchangeSessionHandoff: async (code, audience) => {
189
+ return this.request("POST", "/v1/auth/session-handoff/exchange", { body: { code, audience } });
190
+ },
191
+ /**
192
+ * Register a new user
193
+ */
194
+ register: async (data, options) => {
195
+ return this.request("POST", "/v1/auth/register", { body: data, clientContext: options?.clientContext });
196
+ },
197
+ /**
198
+ * Login user - returns session token (store in HTTP-only cookie)
199
+ */
200
+ sendMfaCode: async (pending_token, method, options) => {
201
+ return this.request("POST", "/v1/auth/mfa/send-code", { body: { pending_token, method }, clientContext: options?.clientContext });
202
+ },
203
+ completeMfa: async (pending_token, code, method, options) => {
204
+ return this.request("POST", "/v1/auth/mfa/verify", { body: { pending_token, code, method }, clientContext: options?.clientContext });
205
+ },
206
+ login: async (data, options) => {
207
+ return this.request("POST", "/v1/auth/login", { body: data, clientContext: options?.clientContext });
208
+ },
209
+ /**
210
+ * Logout user
211
+ */
212
+ logout: async (sessionToken, options) => {
213
+ return this.request("POST", "/v1/auth/logout", {
214
+ sessionToken,
215
+ body: { session_token: sessionToken },
216
+ onTokenRotated: options?.onTokenRotated
217
+ });
218
+ },
219
+ /**
220
+ * Get current user from session token
221
+ */
222
+ me: async (sessionToken, options) => {
223
+ return this.request("GET", "/v1/auth/me", {
224
+ sessionToken,
225
+ onTokenRotated: options?.onTokenRotated
226
+ });
227
+ },
228
+ /**
229
+ * Refresh session token
230
+ */
231
+ refresh: async (sessionToken, options) => {
232
+ return this.request("POST", "/v1/auth/refresh", {
233
+ sessionToken,
234
+ // The auth service reads the token to rotate from the body, not the
235
+ // Authorization header; without it every refresh is rejected.
236
+ body: { session_token: sessionToken },
237
+ clientContext: options?.clientContext,
238
+ isAutoRefresh: options?.isAutoRefresh,
239
+ onTokenRotated: options?.onTokenRotated
240
+ });
241
+ },
242
+ /**
243
+ * Request password reset email
244
+ */
245
+ forgotPassword: async (email, options) => {
246
+ return this.request("POST", "/v1/auth/forgot-password", { body: { email }, clientContext: options?.clientContext });
247
+ },
248
+ /**
249
+ * Reset password with token
250
+ */
251
+ resetPassword: async (token, newPassword, options) => {
252
+ return this.request("POST", "/v1/auth/reset-password", {
253
+ body: { token, new_password: newPassword },
254
+ clientContext: options?.clientContext
255
+ });
256
+ },
257
+ /**
258
+ * Verify email with token
259
+ */
260
+ verifyEmail: async (token) => {
261
+ return this.request("POST", "/v1/auth/verify-email", { body: { token } });
262
+ },
263
+ /**
264
+ * Resend verification email.
265
+ * Can be called with a session token (authenticated) or email (unauthenticated).
266
+ */
267
+ resendVerification: async (sessionTokenOrEmail, options) => {
268
+ if (options?.email) {
269
+ return this.request("POST", "/v1/auth/resend-verification", {
270
+ sessionToken: sessionTokenOrEmail,
271
+ body: { email: options.email },
272
+ onTokenRotated: options?.onTokenRotated
273
+ });
274
+ }
275
+ if (sessionTokenOrEmail.includes("@")) {
276
+ return this.request("POST", "/v1/auth/resend-verification", {
277
+ body: { email: sessionTokenOrEmail }
278
+ });
279
+ }
280
+ return this.request("POST", "/v1/auth/resend-verification", {
281
+ sessionToken: sessionTokenOrEmail,
282
+ onTokenRotated: options?.onTokenRotated
283
+ });
284
+ }
285
+ };
286
+ // ==========================================================================
287
+ // User/Profile Methods
288
+ // ==========================================================================
289
+ this.user = {
290
+ /**
291
+ * Update user profile
292
+ */
293
+ update: async (sessionToken, data, options) => {
294
+ return this.request("PATCH", "/v1/auth/profile", {
295
+ sessionToken,
296
+ body: data,
297
+ onTokenRotated: options?.onTokenRotated
298
+ });
299
+ },
300
+ /**
301
+ * Change password
302
+ */
303
+ changePassword: async (sessionToken, currentPassword, newPassword, options) => {
304
+ return this.request("POST", "/v1/auth/change-password", {
305
+ sessionToken,
306
+ body: { current_password: currentPassword, new_password: newPassword },
307
+ onTokenRotated: options?.onTokenRotated
308
+ });
309
+ },
310
+ /**
311
+ * Change email
312
+ */
313
+ changeEmail: async (sessionToken, newEmail, password, options) => {
314
+ return this.request("POST", "/v1/auth/change-email", {
315
+ sessionToken,
316
+ body: { new_email: newEmail, password },
317
+ onTokenRotated: options?.onTokenRotated
318
+ });
319
+ },
320
+ /**
321
+ * Delete account
322
+ */
323
+ deleteAccount: async (sessionToken, password, options) => {
324
+ return this.request("DELETE", "/v1/auth/me", {
325
+ sessionToken,
326
+ body: { password },
327
+ onTokenRotated: options?.onTokenRotated
328
+ });
329
+ }
330
+ };
331
+ // ==========================================================================
332
+ // Storage/Content Methods
333
+ // ==========================================================================
334
+ // ==========================================================================
335
+ // Secrets Methods (Tenant Vault)
336
+ // ==========================================================================
337
+ this.secrets = {
338
+ /**
339
+ * Get a secret from the tenant vault
340
+ *
341
+ * @example
342
+ * ```typescript
343
+ * const result = await scalemule.secrets.get('ANONYMOUS_USER_SALT')
344
+ * if (result.success) {
345
+ * console.log('Salt:', result.data.value)
346
+ * }
347
+ * ```
348
+ */
349
+ get: async (key) => {
350
+ return this.request("GET", `/v1/vault/secrets/${encodeURIComponent(key)}`);
351
+ },
352
+ /**
353
+ * Set a secret in the tenant vault
354
+ *
355
+ * @example
356
+ * ```typescript
357
+ * await scalemule.secrets.set('ANONYMOUS_USER_SALT', 'my-secret-salt')
358
+ * ```
359
+ */
360
+ set: async (key, value) => {
361
+ return this.request("PUT", `/v1/vault/secrets/${encodeURIComponent(key)}`, {
362
+ body: { value }
363
+ });
364
+ },
365
+ /**
366
+ * Delete a secret from the tenant vault
367
+ */
368
+ delete: async (key) => {
369
+ return this.request("DELETE", `/v1/vault/secrets/${encodeURIComponent(key)}`);
370
+ },
371
+ /**
372
+ * List all secrets in the tenant vault
373
+ */
374
+ list: async () => {
375
+ return this.request("GET", "/v1/vault/secrets");
376
+ },
377
+ /**
378
+ * Get secret version history
379
+ */
380
+ versions: async (key) => {
381
+ return this.request(
382
+ "GET",
383
+ `/v1/vault/versions/${encodeURIComponent(key)}`
384
+ );
385
+ },
386
+ /**
387
+ * Rollback to a specific version
388
+ */
389
+ rollback: async (key, version) => {
390
+ return this.request(
391
+ "POST",
392
+ `/v1/vault/actions/rollback/${encodeURIComponent(key)}`,
393
+ { body: { version } }
394
+ );
395
+ },
396
+ /**
397
+ * Rotate a secret (copy current version as new version)
398
+ */
399
+ rotate: async (key, newValue) => {
400
+ return this.request(
401
+ "POST",
402
+ `/v1/vault/actions/rotate/${encodeURIComponent(key)}`,
403
+ { body: { value: newValue } }
404
+ );
405
+ }
406
+ };
407
+ // ==========================================================================
408
+ // Bundle Methods (Structured Secrets with Inheritance)
409
+ // ==========================================================================
410
+ this.bundles = {
411
+ /**
412
+ * Get a bundle (structured secret like database credentials)
413
+ *
414
+ * @param key - Bundle key (e.g., 'database/prod')
415
+ * @param resolve - Whether to resolve inheritance (default: true)
416
+ *
417
+ * @example
418
+ * ```typescript
419
+ * const result = await scalemule.bundles.get('database/prod')
420
+ * if (result.success) {
421
+ * console.log('DB Host:', result.data.data.host)
422
+ * }
423
+ * ```
424
+ */
425
+ get: async (key, resolve = true) => {
426
+ const params = new URLSearchParams({ resolve: resolve.toString() });
427
+ return this.request(
428
+ "GET",
429
+ `/v1/vault/bundles/${encodeURIComponent(key)}?${params}`
430
+ );
431
+ },
432
+ /**
433
+ * Set a bundle (structured secret)
434
+ *
435
+ * @param key - Bundle key
436
+ * @param type - Bundle type: 'mysql', 'postgres', 'redis', 's3', 'oauth', 'smtp', 'generic'
437
+ * @param data - Bundle data (structure depends on type)
438
+ * @param inheritsFrom - Optional parent bundle key for inheritance
439
+ *
440
+ * @example
441
+ * ```typescript
442
+ * // Create a MySQL bundle
443
+ * await scalemule.bundles.set('database/prod', 'mysql', {
444
+ * host: 'db.example.com',
445
+ * port: 3306,
446
+ * username: 'app',
447
+ * password: 'secret',
448
+ * database: 'myapp'
449
+ * })
450
+ *
451
+ * // Create a bundle that inherits from another
452
+ * await scalemule.bundles.set('database/staging', 'mysql', {
453
+ * host: 'staging-db.example.com', // Override just the host
454
+ * }, 'database/prod')
455
+ * ```
456
+ */
457
+ set: async (key, type, data, inheritsFrom) => {
458
+ return this.request(
459
+ "PUT",
460
+ `/v1/vault/bundles/${encodeURIComponent(key)}`,
461
+ {
462
+ body: {
463
+ type,
464
+ value: data,
465
+ inherits_from: inheritsFrom
466
+ }
467
+ }
468
+ );
469
+ },
470
+ /**
471
+ * Delete a bundle
472
+ */
473
+ delete: async (key) => {
474
+ return this.request("DELETE", `/v1/vault/bundles/${encodeURIComponent(key)}`);
475
+ },
476
+ /**
477
+ * List all bundles
478
+ */
479
+ list: async () => {
480
+ return this.request(
481
+ "GET",
482
+ "/v1/vault/bundles"
483
+ );
484
+ },
485
+ /**
486
+ * Get connection URL for a database bundle
487
+ *
488
+ * @example
489
+ * ```typescript
490
+ * const result = await scalemule.bundles.connectionUrl('database/prod')
491
+ * if (result.success) {
492
+ * const client = mysql.createConnection(result.data.url)
493
+ * }
494
+ * ```
495
+ */
496
+ connectionUrl: async (key) => {
497
+ return this.request(
498
+ "GET",
499
+ `/v1/vault/bundles/${encodeURIComponent(key)}?connection_url=true`
500
+ );
501
+ }
502
+ };
503
+ // ==========================================================================
504
+ // Vault Audit Methods
505
+ // ==========================================================================
506
+ this.vaultAudit = {
507
+ /**
508
+ * Query audit logs for your tenant's vault operations
509
+ *
510
+ * @example
511
+ * ```typescript
512
+ * const result = await scalemule.vaultAudit.query({
513
+ * action: 'read',
514
+ * path: 'database/*',
515
+ * since: '2026-01-01'
516
+ * })
517
+ * ```
518
+ */
519
+ query: async (options) => {
520
+ const params = new URLSearchParams();
521
+ if (options?.action) params.set("action", options.action);
522
+ if (options?.path) params.set("path", options.path);
523
+ if (options?.since) params.set("since", options.since);
524
+ if (options?.until) params.set("until", options.until);
525
+ if (options?.limit) params.set("limit", options.limit.toString());
526
+ const queryStr = params.toString();
527
+ return this.request("GET", `/v1/vault/audit${queryStr ? `?${queryStr}` : ""}`);
528
+ }
529
+ };
530
+ this.storage = {
531
+ /**
532
+ * List user's files
533
+ */
534
+ list: async (userId, params) => {
535
+ const query = new URLSearchParams();
536
+ if (params?.content_type) query.set("content_type", params.content_type);
537
+ if (params?.search) query.set("search", params.search);
538
+ if (params?.limit) query.set("limit", params.limit.toString());
539
+ if (params?.offset) query.set("offset", params.offset.toString());
540
+ const queryStr = query.toString();
541
+ const path = `/v1/storage/my-files${queryStr ? `?${queryStr}` : ""}`;
542
+ return this.request("GET", path, { userId });
543
+ },
544
+ /**
545
+ * Get file info
546
+ */
547
+ get: async (fileId) => {
548
+ return this.request("GET", `/v1/storage/files/${fileId}/info`);
549
+ },
550
+ /**
551
+ * Delete file
552
+ */
553
+ delete: async (userId, fileId) => {
554
+ return this.request("DELETE", `/v1/storage/files/${fileId}`, { userId });
555
+ },
556
+ /**
557
+ * Upload file (from server - use FormData)
558
+ *
559
+ * @param userId - The user ID who owns this file
560
+ * @param file - File data to upload
561
+ * @param options - Upload options
562
+ * @param options.clientContext - End user context to forward (IP, user agent, etc.)
563
+ *
564
+ * @example
565
+ * ```typescript
566
+ * // Forward end user context for proper attribution
567
+ * const result = await scalemule.storage.upload(
568
+ * userId,
569
+ * { buffer, filename, contentType },
570
+ * { clientContext: extractClientContext(request) }
571
+ * )
572
+ * ```
573
+ */
574
+ upload: async (userId, file, options) => {
575
+ const formData = new FormData();
576
+ const blob = new Blob([file.buffer], { type: file.contentType });
577
+ formData.append("file", blob, file.filename);
578
+ formData.append("sm_user_id", userId);
579
+ const url = `${this.gatewayUrl}/v1/storage/upload`;
580
+ const headers2 = {
581
+ "x-api-key": this.apiKey,
582
+ "x-user-id": userId,
583
+ ...buildClientContextHeaders(options?.clientContext)
584
+ };
585
+ if (this.debug && options?.clientContext) {
586
+ console.log(`[ScaleMule Server] Upload with client context: IP=${options.clientContext.ip}`);
587
+ }
588
+ try {
589
+ const response = await fetch(url, {
590
+ method: "POST",
591
+ headers: headers2,
592
+ body: formData
593
+ });
594
+ const text = await response.text();
595
+ let responseData = null;
596
+ try {
597
+ responseData = text ? JSON.parse(text) : null;
598
+ } catch {
599
+ }
600
+ if (!response.ok) {
601
+ throw new ScaleMuleApiError(
602
+ withErrorContext(
603
+ responseData?.error || { code: "UPLOAD_FAILED", message: text || "Upload failed" },
604
+ responseData,
605
+ response.headers
606
+ )
607
+ );
608
+ }
609
+ const data = responseData?.data !== void 0 ? responseData.data : responseData;
610
+ return data;
611
+ } catch (err) {
612
+ if (err instanceof ScaleMuleApiError) {
613
+ throw err;
614
+ }
615
+ throw new ScaleMuleApiError({
616
+ code: "UPLOAD_ERROR",
617
+ message: err instanceof Error ? err.message : "Upload failed"
618
+ });
619
+ }
620
+ }
621
+ };
622
+ // ==========================================================================
623
+ // Analytics Methods
624
+ // ==========================================================================
625
+ // ==========================================================================
626
+ // Webhooks Methods
627
+ // ==========================================================================
628
+ this.webhooks = {
629
+ /**
630
+ * Create a new webhook subscription
631
+ *
632
+ * @example
633
+ * ```typescript
634
+ * const result = await scalemule.webhooks.create({
635
+ * webhook_name: 'Video Status Webhook',
636
+ * url: 'https://myapp.com/api/webhooks/scalemule',
637
+ * events: ['video.ready', 'video.failed']
638
+ * })
639
+ *
640
+ * // Store the secret for signature verification
641
+ * console.log('Webhook secret:', result.secret)
642
+ * ```
643
+ */
644
+ create: async (data) => {
645
+ return this.request(
646
+ "POST",
647
+ "/v1/webhooks",
648
+ { body: data }
649
+ );
650
+ },
651
+ /**
652
+ * List all webhook subscriptions
653
+ */
654
+ list: async () => {
655
+ return this.request("GET", "/v1/webhooks");
656
+ },
657
+ /**
658
+ * Delete a webhook subscription
659
+ */
660
+ delete: async (id) => {
661
+ return this.request("DELETE", `/v1/webhooks/${id}`);
662
+ },
663
+ /**
664
+ * Update a webhook subscription
665
+ */
666
+ update: async (id, data) => {
667
+ return this.request(
668
+ "PATCH",
669
+ `/v1/webhooks/${id}`,
670
+ { body: data }
671
+ );
672
+ },
673
+ /**
674
+ * Get available webhook event types
675
+ */
676
+ eventTypes: async () => {
677
+ return this.request("GET", "/v1/webhooks/events");
678
+ }
679
+ };
680
+ // ==========================================================================
681
+ // Analytics Methods
682
+ // ==========================================================================
683
+ this.analytics = {
684
+ /**
685
+ * Track an analytics event
686
+ *
687
+ * IMPORTANT: When calling from server-side code (API routes), always pass
688
+ * clientContext to ensure the real end user's IP is recorded, not the server's IP.
689
+ *
690
+ * @example
691
+ * ```typescript
692
+ * // In an API route
693
+ * import { extractClientContext, createServerClient } from '@scalemule/nextjs/server'
694
+ *
695
+ * export async function POST(request: NextRequest) {
696
+ * const clientContext = extractClientContext(request)
697
+ * const scalemule = createServerClient()
698
+ *
699
+ * await scalemule.analytics.trackEvent({
700
+ * event_name: 'button_clicked',
701
+ * properties: { button_id: 'signup' }
702
+ * }, { clientContext })
703
+ * }
704
+ * ```
705
+ */
706
+ trackEvent: async (event, options) => {
707
+ return this.request("POST", "/v1/analytics/v2/events", {
708
+ body: event,
709
+ clientContext: options?.clientContext
710
+ });
711
+ },
712
+ /**
713
+ * Track that a visitor saw an experiment variant (once per visitor and flag). The event carries
714
+ * `properties.experiments` so the analytics experiment report attributes it.
715
+ */
716
+ trackExposure: async (flagKey, variant, data, options) => {
717
+ const event = sdk.exposureEvent(flagKey, variant);
718
+ return this.request("POST", "/v1/analytics/v2/events", {
719
+ body: { ...event, ...data ?? {} },
720
+ clientContext: options?.clientContext
721
+ });
722
+ },
723
+ /**
724
+ * Track a page view
725
+ *
726
+ * @example
727
+ * ```typescript
728
+ * await scalemule.analytics.trackPageView({
729
+ * page_url: 'https://example.com/products',
730
+ * page_title: 'Products',
731
+ * referrer: 'https://google.com'
732
+ * }, { clientContext })
733
+ * ```
734
+ */
735
+ trackPageView: async (data, options) => {
736
+ return this.request("POST", "/v1/analytics/v2/events", {
737
+ body: {
738
+ event_name: "page_viewed",
739
+ event_category: "navigation",
740
+ page_url: data.page_url,
741
+ properties: {
742
+ page_title: data.page_title,
743
+ referrer: data.referrer
744
+ },
745
+ session_id: data.session_id,
746
+ user_id: data.user_id
747
+ },
748
+ clientContext: options?.clientContext
749
+ });
750
+ },
751
+ /**
752
+ * Track multiple events in a batch (max 100)
753
+ *
754
+ * @example
755
+ * ```typescript
756
+ * await scalemule.analytics.trackBatch([
757
+ * { event_name: 'item_viewed', properties: { item_id: '123' } },
758
+ * { event_name: 'item_added_to_cart', properties: { item_id: '123' } }
759
+ * ], { clientContext })
760
+ * ```
761
+ */
762
+ trackBatch: async (events, options) => {
763
+ return this.request("POST", "/v1/analytics/v2/events/batch", {
764
+ body: { events },
765
+ clientContext: options?.clientContext
766
+ });
767
+ }
768
+ };
769
+ this.flags = {
770
+ /**
771
+ * Assign a visitor to an experiment (a flag with weighted variants). Pass a stable identifier
772
+ * (`session_id` or `user_id`) so the assignment is sticky. Attach the returned assignment to
773
+ * every analytics event as `properties.experiments` and track one `experiment_exposed` with
774
+ * `analytics.trackExposure` when the variant is shown.
775
+ *
776
+ * @example
777
+ * ```typescript
778
+ * const { variant } = await scalemule.flags.experiment('front_page_layout', { session_id: visitorId })
779
+ * ```
780
+ */
781
+ experiment: async (flagKey, context = {}, environment = "prod", options) => {
782
+ const evaluation = await this.flags.evaluate(flagKey, context, environment, options);
783
+ return { flag_key: flagKey, variant: sdk.experimentVariant(evaluation), evaluation };
784
+ },
785
+ evaluate: async (flagKey, context = {}, environment = "prod", options) => {
786
+ return this.request("POST", "/v1/flags/evaluate", {
787
+ body: {
788
+ flag_key: flagKey,
789
+ environment,
790
+ context
791
+ },
792
+ clientContext: options?.clientContext
793
+ });
794
+ },
795
+ evaluateBatch: async (flagKeys, context = {}, environment = "prod", options) => {
796
+ return this.request("POST", "/v1/flags/evaluate/batch", {
797
+ body: {
798
+ flag_keys: flagKeys,
799
+ environment,
800
+ context
801
+ },
802
+ clientContext: options?.clientContext
803
+ });
804
+ },
805
+ evaluateAll: async (context = {}, environment = "prod", options) => {
806
+ return this.request("POST", "/v1/flags/evaluate/all", {
807
+ body: {
808
+ environment,
809
+ context
810
+ },
811
+ clientContext: options?.clientContext
812
+ });
813
+ }
814
+ };
815
+ this.apiKey = config.apiKey;
816
+ this.gatewayUrl = resolveGatewayUrl(config);
817
+ this.debug = config.debug || false;
818
+ this.onRefreshStart = config.onRefreshStart;
819
+ this.onRefreshEnd = config.onRefreshEnd;
820
+ this.onAutoRefreshFailed = config.onAutoRefreshFailed;
821
+ this.money = money.createMoneyClient({
822
+ apiKey: this.apiKey,
823
+ gatewayUrl: this.gatewayUrl,
824
+ fetch: globalThis.fetch.bind(globalThis)
825
+ });
826
+ }
827
+ moneyWithSession(sessionToken) {
828
+ return this.money.withAccessToken(sessionToken);
829
+ }
830
+ /**
831
+ * Make a request to the ScaleMule API
832
+ *
833
+ * @param method - HTTP method
834
+ * @param path - API path (e.g., /v1/auth/login)
835
+ * @param options - Request options
836
+ * @param options.body - Request body (will be JSON stringified)
837
+ * @param options.userId - User ID (passed through for storage operations)
838
+ * @param options.sessionToken - Session token sent as Authorization: Bearer header
839
+ * @param options.clientContext - End user context to forward (IP, user agent, etc.)
840
+ */
841
+ async request(method, path, options = {}) {
842
+ const url = `${this.gatewayUrl}${path}`;
843
+ const headers2 = {
844
+ "x-api-key": this.apiKey,
845
+ "Content-Type": "application/json",
846
+ // Forward client context headers if provided
847
+ ...buildClientContextHeaders(options.clientContext)
848
+ };
849
+ if (options.sessionToken) {
850
+ headers2["Authorization"] = `Bearer ${options.sessionToken}`;
851
+ }
852
+ if (this.debug) {
853
+ console.log(`[ScaleMule Server] ${method} ${path}`);
854
+ if (options.clientContext) {
855
+ console.log(`[ScaleMule Server] Client context: IP=${options.clientContext.ip}, UA=${options.clientContext.userAgent?.substring(0, 50)}...`);
856
+ }
857
+ }
858
+ try {
859
+ const response = await fetch(url, {
860
+ method,
861
+ headers: headers2,
862
+ body: options.body ? JSON.stringify(options.body) : void 0
863
+ });
864
+ const rotated = response.headers.get("x-rotated-session-token");
865
+ if (rotated && options.onTokenRotated) {
866
+ options.onTokenRotated(rotated);
867
+ }
868
+ const text = await response.text();
869
+ let responseData = null;
870
+ try {
871
+ responseData = text ? JSON.parse(text) : null;
872
+ } catch {
873
+ }
874
+ if (!response.ok || responseData?.success === false) {
875
+ const baseError = responseData?.error || {
876
+ code: `HTTP_${response.status}`,
877
+ message: responseData?.message || text || response.statusText
878
+ };
879
+ const error2 = withErrorContext(baseError, responseData, response.headers);
880
+ if (response.status === 401 && options.sessionToken && !options.isAutoRefresh) {
881
+ if (this.debug) console.log("[ScaleMule Server] 401 received, attempting auto-refresh...");
882
+ try {
883
+ this.onRefreshStart?.();
884
+ const refreshData = await this.auth.refresh(options.sessionToken, {
885
+ clientContext: options.clientContext,
886
+ isAutoRefresh: true
887
+ // Prevent infinite loops
888
+ });
889
+ const newToken = refreshData.session_token;
890
+ if (this.debug) console.log("[ScaleMule Server] Auto-refresh succeeded, retrying original request...");
891
+ options.onTokenRotated?.(newToken);
892
+ return this.request(method, path, {
893
+ ...options,
894
+ sessionToken: newToken,
895
+ isAutoRefresh: true
896
+ // Don't refresh again on this retry
897
+ });
898
+ } catch (refreshErr) {
899
+ if (this.debug) console.error("[ScaleMule Server] Auto-refresh failed:", refreshErr);
900
+ const refreshApiError = refreshErr instanceof ScaleMuleApiError ? { code: refreshErr.code, message: refreshErr.message } : { code: "REFRESH_FAILED", message: "Auto-refresh failed" };
901
+ this.onAutoRefreshFailed?.(refreshApiError);
902
+ throw new ScaleMuleApiError(error2, response.status);
903
+ } finally {
904
+ this.onRefreshEnd?.();
905
+ }
906
+ }
907
+ throw new ScaleMuleApiError(error2, response.status);
908
+ }
909
+ const data = responseData?.data !== void 0 ? responseData.data : responseData;
910
+ return data;
911
+ } catch (err) {
912
+ if (err instanceof ScaleMuleApiError) {
913
+ throw err;
914
+ }
915
+ throw new ScaleMuleApiError({
916
+ code: "SERVER_ERROR",
917
+ message: err instanceof Error ? err.message : "Request failed"
918
+ });
919
+ }
920
+ }
921
+ };
922
+ function createServerClient(config) {
923
+ const apiKey = config?.apiKey || process.env.SCALEMULE_API_KEY;
924
+ if (!apiKey) {
925
+ throw new Error(
926
+ "ScaleMule API key is required. Set SCALEMULE_API_KEY environment variable or pass apiKey in config."
927
+ );
928
+ }
929
+ const environment = config?.environment || process.env.SCALEMULE_ENV || "prod";
930
+ return new ScaleMuleServer({
931
+ apiKey,
932
+ environment,
933
+ gatewayUrl: config?.gatewayUrl,
934
+ debug: config?.debug || process.env.SCALEMULE_DEBUG === "true"
935
+ });
936
+ }
937
+ var SESSION_COOKIE_NAME = "sm_session";
938
+ var USER_ID_COOKIE_NAME = "sm_user_id";
939
+ var KNOWN_ACCOUNTS_COOKIE_NAME = "sm_known_accounts";
940
+ ({
941
+ secure: process.env.NODE_ENV === "production"});
942
+ function createCookieHeader(name, value, options = {}) {
943
+ const maxAge = options.maxAge ?? 7 * 24 * 60 * 60;
944
+ const secure = options.secure ?? process.env.NODE_ENV === "production";
945
+ const sameSite = options.sameSite ?? "lax";
946
+ const path = options.path ?? "/";
947
+ let cookie = `${name}=${encodeURIComponent(value)}; Path=${path}; Max-Age=${maxAge}; HttpOnly; SameSite=${sameSite}`;
948
+ if (secure || options.partitioned) {
949
+ cookie += "; Secure";
950
+ }
951
+ if (options.partitioned) cookie += "; Partitioned";
952
+ if (options.domain) {
953
+ cookie += `; Domain=${options.domain}`;
954
+ }
955
+ return cookie;
956
+ }
957
+ function createClearCookieHeader(name, options = {}) {
958
+ const path = options.path ?? "/";
959
+ const secure = options.secure ?? process.env.NODE_ENV === "production";
960
+ const sameSite = options.sameSite ?? "lax";
961
+ let cookie = `${name}=; Path=${path}; Max-Age=0; HttpOnly; SameSite=${sameSite}`;
962
+ if (secure || options.partitioned) {
963
+ cookie += "; Secure";
964
+ }
965
+ if (options.partitioned) cookie += "; Partitioned";
966
+ if (options.domain) {
967
+ cookie += `; Domain=${options.domain}`;
968
+ }
969
+ return cookie;
970
+ }
971
+ function withSession(loginResponse, responseBody, options = {}) {
972
+ const headers2 = new Headers();
973
+ headers2.set("Content-Type", "application/json");
974
+ if (options.partitioned) {
975
+ headers2.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, { ...options, partitioned: false }));
976
+ headers2.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, { ...options, partitioned: false }));
977
+ }
978
+ headers2.append(
979
+ "Set-Cookie",
980
+ createCookieHeader(SESSION_COOKIE_NAME, loginResponse.session_token, options)
981
+ );
982
+ headers2.append(
983
+ "Set-Cookie",
984
+ createCookieHeader(USER_ID_COOKIE_NAME, loginResponse.user.id, options)
985
+ );
986
+ return new Response(JSON.stringify({ success: true, data: responseBody }), {
987
+ status: 200,
988
+ headers: headers2
989
+ });
990
+ }
991
+ function withRefreshedSession(sessionToken, userId, responseBody, options = {}) {
992
+ const headers2 = new Headers();
993
+ headers2.set("Content-Type", "application/json");
994
+ if (options.partitioned) {
995
+ headers2.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, { ...options, partitioned: false }));
996
+ headers2.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, { ...options, partitioned: false }));
997
+ }
998
+ headers2.append(
999
+ "Set-Cookie",
1000
+ createCookieHeader(SESSION_COOKIE_NAME, sessionToken, options)
1001
+ );
1002
+ headers2.append(
1003
+ "Set-Cookie",
1004
+ createCookieHeader(USER_ID_COOKIE_NAME, userId, options)
1005
+ );
1006
+ return new Response(JSON.stringify({ success: true, data: responseBody }), {
1007
+ status: 200,
1008
+ headers: headers2
1009
+ });
1010
+ }
1011
+ function clearSession(responseBody, options = {}, status = 200) {
1012
+ const headers2 = new Headers();
1013
+ headers2.set("Content-Type", "application/json");
1014
+ appendClearSessionCookies(headers2, options);
1015
+ return new Response(JSON.stringify({ success: status < 300, data: responseBody }), {
1016
+ status,
1017
+ headers: headers2
1018
+ });
1019
+ }
1020
+ function appendClearSessionCookies(headers2, options) {
1021
+ if (options.partitioned) {
1022
+ headers2.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, { ...options, partitioned: false }));
1023
+ headers2.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, { ...options, partitioned: false }));
1024
+ }
1025
+ headers2.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, options));
1026
+ headers2.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, options));
1027
+ }
1028
+ function clearSessionWithError(error2, options = {}, status = 401) {
1029
+ const headers2 = new Headers();
1030
+ headers2.set("Content-Type", "application/json");
1031
+ appendClearSessionCookies(headers2, options);
1032
+ return new Response(JSON.stringify({ success: false, error: error2 }), {
1033
+ status,
1034
+ headers: headers2
1035
+ });
1036
+ }
1037
+ async function getSession(options = {}) {
1038
+ const cookieStore = await headers.cookies();
1039
+ const sessionCookie = cookieStore.get(SESSION_COOKIE_NAME);
1040
+ const userIdCookie = cookieStore.get(USER_ID_COOKIE_NAME);
1041
+ if (sessionCookie?.value && userIdCookie?.value) {
1042
+ return {
1043
+ sessionToken: sessionCookie.value,
1044
+ userId: userIdCookie.value,
1045
+ expiresAt: /* @__PURE__ */ new Date()
1046
+ // Note: actual expiry is managed by ScaleMule backend
1047
+ };
1048
+ }
1049
+ if (options.allowBearer === false) return null;
1050
+ const headerStore = await headers.headers();
1051
+ return sessionFromAuthHeaders(
1052
+ headerStore.get("authorization"),
1053
+ headerStore.get("x-sm-user-id")
1054
+ );
1055
+ }
1056
+ function sessionFromAuthHeaders(authorization, userId) {
1057
+ if (!authorization || !userId) return null;
1058
+ const match = /^Bearer\s+(.+)$/i.exec(authorization.trim());
1059
+ const token = match?.[1]?.trim();
1060
+ if (!token) return null;
1061
+ return {
1062
+ sessionToken: token,
1063
+ userId,
1064
+ expiresAt: /* @__PURE__ */ new Date()
1065
+ };
1066
+ }
1067
+ var MAX_KNOWN_ACCOUNTS = 10;
1068
+ function maskEmail(email) {
1069
+ const [local, domain] = email.split("@");
1070
+ if (!domain) return "***@***.***";
1071
+ const tldDot = domain.lastIndexOf(".");
1072
+ const tld = tldDot > 0 ? domain.slice(tldDot) : "";
1073
+ const domainBase = tldDot > 0 ? domain.slice(0, tldDot) : domain;
1074
+ return `${local[0] || "*"}***@${domainBase[0] || "*"}***${tld}`;
1075
+ }
1076
+ function stableColorIndex(userId) {
1077
+ let hash = 0;
1078
+ for (let i = 0; i < userId.length; i++) {
1079
+ hash = (hash << 5) - hash + userId.charCodeAt(i) | 0;
1080
+ }
1081
+ return Math.abs(hash) % 8;
1082
+ }
1083
+ function applyPrivacyToEntry(entry, privacy) {
1084
+ switch (privacy) {
1085
+ case "full":
1086
+ return entry;
1087
+ case "masked":
1088
+ return {
1089
+ userId: entry.userId,
1090
+ email: entry.email ? maskEmail(entry.email) : void 0,
1091
+ fullName: entry.fullName ? `${entry.fullName[0].toUpperCase()}.` : void 0,
1092
+ provider: entry.provider,
1093
+ lastActiveAt: entry.lastActiveAt,
1094
+ colorIndex: stableColorIndex(entry.userId)
1095
+ };
1096
+ case "minimal":
1097
+ return {
1098
+ userId: entry.userId,
1099
+ provider: entry.provider,
1100
+ lastActiveAt: entry.lastActiveAt,
1101
+ displayLabel: "Account",
1102
+ colorIndex: stableColorIndex(entry.userId)
1103
+ };
1104
+ }
1105
+ }
1106
+ function appendKnownAccountCookie(headers2, account, existingCookie, options = {}, privacy) {
1107
+ let accounts = {};
1108
+ if (existingCookie) {
1109
+ try {
1110
+ accounts = JSON.parse(decodeURIComponent(existingCookie));
1111
+ } catch {
1112
+ }
1113
+ }
1114
+ const effectivePrivacy = privacy || "full";
1115
+ for (const [userId, entry] of Object.entries(accounts)) {
1116
+ accounts[userId] = applyPrivacyToEntry(entry, effectivePrivacy);
1117
+ }
1118
+ accounts[account.userId] = applyPrivacyToEntry(account, effectivePrivacy);
1119
+ const entries = Object.entries(accounts);
1120
+ if (entries.length > MAX_KNOWN_ACCOUNTS) {
1121
+ entries.sort((a, b) => new Date(b[1].lastActiveAt).getTime() - new Date(a[1].lastActiveAt).getTime());
1122
+ accounts = Object.fromEntries(entries.slice(0, MAX_KNOWN_ACCOUNTS));
1123
+ }
1124
+ const maxAge = 365 * 24 * 60 * 60;
1125
+ const secure = options.secure ?? process.env.NODE_ENV === "production";
1126
+ const sameSite = options.sameSite ?? "lax";
1127
+ const path = options.path ?? "/";
1128
+ let cookie = `${KNOWN_ACCOUNTS_COOKIE_NAME}=${encodeURIComponent(JSON.stringify(accounts))}; Path=${path}; Max-Age=${maxAge}; SameSite=${sameSite}`;
1129
+ if (secure) {
1130
+ cookie += "; Secure";
1131
+ }
1132
+ if (options.domain) {
1133
+ cookie += `; Domain=${options.domain}`;
1134
+ }
1135
+ headers2.append("Set-Cookie", cookie);
1136
+ }
1137
+ function removeKnownAccountFromCookie(headers2, userId, existingCookie, options = {}) {
1138
+ let accounts = {};
1139
+ if (existingCookie) {
1140
+ try {
1141
+ accounts = JSON.parse(decodeURIComponent(existingCookie));
1142
+ } catch {
1143
+ }
1144
+ }
1145
+ delete accounts[userId];
1146
+ const maxAge = 365 * 24 * 60 * 60;
1147
+ const secure = options.secure ?? process.env.NODE_ENV === "production";
1148
+ const sameSite = options.sameSite ?? "lax";
1149
+ const path = options.path ?? "/";
1150
+ let cookie = `${KNOWN_ACCOUNTS_COOKIE_NAME}=${encodeURIComponent(JSON.stringify(accounts))}; Path=${path}; Max-Age=${maxAge}; SameSite=${sameSite}`;
1151
+ if (secure) {
1152
+ cookie += "; Secure";
1153
+ }
1154
+ if (options.domain) {
1155
+ cookie += `; Domain=${options.domain}`;
1156
+ }
1157
+ headers2.append("Set-Cookie", cookie);
1158
+ }
1159
+ function clearKnownAccountsCookie(headers2, options = {}) {
1160
+ const path = options.path ?? "/";
1161
+ let cookie = `${KNOWN_ACCOUNTS_COOKIE_NAME}=; Path=${path}; Max-Age=0`;
1162
+ if (options.domain) {
1163
+ cookie += `; Domain=${options.domain}`;
1164
+ }
1165
+ headers2.append("Set-Cookie", cookie);
1166
+ }
1167
+ function getKnownAccountsFromRequest(request) {
1168
+ const cookieHeader = request.headers.get("cookie");
1169
+ if (!cookieHeader) return [];
1170
+ const cookies3 = Object.fromEntries(
1171
+ cookieHeader.split(";").map((c) => {
1172
+ const [key, ...rest] = c.trim().split("=");
1173
+ return [key, decodeURIComponent(rest.join("="))];
1174
+ })
1175
+ );
1176
+ const raw = cookies3[KNOWN_ACCOUNTS_COOKIE_NAME];
1177
+ if (!raw) return [];
1178
+ try {
1179
+ const accounts = JSON.parse(raw);
1180
+ return Object.values(accounts);
1181
+ } catch {
1182
+ return [];
1183
+ }
1184
+ }
1185
+ function getKnownAccountsCookieRaw(request) {
1186
+ const cookieHeader = request.headers.get("cookie");
1187
+ if (!cookieHeader) return null;
1188
+ const cookies3 = Object.fromEntries(
1189
+ cookieHeader.split(";").map((c) => {
1190
+ const [key, ...rest] = c.trim().split("=");
1191
+ return [key, decodeURIComponent(rest.join("="))];
1192
+ })
1193
+ );
1194
+ return cookies3[KNOWN_ACCOUNTS_COOKIE_NAME] || null;
1195
+ }
1196
+ function normalizeKnownAccountsCookie(request, privacy, options = {}) {
1197
+ if (!privacy || privacy === "full") return null;
1198
+ const raw = getKnownAccountsCookieRaw(request);
1199
+ if (!raw) return null;
1200
+ let accounts = {};
1201
+ try {
1202
+ accounts = JSON.parse(raw);
1203
+ } catch {
1204
+ return null;
1205
+ }
1206
+ let changed = false;
1207
+ for (const [userId, entry] of Object.entries(accounts)) {
1208
+ const normalized = applyPrivacyToEntry(entry, privacy);
1209
+ if (JSON.stringify(normalized) !== JSON.stringify(entry)) {
1210
+ accounts[userId] = normalized;
1211
+ changed = true;
1212
+ }
1213
+ }
1214
+ if (!changed) return null;
1215
+ const maxAge = 365 * 24 * 60 * 60;
1216
+ const secure = options.secure ?? process.env.NODE_ENV === "production";
1217
+ const sameSite = options.sameSite ?? "lax";
1218
+ const path = options.path ?? "/";
1219
+ let cookie = `${KNOWN_ACCOUNTS_COOKIE_NAME}=${encodeURIComponent(JSON.stringify(accounts))}; Path=${path}; Max-Age=${maxAge}; SameSite=${sameSite}`;
1220
+ if (secure) cookie += "; Secure";
1221
+ if (options.domain) cookie += `; Domain=${options.domain}`;
1222
+ return cookie;
1223
+ }
1224
+
1225
+ // src/server/timing.ts
1226
+ function constantTimeEqual(a, b) {
1227
+ const maxLength = Math.max(a.length, b.length);
1228
+ let mismatch = a.length ^ b.length;
1229
+ for (let i = 0; i < maxLength; i++) {
1230
+ const aCode = i < a.length ? a.charCodeAt(i) : 0;
1231
+ const bCode = i < b.length ? b.charCodeAt(i) : 0;
1232
+ mismatch |= aCode ^ bCode;
1233
+ }
1234
+ return mismatch === 0;
1235
+ }
1236
+
1237
+ // src/server/csrf.ts
1238
+ var CSRF_COOKIE_NAME = "sm_csrf";
1239
+ var CSRF_HEADER_NAME = "x-csrf-token";
1240
+ function validateCSRFToken(request) {
1241
+ const cookieToken = request.cookies.get(CSRF_COOKIE_NAME)?.value;
1242
+ if (!cookieToken) {
1243
+ return "Missing CSRF cookie";
1244
+ }
1245
+ const headerToken = request.headers.get(CSRF_HEADER_NAME);
1246
+ if (!headerToken) {
1247
+ return "Missing CSRF token header";
1248
+ }
1249
+ if (!constantTimeEqual(cookieToken, headerToken)) {
1250
+ return "CSRF token mismatch";
1251
+ }
1252
+ return void 0;
1253
+ }
1254
+
1255
+ // src/server/browser-proxy.ts
1256
+ function error(code, status) {
1257
+ return Response.json({ success: false, error: { code, message: code === "UNAUTHORIZED" ? "Authentication required" : "Request not permitted" } }, { status, headers: { "Cache-Control": "no-store" } });
1258
+ }
1259
+ function isSameOriginRequest(request) {
1260
+ const origin = request.headers.get("origin");
1261
+ const site = request.headers.get("sec-fetch-site");
1262
+ if (site) return site === "same-origin" || site === "none";
1263
+ const url = new URL(request.url);
1264
+ const host = request.headers.get("host") || url.host;
1265
+ if (origin) {
1266
+ try {
1267
+ const source = new URL(origin);
1268
+ if (!["http:", "https:"].includes(source.protocol) || source.host !== host) return false;
1269
+ } catch {
1270
+ return false;
1271
+ }
1272
+ }
1273
+ return true;
1274
+ }
1275
+ 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"]);
1276
+ var AUTH_ROUTES = /* @__PURE__ */ new Set([
1277
+ "GET me",
1278
+ "GET mfa/status",
1279
+ "GET oauth/providers",
1280
+ "PATCH profile",
1281
+ "POST change-password",
1282
+ "POST change-email",
1283
+ "POST delete-account",
1284
+ "POST export-data",
1285
+ "POST mfa/setup",
1286
+ "POST mfa/verify",
1287
+ "POST mfa/disable",
1288
+ "POST mfa/backup-codes",
1289
+ "POST oauth/start",
1290
+ "POST oauth/callback"
1291
+ ]);
1292
+ var PUBLIC_AUTH_ROUTES = /* @__PURE__ */ new Set(["POST oauth/start", "POST oauth/callback"]);
1293
+ 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"]);
1294
+ var MAX_BODY_BYTES = 25 * 1024 * 1024;
1295
+ async function boundedBody(request) {
1296
+ if (request.method === "GET" || request.method === "HEAD" || !request.body) return void 0;
1297
+ const reader = request.body.getReader();
1298
+ const chunks = [];
1299
+ let size = 0;
1300
+ try {
1301
+ while (true) {
1302
+ const part = await reader.read();
1303
+ if (part.done) break;
1304
+ size += part.value.byteLength;
1305
+ if (size > MAX_BODY_BYTES) {
1306
+ await reader.cancel();
1307
+ throw new Error("BODY_TOO_LARGE");
1308
+ }
1309
+ chunks.push(part.value);
1310
+ }
1311
+ } finally {
1312
+ reader.releaseLock();
1313
+ }
1314
+ const bytes = new Uint8Array(size);
1315
+ let offset = 0;
1316
+ for (const chunk of chunks) {
1317
+ bytes.set(chunk, offset);
1318
+ offset += chunk.byteLength;
1319
+ }
1320
+ return bytes;
1321
+ }
1322
+ async function browserProxy(request, path, config) {
1323
+ if (!isSameOriginRequest(request)) return error("CSRF_ERROR", 403);
1324
+ const key = config.publishableKey || process.env.NEXT_PUBLIC_SCALEMULE_PUBLISHABLE_KEY;
1325
+ if (!key?.startsWith("sm_pb_")) return error("BROWSER_KEY_NOT_CONFIGURED", 503);
1326
+ if (request.headers.get("x-api-key") !== key) return error("CSRF_ERROR", 403);
1327
+ const authOperation = `${request.method} ${path.slice(2).join("/")}`;
1328
+ const authRoute = path[1] === "auth" && (AUTH_ROUTES.has(authOperation) || request.method === "DELETE" && path[2] === "oauth" && path[3] === "providers" && path.length === 5);
1329
+ if (path[0] !== "v1" || !(SERVICES.has(path[1]) || authRoute) || path.some((part) => !part || part === "." || part === ".." || /[\\/%\u0000-\u001f]/.test(part))) return error("NOT_FOUND", 404);
1330
+ const session = await getSession({ allowBearer: false });
1331
+ if (!session && !(authRoute && PUBLIC_AUTH_ROUTES.has(authOperation)) && !PUBLIC_DATA_ROUTES.has(`${request.method} ${path.slice(1).join("/")}`)) return error("UNAUTHORIZED", 401);
1332
+ const gateway = resolveGatewayUrl({ ...config.client, gatewayUrl: config.browserGatewayUrl || process.env.NEXT_PUBLIC_SCALEMULE_GATEWAY_URL || config.client?.gatewayUrl });
1333
+ const target = new URL(`${gateway.replace(/\/$/, "")}/${path.map(encodeURIComponent).join("/")}`);
1334
+ target.search = new URL(request.url).search;
1335
+ const headers2 = new Headers({ "x-api-key": key });
1336
+ if (session) headers2.set("Authorization", `Bearer ${session.sessionToken}`);
1337
+ for (const name of ["x-anonymous-id", "origin", "content-type", "accept", "user-agent", "range", "if-none-match", "x-idempotency-key", "x-sm-workspace-id"]) {
1338
+ const value = request.headers.get(name);
1339
+ if (value) headers2.set(name, value);
1340
+ }
1341
+ try {
1342
+ const body = await boundedBody(request);
1343
+ const upstream = await fetch(target, { method: request.method, headers: headers2, body, redirect: "error", cache: "no-store", signal: AbortSignal.timeout(6e4) });
1344
+ const outputHeaders = new Headers({ "Cache-Control": "no-store", "Vary": "Cookie" });
1345
+ for (const name of ["content-type", "content-disposition", "content-range", "accept-ranges", "etag", "retry-after", "x-request-id"]) {
1346
+ const value = upstream.headers.get(name);
1347
+ if (value) outputHeaders.set(name, value);
1348
+ }
1349
+ const rotated = upstream.headers.get("x-rotated-session-token");
1350
+ if (rotated && session) {
1351
+ const refreshed = withRefreshedSession(rotated, session.userId, {}, config.cookies);
1352
+ for (const cookie of refreshed.headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
1353
+ }
1354
+ if ([204, 205, 304].includes(upstream.status)) {
1355
+ if (authOperation === "POST delete-account" && upstream.ok) {
1356
+ for (const cookie of clearSession({}, config.cookies).headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
1357
+ }
1358
+ return new Response(null, { status: upstream.status, headers: outputHeaders });
1359
+ }
1360
+ if (authRoute) {
1361
+ const payload = await upstream.json();
1362
+ const data = payload?.data || payload;
1363
+ if (authOperation === "POST delete-account" && upstream.ok && payload.success !== false) {
1364
+ for (const cookie of clearSession({}, config.cookies).headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
1365
+ }
1366
+ const token = data?.session_token;
1367
+ if (typeof token === "string" && data?.user?.id && upstream.ok && payload.success !== false) {
1368
+ const established = withSession({ session_token: token, user: data.user }, {}, config.cookies);
1369
+ for (const cookie of established.headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
1370
+ data.authenticated = true;
1371
+ }
1372
+ if (data && typeof data === "object") {
1373
+ delete data.session_token;
1374
+ delete data.sessionToken;
1375
+ delete data.refresh_token;
1376
+ delete data.access_token;
1377
+ }
1378
+ return Response.json(payload, { status: upstream.status, headers: outputHeaders });
1379
+ }
1380
+ return new Response(upstream.body, { status: upstream.status, headers: outputHeaders });
1381
+ } catch (err) {
1382
+ if (err instanceof Error && err.message === "BODY_TOO_LARGE") return error("BODY_TOO_LARGE", 413);
1383
+ console.error("[ScaleMule] Browser proxy upstream request failed");
1384
+ return error("UPSTREAM_UNAVAILABLE", 502);
1385
+ }
1386
+ }
1387
+
1388
+ // src/session-errors.ts
1389
+ var SESSION_ENDED_CODES = /* @__PURE__ */ new Set([
1390
+ "UNAUTHORIZED",
1391
+ "INVALID_SESSION",
1392
+ "SESSION_EXPIRED",
1393
+ "SESSION_IDLE_EXPIRED",
1394
+ "SESSION_ABSOLUTE_EXPIRED",
1395
+ "SESSION_REVOKED",
1396
+ "TOKEN_EXPIRED",
1397
+ "TOKEN_INVALID"
1398
+ ]);
1399
+ function isSessionEndedError(error2) {
1400
+ if (!error2 || typeof error2 !== "object") return false;
1401
+ const { status, code } = error2;
1402
+ if (status === 401) return true;
1403
+ return typeof code === "string" && SESSION_ENDED_CODES.has(code);
1404
+ }
1405
+
1406
+ // src/server/routes.ts
1407
+ function errorResponse(code, message, status) {
1408
+ return new Response(
1409
+ JSON.stringify({ success: false, error: { code, message } }),
1410
+ { status, headers: { "Content-Type": "application/json" } }
1411
+ );
1412
+ }
1413
+ function successResponse(data, status = 200) {
1414
+ return new Response(
1415
+ JSON.stringify({ success: true, data }),
1416
+ { status, headers: { "Content-Type": "application/json" } }
1417
+ );
1418
+ }
1419
+ function createAuthRoutes(config = {}) {
1420
+ const sm = createServerClient(config.client);
1421
+ const cookieOptions = config.cookies || {};
1422
+ const sessionData = (user, token) => ({
1423
+ user,
1424
+ userId: user.id,
1425
+ authenticated: true,
1426
+ ...config.sessionMode === "bearer" ? { sessionToken: token } : {}
1427
+ });
1428
+ const POST2 = async (request, context) => {
1429
+ if (config.csrf) {
1430
+ const csrfError = validateCSRFToken(request);
1431
+ if (csrfError) {
1432
+ return errorResponse("CSRF_ERROR", "CSRF validation failed", 403);
1433
+ }
1434
+ }
1435
+ const params = await context?.params;
1436
+ const path = params?.scalemule?.join("/") || "";
1437
+ try {
1438
+ const body = await request.json().catch(() => ({}));
1439
+ const clientContext = extractClientContext(request, config.clientContext);
1440
+ switch (path) {
1441
+ // ==================== Register ====================
1442
+ case "register": {
1443
+ const { email, password, full_name, username, phone, publication_code, website, company, hp_field } = body;
1444
+ if (!email || !password) {
1445
+ return errorResponse("VALIDATION_ERROR", "Email and password required", 400);
1446
+ }
1447
+ const honeypotVal = publication_code || website || company || hp_field;
1448
+ if (typeof honeypotVal === "string" && honeypotVal.trim().length > 0) {
1449
+ return successResponse(
1450
+ {
1451
+ user: {
1452
+ id: "01000000-0000-7000-8000-000000000000",
1453
+ email,
1454
+ full_name: full_name ?? null
1455
+ },
1456
+ message: "Registration successful"
1457
+ },
1458
+ 201
1459
+ );
1460
+ }
1461
+ let registeredUser;
1462
+ try {
1463
+ registeredUser = await sm.auth.register({ email, password, full_name, username, phone }, { clientContext });
1464
+ } catch (err) {
1465
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1466
+ return errorResponse(
1467
+ apiErr?.code || "REGISTER_FAILED",
1468
+ apiErr?.message || "Registration failed",
1469
+ 400
1470
+ );
1471
+ }
1472
+ if (config.onRegister) {
1473
+ await config.onRegister({ id: registeredUser.id, email: registeredUser.email });
1474
+ }
1475
+ let loginData;
1476
+ try {
1477
+ loginData = await sm.auth.login({ email, password }, { clientContext });
1478
+ } catch {
1479
+ return successResponse({ user: registeredUser, authenticated: false, message: "Registration successful" }, 201);
1480
+ }
1481
+ const registerResponse = withSession(loginData, sessionData(registeredUser, loginData.session_token), cookieOptions);
1482
+ if (config.enableAccountSwitcher) {
1483
+ const existingKnown = getKnownAccountsCookieRaw(request);
1484
+ appendKnownAccountCookie(
1485
+ registerResponse.headers,
1486
+ {
1487
+ userId: registeredUser.id,
1488
+ email: registeredUser.email,
1489
+ fullName: registeredUser.full_name ?? void 0,
1490
+ avatarUrl: registeredUser.avatar_url ?? void 0,
1491
+ provider: "email",
1492
+ lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
1493
+ },
1494
+ existingKnown,
1495
+ cookieOptions,
1496
+ config.accountSwitcherPrivacy
1497
+ );
1498
+ }
1499
+ return registerResponse;
1500
+ }
1501
+ case "handoff/exchange": {
1502
+ if (!config.handoffAudience) return errorResponse("HANDOFF_DISABLED", "Session transfer is not configured", 404);
1503
+ if (typeof body.code !== "string" || !body.code || body.code.length > 256) return errorResponse("INVALID_HANDOFF", "Invalid sign-in transfer", 400);
1504
+ const result = await sm.auth.exchangeSessionHandoff(body.code, config.handoffAudience);
1505
+ return withRefreshedSession(result.session_token, result.user_id, { authenticated: true, userId: result.user_id }, cookieOptions);
1506
+ }
1507
+ case "mfa/send-code": {
1508
+ const { pending_token, method } = body;
1509
+ if (!pending_token || !["email", "sms"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token and method required", 400);
1510
+ return successResponse(await sm.auth.sendMfaCode(pending_token, method, { clientContext }));
1511
+ }
1512
+ case "mfa/verify": {
1513
+ const { pending_token, code, method } = body;
1514
+ if (!pending_token || !code || !["totp", "email", "sms", "backup_code"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token, code, and valid method required", 400);
1515
+ const result = await sm.auth.completeMfa(pending_token, code, method, { clientContext });
1516
+ if (!result.session_token || !result.user) return errorResponse("MFA_FAILED", "Unable to complete sign-in", 400);
1517
+ await config.onLogin?.({ id: result.user.id, email: result.user.email });
1518
+ const response = withSession(result, sessionData(result.user, result.session_token), cookieOptions);
1519
+ if (config.enableAccountSwitcher) {
1520
+ appendKnownAccountCookie(response.headers, {
1521
+ userId: result.user.id,
1522
+ email: result.user.email,
1523
+ fullName: result.user.full_name ?? void 0,
1524
+ avatarUrl: result.user.avatar_url ?? void 0,
1525
+ provider: "email",
1526
+ lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
1527
+ }, getKnownAccountsCookieRaw(request), cookieOptions, config.accountSwitcherPrivacy);
1528
+ }
1529
+ return response;
1530
+ }
1531
+ // ==================== Login ====================
1532
+ case "login": {
1533
+ const { email, password, remember_me, device_fingerprint, challenge_token, challenge_code } = body;
1534
+ if (!email || !password) {
1535
+ return errorResponse("VALIDATION_ERROR", "Email and password required", 400);
1536
+ }
1537
+ let loginData;
1538
+ try {
1539
+ loginData = await sm.auth.login({ email, password, remember_me, device_fingerprint, challenge_token, challenge_code }, { clientContext });
1540
+ } catch (err) {
1541
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1542
+ const errorCode = apiErr?.code || "LOGIN_FAILED";
1543
+ let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 403 : 400;
1544
+ if (errorCode === "CHALLENGE_RATE_LIMITED") status = 429;
1545
+ if (errorCode === "INVALID_CREDENTIALS" || errorCode === "UNAUTHORIZED") status = 401;
1546
+ if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED"].includes(errorCode)) {
1547
+ status = 403;
1548
+ }
1549
+ return errorResponse(
1550
+ errorCode,
1551
+ apiErr?.message || "Login failed",
1552
+ status
1553
+ );
1554
+ }
1555
+ if (config.onLogin) {
1556
+ await config.onLogin({
1557
+ id: loginData.user.id,
1558
+ email: loginData.user.email
1559
+ });
1560
+ }
1561
+ const loginResponse = withSession(loginData, sessionData(loginData.user, loginData.session_token), cookieOptions);
1562
+ if (config.enableAccountSwitcher) {
1563
+ const existingKnown = getKnownAccountsCookieRaw(request);
1564
+ appendKnownAccountCookie(
1565
+ loginResponse.headers,
1566
+ {
1567
+ userId: loginData.user.id,
1568
+ email: loginData.user.email,
1569
+ fullName: loginData.user.full_name ?? void 0,
1570
+ avatarUrl: loginData.user.avatar_url ?? void 0,
1571
+ provider: "email",
1572
+ lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
1573
+ },
1574
+ existingKnown,
1575
+ cookieOptions,
1576
+ config.accountSwitcherPrivacy
1577
+ );
1578
+ }
1579
+ return loginResponse;
1580
+ }
1581
+ // ==================== Logout ====================
1582
+ case "logout": {
1583
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1584
+ let rotated = null;
1585
+ if (session) {
1586
+ try {
1587
+ await sm.auth.logout(session.sessionToken, {
1588
+ onTokenRotated: (newToken) => {
1589
+ rotated = newToken;
1590
+ }
1591
+ });
1592
+ } catch {
1593
+ }
1594
+ }
1595
+ if (config.onLogout) {
1596
+ await config.onLogout();
1597
+ }
1598
+ return clearSession({ message: "Logged out successfully" }, cookieOptions);
1599
+ }
1600
+ // ==================== Forgot Password ====================
1601
+ case "forgot-password": {
1602
+ const { email } = body;
1603
+ if (!email) {
1604
+ return errorResponse("VALIDATION_ERROR", "Email required", 400);
1605
+ }
1606
+ const result = await sm.auth.forgotPassword(email, { clientContext });
1607
+ return successResponse({ message: "If an account exists, a reset email has been sent" });
1608
+ }
1609
+ // ==================== Reset Password ====================
1610
+ case "reset-password": {
1611
+ const { token, new_password } = body;
1612
+ if (!token || !new_password) {
1613
+ return errorResponse("VALIDATION_ERROR", "Token and new password required", 400);
1614
+ }
1615
+ try {
1616
+ await sm.auth.resetPassword(token, new_password, { clientContext });
1617
+ } catch (err) {
1618
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1619
+ return errorResponse(
1620
+ apiErr?.code || "RESET_FAILED",
1621
+ apiErr?.message || "Password reset failed",
1622
+ 400
1623
+ );
1624
+ }
1625
+ return clearSession({ message: "Password reset successful" }, cookieOptions);
1626
+ }
1627
+ // ==================== Verify Email ====================
1628
+ case "verify-email": {
1629
+ const { token } = body;
1630
+ if (!token) {
1631
+ return errorResponse("VALIDATION_ERROR", "Token required", 400);
1632
+ }
1633
+ let verifyData;
1634
+ try {
1635
+ verifyData = await sm.auth.verifyEmail(token);
1636
+ } catch (err) {
1637
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1638
+ return errorResponse(
1639
+ apiErr?.code || "VERIFY_FAILED",
1640
+ apiErr?.message || "Email verification failed",
1641
+ 400
1642
+ );
1643
+ }
1644
+ if (verifyData?.session_token && verifyData?.user) {
1645
+ return withSession(
1646
+ { session_token: verifyData.session_token, user: verifyData.user },
1647
+ { message: "Email verified successfully", verified: true, ...sessionData(verifyData.user, verifyData.session_token) },
1648
+ cookieOptions
1649
+ );
1650
+ }
1651
+ return successResponse({ message: "Email verified successfully" });
1652
+ }
1653
+ // ==================== Resend Verification ====================
1654
+ // Supports both authenticated (session-based) and unauthenticated (email-based) resend
1655
+ case "resend-verification": {
1656
+ const { email } = body;
1657
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1658
+ let rotated = null;
1659
+ if (email) {
1660
+ try {
1661
+ await sm.auth.resendVerification(email);
1662
+ } catch (err) {
1663
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1664
+ return errorResponse(
1665
+ apiErr?.code || "RESEND_FAILED",
1666
+ apiErr?.message || "Failed to resend verification",
1667
+ apiErr?.code === "RATE_LIMITED" ? 429 : 400
1668
+ );
1669
+ }
1670
+ return successResponse({ message: "Verification email sent" });
1671
+ }
1672
+ if (!session) {
1673
+ return errorResponse("UNAUTHORIZED", "Email or session required", 401);
1674
+ }
1675
+ try {
1676
+ await sm.auth.resendVerification(session.sessionToken, {
1677
+ onTokenRotated: (newToken) => {
1678
+ rotated = newToken;
1679
+ }
1680
+ });
1681
+ } catch (err) {
1682
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1683
+ return errorResponse(
1684
+ apiErr?.code || "RESEND_FAILED",
1685
+ apiErr?.message || "Failed to resend verification",
1686
+ 400
1687
+ );
1688
+ }
1689
+ if (rotated) {
1690
+ return withRefreshedSession(
1691
+ rotated,
1692
+ session.userId,
1693
+ { success: true, data: { message: "Verification email sent" } },
1694
+ cookieOptions
1695
+ );
1696
+ }
1697
+ return successResponse({ message: "Verification email sent" });
1698
+ }
1699
+ // ==================== Refresh Session ====================
1700
+ case "refresh": {
1701
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1702
+ if (!session) {
1703
+ return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1704
+ }
1705
+ let refreshData;
1706
+ try {
1707
+ refreshData = await sm.auth.refresh(session.sessionToken);
1708
+ } catch (err) {
1709
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1710
+ if (isSessionEndedError(apiErr)) {
1711
+ return clearSessionWithError(
1712
+ { code: apiErr?.code || "SESSION_EXPIRED", message: apiErr?.message || "Session expired" },
1713
+ cookieOptions
1714
+ );
1715
+ }
1716
+ return errorResponse(
1717
+ apiErr?.code || "REFRESH_FAILED",
1718
+ apiErr?.message || "Session refresh failed",
1719
+ apiErr?.status && apiErr.status >= 400 ? apiErr.status : 503
1720
+ );
1721
+ }
1722
+ return withRefreshedSession(
1723
+ refreshData.session_token,
1724
+ session.userId,
1725
+ { message: "Session refreshed", ...config.sessionMode === "bearer" ? { sessionToken: refreshData.session_token, userId: session.userId } : {} },
1726
+ cookieOptions
1727
+ );
1728
+ }
1729
+ // ==================== Change Password ====================
1730
+ case "change-password": {
1731
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1732
+ if (!session) {
1733
+ return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1734
+ }
1735
+ const { current_password, new_password } = body;
1736
+ if (!current_password || !new_password) {
1737
+ return errorResponse("VALIDATION_ERROR", "Current and new password required", 400);
1738
+ }
1739
+ let rotated = null;
1740
+ try {
1741
+ await sm.user.changePassword(
1742
+ session.sessionToken,
1743
+ current_password,
1744
+ new_password,
1745
+ {
1746
+ onTokenRotated: (newToken) => {
1747
+ rotated = newToken;
1748
+ }
1749
+ }
1750
+ );
1751
+ } catch (err) {
1752
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1753
+ return errorResponse(
1754
+ apiErr?.code || "CHANGE_FAILED",
1755
+ apiErr?.message || "Failed to change password",
1756
+ 400
1757
+ );
1758
+ }
1759
+ if (rotated) {
1760
+ return withRefreshedSession(
1761
+ rotated,
1762
+ session.userId,
1763
+ { success: true, data: { message: "Password changed successfully" } },
1764
+ cookieOptions
1765
+ );
1766
+ }
1767
+ return successResponse({ message: "Password changed successfully" });
1768
+ }
1769
+ // ==================== Switch Account ====================
1770
+ // Clears the active session so the user can re-authenticate as a different account.
1771
+ // The known accounts cookie is preserved — only the session cookie is cleared.
1772
+ case "switch-account": {
1773
+ if (!config.enableAccountSwitcher) {
1774
+ return errorResponse("NOT_FOUND", "Account switcher not enabled", 404);
1775
+ }
1776
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1777
+ if (session) {
1778
+ try {
1779
+ await sm.auth.logout(session.sessionToken);
1780
+ } catch {
1781
+ }
1782
+ }
1783
+ const switchResponse = clearSession({ message: "Session cleared for account switch" }, cookieOptions);
1784
+ const knownAccounts = getKnownAccountsFromRequest(request);
1785
+ return new Response(
1786
+ JSON.stringify({ success: true, data: { message: "Session cleared for account switch", knownAccounts } }),
1787
+ { status: 200, headers: switchResponse.headers }
1788
+ );
1789
+ }
1790
+ // ==================== Forget Account ====================
1791
+ // Remove a specific account from the known accounts cookie.
1792
+ case "forget-account": {
1793
+ if (!config.enableAccountSwitcher) {
1794
+ return errorResponse("NOT_FOUND", "Account switcher not enabled", 404);
1795
+ }
1796
+ const { user_id } = body;
1797
+ if (!user_id) {
1798
+ return errorResponse("VALIDATION_ERROR", "user_id required", 400);
1799
+ }
1800
+ const headers2 = new Headers();
1801
+ headers2.set("Content-Type", "application/json");
1802
+ const existingKnown = getKnownAccountsCookieRaw(request);
1803
+ removeKnownAccountFromCookie(headers2, user_id, existingKnown, cookieOptions);
1804
+ return new Response(
1805
+ JSON.stringify({ success: true, data: { message: "Account forgotten" } }),
1806
+ { status: 200, headers: headers2 }
1807
+ );
1808
+ }
1809
+ // ==================== Forget All Accounts ====================
1810
+ case "forget-all-accounts": {
1811
+ if (!config.enableAccountSwitcher) {
1812
+ return errorResponse("NOT_FOUND", "Account switcher not enabled", 404);
1813
+ }
1814
+ const headers2 = new Headers();
1815
+ headers2.set("Content-Type", "application/json");
1816
+ clearKnownAccountsCookie(headers2, cookieOptions);
1817
+ return new Response(
1818
+ JSON.stringify({ success: true, data: { message: "All accounts forgotten" } }),
1819
+ { status: 200, headers: headers2 }
1820
+ );
1821
+ }
1822
+ default:
1823
+ return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
1824
+ }
1825
+ } catch (err) {
1826
+ if (path === "handoff/exchange" && err instanceof ScaleMuleApiError) {
1827
+ return errorResponse(err.code, err.message, err.code === "HANDOFF_UNAVAILABLE" ? 503 : 401);
1828
+ }
1829
+ if (path.startsWith("mfa/") && err instanceof ScaleMuleApiError) {
1830
+ const status = ["CHALLENGE_RATE_LIMITED", "MFA_RATE_LIMITED", "MFA_MAX_ATTEMPTS"].includes(err.code) ? 429 : 400;
1831
+ return errorResponse(err.code, err.message, status);
1832
+ }
1833
+ console.error("[ScaleMule Auth] Error:", err);
1834
+ return errorResponse("SERVER_ERROR", "Internal server error", 500);
1835
+ }
1836
+ };
1837
+ const GET2 = async (request, context) => {
1838
+ const params = await context?.params;
1839
+ const path = params?.scalemule?.join("/") || "";
1840
+ try {
1841
+ switch (path) {
1842
+ // ==================== Get Current User ====================
1843
+ case "me": {
1844
+ const normCookie = config.enableAccountSwitcher ? normalizeKnownAccountsCookie(request, config.accountSwitcherPrivacy, cookieOptions) : null;
1845
+ const withNorm = (resp) => {
1846
+ if (normCookie) resp.headers.append("Set-Cookie", normCookie);
1847
+ return resp;
1848
+ };
1849
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1850
+ if (!session) {
1851
+ return withNorm(errorResponse("UNAUTHORIZED", "Authentication required", 401));
1852
+ }
1853
+ let userData;
1854
+ let rotated = null;
1855
+ try {
1856
+ userData = await sm.auth.me(session.sessionToken, {
1857
+ onTokenRotated: (newToken) => {
1858
+ rotated = newToken;
1859
+ }
1860
+ });
1861
+ } catch {
1862
+ return withNorm(clearSession(
1863
+ { error: { code: "SESSION_EXPIRED", message: "Session expired" } },
1864
+ cookieOptions
1865
+ ));
1866
+ }
1867
+ if (rotated) {
1868
+ return withNorm(withRefreshedSession(
1869
+ rotated,
1870
+ session.userId,
1871
+ sessionData(userData, rotated),
1872
+ cookieOptions
1873
+ ));
1874
+ }
1875
+ return withNorm(successResponse(sessionData(userData, session.sessionToken)));
1876
+ }
1877
+ // ==================== Get Session Status ====================
1878
+ case "session": {
1879
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1880
+ return successResponse({
1881
+ authenticated: !!session,
1882
+ userId: session?.userId || null
1883
+ });
1884
+ }
1885
+ // ==================== Get Known Accounts ====================
1886
+ case "known-accounts": {
1887
+ if (!config.enableAccountSwitcher) {
1888
+ return errorResponse("NOT_FOUND", "Account switcher not enabled", 404);
1889
+ }
1890
+ const knownAccounts = getKnownAccountsFromRequest(request);
1891
+ return successResponse({ knownAccounts });
1892
+ }
1893
+ default:
1894
+ return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
1895
+ }
1896
+ } catch (err) {
1897
+ console.error("[ScaleMule Auth] Error:", err);
1898
+ return errorResponse("SERVER_ERROR", "Internal server error", 500);
1899
+ }
1900
+ };
1901
+ const DELETE2 = async (request, context) => {
1902
+ const params = await context?.params;
1903
+ const path = params?.scalemule?.join("/") || "";
1904
+ try {
1905
+ switch (path) {
1906
+ // ==================== Delete Account ====================
1907
+ case "me":
1908
+ case "account": {
1909
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1910
+ if (!session) {
1911
+ return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1912
+ }
1913
+ const body = await request.json().catch(() => ({}));
1914
+ const { password } = body;
1915
+ if (!password) {
1916
+ return errorResponse("VALIDATION_ERROR", "Password required", 400);
1917
+ }
1918
+ try {
1919
+ await sm.user.deleteAccount(session.sessionToken, password);
1920
+ } catch (err) {
1921
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1922
+ return errorResponse(
1923
+ apiErr?.code || "DELETE_FAILED",
1924
+ apiErr?.message || "Failed to delete account",
1925
+ 400
1926
+ );
1927
+ }
1928
+ return clearSession({ message: "Account deleted successfully" }, cookieOptions);
1929
+ }
1930
+ default:
1931
+ return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
1932
+ }
1933
+ } catch (err) {
1934
+ console.error("[ScaleMule Auth] Error:", err);
1935
+ return errorResponse("SERVER_ERROR", "Internal server error", 500);
1936
+ }
1937
+ };
1938
+ const PATCH2 = async (request, context) => {
1939
+ const params = await context?.params;
1940
+ const path = params?.scalemule?.join("/") || "";
1941
+ try {
1942
+ switch (path) {
1943
+ // ==================== Update Profile ====================
1944
+ case "me":
1945
+ case "profile": {
1946
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1947
+ if (!session) {
1948
+ return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1949
+ }
1950
+ const body = await request.json().catch(() => ({}));
1951
+ const { full_name, avatar_url } = body;
1952
+ let updatedUser;
1953
+ let rotated = null;
1954
+ try {
1955
+ updatedUser = await sm.user.update(session.sessionToken, { full_name, avatar_url }, {
1956
+ onTokenRotated: (newToken) => {
1957
+ rotated = newToken;
1958
+ }
1959
+ });
1960
+ } catch (err) {
1961
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1962
+ return errorResponse(
1963
+ apiErr?.code || "UPDATE_FAILED",
1964
+ apiErr?.message || "Failed to update profile",
1965
+ 400
1966
+ );
1967
+ }
1968
+ if (rotated) {
1969
+ return withRefreshedSession(
1970
+ rotated,
1971
+ session.userId,
1972
+ { success: true, data: { user: updatedUser } },
1973
+ cookieOptions
1974
+ );
1975
+ }
1976
+ return successResponse({ user: updatedUser });
1977
+ }
1978
+ default:
1979
+ return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
1980
+ }
1981
+ } catch (err) {
1982
+ console.error("[ScaleMule Auth] Error:", err);
1983
+ return errorResponse("SERVER_ERROR", "Internal server error", 500);
1984
+ }
1985
+ };
1986
+ const wrap = (handler) => async (request, context) => {
1987
+ const params = await context.params;
1988
+ const path = params.scalemule || [];
1989
+ let response;
1990
+ if (path[0] === "client") {
1991
+ response = await browserProxy(request, path.slice(1), config);
1992
+ } else if (!["GET", "HEAD"].includes(request.method) && (!isSameOriginRequest(request) || !request.headers.get("content-type")?.toLowerCase().startsWith("application/json"))) {
1993
+ response = errorResponse("CSRF_ERROR", "Same-origin JSON request required", 403);
1994
+ } else {
1995
+ response = await handler(request, context);
1996
+ }
1997
+ response.headers.set("Cache-Control", "no-store");
1998
+ response.headers.set("Vary", "Cookie");
1999
+ return response;
2000
+ };
2001
+ return { GET: wrap(GET2), POST: wrap(POST2), DELETE: wrap(DELETE2), PATCH: wrap(PATCH2), PUT: wrap(async () => errorResponse("NOT_FOUND", "Unknown endpoint", 404)) };
2002
+ }
2003
+
2004
+ // src/server/auth.ts
2005
+ var cookieDomain = typeof process !== "undefined" ? process.env.SCALEMULE_COOKIE_DOMAIN : void 0;
2006
+ var handlers = createAuthRoutes({
2007
+ cookies: cookieDomain ? { domain: cookieDomain } : void 0
2008
+ });
2009
+ var { GET, POST, DELETE, PATCH, PUT } = handlers;
2010
+
2011
+ exports.DELETE = DELETE;
2012
+ exports.GET = GET;
2013
+ exports.PATCH = PATCH;
2014
+ exports.POST = POST;
2015
+ exports.PUT = PUT;