@scalemule/nextjs 0.1.60 → 0.1.61

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