@scalemule/nextjs 0.1.58 → 0.1.61

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