@scalemule/nextjs 0.1.52 → 0.1.54

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.
@@ -11,15 +11,15 @@ var server$1 = require('@scalemule/sdk/flags/server');
11
11
 
12
12
  // src/types/index.ts
13
13
  var ScaleMuleApiError = class extends Error {
14
- constructor(error, status) {
15
- super(error.message);
14
+ constructor(error2, status) {
15
+ super(error2.message);
16
16
  this.name = "ScaleMuleApiError";
17
- this.code = error.code;
18
- this.field = error.field;
17
+ this.code = error2.code;
18
+ this.field = error2.field;
19
19
  this.status = status;
20
- this.requestId = error.requestId;
21
- this.traceId = error.traceId;
22
- this.problem = error.problem;
20
+ this.requestId = error2.requestId;
21
+ this.traceId = error2.traceId;
22
+ this.problem = error2.problem;
23
23
  }
24
24
  };
25
25
 
@@ -64,7 +64,7 @@ function validateIP(ip) {
64
64
  }
65
65
  return void 0;
66
66
  }
67
- function extractClientContext(request) {
67
+ function extractClientContext(request, options = {}) {
68
68
  const headers3 = request.headers;
69
69
  let ip;
70
70
  ip = validateIP(headers3.get("x-real-ip"));
@@ -107,6 +107,11 @@ function extractClientContext(request) {
107
107
  if (!ip && request.ip) {
108
108
  ip = validateIP(request.ip);
109
109
  }
110
+ if (options.trustedIpHeader) {
111
+ const value = headers3.get(options.trustedIpHeader);
112
+ const hop = options.trustedIpHeader === "x-forwarded-for" ? value?.split(",").at(-1)?.trim() : value;
113
+ ip = validateIP(hop);
114
+ }
110
115
  const userAgent = headers3.get("user-agent") || void 0;
111
116
  const deviceFingerprint = headers3.get("x-device-fingerprint") || void 0;
112
117
  const referrer = withoutAuthSecrets(headers3.get("referer") || void 0);
@@ -213,8 +218,8 @@ function buildFlagContext(clientContext, extraContext = {}) {
213
218
  }
214
219
 
215
220
  // src/error-context.ts
216
- function withErrorContext(error, responseData, headers3) {
217
- const enriched = { ...error };
221
+ function withErrorContext(error2, responseData, headers3) {
222
+ const enriched = { ...error2 };
218
223
  const meta = responseData?.meta;
219
224
  const requestId = meta?.request_id ?? headers3?.get("x-request-id") ?? void 0;
220
225
  if (requestId !== void 0 && enriched.requestId === void 0) {
@@ -248,6 +253,14 @@ var ScaleMuleServer = class {
248
253
  // Auth Methods
249
254
  // ==========================================================================
250
255
  this.auth = {
256
+ /** Issue a 60-second, single-use transfer code after a server OAuth callback. */
257
+ createSessionHandoff: async (sessionToken, audience) => {
258
+ return this.request("POST", "/v1/auth/session-handoff", { sessionToken, body: { session_token: sessionToken, audience } });
259
+ },
260
+ /** Exchange only on the server; write the returned session into an HTTP-only cookie. */
261
+ exchangeSessionHandoff: async (code, audience) => {
262
+ return this.request("POST", "/v1/auth/session-handoff/exchange", { body: { code, audience } });
263
+ },
251
264
  /**
252
265
  * Register a new user
253
266
  */
@@ -907,7 +920,7 @@ var ScaleMuleServer = class {
907
920
  code: `HTTP_${response.status}`,
908
921
  message: responseData?.message || text || response.statusText
909
922
  };
910
- const error = withErrorContext(baseError, responseData, response.headers);
923
+ const error2 = withErrorContext(baseError, responseData, response.headers);
911
924
  if (response.status === 401 && options.sessionToken && !options.isAutoRefresh) {
912
925
  if (this.debug) console.log("[ScaleMule Server] 401 received, attempting auto-refresh...");
913
926
  try {
@@ -930,12 +943,12 @@ var ScaleMuleServer = class {
930
943
  if (this.debug) console.error("[ScaleMule Server] Auto-refresh failed:", refreshErr);
931
944
  const refreshApiError = refreshErr instanceof ScaleMuleApiError ? { code: refreshErr.code, message: refreshErr.message } : { code: "REFRESH_FAILED", message: "Auto-refresh failed" };
932
945
  this.onAutoRefreshFailed?.(refreshApiError);
933
- throw new ScaleMuleApiError(error);
946
+ throw new ScaleMuleApiError(error2);
934
947
  } finally {
935
948
  this.onRefreshEnd?.();
936
949
  }
937
950
  }
938
- throw new ScaleMuleApiError(error);
951
+ throw new ScaleMuleApiError(error2);
939
952
  }
940
953
  const data = responseData?.data !== void 0 ? responseData.data : responseData;
941
954
  return data;
@@ -976,9 +989,10 @@ function createCookieHeader(name, value, options = {}) {
976
989
  const sameSite = options.sameSite ?? "lax";
977
990
  const path = options.path ?? "/";
978
991
  let cookie = `${name}=${encodeURIComponent(value)}; Path=${path}; Max-Age=${maxAge}; HttpOnly; SameSite=${sameSite}`;
979
- if (secure) {
992
+ if (secure || options.partitioned) {
980
993
  cookie += "; Secure";
981
994
  }
995
+ if (options.partitioned) cookie += "; Partitioned";
982
996
  if (options.domain) {
983
997
  cookie += `; Domain=${options.domain}`;
984
998
  }
@@ -989,9 +1003,10 @@ function createClearCookieHeader(name, options = {}) {
989
1003
  const secure = options.secure ?? process.env.NODE_ENV === "production";
990
1004
  const sameSite = options.sameSite ?? "lax";
991
1005
  let cookie = `${name}=; Path=${path}; Max-Age=0; HttpOnly; SameSite=${sameSite}`;
992
- if (secure) {
1006
+ if (secure || options.partitioned) {
993
1007
  cookie += "; Secure";
994
1008
  }
1009
+ if (options.partitioned) cookie += "; Partitioned";
995
1010
  if (options.domain) {
996
1011
  cookie += `; Domain=${options.domain}`;
997
1012
  }
@@ -1000,6 +1015,10 @@ function createClearCookieHeader(name, options = {}) {
1000
1015
  function withSession(loginResponse, responseBody, options = {}) {
1001
1016
  const headers3 = new Headers();
1002
1017
  headers3.set("Content-Type", "application/json");
1018
+ if (options.partitioned) {
1019
+ headers3.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, { ...options, partitioned: false }));
1020
+ headers3.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, { ...options, partitioned: false }));
1021
+ }
1003
1022
  headers3.append(
1004
1023
  "Set-Cookie",
1005
1024
  createCookieHeader(SESSION_COOKIE_NAME, loginResponse.session_token, options)
@@ -1016,6 +1035,10 @@ function withSession(loginResponse, responseBody, options = {}) {
1016
1035
  function withRefreshedSession(sessionToken, userId, responseBody, options = {}) {
1017
1036
  const headers3 = new Headers();
1018
1037
  headers3.set("Content-Type", "application/json");
1038
+ if (options.partitioned) {
1039
+ headers3.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, { ...options, partitioned: false }));
1040
+ headers3.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, { ...options, partitioned: false }));
1041
+ }
1019
1042
  headers3.append(
1020
1043
  "Set-Cookie",
1021
1044
  createCookieHeader(SESSION_COOKIE_NAME, sessionToken, options)
@@ -1032,6 +1055,10 @@ function withRefreshedSession(sessionToken, userId, responseBody, options = {})
1032
1055
  function clearSession(responseBody, options = {}, status = 200) {
1033
1056
  const headers3 = new Headers();
1034
1057
  headers3.set("Content-Type", "application/json");
1058
+ if (options.partitioned) {
1059
+ headers3.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, { ...options, partitioned: false }));
1060
+ headers3.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, { ...options, partitioned: false }));
1061
+ }
1035
1062
  headers3.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, options));
1036
1063
  headers3.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, options));
1037
1064
  return new Response(JSON.stringify({ success: status < 300, data: responseBody }), {
@@ -1039,7 +1066,7 @@ function clearSession(responseBody, options = {}, status = 200) {
1039
1066
  headers: headers3
1040
1067
  });
1041
1068
  }
1042
- async function getSession() {
1069
+ async function getSession(options = {}) {
1043
1070
  const cookieStore = await headers.cookies();
1044
1071
  const sessionCookie = cookieStore.get(SESSION_COOKIE_NAME);
1045
1072
  const userIdCookie = cookieStore.get(USER_ID_COOKIE_NAME);
@@ -1051,6 +1078,7 @@ async function getSession() {
1051
1078
  // Note: actual expiry is managed by ScaleMule backend
1052
1079
  };
1053
1080
  }
1081
+ if (options.allowBearer === false) return null;
1054
1082
  const headerStore = await headers.headers();
1055
1083
  return sessionFromAuthHeaders(
1056
1084
  headerStore.get("authorization"),
@@ -1333,10 +1361,10 @@ async function validateCSRFTokenAsync(request, body) {
1333
1361
  function withCSRFProtection(handler) {
1334
1362
  return async (request) => {
1335
1363
  if (["POST", "PUT", "PATCH", "DELETE"].includes(request.method)) {
1336
- const error = validateCSRFToken(request);
1337
- if (error) {
1364
+ const error2 = validateCSRFToken(request);
1365
+ if (error2) {
1338
1366
  return server.NextResponse.json(
1339
- { error: "CSRF validation failed", message: error },
1367
+ { error: "CSRF validation failed", message: error2 },
1340
1368
  { status: 403 }
1341
1369
  );
1342
1370
  }
@@ -1353,6 +1381,139 @@ async function getCSRFToken() {
1353
1381
  return token;
1354
1382
  }
1355
1383
 
1384
+ // src/server/browser-proxy.ts
1385
+ function error(code, status) {
1386
+ return Response.json({ success: false, error: { code, message: code === "UNAUTHORIZED" ? "Authentication required" : "Request not permitted" } }, { status, headers: { "Cache-Control": "no-store" } });
1387
+ }
1388
+ function isSameOriginRequest(request) {
1389
+ const origin = request.headers.get("origin");
1390
+ const site = request.headers.get("sec-fetch-site");
1391
+ if (site) return site === "same-origin" || site === "none";
1392
+ const url = new URL(request.url);
1393
+ const host = request.headers.get("host") || url.host;
1394
+ if (origin) {
1395
+ try {
1396
+ const source = new URL(origin);
1397
+ if (!["http:", "https:"].includes(source.protocol) || source.host !== host) return false;
1398
+ } catch {
1399
+ return false;
1400
+ }
1401
+ }
1402
+ return true;
1403
+ }
1404
+ 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"]);
1405
+ var AUTH_ROUTES = /* @__PURE__ */ new Set([
1406
+ "GET me",
1407
+ "GET mfa/status",
1408
+ "GET oauth/providers",
1409
+ "PATCH profile",
1410
+ "POST change-password",
1411
+ "POST change-email",
1412
+ "POST delete-account",
1413
+ "POST export-data",
1414
+ "POST mfa/setup",
1415
+ "POST mfa/verify",
1416
+ "POST mfa/disable",
1417
+ "POST mfa/backup-codes",
1418
+ "POST oauth/start",
1419
+ "POST oauth/callback"
1420
+ ]);
1421
+ var PUBLIC_AUTH_ROUTES = /* @__PURE__ */ new Set(["POST oauth/start", "POST oauth/callback"]);
1422
+ 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"]);
1423
+ var MAX_BODY_BYTES = 25 * 1024 * 1024;
1424
+ async function boundedBody(request) {
1425
+ if (request.method === "GET" || request.method === "HEAD" || !request.body) return void 0;
1426
+ const reader = request.body.getReader();
1427
+ const chunks = [];
1428
+ let size = 0;
1429
+ try {
1430
+ while (true) {
1431
+ const part = await reader.read();
1432
+ if (part.done) break;
1433
+ size += part.value.byteLength;
1434
+ if (size > MAX_BODY_BYTES) {
1435
+ await reader.cancel();
1436
+ throw new Error("BODY_TOO_LARGE");
1437
+ }
1438
+ chunks.push(part.value);
1439
+ }
1440
+ } finally {
1441
+ reader.releaseLock();
1442
+ }
1443
+ const bytes = new Uint8Array(size);
1444
+ let offset = 0;
1445
+ for (const chunk of chunks) {
1446
+ bytes.set(chunk, offset);
1447
+ offset += chunk.byteLength;
1448
+ }
1449
+ return bytes;
1450
+ }
1451
+ async function browserProxy(request, path, config) {
1452
+ if (!isSameOriginRequest(request)) return error("CSRF_ERROR", 403);
1453
+ const key = config.publishableKey || process.env.NEXT_PUBLIC_SCALEMULE_PUBLISHABLE_KEY;
1454
+ if (!key?.startsWith("sm_pb_")) return error("BROWSER_KEY_NOT_CONFIGURED", 503);
1455
+ if (request.headers.get("x-api-key") !== key) return error("CSRF_ERROR", 403);
1456
+ const authOperation = `${request.method} ${path.slice(2).join("/")}`;
1457
+ const authRoute = path[1] === "auth" && (AUTH_ROUTES.has(authOperation) || request.method === "DELETE" && path[2] === "oauth" && path[3] === "providers" && path.length === 5);
1458
+ if (path[0] !== "v1" || !(SERVICES.has(path[1]) || authRoute) || path.some((part) => !part || part === "." || part === ".." || /[\\/%\u0000-\u001f]/.test(part))) return error("NOT_FOUND", 404);
1459
+ const session = await getSession({ allowBearer: false });
1460
+ if (!session && !(authRoute && PUBLIC_AUTH_ROUTES.has(authOperation)) && !PUBLIC_DATA_ROUTES.has(`${request.method} ${path.slice(1).join("/")}`)) return error("UNAUTHORIZED", 401);
1461
+ const gateway = resolveGatewayUrl({ ...config.client, gatewayUrl: config.browserGatewayUrl || process.env.NEXT_PUBLIC_SCALEMULE_GATEWAY_URL || config.client?.gatewayUrl });
1462
+ const target = new URL(`${gateway.replace(/\/$/, "")}/${path.map(encodeURIComponent).join("/")}`);
1463
+ target.search = new URL(request.url).search;
1464
+ const headers3 = new Headers({ "x-api-key": key });
1465
+ if (session) headers3.set("Authorization", `Bearer ${session.sessionToken}`);
1466
+ for (const name of ["x-anonymous-id", "origin", "content-type", "accept", "user-agent", "range", "if-none-match", "x-idempotency-key", "x-sm-workspace-id"]) {
1467
+ const value = request.headers.get(name);
1468
+ if (value) headers3.set(name, value);
1469
+ }
1470
+ try {
1471
+ const body = await boundedBody(request);
1472
+ const upstream = await fetch(target, { method: request.method, headers: headers3, body, redirect: "error", cache: "no-store", signal: AbortSignal.timeout(6e4) });
1473
+ const outputHeaders = new Headers({ "Cache-Control": "no-store", "Vary": "Cookie" });
1474
+ for (const name of ["content-type", "content-disposition", "content-range", "accept-ranges", "etag", "retry-after", "x-request-id"]) {
1475
+ const value = upstream.headers.get(name);
1476
+ if (value) outputHeaders.set(name, value);
1477
+ }
1478
+ const rotated = upstream.headers.get("x-rotated-session-token");
1479
+ if (rotated && session) {
1480
+ const refreshed = withRefreshedSession(rotated, session.userId, {}, config.cookies);
1481
+ for (const cookie of refreshed.headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
1482
+ }
1483
+ if ([204, 205, 304].includes(upstream.status)) {
1484
+ if (authOperation === "POST delete-account" && upstream.ok) {
1485
+ for (const cookie of clearSession({}, config.cookies).headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
1486
+ }
1487
+ return new Response(null, { status: upstream.status, headers: outputHeaders });
1488
+ }
1489
+ if (authRoute) {
1490
+ const payload = await upstream.json();
1491
+ const data = payload?.data || payload;
1492
+ if (authOperation === "POST delete-account" && upstream.ok && payload.success !== false) {
1493
+ for (const cookie of clearSession({}, config.cookies).headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
1494
+ }
1495
+ const token = data?.session_token;
1496
+ if (typeof token === "string" && data?.user?.id && upstream.ok && payload.success !== false) {
1497
+ const established = withSession({ session_token: token, user: data.user }, {}, config.cookies);
1498
+ for (const cookie of established.headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
1499
+ data.authenticated = true;
1500
+ }
1501
+ if (data && typeof data === "object") {
1502
+ delete data.session_token;
1503
+ delete data.sessionToken;
1504
+ delete data.refresh_token;
1505
+ delete data.access_token;
1506
+ }
1507
+ return Response.json(payload, { status: upstream.status, headers: outputHeaders });
1508
+ }
1509
+ return new Response(upstream.body, { status: upstream.status, headers: outputHeaders });
1510
+ } catch (err) {
1511
+ if (err instanceof Error && err.message === "BODY_TOO_LARGE") return error("BODY_TOO_LARGE", 413);
1512
+ console.error("[ScaleMule] Browser proxy upstream request failed");
1513
+ return error("UPSTREAM_UNAVAILABLE", 502);
1514
+ }
1515
+ }
1516
+
1356
1517
  // src/server/routes.ts
1357
1518
  function errorResponse(code, message, status) {
1358
1519
  return new Response(
@@ -1369,6 +1530,12 @@ function successResponse(data, status = 200) {
1369
1530
  function createAuthRoutes(config = {}) {
1370
1531
  const sm = createServerClient(config.client);
1371
1532
  const cookieOptions = config.cookies || {};
1533
+ const sessionData = (user, token) => ({
1534
+ user,
1535
+ userId: user.id,
1536
+ authenticated: true,
1537
+ ...config.sessionMode === "bearer" ? { sessionToken: token } : {}
1538
+ });
1372
1539
  const POST = async (request, context) => {
1373
1540
  if (config.csrf) {
1374
1541
  const csrfError = validateCSRFToken(request);
@@ -1380,7 +1547,7 @@ function createAuthRoutes(config = {}) {
1380
1547
  const path = params?.scalemule?.join("/") || "";
1381
1548
  try {
1382
1549
  const body = await request.json().catch(() => ({}));
1383
- const clientContext = extractClientContext(request);
1550
+ const clientContext = extractClientContext(request, config.clientContext);
1384
1551
  switch (path) {
1385
1552
  // ==================== Register ====================
1386
1553
  case "register": {
@@ -1406,9 +1573,9 @@ function createAuthRoutes(config = {}) {
1406
1573
  try {
1407
1574
  loginData = await sm.auth.login({ email, password }, { clientContext });
1408
1575
  } catch {
1409
- return successResponse({ user: registeredUser, message: "Registration successful" }, 201);
1576
+ return successResponse({ user: registeredUser, authenticated: false, message: "Registration successful" }, 201);
1410
1577
  }
1411
- const registerResponse = withSession(loginData, { user: registeredUser, sessionToken: loginData.session_token, userId: registeredUser.id }, cookieOptions);
1578
+ const registerResponse = withSession(loginData, sessionData(registeredUser, loginData.session_token), cookieOptions);
1412
1579
  if (config.enableAccountSwitcher) {
1413
1580
  const existingKnown = getKnownAccountsCookieRaw(request);
1414
1581
  appendKnownAccountCookie(
@@ -1428,6 +1595,12 @@ function createAuthRoutes(config = {}) {
1428
1595
  }
1429
1596
  return registerResponse;
1430
1597
  }
1598
+ case "handoff/exchange": {
1599
+ if (!config.handoffAudience) return errorResponse("HANDOFF_DISABLED", "Session transfer is not configured", 404);
1600
+ if (typeof body.code !== "string" || !body.code || body.code.length > 256) return errorResponse("INVALID_HANDOFF", "Invalid sign-in transfer", 400);
1601
+ const result = await sm.auth.exchangeSessionHandoff(body.code, config.handoffAudience);
1602
+ return withRefreshedSession(result.session_token, result.user_id, { authenticated: true, userId: result.user_id }, cookieOptions);
1603
+ }
1431
1604
  case "mfa/send-code": {
1432
1605
  const { pending_token, method } = body;
1433
1606
  if (!pending_token || !["email", "sms"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token and method required", 400);
@@ -1439,7 +1612,7 @@ function createAuthRoutes(config = {}) {
1439
1612
  const result = await sm.auth.completeMfa(pending_token, code, method, { clientContext });
1440
1613
  if (!result.session_token || !result.user) return errorResponse("MFA_FAILED", "Unable to complete sign-in", 400);
1441
1614
  await config.onLogin?.({ id: result.user.id, email: result.user.email });
1442
- const response = withSession(result, { user: result.user, sessionToken: result.session_token, userId: result.user.id }, cookieOptions);
1615
+ const response = withSession(result, sessionData(result.user, result.session_token), cookieOptions);
1443
1616
  if (config.enableAccountSwitcher) {
1444
1617
  appendKnownAccountCookie(response.headers, {
1445
1618
  userId: result.user.id,
@@ -1464,7 +1637,7 @@ function createAuthRoutes(config = {}) {
1464
1637
  } catch (err) {
1465
1638
  const apiErr = err instanceof ScaleMuleApiError ? err : null;
1466
1639
  const errorCode = apiErr?.code || "LOGIN_FAILED";
1467
- let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 202 : 400;
1640
+ let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 403 : 400;
1468
1641
  if (errorCode === "CHALLENGE_RATE_LIMITED") status = 429;
1469
1642
  if (errorCode === "INVALID_CREDENTIALS" || errorCode === "UNAUTHORIZED") status = 401;
1470
1643
  if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED"].includes(errorCode)) {
@@ -1482,7 +1655,7 @@ function createAuthRoutes(config = {}) {
1482
1655
  email: loginData.user.email
1483
1656
  });
1484
1657
  }
1485
- const loginResponse = withSession(loginData, { user: loginData.user, sessionToken: loginData.session_token, userId: loginData.user.id }, cookieOptions);
1658
+ const loginResponse = withSession(loginData, sessionData(loginData.user, loginData.session_token), cookieOptions);
1486
1659
  if (config.enableAccountSwitcher) {
1487
1660
  const existingKnown = getKnownAccountsCookieRaw(request);
1488
1661
  appendKnownAccountCookie(
@@ -1504,7 +1677,7 @@ function createAuthRoutes(config = {}) {
1504
1677
  }
1505
1678
  // ==================== Logout ====================
1506
1679
  case "logout": {
1507
- const session = await getSession();
1680
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1508
1681
  let rotated = null;
1509
1682
  if (session) {
1510
1683
  try {
@@ -1568,7 +1741,7 @@ function createAuthRoutes(config = {}) {
1568
1741
  if (verifyData?.session_token && verifyData?.user) {
1569
1742
  return withSession(
1570
1743
  { session_token: verifyData.session_token, user: verifyData.user },
1571
- { message: "Email verified successfully", verified: true, user: verifyData.user, sessionToken: verifyData.session_token, userId: verifyData.user.id },
1744
+ { message: "Email verified successfully", verified: true, ...sessionData(verifyData.user, verifyData.session_token) },
1572
1745
  cookieOptions
1573
1746
  );
1574
1747
  }
@@ -1578,7 +1751,7 @@ function createAuthRoutes(config = {}) {
1578
1751
  // Supports both authenticated (session-based) and unauthenticated (email-based) resend
1579
1752
  case "resend-verification": {
1580
1753
  const { email } = body;
1581
- const session = await getSession();
1754
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1582
1755
  let rotated = null;
1583
1756
  if (email) {
1584
1757
  try {
@@ -1622,7 +1795,7 @@ function createAuthRoutes(config = {}) {
1622
1795
  }
1623
1796
  // ==================== Refresh Session ====================
1624
1797
  case "refresh": {
1625
- const session = await getSession();
1798
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1626
1799
  if (!session) {
1627
1800
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1628
1801
  }
@@ -1632,19 +1805,20 @@ function createAuthRoutes(config = {}) {
1632
1805
  } catch {
1633
1806
  return clearSession(
1634
1807
  { message: "Session expired" },
1635
- cookieOptions
1808
+ cookieOptions,
1809
+ 401
1636
1810
  );
1637
1811
  }
1638
1812
  return withRefreshedSession(
1639
1813
  refreshData.session_token,
1640
1814
  session.userId,
1641
- { message: "Session refreshed" },
1815
+ { message: "Session refreshed", ...config.sessionMode === "bearer" ? { sessionToken: refreshData.session_token, userId: session.userId } : {} },
1642
1816
  cookieOptions
1643
1817
  );
1644
1818
  }
1645
1819
  // ==================== Change Password ====================
1646
1820
  case "change-password": {
1647
- const session = await getSession();
1821
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1648
1822
  if (!session) {
1649
1823
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1650
1824
  }
@@ -1689,7 +1863,7 @@ function createAuthRoutes(config = {}) {
1689
1863
  if (!config.enableAccountSwitcher) {
1690
1864
  return errorResponse("NOT_FOUND", "Account switcher not enabled", 404);
1691
1865
  }
1692
- const session = await getSession();
1866
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1693
1867
  if (session) {
1694
1868
  try {
1695
1869
  await sm.auth.logout(session.sessionToken);
@@ -1739,6 +1913,9 @@ function createAuthRoutes(config = {}) {
1739
1913
  return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
1740
1914
  }
1741
1915
  } catch (err) {
1916
+ if (path === "handoff/exchange" && err instanceof ScaleMuleApiError) {
1917
+ return errorResponse(err.code, err.message, err.code === "HANDOFF_UNAVAILABLE" ? 503 : 401);
1918
+ }
1742
1919
  if (path.startsWith("mfa/") && err instanceof ScaleMuleApiError) {
1743
1920
  const status = ["CHALLENGE_RATE_LIMITED", "MFA_RATE_LIMITED", "MFA_MAX_ATTEMPTS"].includes(err.code) ? 429 : 400;
1744
1921
  return errorResponse(err.code, err.message, status);
@@ -1759,7 +1936,7 @@ function createAuthRoutes(config = {}) {
1759
1936
  if (normCookie) resp.headers.append("Set-Cookie", normCookie);
1760
1937
  return resp;
1761
1938
  };
1762
- const session = await getSession();
1939
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1763
1940
  if (!session) {
1764
1941
  return withNorm(errorResponse("UNAUTHORIZED", "Authentication required", 401));
1765
1942
  }
@@ -1781,15 +1958,15 @@ function createAuthRoutes(config = {}) {
1781
1958
  return withNorm(withRefreshedSession(
1782
1959
  rotated,
1783
1960
  session.userId,
1784
- { user: userData, sessionToken: rotated, userId: session.userId },
1961
+ sessionData(userData, rotated),
1785
1962
  cookieOptions
1786
1963
  ));
1787
1964
  }
1788
- return withNorm(successResponse({ user: userData, sessionToken: session.sessionToken, userId: session.userId }));
1965
+ return withNorm(successResponse(sessionData(userData, session.sessionToken)));
1789
1966
  }
1790
1967
  // ==================== Get Session Status ====================
1791
1968
  case "session": {
1792
- const session = await getSession();
1969
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1793
1970
  return successResponse({
1794
1971
  authenticated: !!session,
1795
1972
  userId: session?.userId || null
@@ -1819,7 +1996,7 @@ function createAuthRoutes(config = {}) {
1819
1996
  // ==================== Delete Account ====================
1820
1997
  case "me":
1821
1998
  case "account": {
1822
- const session = await getSession();
1999
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1823
2000
  if (!session) {
1824
2001
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1825
2002
  }
@@ -1856,7 +2033,7 @@ function createAuthRoutes(config = {}) {
1856
2033
  // ==================== Update Profile ====================
1857
2034
  case "me":
1858
2035
  case "profile": {
1859
- const session = await getSession();
2036
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1860
2037
  if (!session) {
1861
2038
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1862
2039
  }
@@ -1896,7 +2073,22 @@ function createAuthRoutes(config = {}) {
1896
2073
  return errorResponse("SERVER_ERROR", "Internal server error", 500);
1897
2074
  }
1898
2075
  };
1899
- return { GET, POST, DELETE, PATCH };
2076
+ const wrap = (handler) => async (request, context) => {
2077
+ const params = await context.params;
2078
+ const path = params.scalemule || [];
2079
+ let response;
2080
+ if (path[0] === "client") {
2081
+ response = await browserProxy(request, path.slice(1), config);
2082
+ } else if (!["GET", "HEAD"].includes(request.method) && (!isSameOriginRequest(request) || !request.headers.get("content-type")?.toLowerCase().startsWith("application/json"))) {
2083
+ response = errorResponse("CSRF_ERROR", "Same-origin JSON request required", 403);
2084
+ } else {
2085
+ response = await handler(request, context);
2086
+ }
2087
+ response.headers.set("Cache-Control", "no-store");
2088
+ response.headers.set("Vary", "Cookie");
2089
+ return response;
2090
+ };
2091
+ return { GET: wrap(GET), POST: wrap(POST), DELETE: wrap(DELETE), PATCH: wrap(PATCH), PUT: wrap(async () => errorResponse("NOT_FOUND", "Unknown endpoint", 404)) };
1900
2092
  }
1901
2093
  function getPrimaryTrackingContextSource(body) {
1902
2094
  if (Array.isArray(body.events)) {
@@ -2300,10 +2492,10 @@ function createLedveryRoutes(config) {
2300
2492
  const code = url.searchParams.get("code");
2301
2493
  const callbackState = url.searchParams.get("state");
2302
2494
  if (!code) {
2303
- const error = url.searchParams.get("error");
2495
+ const error2 = url.searchParams.get("error");
2304
2496
  const errorDesc = url.searchParams.get("error_description");
2305
2497
  return new Response(
2306
- JSON.stringify({ error: error || "missing_code", message: errorDesc || "No authorization code in callback" }),
2498
+ JSON.stringify({ error: error2 || "missing_code", message: errorDesc || "No authorization code in callback" }),
2307
2499
  { status: 403, headers: { "Content-Type": "application/json" } }
2308
2500
  );
2309
2501
  }
@@ -2727,27 +2919,27 @@ function apiHandler(handler, options) {
2727
2919
  return Response.json({ success: true, data: result }, { status: 200 });
2728
2920
  }
2729
2921
  return new Response(null, { status: 204 });
2730
- } catch (error) {
2731
- if (error instanceof ScaleMuleError) {
2922
+ } catch (error2) {
2923
+ if (error2 instanceof ScaleMuleError) {
2732
2924
  if (options?.onError) {
2733
- const custom = options.onError(error);
2925
+ const custom = options.onError(error2);
2734
2926
  if (custom) return custom;
2735
2927
  }
2736
- const safeMessage = error.status >= 500 ? "An unexpected error occurred" : error.message;
2737
- if (error.status >= 500) {
2738
- console.error("Internal API error:", error.message);
2928
+ const safeMessage = error2.status >= 500 ? "An unexpected error occurred" : error2.message;
2929
+ if (error2.status >= 500) {
2930
+ console.error("Internal API error:", error2.message);
2739
2931
  }
2740
2932
  return Response.json(
2741
2933
  {
2742
2934
  success: false,
2743
- error: { code: error.code, message: safeMessage },
2744
- ...error.requestId ? { meta: { request_id: error.requestId } } : {}
2935
+ error: { code: error2.code, message: safeMessage },
2936
+ ...error2.requestId ? { meta: { request_id: error2.requestId } } : {}
2745
2937
  },
2746
- { status: error.status }
2938
+ { status: error2.status }
2747
2939
  );
2748
2940
  }
2749
- if (error instanceof Response) return error;
2750
- console.error("Unhandled API error:", error);
2941
+ if (error2 instanceof Response) return error2;
2942
+ console.error("Unhandled API error:", error2);
2751
2943
  return Response.json(
2752
2944
  { success: false, error: { code: "INTERNAL_ERROR", message: "An unexpected error occurred" } },
2753
2945
  { status: 500 }
@@ -2828,8 +3020,8 @@ function createWebhookRoutes(config = {}) {
2828
3020
  status: 200,
2829
3021
  headers: { "Content-Type": "application/json" }
2830
3022
  });
2831
- } catch (error) {
2832
- console.error("Webhook handler error:", error);
3023
+ } catch (error2) {
3024
+ console.error("Webhook handler error:", error2);
2833
3025
  return new Response(JSON.stringify({ error: "Handler failed" }), {
2834
3026
  status: 500,
2835
3027
  headers: { "Content-Type": "application/json" }
@@ -2861,7 +3053,7 @@ function createWebhookHandler(config = {}) {
2861
3053
  status: 200,
2862
3054
  headers: { "Content-Type": "application/json" }
2863
3055
  });
2864
- } catch (error) {
3056
+ } catch (error2) {
2865
3057
  return new Response(JSON.stringify({ error: "Webhook processing failed" }), {
2866
3058
  status: 500,
2867
3059
  headers: { "Content-Type": "application/json" }
@@ -3007,8 +3199,8 @@ function createAuthMiddleware(config = {}) {
3007
3199
  try {
3008
3200
  const sm = createServerClient();
3009
3201
  await sm.auth.me(session.sessionToken);
3010
- } catch (error) {
3011
- console.error("[ScaleMule Middleware] Session validation failed, blocking request:", error);
3202
+ } catch (error2) {
3203
+ console.error("[ScaleMule Middleware] Session validation failed, blocking request:", error2);
3012
3204
  const response = server.NextResponse.redirect(new URL(redirectTo, request.url));
3013
3205
  response.cookies.delete(SESSION_COOKIE_NAME);
3014
3206
  response.cookies.delete(USER_ID_COOKIE_NAME);
@@ -3105,11 +3297,11 @@ async function getAppSecret(key) {
3105
3297
  };
3106
3298
  }
3107
3299
  return result?.value;
3108
- } catch (error) {
3109
- if (error instanceof ScaleMuleApiError && error.code === "SECRET_NOT_FOUND") {
3300
+ } catch (error2) {
3301
+ if (error2 instanceof ScaleMuleApiError && error2.code === "SECRET_NOT_FOUND") {
3110
3302
  return void 0;
3111
3303
  }
3112
- console.error(`[ScaleMule Secrets] Error fetching ${key}:`, error);
3304
+ console.error(`[ScaleMule Secrets] Error fetching ${key}:`, error2);
3113
3305
  return void 0;
3114
3306
  }
3115
3307
  }
@@ -3166,11 +3358,11 @@ async function getBundle(key, resolve = true) {
3166
3358
  };
3167
3359
  }
3168
3360
  return result?.data;
3169
- } catch (error) {
3170
- if (error instanceof ScaleMuleApiError && error.code === "BUNDLE_NOT_FOUND") {
3361
+ } catch (error2) {
3362
+ if (error2 instanceof ScaleMuleApiError && error2.code === "BUNDLE_NOT_FOUND") {
3171
3363
  return void 0;
3172
3364
  }
3173
- console.error(`[ScaleMule Bundles] Error fetching ${key}:`, error);
3365
+ console.error(`[ScaleMule Bundles] Error fetching ${key}:`, error2);
3174
3366
  return void 0;
3175
3367
  }
3176
3368
  }