@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.
@@ -4,7 +4,7 @@
4
4
  * Usage in your Next.js app:
5
5
  * ```ts
6
6
  * // app/api/auth/[...scalemule]/route.ts
7
- * export { GET, POST, DELETE, PATCH } from '@scalemule/nextjs/server/auth'
7
+ * export { GET, POST, DELETE, PATCH, PUT } from '@scalemule/nextjs/server/auth'
8
8
  * ```
9
9
  *
10
10
  * Configuration via environment variables:
@@ -34,5 +34,10 @@ declare const PATCH: (request: Request, context: {
34
34
  scalemule?: string[];
35
35
  }>;
36
36
  }) => Promise<Response>;
37
+ declare const PUT: (request: Request, context: {
38
+ params: Promise<{
39
+ scalemule?: string[];
40
+ }>;
41
+ }) => Promise<Response>;
37
42
 
38
- export { DELETE, GET, PATCH, POST };
43
+ export { DELETE, GET, PATCH, POST, PUT };
@@ -4,7 +4,7 @@
4
4
  * Usage in your Next.js app:
5
5
  * ```ts
6
6
  * // app/api/auth/[...scalemule]/route.ts
7
- * export { GET, POST, DELETE, PATCH } from '@scalemule/nextjs/server/auth'
7
+ * export { GET, POST, DELETE, PATCH, PUT } from '@scalemule/nextjs/server/auth'
8
8
  * ```
9
9
  *
10
10
  * Configuration via environment variables:
@@ -34,5 +34,10 @@ declare const PATCH: (request: Request, context: {
34
34
  scalemule?: string[];
35
35
  }>;
36
36
  }) => Promise<Response>;
37
+ declare const PUT: (request: Request, context: {
38
+ params: Promise<{
39
+ scalemule?: string[];
40
+ }>;
41
+ }) => Promise<Response>;
37
42
 
38
- export { DELETE, GET, PATCH, POST };
43
+ export { DELETE, GET, PATCH, POST, PUT };
@@ -6,15 +6,15 @@ require('next/server');
6
6
 
7
7
  // src/types/index.ts
8
8
  var ScaleMuleApiError = class extends Error {
9
- constructor(error, status) {
10
- super(error.message);
9
+ constructor(error2, status) {
10
+ super(error2.message);
11
11
  this.name = "ScaleMuleApiError";
12
- this.code = error.code;
13
- this.field = error.field;
12
+ this.code = error2.code;
13
+ this.field = error2.field;
14
14
  this.status = status;
15
- this.requestId = error.requestId;
16
- this.traceId = error.traceId;
17
- this.problem = error.problem;
15
+ this.requestId = error2.requestId;
16
+ this.traceId = error2.traceId;
17
+ this.problem = error2.problem;
18
18
  }
19
19
  };
20
20
 
@@ -59,7 +59,7 @@ function validateIP(ip) {
59
59
  }
60
60
  return void 0;
61
61
  }
62
- function extractClientContext(request) {
62
+ function extractClientContext(request, options = {}) {
63
63
  const headers2 = request.headers;
64
64
  let ip;
65
65
  ip = validateIP(headers2.get("x-real-ip"));
@@ -102,6 +102,11 @@ function extractClientContext(request) {
102
102
  if (!ip && request.ip) {
103
103
  ip = validateIP(request.ip);
104
104
  }
105
+ if (options.trustedIpHeader) {
106
+ const value = headers2.get(options.trustedIpHeader);
107
+ const hop = options.trustedIpHeader === "x-forwarded-for" ? value?.split(",").at(-1)?.trim() : value;
108
+ ip = validateIP(hop);
109
+ }
105
110
  const userAgent = headers2.get("user-agent") || void 0;
106
111
  const deviceFingerprint = headers2.get("x-device-fingerprint") || void 0;
107
112
  const referrer = withoutAuthSecrets(headers2.get("referer") || void 0);
@@ -139,8 +144,8 @@ function buildClientContextHeaders(context) {
139
144
  }
140
145
 
141
146
  // src/error-context.ts
142
- function withErrorContext(error, responseData, headers2) {
143
- const enriched = { ...error };
147
+ function withErrorContext(error2, responseData, headers2) {
148
+ const enriched = { ...error2 };
144
149
  const meta = responseData?.meta;
145
150
  const requestId = meta?.request_id ?? headers2?.get("x-request-id") ?? void 0;
146
151
  if (requestId !== void 0 && enriched.requestId === void 0) {
@@ -174,6 +179,14 @@ var ScaleMuleServer = class {
174
179
  // Auth Methods
175
180
  // ==========================================================================
176
181
  this.auth = {
182
+ /** Issue a 60-second, single-use transfer code after a server OAuth callback. */
183
+ createSessionHandoff: async (sessionToken, audience) => {
184
+ return this.request("POST", "/v1/auth/session-handoff", { sessionToken, body: { session_token: sessionToken, audience } });
185
+ },
186
+ /** Exchange only on the server; write the returned session into an HTTP-only cookie. */
187
+ exchangeSessionHandoff: async (code, audience) => {
188
+ return this.request("POST", "/v1/auth/session-handoff/exchange", { body: { code, audience } });
189
+ },
177
190
  /**
178
191
  * Register a new user
179
192
  */
@@ -833,7 +846,7 @@ var ScaleMuleServer = class {
833
846
  code: `HTTP_${response.status}`,
834
847
  message: responseData?.message || text || response.statusText
835
848
  };
836
- const error = withErrorContext(baseError, responseData, response.headers);
849
+ const error2 = withErrorContext(baseError, responseData, response.headers);
837
850
  if (response.status === 401 && options.sessionToken && !options.isAutoRefresh) {
838
851
  if (this.debug) console.log("[ScaleMule Server] 401 received, attempting auto-refresh...");
839
852
  try {
@@ -856,12 +869,12 @@ var ScaleMuleServer = class {
856
869
  if (this.debug) console.error("[ScaleMule Server] Auto-refresh failed:", refreshErr);
857
870
  const refreshApiError = refreshErr instanceof ScaleMuleApiError ? { code: refreshErr.code, message: refreshErr.message } : { code: "REFRESH_FAILED", message: "Auto-refresh failed" };
858
871
  this.onAutoRefreshFailed?.(refreshApiError);
859
- throw new ScaleMuleApiError(error);
872
+ throw new ScaleMuleApiError(error2);
860
873
  } finally {
861
874
  this.onRefreshEnd?.();
862
875
  }
863
876
  }
864
- throw new ScaleMuleApiError(error);
877
+ throw new ScaleMuleApiError(error2);
865
878
  }
866
879
  const data = responseData?.data !== void 0 ? responseData.data : responseData;
867
880
  return data;
@@ -902,9 +915,10 @@ function createCookieHeader(name, value, options = {}) {
902
915
  const sameSite = options.sameSite ?? "lax";
903
916
  const path = options.path ?? "/";
904
917
  let cookie = `${name}=${encodeURIComponent(value)}; Path=${path}; Max-Age=${maxAge}; HttpOnly; SameSite=${sameSite}`;
905
- if (secure) {
918
+ if (secure || options.partitioned) {
906
919
  cookie += "; Secure";
907
920
  }
921
+ if (options.partitioned) cookie += "; Partitioned";
908
922
  if (options.domain) {
909
923
  cookie += `; Domain=${options.domain}`;
910
924
  }
@@ -915,9 +929,10 @@ function createClearCookieHeader(name, options = {}) {
915
929
  const secure = options.secure ?? process.env.NODE_ENV === "production";
916
930
  const sameSite = options.sameSite ?? "lax";
917
931
  let cookie = `${name}=; Path=${path}; Max-Age=0; HttpOnly; SameSite=${sameSite}`;
918
- if (secure) {
932
+ if (secure || options.partitioned) {
919
933
  cookie += "; Secure";
920
934
  }
935
+ if (options.partitioned) cookie += "; Partitioned";
921
936
  if (options.domain) {
922
937
  cookie += `; Domain=${options.domain}`;
923
938
  }
@@ -926,6 +941,10 @@ function createClearCookieHeader(name, options = {}) {
926
941
  function withSession(loginResponse, responseBody, options = {}) {
927
942
  const headers2 = new Headers();
928
943
  headers2.set("Content-Type", "application/json");
944
+ if (options.partitioned) {
945
+ headers2.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, { ...options, partitioned: false }));
946
+ headers2.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, { ...options, partitioned: false }));
947
+ }
929
948
  headers2.append(
930
949
  "Set-Cookie",
931
950
  createCookieHeader(SESSION_COOKIE_NAME, loginResponse.session_token, options)
@@ -942,6 +961,10 @@ function withSession(loginResponse, responseBody, options = {}) {
942
961
  function withRefreshedSession(sessionToken, userId, responseBody, options = {}) {
943
962
  const headers2 = new Headers();
944
963
  headers2.set("Content-Type", "application/json");
964
+ if (options.partitioned) {
965
+ headers2.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, { ...options, partitioned: false }));
966
+ headers2.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, { ...options, partitioned: false }));
967
+ }
945
968
  headers2.append(
946
969
  "Set-Cookie",
947
970
  createCookieHeader(SESSION_COOKIE_NAME, sessionToken, options)
@@ -958,6 +981,10 @@ function withRefreshedSession(sessionToken, userId, responseBody, options = {})
958
981
  function clearSession(responseBody, options = {}, status = 200) {
959
982
  const headers2 = new Headers();
960
983
  headers2.set("Content-Type", "application/json");
984
+ if (options.partitioned) {
985
+ headers2.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, { ...options, partitioned: false }));
986
+ headers2.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, { ...options, partitioned: false }));
987
+ }
961
988
  headers2.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, options));
962
989
  headers2.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, options));
963
990
  return new Response(JSON.stringify({ success: status < 300, data: responseBody }), {
@@ -965,7 +992,7 @@ function clearSession(responseBody, options = {}, status = 200) {
965
992
  headers: headers2
966
993
  });
967
994
  }
968
- async function getSession() {
995
+ async function getSession(options = {}) {
969
996
  const cookieStore = await headers.cookies();
970
997
  const sessionCookie = cookieStore.get(SESSION_COOKIE_NAME);
971
998
  const userIdCookie = cookieStore.get(USER_ID_COOKIE_NAME);
@@ -977,6 +1004,7 @@ async function getSession() {
977
1004
  // Note: actual expiry is managed by ScaleMule backend
978
1005
  };
979
1006
  }
1007
+ if (options.allowBearer === false) return null;
980
1008
  const headerStore = await headers.headers();
981
1009
  return sessionFromAuthHeaders(
982
1010
  headerStore.get("authorization"),
@@ -1182,6 +1210,139 @@ function validateCSRFToken(request) {
1182
1210
  return void 0;
1183
1211
  }
1184
1212
 
1213
+ // src/server/browser-proxy.ts
1214
+ function error(code, status) {
1215
+ return Response.json({ success: false, error: { code, message: code === "UNAUTHORIZED" ? "Authentication required" : "Request not permitted" } }, { status, headers: { "Cache-Control": "no-store" } });
1216
+ }
1217
+ function isSameOriginRequest(request) {
1218
+ const origin = request.headers.get("origin");
1219
+ const site = request.headers.get("sec-fetch-site");
1220
+ if (site) return site === "same-origin" || site === "none";
1221
+ const url = new URL(request.url);
1222
+ const host = request.headers.get("host") || url.host;
1223
+ if (origin) {
1224
+ try {
1225
+ const source = new URL(origin);
1226
+ if (!["http:", "https:"].includes(source.protocol) || source.host !== host) return false;
1227
+ } catch {
1228
+ return false;
1229
+ }
1230
+ }
1231
+ return true;
1232
+ }
1233
+ 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"]);
1234
+ var AUTH_ROUTES = /* @__PURE__ */ new Set([
1235
+ "GET me",
1236
+ "GET mfa/status",
1237
+ "GET oauth/providers",
1238
+ "PATCH profile",
1239
+ "POST change-password",
1240
+ "POST change-email",
1241
+ "POST delete-account",
1242
+ "POST export-data",
1243
+ "POST mfa/setup",
1244
+ "POST mfa/verify",
1245
+ "POST mfa/disable",
1246
+ "POST mfa/backup-codes",
1247
+ "POST oauth/start",
1248
+ "POST oauth/callback"
1249
+ ]);
1250
+ var PUBLIC_AUTH_ROUTES = /* @__PURE__ */ new Set(["POST oauth/start", "POST oauth/callback"]);
1251
+ 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"]);
1252
+ var MAX_BODY_BYTES = 25 * 1024 * 1024;
1253
+ async function boundedBody(request) {
1254
+ if (request.method === "GET" || request.method === "HEAD" || !request.body) return void 0;
1255
+ const reader = request.body.getReader();
1256
+ const chunks = [];
1257
+ let size = 0;
1258
+ try {
1259
+ while (true) {
1260
+ const part = await reader.read();
1261
+ if (part.done) break;
1262
+ size += part.value.byteLength;
1263
+ if (size > MAX_BODY_BYTES) {
1264
+ await reader.cancel();
1265
+ throw new Error("BODY_TOO_LARGE");
1266
+ }
1267
+ chunks.push(part.value);
1268
+ }
1269
+ } finally {
1270
+ reader.releaseLock();
1271
+ }
1272
+ const bytes = new Uint8Array(size);
1273
+ let offset = 0;
1274
+ for (const chunk of chunks) {
1275
+ bytes.set(chunk, offset);
1276
+ offset += chunk.byteLength;
1277
+ }
1278
+ return bytes;
1279
+ }
1280
+ async function browserProxy(request, path, config) {
1281
+ if (!isSameOriginRequest(request)) return error("CSRF_ERROR", 403);
1282
+ const key = config.publishableKey || process.env.NEXT_PUBLIC_SCALEMULE_PUBLISHABLE_KEY;
1283
+ if (!key?.startsWith("sm_pb_")) return error("BROWSER_KEY_NOT_CONFIGURED", 503);
1284
+ if (request.headers.get("x-api-key") !== key) return error("CSRF_ERROR", 403);
1285
+ const authOperation = `${request.method} ${path.slice(2).join("/")}`;
1286
+ const authRoute = path[1] === "auth" && (AUTH_ROUTES.has(authOperation) || request.method === "DELETE" && path[2] === "oauth" && path[3] === "providers" && path.length === 5);
1287
+ if (path[0] !== "v1" || !(SERVICES.has(path[1]) || authRoute) || path.some((part) => !part || part === "." || part === ".." || /[\\/%\u0000-\u001f]/.test(part))) return error("NOT_FOUND", 404);
1288
+ const session = await getSession({ allowBearer: false });
1289
+ if (!session && !(authRoute && PUBLIC_AUTH_ROUTES.has(authOperation)) && !PUBLIC_DATA_ROUTES.has(`${request.method} ${path.slice(1).join("/")}`)) return error("UNAUTHORIZED", 401);
1290
+ const gateway = resolveGatewayUrl({ ...config.client, gatewayUrl: config.browserGatewayUrl || process.env.NEXT_PUBLIC_SCALEMULE_GATEWAY_URL || config.client?.gatewayUrl });
1291
+ const target = new URL(`${gateway.replace(/\/$/, "")}/${path.map(encodeURIComponent).join("/")}`);
1292
+ target.search = new URL(request.url).search;
1293
+ const headers2 = new Headers({ "x-api-key": key });
1294
+ if (session) headers2.set("Authorization", `Bearer ${session.sessionToken}`);
1295
+ for (const name of ["x-anonymous-id", "origin", "content-type", "accept", "user-agent", "range", "if-none-match", "x-idempotency-key", "x-sm-workspace-id"]) {
1296
+ const value = request.headers.get(name);
1297
+ if (value) headers2.set(name, value);
1298
+ }
1299
+ try {
1300
+ const body = await boundedBody(request);
1301
+ const upstream = await fetch(target, { method: request.method, headers: headers2, body, redirect: "error", cache: "no-store", signal: AbortSignal.timeout(6e4) });
1302
+ const outputHeaders = new Headers({ "Cache-Control": "no-store", "Vary": "Cookie" });
1303
+ for (const name of ["content-type", "content-disposition", "content-range", "accept-ranges", "etag", "retry-after", "x-request-id"]) {
1304
+ const value = upstream.headers.get(name);
1305
+ if (value) outputHeaders.set(name, value);
1306
+ }
1307
+ const rotated = upstream.headers.get("x-rotated-session-token");
1308
+ if (rotated && session) {
1309
+ const refreshed = withRefreshedSession(rotated, session.userId, {}, config.cookies);
1310
+ for (const cookie of refreshed.headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
1311
+ }
1312
+ if ([204, 205, 304].includes(upstream.status)) {
1313
+ if (authOperation === "POST delete-account" && upstream.ok) {
1314
+ for (const cookie of clearSession({}, config.cookies).headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
1315
+ }
1316
+ return new Response(null, { status: upstream.status, headers: outputHeaders });
1317
+ }
1318
+ if (authRoute) {
1319
+ const payload = await upstream.json();
1320
+ const data = payload?.data || payload;
1321
+ if (authOperation === "POST delete-account" && upstream.ok && payload.success !== false) {
1322
+ for (const cookie of clearSession({}, config.cookies).headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
1323
+ }
1324
+ const token = data?.session_token;
1325
+ if (typeof token === "string" && data?.user?.id && upstream.ok && payload.success !== false) {
1326
+ const established = withSession({ session_token: token, user: data.user }, {}, config.cookies);
1327
+ for (const cookie of established.headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
1328
+ data.authenticated = true;
1329
+ }
1330
+ if (data && typeof data === "object") {
1331
+ delete data.session_token;
1332
+ delete data.sessionToken;
1333
+ delete data.refresh_token;
1334
+ delete data.access_token;
1335
+ }
1336
+ return Response.json(payload, { status: upstream.status, headers: outputHeaders });
1337
+ }
1338
+ return new Response(upstream.body, { status: upstream.status, headers: outputHeaders });
1339
+ } catch (err) {
1340
+ if (err instanceof Error && err.message === "BODY_TOO_LARGE") return error("BODY_TOO_LARGE", 413);
1341
+ console.error("[ScaleMule] Browser proxy upstream request failed");
1342
+ return error("UPSTREAM_UNAVAILABLE", 502);
1343
+ }
1344
+ }
1345
+
1185
1346
  // src/server/routes.ts
1186
1347
  function errorResponse(code, message, status) {
1187
1348
  return new Response(
@@ -1198,6 +1359,12 @@ function successResponse(data, status = 200) {
1198
1359
  function createAuthRoutes(config = {}) {
1199
1360
  const sm = createServerClient(config.client);
1200
1361
  const cookieOptions = config.cookies || {};
1362
+ const sessionData = (user, token) => ({
1363
+ user,
1364
+ userId: user.id,
1365
+ authenticated: true,
1366
+ ...config.sessionMode === "bearer" ? { sessionToken: token } : {}
1367
+ });
1201
1368
  const POST2 = async (request, context) => {
1202
1369
  if (config.csrf) {
1203
1370
  const csrfError = validateCSRFToken(request);
@@ -1209,7 +1376,7 @@ function createAuthRoutes(config = {}) {
1209
1376
  const path = params?.scalemule?.join("/") || "";
1210
1377
  try {
1211
1378
  const body = await request.json().catch(() => ({}));
1212
- const clientContext = extractClientContext(request);
1379
+ const clientContext = extractClientContext(request, config.clientContext);
1213
1380
  switch (path) {
1214
1381
  // ==================== Register ====================
1215
1382
  case "register": {
@@ -1235,9 +1402,9 @@ function createAuthRoutes(config = {}) {
1235
1402
  try {
1236
1403
  loginData = await sm.auth.login({ email, password }, { clientContext });
1237
1404
  } catch {
1238
- return successResponse({ user: registeredUser, message: "Registration successful" }, 201);
1405
+ return successResponse({ user: registeredUser, authenticated: false, message: "Registration successful" }, 201);
1239
1406
  }
1240
- const registerResponse = withSession(loginData, { user: registeredUser, sessionToken: loginData.session_token, userId: registeredUser.id }, cookieOptions);
1407
+ const registerResponse = withSession(loginData, sessionData(registeredUser, loginData.session_token), cookieOptions);
1241
1408
  if (config.enableAccountSwitcher) {
1242
1409
  const existingKnown = getKnownAccountsCookieRaw(request);
1243
1410
  appendKnownAccountCookie(
@@ -1257,6 +1424,12 @@ function createAuthRoutes(config = {}) {
1257
1424
  }
1258
1425
  return registerResponse;
1259
1426
  }
1427
+ case "handoff/exchange": {
1428
+ if (!config.handoffAudience) return errorResponse("HANDOFF_DISABLED", "Session transfer is not configured", 404);
1429
+ if (typeof body.code !== "string" || !body.code || body.code.length > 256) return errorResponse("INVALID_HANDOFF", "Invalid sign-in transfer", 400);
1430
+ const result = await sm.auth.exchangeSessionHandoff(body.code, config.handoffAudience);
1431
+ return withRefreshedSession(result.session_token, result.user_id, { authenticated: true, userId: result.user_id }, cookieOptions);
1432
+ }
1260
1433
  case "mfa/send-code": {
1261
1434
  const { pending_token, method } = body;
1262
1435
  if (!pending_token || !["email", "sms"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token and method required", 400);
@@ -1268,7 +1441,7 @@ function createAuthRoutes(config = {}) {
1268
1441
  const result = await sm.auth.completeMfa(pending_token, code, method, { clientContext });
1269
1442
  if (!result.session_token || !result.user) return errorResponse("MFA_FAILED", "Unable to complete sign-in", 400);
1270
1443
  await config.onLogin?.({ id: result.user.id, email: result.user.email });
1271
- const response = withSession(result, { user: result.user, sessionToken: result.session_token, userId: result.user.id }, cookieOptions);
1444
+ const response = withSession(result, sessionData(result.user, result.session_token), cookieOptions);
1272
1445
  if (config.enableAccountSwitcher) {
1273
1446
  appendKnownAccountCookie(response.headers, {
1274
1447
  userId: result.user.id,
@@ -1293,7 +1466,7 @@ function createAuthRoutes(config = {}) {
1293
1466
  } catch (err) {
1294
1467
  const apiErr = err instanceof ScaleMuleApiError ? err : null;
1295
1468
  const errorCode = apiErr?.code || "LOGIN_FAILED";
1296
- let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 202 : 400;
1469
+ let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 403 : 400;
1297
1470
  if (errorCode === "CHALLENGE_RATE_LIMITED") status = 429;
1298
1471
  if (errorCode === "INVALID_CREDENTIALS" || errorCode === "UNAUTHORIZED") status = 401;
1299
1472
  if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED"].includes(errorCode)) {
@@ -1311,7 +1484,7 @@ function createAuthRoutes(config = {}) {
1311
1484
  email: loginData.user.email
1312
1485
  });
1313
1486
  }
1314
- const loginResponse = withSession(loginData, { user: loginData.user, sessionToken: loginData.session_token, userId: loginData.user.id }, cookieOptions);
1487
+ const loginResponse = withSession(loginData, sessionData(loginData.user, loginData.session_token), cookieOptions);
1315
1488
  if (config.enableAccountSwitcher) {
1316
1489
  const existingKnown = getKnownAccountsCookieRaw(request);
1317
1490
  appendKnownAccountCookie(
@@ -1333,7 +1506,7 @@ function createAuthRoutes(config = {}) {
1333
1506
  }
1334
1507
  // ==================== Logout ====================
1335
1508
  case "logout": {
1336
- const session = await getSession();
1509
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1337
1510
  let rotated = null;
1338
1511
  if (session) {
1339
1512
  try {
@@ -1397,7 +1570,7 @@ function createAuthRoutes(config = {}) {
1397
1570
  if (verifyData?.session_token && verifyData?.user) {
1398
1571
  return withSession(
1399
1572
  { session_token: verifyData.session_token, user: verifyData.user },
1400
- { message: "Email verified successfully", verified: true, user: verifyData.user, sessionToken: verifyData.session_token, userId: verifyData.user.id },
1573
+ { message: "Email verified successfully", verified: true, ...sessionData(verifyData.user, verifyData.session_token) },
1401
1574
  cookieOptions
1402
1575
  );
1403
1576
  }
@@ -1407,7 +1580,7 @@ function createAuthRoutes(config = {}) {
1407
1580
  // Supports both authenticated (session-based) and unauthenticated (email-based) resend
1408
1581
  case "resend-verification": {
1409
1582
  const { email } = body;
1410
- const session = await getSession();
1583
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1411
1584
  let rotated = null;
1412
1585
  if (email) {
1413
1586
  try {
@@ -1451,7 +1624,7 @@ function createAuthRoutes(config = {}) {
1451
1624
  }
1452
1625
  // ==================== Refresh Session ====================
1453
1626
  case "refresh": {
1454
- const session = await getSession();
1627
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1455
1628
  if (!session) {
1456
1629
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1457
1630
  }
@@ -1461,19 +1634,20 @@ function createAuthRoutes(config = {}) {
1461
1634
  } catch {
1462
1635
  return clearSession(
1463
1636
  { message: "Session expired" },
1464
- cookieOptions
1637
+ cookieOptions,
1638
+ 401
1465
1639
  );
1466
1640
  }
1467
1641
  return withRefreshedSession(
1468
1642
  refreshData.session_token,
1469
1643
  session.userId,
1470
- { message: "Session refreshed" },
1644
+ { message: "Session refreshed", ...config.sessionMode === "bearer" ? { sessionToken: refreshData.session_token, userId: session.userId } : {} },
1471
1645
  cookieOptions
1472
1646
  );
1473
1647
  }
1474
1648
  // ==================== Change Password ====================
1475
1649
  case "change-password": {
1476
- const session = await getSession();
1650
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1477
1651
  if (!session) {
1478
1652
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1479
1653
  }
@@ -1518,7 +1692,7 @@ function createAuthRoutes(config = {}) {
1518
1692
  if (!config.enableAccountSwitcher) {
1519
1693
  return errorResponse("NOT_FOUND", "Account switcher not enabled", 404);
1520
1694
  }
1521
- const session = await getSession();
1695
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1522
1696
  if (session) {
1523
1697
  try {
1524
1698
  await sm.auth.logout(session.sessionToken);
@@ -1568,6 +1742,9 @@ function createAuthRoutes(config = {}) {
1568
1742
  return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
1569
1743
  }
1570
1744
  } catch (err) {
1745
+ if (path === "handoff/exchange" && err instanceof ScaleMuleApiError) {
1746
+ return errorResponse(err.code, err.message, err.code === "HANDOFF_UNAVAILABLE" ? 503 : 401);
1747
+ }
1571
1748
  if (path.startsWith("mfa/") && err instanceof ScaleMuleApiError) {
1572
1749
  const status = ["CHALLENGE_RATE_LIMITED", "MFA_RATE_LIMITED", "MFA_MAX_ATTEMPTS"].includes(err.code) ? 429 : 400;
1573
1750
  return errorResponse(err.code, err.message, status);
@@ -1588,7 +1765,7 @@ function createAuthRoutes(config = {}) {
1588
1765
  if (normCookie) resp.headers.append("Set-Cookie", normCookie);
1589
1766
  return resp;
1590
1767
  };
1591
- const session = await getSession();
1768
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1592
1769
  if (!session) {
1593
1770
  return withNorm(errorResponse("UNAUTHORIZED", "Authentication required", 401));
1594
1771
  }
@@ -1610,15 +1787,15 @@ function createAuthRoutes(config = {}) {
1610
1787
  return withNorm(withRefreshedSession(
1611
1788
  rotated,
1612
1789
  session.userId,
1613
- { user: userData, sessionToken: rotated, userId: session.userId },
1790
+ sessionData(userData, rotated),
1614
1791
  cookieOptions
1615
1792
  ));
1616
1793
  }
1617
- return withNorm(successResponse({ user: userData, sessionToken: session.sessionToken, userId: session.userId }));
1794
+ return withNorm(successResponse(sessionData(userData, session.sessionToken)));
1618
1795
  }
1619
1796
  // ==================== Get Session Status ====================
1620
1797
  case "session": {
1621
- const session = await getSession();
1798
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1622
1799
  return successResponse({
1623
1800
  authenticated: !!session,
1624
1801
  userId: session?.userId || null
@@ -1648,7 +1825,7 @@ function createAuthRoutes(config = {}) {
1648
1825
  // ==================== Delete Account ====================
1649
1826
  case "me":
1650
1827
  case "account": {
1651
- const session = await getSession();
1828
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1652
1829
  if (!session) {
1653
1830
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1654
1831
  }
@@ -1685,7 +1862,7 @@ function createAuthRoutes(config = {}) {
1685
1862
  // ==================== Update Profile ====================
1686
1863
  case "me":
1687
1864
  case "profile": {
1688
- const session = await getSession();
1865
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1689
1866
  if (!session) {
1690
1867
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1691
1868
  }
@@ -1725,7 +1902,22 @@ function createAuthRoutes(config = {}) {
1725
1902
  return errorResponse("SERVER_ERROR", "Internal server error", 500);
1726
1903
  }
1727
1904
  };
1728
- return { GET: GET2, POST: POST2, DELETE: DELETE2, PATCH: PATCH2 };
1905
+ const wrap = (handler) => async (request, context) => {
1906
+ const params = await context.params;
1907
+ const path = params.scalemule || [];
1908
+ let response;
1909
+ if (path[0] === "client") {
1910
+ response = await browserProxy(request, path.slice(1), config);
1911
+ } else if (!["GET", "HEAD"].includes(request.method) && (!isSameOriginRequest(request) || !request.headers.get("content-type")?.toLowerCase().startsWith("application/json"))) {
1912
+ response = errorResponse("CSRF_ERROR", "Same-origin JSON request required", 403);
1913
+ } else {
1914
+ response = await handler(request, context);
1915
+ }
1916
+ response.headers.set("Cache-Control", "no-store");
1917
+ response.headers.set("Vary", "Cookie");
1918
+ return response;
1919
+ };
1920
+ return { GET: wrap(GET2), POST: wrap(POST2), DELETE: wrap(DELETE2), PATCH: wrap(PATCH2), PUT: wrap(async () => errorResponse("NOT_FOUND", "Unknown endpoint", 404)) };
1729
1921
  }
1730
1922
 
1731
1923
  // src/server/auth.ts
@@ -1733,9 +1925,10 @@ var cookieDomain = typeof process !== "undefined" ? process.env.SCALEMULE_COOKIE
1733
1925
  var handlers = createAuthRoutes({
1734
1926
  cookies: cookieDomain ? { domain: cookieDomain } : void 0
1735
1927
  });
1736
- var { GET, POST, DELETE, PATCH } = handlers;
1928
+ var { GET, POST, DELETE, PATCH, PUT } = handlers;
1737
1929
 
1738
1930
  exports.DELETE = DELETE;
1739
1931
  exports.GET = GET;
1740
1932
  exports.PATCH = PATCH;
1741
1933
  exports.POST = POST;
1934
+ exports.PUT = PUT;