@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.
@@ -9,18 +9,46 @@ 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
 
24
+ // src/url-privacy.ts
25
+ function withoutAuthSecrets(value) {
26
+ if (!value) return value;
27
+ try {
28
+ const absolute = /^[a-z][a-z0-9+.-]*:/i.test(value);
29
+ const protocolRelative = value.startsWith("//");
30
+ const url = new URL(value, "https://relative.invalid");
31
+ if (!["http:", "https:"].includes(url.protocol)) return void 0;
32
+ let changed = false;
33
+ for (const name of [...url.searchParams.keys()]) {
34
+ if (/^(token|code|state|password|new_password|access_token|refresh_token|id_token|api_key|client_secret|challenge_token|challenge_code)$/i.test(name)) {
35
+ url.searchParams.delete(name);
36
+ changed = true;
37
+ }
38
+ }
39
+ if (url.hash) {
40
+ url.hash = "";
41
+ changed = true;
42
+ }
43
+ if (!changed) return value;
44
+ if (absolute) return url.toString();
45
+ if (protocolRelative) return url.toString().replace(/^https:/, "");
46
+ return value.split(/[?#]/, 1)[0] + url.search;
47
+ } catch {
48
+ return void 0;
49
+ }
50
+ }
51
+
24
52
  // src/server/context.ts
25
53
  function validateIP(ip) {
26
54
  if (!ip) return void 0;
@@ -34,7 +62,7 @@ function validateIP(ip) {
34
62
  }
35
63
  return void 0;
36
64
  }
37
- function extractClientContext(request) {
65
+ function extractClientContext(request, options = {}) {
38
66
  const headers3 = request.headers;
39
67
  let ip;
40
68
  ip = validateIP(headers3.get("x-real-ip"));
@@ -77,9 +105,14 @@ function extractClientContext(request) {
77
105
  if (!ip && request.ip) {
78
106
  ip = validateIP(request.ip);
79
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
+ }
80
113
  const userAgent = headers3.get("user-agent") || void 0;
81
114
  const deviceFingerprint = headers3.get("x-device-fingerprint") || void 0;
82
- const referrer = headers3.get("referer") || void 0;
115
+ const referrer = withoutAuthSecrets(headers3.get("referer") || void 0);
83
116
  const anonymousId = headers3.get("x-anonymous-id") || void 0;
84
117
  return {
85
118
  ip,
@@ -141,7 +174,7 @@ function extractClientContextFromReq(req) {
141
174
  }
142
175
  const userAgent = getHeader("user-agent");
143
176
  const deviceFingerprint = getHeader("x-device-fingerprint");
144
- const referrer = getHeader("referer");
177
+ const referrer = withoutAuthSecrets(getHeader("referer"));
145
178
  const anonymousId = getHeader("x-anonymous-id");
146
179
  return {
147
180
  ip,
@@ -183,8 +216,8 @@ function buildFlagContext(clientContext, extraContext = {}) {
183
216
  }
184
217
 
185
218
  // src/error-context.ts
186
- function withErrorContext(error, responseData, headers3) {
187
- const enriched = { ...error };
219
+ function withErrorContext(error2, responseData, headers3) {
220
+ const enriched = { ...error2 };
188
221
  const meta = responseData?.meta;
189
222
  const requestId = meta?.request_id ?? headers3?.get("x-request-id") ?? void 0;
190
223
  if (requestId !== void 0 && enriched.requestId === void 0) {
@@ -218,6 +251,14 @@ var ScaleMuleServer = class {
218
251
  // Auth Methods
219
252
  // ==========================================================================
220
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
+ },
221
262
  /**
222
263
  * Register a new user
223
264
  */
@@ -877,7 +918,7 @@ var ScaleMuleServer = class {
877
918
  code: `HTTP_${response.status}`,
878
919
  message: responseData?.message || text || response.statusText
879
920
  };
880
- const error = withErrorContext(baseError, responseData, response.headers);
921
+ const error2 = withErrorContext(baseError, responseData, response.headers);
881
922
  if (response.status === 401 && options.sessionToken && !options.isAutoRefresh) {
882
923
  if (this.debug) console.log("[ScaleMule Server] 401 received, attempting auto-refresh...");
883
924
  try {
@@ -900,12 +941,12 @@ var ScaleMuleServer = class {
900
941
  if (this.debug) console.error("[ScaleMule Server] Auto-refresh failed:", refreshErr);
901
942
  const refreshApiError = refreshErr instanceof ScaleMuleApiError ? { code: refreshErr.code, message: refreshErr.message } : { code: "REFRESH_FAILED", message: "Auto-refresh failed" };
902
943
  this.onAutoRefreshFailed?.(refreshApiError);
903
- throw new ScaleMuleApiError(error);
944
+ throw new ScaleMuleApiError(error2);
904
945
  } finally {
905
946
  this.onRefreshEnd?.();
906
947
  }
907
948
  }
908
- throw new ScaleMuleApiError(error);
949
+ throw new ScaleMuleApiError(error2);
909
950
  }
910
951
  const data = responseData?.data !== void 0 ? responseData.data : responseData;
911
952
  return data;
@@ -946,9 +987,10 @@ function createCookieHeader(name, value, options = {}) {
946
987
  const sameSite = options.sameSite ?? "lax";
947
988
  const path = options.path ?? "/";
948
989
  let cookie = `${name}=${encodeURIComponent(value)}; Path=${path}; Max-Age=${maxAge}; HttpOnly; SameSite=${sameSite}`;
949
- if (secure) {
990
+ if (secure || options.partitioned) {
950
991
  cookie += "; Secure";
951
992
  }
993
+ if (options.partitioned) cookie += "; Partitioned";
952
994
  if (options.domain) {
953
995
  cookie += `; Domain=${options.domain}`;
954
996
  }
@@ -959,9 +1001,10 @@ function createClearCookieHeader(name, options = {}) {
959
1001
  const secure = options.secure ?? process.env.NODE_ENV === "production";
960
1002
  const sameSite = options.sameSite ?? "lax";
961
1003
  let cookie = `${name}=; Path=${path}; Max-Age=0; HttpOnly; SameSite=${sameSite}`;
962
- if (secure) {
1004
+ if (secure || options.partitioned) {
963
1005
  cookie += "; Secure";
964
1006
  }
1007
+ if (options.partitioned) cookie += "; Partitioned";
965
1008
  if (options.domain) {
966
1009
  cookie += `; Domain=${options.domain}`;
967
1010
  }
@@ -970,6 +1013,10 @@ function createClearCookieHeader(name, options = {}) {
970
1013
  function withSession(loginResponse, responseBody, options = {}) {
971
1014
  const headers3 = new Headers();
972
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
+ }
973
1020
  headers3.append(
974
1021
  "Set-Cookie",
975
1022
  createCookieHeader(SESSION_COOKIE_NAME, loginResponse.session_token, options)
@@ -986,6 +1033,10 @@ function withSession(loginResponse, responseBody, options = {}) {
986
1033
  function withRefreshedSession(sessionToken, userId, responseBody, options = {}) {
987
1034
  const headers3 = new Headers();
988
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
+ }
989
1040
  headers3.append(
990
1041
  "Set-Cookie",
991
1042
  createCookieHeader(SESSION_COOKIE_NAME, sessionToken, options)
@@ -1002,6 +1053,10 @@ function withRefreshedSession(sessionToken, userId, responseBody, options = {})
1002
1053
  function clearSession(responseBody, options = {}, status = 200) {
1003
1054
  const headers3 = new Headers();
1004
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
+ }
1005
1060
  headers3.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, options));
1006
1061
  headers3.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, options));
1007
1062
  return new Response(JSON.stringify({ success: status < 300, data: responseBody }), {
@@ -1009,7 +1064,7 @@ function clearSession(responseBody, options = {}, status = 200) {
1009
1064
  headers: headers3
1010
1065
  });
1011
1066
  }
1012
- async function getSession() {
1067
+ async function getSession(options = {}) {
1013
1068
  const cookieStore = await cookies();
1014
1069
  const sessionCookie = cookieStore.get(SESSION_COOKIE_NAME);
1015
1070
  const userIdCookie = cookieStore.get(USER_ID_COOKIE_NAME);
@@ -1021,6 +1076,7 @@ async function getSession() {
1021
1076
  // Note: actual expiry is managed by ScaleMule backend
1022
1077
  };
1023
1078
  }
1079
+ if (options.allowBearer === false) return null;
1024
1080
  const headerStore = await headers();
1025
1081
  return sessionFromAuthHeaders(
1026
1082
  headerStore.get("authorization"),
@@ -1303,10 +1359,10 @@ async function validateCSRFTokenAsync(request, body) {
1303
1359
  function withCSRFProtection(handler) {
1304
1360
  return async (request) => {
1305
1361
  if (["POST", "PUT", "PATCH", "DELETE"].includes(request.method)) {
1306
- const error = validateCSRFToken(request);
1307
- if (error) {
1362
+ const error2 = validateCSRFToken(request);
1363
+ if (error2) {
1308
1364
  return NextResponse.json(
1309
- { error: "CSRF validation failed", message: error },
1365
+ { error: "CSRF validation failed", message: error2 },
1310
1366
  { status: 403 }
1311
1367
  );
1312
1368
  }
@@ -1323,6 +1379,139 @@ async function getCSRFToken() {
1323
1379
  return token;
1324
1380
  }
1325
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/items", "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
+
1326
1515
  // src/server/routes.ts
1327
1516
  function errorResponse(code, message, status) {
1328
1517
  return new Response(
@@ -1339,6 +1528,12 @@ function successResponse(data, status = 200) {
1339
1528
  function createAuthRoutes(config = {}) {
1340
1529
  const sm = createServerClient(config.client);
1341
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
+ });
1342
1537
  const POST = async (request, context) => {
1343
1538
  if (config.csrf) {
1344
1539
  const csrfError = validateCSRFToken(request);
@@ -1350,7 +1545,7 @@ function createAuthRoutes(config = {}) {
1350
1545
  const path = params?.scalemule?.join("/") || "";
1351
1546
  try {
1352
1547
  const body = await request.json().catch(() => ({}));
1353
- const clientContext = extractClientContext(request);
1548
+ const clientContext = extractClientContext(request, config.clientContext);
1354
1549
  switch (path) {
1355
1550
  // ==================== Register ====================
1356
1551
  case "register": {
@@ -1376,9 +1571,9 @@ function createAuthRoutes(config = {}) {
1376
1571
  try {
1377
1572
  loginData = await sm.auth.login({ email, password }, { clientContext });
1378
1573
  } catch {
1379
- return successResponse({ user: registeredUser, message: "Registration successful" }, 201);
1574
+ return successResponse({ user: registeredUser, authenticated: false, message: "Registration successful" }, 201);
1380
1575
  }
1381
- 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);
1382
1577
  if (config.enableAccountSwitcher) {
1383
1578
  const existingKnown = getKnownAccountsCookieRaw(request);
1384
1579
  appendKnownAccountCookie(
@@ -1398,6 +1593,12 @@ function createAuthRoutes(config = {}) {
1398
1593
  }
1399
1594
  return registerResponse;
1400
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
+ }
1401
1602
  case "mfa/send-code": {
1402
1603
  const { pending_token, method } = body;
1403
1604
  if (!pending_token || !["email", "sms"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token and method required", 400);
@@ -1409,7 +1610,7 @@ function createAuthRoutes(config = {}) {
1409
1610
  const result = await sm.auth.completeMfa(pending_token, code, method, { clientContext });
1410
1611
  if (!result.session_token || !result.user) return errorResponse("MFA_FAILED", "Unable to complete sign-in", 400);
1411
1612
  await config.onLogin?.({ id: result.user.id, email: result.user.email });
1412
- 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);
1413
1614
  if (config.enableAccountSwitcher) {
1414
1615
  appendKnownAccountCookie(response.headers, {
1415
1616
  userId: result.user.id,
@@ -1434,7 +1635,7 @@ function createAuthRoutes(config = {}) {
1434
1635
  } catch (err) {
1435
1636
  const apiErr = err instanceof ScaleMuleApiError ? err : null;
1436
1637
  const errorCode = apiErr?.code || "LOGIN_FAILED";
1437
- let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 202 : 400;
1638
+ let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 403 : 400;
1438
1639
  if (errorCode === "CHALLENGE_RATE_LIMITED") status = 429;
1439
1640
  if (errorCode === "INVALID_CREDENTIALS" || errorCode === "UNAUTHORIZED") status = 401;
1440
1641
  if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED"].includes(errorCode)) {
@@ -1452,7 +1653,7 @@ function createAuthRoutes(config = {}) {
1452
1653
  email: loginData.user.email
1453
1654
  });
1454
1655
  }
1455
- 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);
1456
1657
  if (config.enableAccountSwitcher) {
1457
1658
  const existingKnown = getKnownAccountsCookieRaw(request);
1458
1659
  appendKnownAccountCookie(
@@ -1474,7 +1675,7 @@ function createAuthRoutes(config = {}) {
1474
1675
  }
1475
1676
  // ==================== Logout ====================
1476
1677
  case "logout": {
1477
- const session = await getSession();
1678
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1478
1679
  let rotated = null;
1479
1680
  if (session) {
1480
1681
  try {
@@ -1538,7 +1739,7 @@ function createAuthRoutes(config = {}) {
1538
1739
  if (verifyData?.session_token && verifyData?.user) {
1539
1740
  return withSession(
1540
1741
  { session_token: verifyData.session_token, user: verifyData.user },
1541
- { 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) },
1542
1743
  cookieOptions
1543
1744
  );
1544
1745
  }
@@ -1548,7 +1749,7 @@ function createAuthRoutes(config = {}) {
1548
1749
  // Supports both authenticated (session-based) and unauthenticated (email-based) resend
1549
1750
  case "resend-verification": {
1550
1751
  const { email } = body;
1551
- const session = await getSession();
1752
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1552
1753
  let rotated = null;
1553
1754
  if (email) {
1554
1755
  try {
@@ -1592,7 +1793,7 @@ function createAuthRoutes(config = {}) {
1592
1793
  }
1593
1794
  // ==================== Refresh Session ====================
1594
1795
  case "refresh": {
1595
- const session = await getSession();
1796
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1596
1797
  if (!session) {
1597
1798
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1598
1799
  }
@@ -1602,19 +1803,20 @@ function createAuthRoutes(config = {}) {
1602
1803
  } catch {
1603
1804
  return clearSession(
1604
1805
  { message: "Session expired" },
1605
- cookieOptions
1806
+ cookieOptions,
1807
+ 401
1606
1808
  );
1607
1809
  }
1608
1810
  return withRefreshedSession(
1609
1811
  refreshData.session_token,
1610
1812
  session.userId,
1611
- { message: "Session refreshed" },
1813
+ { message: "Session refreshed", ...config.sessionMode === "bearer" ? { sessionToken: refreshData.session_token, userId: session.userId } : {} },
1612
1814
  cookieOptions
1613
1815
  );
1614
1816
  }
1615
1817
  // ==================== Change Password ====================
1616
1818
  case "change-password": {
1617
- const session = await getSession();
1819
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1618
1820
  if (!session) {
1619
1821
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1620
1822
  }
@@ -1659,7 +1861,7 @@ function createAuthRoutes(config = {}) {
1659
1861
  if (!config.enableAccountSwitcher) {
1660
1862
  return errorResponse("NOT_FOUND", "Account switcher not enabled", 404);
1661
1863
  }
1662
- const session = await getSession();
1864
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1663
1865
  if (session) {
1664
1866
  try {
1665
1867
  await sm.auth.logout(session.sessionToken);
@@ -1709,6 +1911,9 @@ function createAuthRoutes(config = {}) {
1709
1911
  return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
1710
1912
  }
1711
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
+ }
1712
1917
  if (path.startsWith("mfa/") && err instanceof ScaleMuleApiError) {
1713
1918
  const status = ["CHALLENGE_RATE_LIMITED", "MFA_RATE_LIMITED", "MFA_MAX_ATTEMPTS"].includes(err.code) ? 429 : 400;
1714
1919
  return errorResponse(err.code, err.message, status);
@@ -1729,7 +1934,7 @@ function createAuthRoutes(config = {}) {
1729
1934
  if (normCookie) resp.headers.append("Set-Cookie", normCookie);
1730
1935
  return resp;
1731
1936
  };
1732
- const session = await getSession();
1937
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1733
1938
  if (!session) {
1734
1939
  return withNorm(errorResponse("UNAUTHORIZED", "Authentication required", 401));
1735
1940
  }
@@ -1751,15 +1956,15 @@ function createAuthRoutes(config = {}) {
1751
1956
  return withNorm(withRefreshedSession(
1752
1957
  rotated,
1753
1958
  session.userId,
1754
- { user: userData, sessionToken: rotated, userId: session.userId },
1959
+ sessionData(userData, rotated),
1755
1960
  cookieOptions
1756
1961
  ));
1757
1962
  }
1758
- return withNorm(successResponse({ user: userData, sessionToken: session.sessionToken, userId: session.userId }));
1963
+ return withNorm(successResponse(sessionData(userData, session.sessionToken)));
1759
1964
  }
1760
1965
  // ==================== Get Session Status ====================
1761
1966
  case "session": {
1762
- const session = await getSession();
1967
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1763
1968
  return successResponse({
1764
1969
  authenticated: !!session,
1765
1970
  userId: session?.userId || null
@@ -1789,7 +1994,7 @@ function createAuthRoutes(config = {}) {
1789
1994
  // ==================== Delete Account ====================
1790
1995
  case "me":
1791
1996
  case "account": {
1792
- const session = await getSession();
1997
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1793
1998
  if (!session) {
1794
1999
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1795
2000
  }
@@ -1826,7 +2031,7 @@ function createAuthRoutes(config = {}) {
1826
2031
  // ==================== Update Profile ====================
1827
2032
  case "me":
1828
2033
  case "profile": {
1829
- const session = await getSession();
2034
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1830
2035
  if (!session) {
1831
2036
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1832
2037
  }
@@ -1866,7 +2071,22 @@ function createAuthRoutes(config = {}) {
1866
2071
  return errorResponse("SERVER_ERROR", "Internal server error", 500);
1867
2072
  }
1868
2073
  };
1869
- 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)) };
1870
2090
  }
1871
2091
  function getPrimaryTrackingContextSource(body) {
1872
2092
  if (Array.isArray(body.events)) {
@@ -2270,10 +2490,10 @@ function createLedveryRoutes(config) {
2270
2490
  const code = url.searchParams.get("code");
2271
2491
  const callbackState = url.searchParams.get("state");
2272
2492
  if (!code) {
2273
- const error = url.searchParams.get("error");
2493
+ const error2 = url.searchParams.get("error");
2274
2494
  const errorDesc = url.searchParams.get("error_description");
2275
2495
  return new Response(
2276
- 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" }),
2277
2497
  { status: 403, headers: { "Content-Type": "application/json" } }
2278
2498
  );
2279
2499
  }
@@ -2697,27 +2917,27 @@ function apiHandler(handler, options) {
2697
2917
  return Response.json({ success: true, data: result }, { status: 200 });
2698
2918
  }
2699
2919
  return new Response(null, { status: 204 });
2700
- } catch (error) {
2701
- if (error instanceof ScaleMuleError) {
2920
+ } catch (error2) {
2921
+ if (error2 instanceof ScaleMuleError) {
2702
2922
  if (options?.onError) {
2703
- const custom = options.onError(error);
2923
+ const custom = options.onError(error2);
2704
2924
  if (custom) return custom;
2705
2925
  }
2706
- const safeMessage = error.status >= 500 ? "An unexpected error occurred" : error.message;
2707
- if (error.status >= 500) {
2708
- 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);
2709
2929
  }
2710
2930
  return Response.json(
2711
2931
  {
2712
2932
  success: false,
2713
- error: { code: error.code, message: safeMessage },
2714
- ...error.requestId ? { meta: { request_id: error.requestId } } : {}
2933
+ error: { code: error2.code, message: safeMessage },
2934
+ ...error2.requestId ? { meta: { request_id: error2.requestId } } : {}
2715
2935
  },
2716
- { status: error.status }
2936
+ { status: error2.status }
2717
2937
  );
2718
2938
  }
2719
- if (error instanceof Response) return error;
2720
- console.error("Unhandled API error:", error);
2939
+ if (error2 instanceof Response) return error2;
2940
+ console.error("Unhandled API error:", error2);
2721
2941
  return Response.json(
2722
2942
  { success: false, error: { code: "INTERNAL_ERROR", message: "An unexpected error occurred" } },
2723
2943
  { status: 500 }
@@ -2798,8 +3018,8 @@ function createWebhookRoutes(config = {}) {
2798
3018
  status: 200,
2799
3019
  headers: { "Content-Type": "application/json" }
2800
3020
  });
2801
- } catch (error) {
2802
- console.error("Webhook handler error:", error);
3021
+ } catch (error2) {
3022
+ console.error("Webhook handler error:", error2);
2803
3023
  return new Response(JSON.stringify({ error: "Handler failed" }), {
2804
3024
  status: 500,
2805
3025
  headers: { "Content-Type": "application/json" }
@@ -2831,7 +3051,7 @@ function createWebhookHandler(config = {}) {
2831
3051
  status: 200,
2832
3052
  headers: { "Content-Type": "application/json" }
2833
3053
  });
2834
- } catch (error) {
3054
+ } catch (error2) {
2835
3055
  return new Response(JSON.stringify({ error: "Webhook processing failed" }), {
2836
3056
  status: 500,
2837
3057
  headers: { "Content-Type": "application/json" }
@@ -2977,8 +3197,8 @@ function createAuthMiddleware(config = {}) {
2977
3197
  try {
2978
3198
  const sm = createServerClient();
2979
3199
  await sm.auth.me(session.sessionToken);
2980
- } catch (error) {
2981
- console.error("[ScaleMule Middleware] Session validation failed, blocking request:", error);
3200
+ } catch (error2) {
3201
+ console.error("[ScaleMule Middleware] Session validation failed, blocking request:", error2);
2982
3202
  const response = NextResponse.redirect(new URL(redirectTo, request.url));
2983
3203
  response.cookies.delete(SESSION_COOKIE_NAME);
2984
3204
  response.cookies.delete(USER_ID_COOKIE_NAME);
@@ -3075,11 +3295,11 @@ async function getAppSecret(key) {
3075
3295
  };
3076
3296
  }
3077
3297
  return result?.value;
3078
- } catch (error) {
3079
- if (error instanceof ScaleMuleApiError && error.code === "SECRET_NOT_FOUND") {
3298
+ } catch (error2) {
3299
+ if (error2 instanceof ScaleMuleApiError && error2.code === "SECRET_NOT_FOUND") {
3080
3300
  return void 0;
3081
3301
  }
3082
- console.error(`[ScaleMule Secrets] Error fetching ${key}:`, error);
3302
+ console.error(`[ScaleMule Secrets] Error fetching ${key}:`, error2);
3083
3303
  return void 0;
3084
3304
  }
3085
3305
  }
@@ -3136,11 +3356,11 @@ async function getBundle(key, resolve = true) {
3136
3356
  };
3137
3357
  }
3138
3358
  return result?.data;
3139
- } catch (error) {
3140
- if (error instanceof ScaleMuleApiError && error.code === "BUNDLE_NOT_FOUND") {
3359
+ } catch (error2) {
3360
+ if (error2 instanceof ScaleMuleApiError && error2.code === "BUNDLE_NOT_FOUND") {
3141
3361
  return void 0;
3142
3362
  }
3143
- console.error(`[ScaleMule Bundles] Error fetching ${key}:`, error);
3363
+ console.error(`[ScaleMule Bundles] Error fetching ${key}:`, error2);
3144
3364
  return void 0;
3145
3365
  }
3146
3366
  }