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