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