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