@scalemule/nextjs 0.1.51 → 0.1.53

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,18 +11,46 @@ 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
 
26
+ // src/url-privacy.ts
27
+ function withoutAuthSecrets(value) {
28
+ if (!value) return value;
29
+ try {
30
+ const absolute = /^[a-z][a-z0-9+.-]*:/i.test(value);
31
+ const protocolRelative = value.startsWith("//");
32
+ const url = new URL(value, "https://relative.invalid");
33
+ if (!["http:", "https:"].includes(url.protocol)) return void 0;
34
+ let changed = false;
35
+ for (const name of [...url.searchParams.keys()]) {
36
+ if (/^(token|code|state|password|new_password|access_token|refresh_token|id_token|api_key|client_secret|challenge_token|challenge_code)$/i.test(name)) {
37
+ url.searchParams.delete(name);
38
+ changed = true;
39
+ }
40
+ }
41
+ if (url.hash) {
42
+ url.hash = "";
43
+ changed = true;
44
+ }
45
+ if (!changed) return value;
46
+ if (absolute) return url.toString();
47
+ if (protocolRelative) return url.toString().replace(/^https:/, "");
48
+ return value.split(/[?#]/, 1)[0] + url.search;
49
+ } catch {
50
+ return void 0;
51
+ }
52
+ }
53
+
26
54
  // src/server/context.ts
27
55
  function validateIP(ip) {
28
56
  if (!ip) return void 0;
@@ -36,7 +64,7 @@ function validateIP(ip) {
36
64
  }
37
65
  return void 0;
38
66
  }
39
- function extractClientContext(request) {
67
+ function extractClientContext(request, options = {}) {
40
68
  const headers3 = request.headers;
41
69
  let ip;
42
70
  ip = validateIP(headers3.get("x-real-ip"));
@@ -79,9 +107,14 @@ function extractClientContext(request) {
79
107
  if (!ip && request.ip) {
80
108
  ip = validateIP(request.ip);
81
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
+ }
82
115
  const userAgent = headers3.get("user-agent") || void 0;
83
116
  const deviceFingerprint = headers3.get("x-device-fingerprint") || void 0;
84
- const referrer = headers3.get("referer") || void 0;
117
+ const referrer = withoutAuthSecrets(headers3.get("referer") || void 0);
85
118
  const anonymousId = headers3.get("x-anonymous-id") || void 0;
86
119
  return {
87
120
  ip,
@@ -143,7 +176,7 @@ function extractClientContextFromReq(req) {
143
176
  }
144
177
  const userAgent = getHeader("user-agent");
145
178
  const deviceFingerprint = getHeader("x-device-fingerprint");
146
- const referrer = getHeader("referer");
179
+ const referrer = withoutAuthSecrets(getHeader("referer"));
147
180
  const anonymousId = getHeader("x-anonymous-id");
148
181
  return {
149
182
  ip,
@@ -185,8 +218,8 @@ function buildFlagContext(clientContext, extraContext = {}) {
185
218
  }
186
219
 
187
220
  // src/error-context.ts
188
- function withErrorContext(error, responseData, headers3) {
189
- const enriched = { ...error };
221
+ function withErrorContext(error2, responseData, headers3) {
222
+ const enriched = { ...error2 };
190
223
  const meta = responseData?.meta;
191
224
  const requestId = meta?.request_id ?? headers3?.get("x-request-id") ?? void 0;
192
225
  if (requestId !== void 0 && enriched.requestId === void 0) {
@@ -220,6 +253,14 @@ var ScaleMuleServer = class {
220
253
  // Auth Methods
221
254
  // ==========================================================================
222
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
+ },
223
264
  /**
224
265
  * Register a new user
225
266
  */
@@ -879,7 +920,7 @@ var ScaleMuleServer = class {
879
920
  code: `HTTP_${response.status}`,
880
921
  message: responseData?.message || text || response.statusText
881
922
  };
882
- const error = withErrorContext(baseError, responseData, response.headers);
923
+ const error2 = withErrorContext(baseError, responseData, response.headers);
883
924
  if (response.status === 401 && options.sessionToken && !options.isAutoRefresh) {
884
925
  if (this.debug) console.log("[ScaleMule Server] 401 received, attempting auto-refresh...");
885
926
  try {
@@ -902,12 +943,12 @@ var ScaleMuleServer = class {
902
943
  if (this.debug) console.error("[ScaleMule Server] Auto-refresh failed:", refreshErr);
903
944
  const refreshApiError = refreshErr instanceof ScaleMuleApiError ? { code: refreshErr.code, message: refreshErr.message } : { code: "REFRESH_FAILED", message: "Auto-refresh failed" };
904
945
  this.onAutoRefreshFailed?.(refreshApiError);
905
- throw new ScaleMuleApiError(error);
946
+ throw new ScaleMuleApiError(error2);
906
947
  } finally {
907
948
  this.onRefreshEnd?.();
908
949
  }
909
950
  }
910
- throw new ScaleMuleApiError(error);
951
+ throw new ScaleMuleApiError(error2);
911
952
  }
912
953
  const data = responseData?.data !== void 0 ? responseData.data : responseData;
913
954
  return data;
@@ -948,9 +989,10 @@ function createCookieHeader(name, value, options = {}) {
948
989
  const sameSite = options.sameSite ?? "lax";
949
990
  const path = options.path ?? "/";
950
991
  let cookie = `${name}=${encodeURIComponent(value)}; Path=${path}; Max-Age=${maxAge}; HttpOnly; SameSite=${sameSite}`;
951
- if (secure) {
992
+ if (secure || options.partitioned) {
952
993
  cookie += "; Secure";
953
994
  }
995
+ if (options.partitioned) cookie += "; Partitioned";
954
996
  if (options.domain) {
955
997
  cookie += `; Domain=${options.domain}`;
956
998
  }
@@ -961,9 +1003,10 @@ function createClearCookieHeader(name, options = {}) {
961
1003
  const secure = options.secure ?? process.env.NODE_ENV === "production";
962
1004
  const sameSite = options.sameSite ?? "lax";
963
1005
  let cookie = `${name}=; Path=${path}; Max-Age=0; HttpOnly; SameSite=${sameSite}`;
964
- if (secure) {
1006
+ if (secure || options.partitioned) {
965
1007
  cookie += "; Secure";
966
1008
  }
1009
+ if (options.partitioned) cookie += "; Partitioned";
967
1010
  if (options.domain) {
968
1011
  cookie += `; Domain=${options.domain}`;
969
1012
  }
@@ -972,6 +1015,10 @@ function createClearCookieHeader(name, options = {}) {
972
1015
  function withSession(loginResponse, responseBody, options = {}) {
973
1016
  const headers3 = new Headers();
974
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
+ }
975
1022
  headers3.append(
976
1023
  "Set-Cookie",
977
1024
  createCookieHeader(SESSION_COOKIE_NAME, loginResponse.session_token, options)
@@ -988,6 +1035,10 @@ function withSession(loginResponse, responseBody, options = {}) {
988
1035
  function withRefreshedSession(sessionToken, userId, responseBody, options = {}) {
989
1036
  const headers3 = new Headers();
990
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
+ }
991
1042
  headers3.append(
992
1043
  "Set-Cookie",
993
1044
  createCookieHeader(SESSION_COOKIE_NAME, sessionToken, options)
@@ -1004,6 +1055,10 @@ function withRefreshedSession(sessionToken, userId, responseBody, options = {})
1004
1055
  function clearSession(responseBody, options = {}, status = 200) {
1005
1056
  const headers3 = new Headers();
1006
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
+ }
1007
1062
  headers3.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, options));
1008
1063
  headers3.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, options));
1009
1064
  return new Response(JSON.stringify({ success: status < 300, data: responseBody }), {
@@ -1011,7 +1066,7 @@ function clearSession(responseBody, options = {}, status = 200) {
1011
1066
  headers: headers3
1012
1067
  });
1013
1068
  }
1014
- async function getSession() {
1069
+ async function getSession(options = {}) {
1015
1070
  const cookieStore = await headers.cookies();
1016
1071
  const sessionCookie = cookieStore.get(SESSION_COOKIE_NAME);
1017
1072
  const userIdCookie = cookieStore.get(USER_ID_COOKIE_NAME);
@@ -1023,6 +1078,7 @@ async function getSession() {
1023
1078
  // Note: actual expiry is managed by ScaleMule backend
1024
1079
  };
1025
1080
  }
1081
+ if (options.allowBearer === false) return null;
1026
1082
  const headerStore = await headers.headers();
1027
1083
  return sessionFromAuthHeaders(
1028
1084
  headerStore.get("authorization"),
@@ -1305,10 +1361,10 @@ async function validateCSRFTokenAsync(request, body) {
1305
1361
  function withCSRFProtection(handler) {
1306
1362
  return async (request) => {
1307
1363
  if (["POST", "PUT", "PATCH", "DELETE"].includes(request.method)) {
1308
- const error = validateCSRFToken(request);
1309
- if (error) {
1364
+ const error2 = validateCSRFToken(request);
1365
+ if (error2) {
1310
1366
  return server.NextResponse.json(
1311
- { error: "CSRF validation failed", message: error },
1367
+ { error: "CSRF validation failed", message: error2 },
1312
1368
  { status: 403 }
1313
1369
  );
1314
1370
  }
@@ -1325,6 +1381,139 @@ async function getCSRFToken() {
1325
1381
  return token;
1326
1382
  }
1327
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/items", "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
+
1328
1517
  // src/server/routes.ts
1329
1518
  function errorResponse(code, message, status) {
1330
1519
  return new Response(
@@ -1341,6 +1530,12 @@ function successResponse(data, status = 200) {
1341
1530
  function createAuthRoutes(config = {}) {
1342
1531
  const sm = createServerClient(config.client);
1343
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
+ });
1344
1539
  const POST = async (request, context) => {
1345
1540
  if (config.csrf) {
1346
1541
  const csrfError = validateCSRFToken(request);
@@ -1352,7 +1547,7 @@ function createAuthRoutes(config = {}) {
1352
1547
  const path = params?.scalemule?.join("/") || "";
1353
1548
  try {
1354
1549
  const body = await request.json().catch(() => ({}));
1355
- const clientContext = extractClientContext(request);
1550
+ const clientContext = extractClientContext(request, config.clientContext);
1356
1551
  switch (path) {
1357
1552
  // ==================== Register ====================
1358
1553
  case "register": {
@@ -1378,9 +1573,9 @@ function createAuthRoutes(config = {}) {
1378
1573
  try {
1379
1574
  loginData = await sm.auth.login({ email, password }, { clientContext });
1380
1575
  } catch {
1381
- return successResponse({ user: registeredUser, message: "Registration successful" }, 201);
1576
+ return successResponse({ user: registeredUser, authenticated: false, message: "Registration successful" }, 201);
1382
1577
  }
1383
- 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);
1384
1579
  if (config.enableAccountSwitcher) {
1385
1580
  const existingKnown = getKnownAccountsCookieRaw(request);
1386
1581
  appendKnownAccountCookie(
@@ -1400,6 +1595,12 @@ function createAuthRoutes(config = {}) {
1400
1595
  }
1401
1596
  return registerResponse;
1402
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
+ }
1403
1604
  case "mfa/send-code": {
1404
1605
  const { pending_token, method } = body;
1405
1606
  if (!pending_token || !["email", "sms"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token and method required", 400);
@@ -1411,7 +1612,7 @@ function createAuthRoutes(config = {}) {
1411
1612
  const result = await sm.auth.completeMfa(pending_token, code, method, { clientContext });
1412
1613
  if (!result.session_token || !result.user) return errorResponse("MFA_FAILED", "Unable to complete sign-in", 400);
1413
1614
  await config.onLogin?.({ id: result.user.id, email: result.user.email });
1414
- 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);
1415
1616
  if (config.enableAccountSwitcher) {
1416
1617
  appendKnownAccountCookie(response.headers, {
1417
1618
  userId: result.user.id,
@@ -1436,7 +1637,7 @@ function createAuthRoutes(config = {}) {
1436
1637
  } catch (err) {
1437
1638
  const apiErr = err instanceof ScaleMuleApiError ? err : null;
1438
1639
  const errorCode = apiErr?.code || "LOGIN_FAILED";
1439
- let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 202 : 400;
1640
+ let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 403 : 400;
1440
1641
  if (errorCode === "CHALLENGE_RATE_LIMITED") status = 429;
1441
1642
  if (errorCode === "INVALID_CREDENTIALS" || errorCode === "UNAUTHORIZED") status = 401;
1442
1643
  if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED"].includes(errorCode)) {
@@ -1454,7 +1655,7 @@ function createAuthRoutes(config = {}) {
1454
1655
  email: loginData.user.email
1455
1656
  });
1456
1657
  }
1457
- 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);
1458
1659
  if (config.enableAccountSwitcher) {
1459
1660
  const existingKnown = getKnownAccountsCookieRaw(request);
1460
1661
  appendKnownAccountCookie(
@@ -1476,7 +1677,7 @@ function createAuthRoutes(config = {}) {
1476
1677
  }
1477
1678
  // ==================== Logout ====================
1478
1679
  case "logout": {
1479
- const session = await getSession();
1680
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1480
1681
  let rotated = null;
1481
1682
  if (session) {
1482
1683
  try {
@@ -1540,7 +1741,7 @@ function createAuthRoutes(config = {}) {
1540
1741
  if (verifyData?.session_token && verifyData?.user) {
1541
1742
  return withSession(
1542
1743
  { session_token: verifyData.session_token, user: verifyData.user },
1543
- { 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) },
1544
1745
  cookieOptions
1545
1746
  );
1546
1747
  }
@@ -1550,7 +1751,7 @@ function createAuthRoutes(config = {}) {
1550
1751
  // Supports both authenticated (session-based) and unauthenticated (email-based) resend
1551
1752
  case "resend-verification": {
1552
1753
  const { email } = body;
1553
- const session = await getSession();
1754
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1554
1755
  let rotated = null;
1555
1756
  if (email) {
1556
1757
  try {
@@ -1594,7 +1795,7 @@ function createAuthRoutes(config = {}) {
1594
1795
  }
1595
1796
  // ==================== Refresh Session ====================
1596
1797
  case "refresh": {
1597
- const session = await getSession();
1798
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1598
1799
  if (!session) {
1599
1800
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1600
1801
  }
@@ -1604,19 +1805,20 @@ function createAuthRoutes(config = {}) {
1604
1805
  } catch {
1605
1806
  return clearSession(
1606
1807
  { message: "Session expired" },
1607
- cookieOptions
1808
+ cookieOptions,
1809
+ 401
1608
1810
  );
1609
1811
  }
1610
1812
  return withRefreshedSession(
1611
1813
  refreshData.session_token,
1612
1814
  session.userId,
1613
- { message: "Session refreshed" },
1815
+ { message: "Session refreshed", ...config.sessionMode === "bearer" ? { sessionToken: refreshData.session_token, userId: session.userId } : {} },
1614
1816
  cookieOptions
1615
1817
  );
1616
1818
  }
1617
1819
  // ==================== Change Password ====================
1618
1820
  case "change-password": {
1619
- const session = await getSession();
1821
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1620
1822
  if (!session) {
1621
1823
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1622
1824
  }
@@ -1661,7 +1863,7 @@ function createAuthRoutes(config = {}) {
1661
1863
  if (!config.enableAccountSwitcher) {
1662
1864
  return errorResponse("NOT_FOUND", "Account switcher not enabled", 404);
1663
1865
  }
1664
- const session = await getSession();
1866
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1665
1867
  if (session) {
1666
1868
  try {
1667
1869
  await sm.auth.logout(session.sessionToken);
@@ -1711,6 +1913,9 @@ function createAuthRoutes(config = {}) {
1711
1913
  return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
1712
1914
  }
1713
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
+ }
1714
1919
  if (path.startsWith("mfa/") && err instanceof ScaleMuleApiError) {
1715
1920
  const status = ["CHALLENGE_RATE_LIMITED", "MFA_RATE_LIMITED", "MFA_MAX_ATTEMPTS"].includes(err.code) ? 429 : 400;
1716
1921
  return errorResponse(err.code, err.message, status);
@@ -1731,7 +1936,7 @@ function createAuthRoutes(config = {}) {
1731
1936
  if (normCookie) resp.headers.append("Set-Cookie", normCookie);
1732
1937
  return resp;
1733
1938
  };
1734
- const session = await getSession();
1939
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1735
1940
  if (!session) {
1736
1941
  return withNorm(errorResponse("UNAUTHORIZED", "Authentication required", 401));
1737
1942
  }
@@ -1753,15 +1958,15 @@ function createAuthRoutes(config = {}) {
1753
1958
  return withNorm(withRefreshedSession(
1754
1959
  rotated,
1755
1960
  session.userId,
1756
- { user: userData, sessionToken: rotated, userId: session.userId },
1961
+ sessionData(userData, rotated),
1757
1962
  cookieOptions
1758
1963
  ));
1759
1964
  }
1760
- return withNorm(successResponse({ user: userData, sessionToken: session.sessionToken, userId: session.userId }));
1965
+ return withNorm(successResponse(sessionData(userData, session.sessionToken)));
1761
1966
  }
1762
1967
  // ==================== Get Session Status ====================
1763
1968
  case "session": {
1764
- const session = await getSession();
1969
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1765
1970
  return successResponse({
1766
1971
  authenticated: !!session,
1767
1972
  userId: session?.userId || null
@@ -1791,7 +1996,7 @@ function createAuthRoutes(config = {}) {
1791
1996
  // ==================== Delete Account ====================
1792
1997
  case "me":
1793
1998
  case "account": {
1794
- const session = await getSession();
1999
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1795
2000
  if (!session) {
1796
2001
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1797
2002
  }
@@ -1828,7 +2033,7 @@ function createAuthRoutes(config = {}) {
1828
2033
  // ==================== Update Profile ====================
1829
2034
  case "me":
1830
2035
  case "profile": {
1831
- const session = await getSession();
2036
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1832
2037
  if (!session) {
1833
2038
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1834
2039
  }
@@ -1868,7 +2073,22 @@ function createAuthRoutes(config = {}) {
1868
2073
  return errorResponse("SERVER_ERROR", "Internal server error", 500);
1869
2074
  }
1870
2075
  };
1871
- 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)) };
1872
2092
  }
1873
2093
  function getPrimaryTrackingContextSource(body) {
1874
2094
  if (Array.isArray(body.events)) {
@@ -2272,10 +2492,10 @@ function createLedveryRoutes(config) {
2272
2492
  const code = url.searchParams.get("code");
2273
2493
  const callbackState = url.searchParams.get("state");
2274
2494
  if (!code) {
2275
- const error = url.searchParams.get("error");
2495
+ const error2 = url.searchParams.get("error");
2276
2496
  const errorDesc = url.searchParams.get("error_description");
2277
2497
  return new Response(
2278
- 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" }),
2279
2499
  { status: 403, headers: { "Content-Type": "application/json" } }
2280
2500
  );
2281
2501
  }
@@ -2699,27 +2919,27 @@ function apiHandler(handler, options) {
2699
2919
  return Response.json({ success: true, data: result }, { status: 200 });
2700
2920
  }
2701
2921
  return new Response(null, { status: 204 });
2702
- } catch (error) {
2703
- if (error instanceof ScaleMuleError) {
2922
+ } catch (error2) {
2923
+ if (error2 instanceof ScaleMuleError) {
2704
2924
  if (options?.onError) {
2705
- const custom = options.onError(error);
2925
+ const custom = options.onError(error2);
2706
2926
  if (custom) return custom;
2707
2927
  }
2708
- const safeMessage = error.status >= 500 ? "An unexpected error occurred" : error.message;
2709
- if (error.status >= 500) {
2710
- 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);
2711
2931
  }
2712
2932
  return Response.json(
2713
2933
  {
2714
2934
  success: false,
2715
- error: { code: error.code, message: safeMessage },
2716
- ...error.requestId ? { meta: { request_id: error.requestId } } : {}
2935
+ error: { code: error2.code, message: safeMessage },
2936
+ ...error2.requestId ? { meta: { request_id: error2.requestId } } : {}
2717
2937
  },
2718
- { status: error.status }
2938
+ { status: error2.status }
2719
2939
  );
2720
2940
  }
2721
- if (error instanceof Response) return error;
2722
- console.error("Unhandled API error:", error);
2941
+ if (error2 instanceof Response) return error2;
2942
+ console.error("Unhandled API error:", error2);
2723
2943
  return Response.json(
2724
2944
  { success: false, error: { code: "INTERNAL_ERROR", message: "An unexpected error occurred" } },
2725
2945
  { status: 500 }
@@ -2800,8 +3020,8 @@ function createWebhookRoutes(config = {}) {
2800
3020
  status: 200,
2801
3021
  headers: { "Content-Type": "application/json" }
2802
3022
  });
2803
- } catch (error) {
2804
- console.error("Webhook handler error:", error);
3023
+ } catch (error2) {
3024
+ console.error("Webhook handler error:", error2);
2805
3025
  return new Response(JSON.stringify({ error: "Handler failed" }), {
2806
3026
  status: 500,
2807
3027
  headers: { "Content-Type": "application/json" }
@@ -2833,7 +3053,7 @@ function createWebhookHandler(config = {}) {
2833
3053
  status: 200,
2834
3054
  headers: { "Content-Type": "application/json" }
2835
3055
  });
2836
- } catch (error) {
3056
+ } catch (error2) {
2837
3057
  return new Response(JSON.stringify({ error: "Webhook processing failed" }), {
2838
3058
  status: 500,
2839
3059
  headers: { "Content-Type": "application/json" }
@@ -2979,8 +3199,8 @@ function createAuthMiddleware(config = {}) {
2979
3199
  try {
2980
3200
  const sm = createServerClient();
2981
3201
  await sm.auth.me(session.sessionToken);
2982
- } catch (error) {
2983
- console.error("[ScaleMule Middleware] Session validation failed, blocking request:", error);
3202
+ } catch (error2) {
3203
+ console.error("[ScaleMule Middleware] Session validation failed, blocking request:", error2);
2984
3204
  const response = server.NextResponse.redirect(new URL(redirectTo, request.url));
2985
3205
  response.cookies.delete(SESSION_COOKIE_NAME);
2986
3206
  response.cookies.delete(USER_ID_COOKIE_NAME);
@@ -3077,11 +3297,11 @@ async function getAppSecret(key) {
3077
3297
  };
3078
3298
  }
3079
3299
  return result?.value;
3080
- } catch (error) {
3081
- if (error instanceof ScaleMuleApiError && error.code === "SECRET_NOT_FOUND") {
3300
+ } catch (error2) {
3301
+ if (error2 instanceof ScaleMuleApiError && error2.code === "SECRET_NOT_FOUND") {
3082
3302
  return void 0;
3083
3303
  }
3084
- console.error(`[ScaleMule Secrets] Error fetching ${key}:`, error);
3304
+ console.error(`[ScaleMule Secrets] Error fetching ${key}:`, error2);
3085
3305
  return void 0;
3086
3306
  }
3087
3307
  }
@@ -3138,11 +3358,11 @@ async function getBundle(key, resolve = true) {
3138
3358
  };
3139
3359
  }
3140
3360
  return result?.data;
3141
- } catch (error) {
3142
- if (error instanceof ScaleMuleApiError && error.code === "BUNDLE_NOT_FOUND") {
3361
+ } catch (error2) {
3362
+ if (error2 instanceof ScaleMuleApiError && error2.code === "BUNDLE_NOT_FOUND") {
3143
3363
  return void 0;
3144
3364
  }
3145
- console.error(`[ScaleMule Bundles] Error fetching ${key}:`, error);
3365
+ console.error(`[ScaleMule Bundles] Error fetching ${key}:`, error2);
3146
3366
  return void 0;
3147
3367
  }
3148
3368
  }