@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.
@@ -4,18 +4,46 @@ import 'next/server';
4
4
 
5
5
  // src/types/index.ts
6
6
  var ScaleMuleApiError = class extends Error {
7
- constructor(error, status) {
8
- super(error.message);
7
+ constructor(error2, status) {
8
+ super(error2.message);
9
9
  this.name = "ScaleMuleApiError";
10
- this.code = error.code;
11
- this.field = error.field;
10
+ this.code = error2.code;
11
+ this.field = error2.field;
12
12
  this.status = status;
13
- this.requestId = error.requestId;
14
- this.traceId = error.traceId;
15
- this.problem = error.problem;
13
+ this.requestId = error2.requestId;
14
+ this.traceId = error2.traceId;
15
+ this.problem = error2.problem;
16
16
  }
17
17
  };
18
18
 
19
+ // src/url-privacy.ts
20
+ function withoutAuthSecrets(value) {
21
+ if (!value) return value;
22
+ try {
23
+ const absolute = /^[a-z][a-z0-9+.-]*:/i.test(value);
24
+ const protocolRelative = value.startsWith("//");
25
+ const url = new URL(value, "https://relative.invalid");
26
+ if (!["http:", "https:"].includes(url.protocol)) return void 0;
27
+ let changed = false;
28
+ for (const name of [...url.searchParams.keys()]) {
29
+ if (/^(token|code|state|password|new_password|access_token|refresh_token|id_token|api_key|client_secret|challenge_token|challenge_code)$/i.test(name)) {
30
+ url.searchParams.delete(name);
31
+ changed = true;
32
+ }
33
+ }
34
+ if (url.hash) {
35
+ url.hash = "";
36
+ changed = true;
37
+ }
38
+ if (!changed) return value;
39
+ if (absolute) return url.toString();
40
+ if (protocolRelative) return url.toString().replace(/^https:/, "");
41
+ return value.split(/[?#]/, 1)[0] + url.search;
42
+ } catch {
43
+ return void 0;
44
+ }
45
+ }
46
+
19
47
  // src/server/context.ts
20
48
  function validateIP(ip) {
21
49
  if (!ip) return void 0;
@@ -29,7 +57,7 @@ function validateIP(ip) {
29
57
  }
30
58
  return void 0;
31
59
  }
32
- function extractClientContext(request) {
60
+ function extractClientContext(request, options = {}) {
33
61
  const headers2 = request.headers;
34
62
  let ip;
35
63
  ip = validateIP(headers2.get("x-real-ip"));
@@ -72,9 +100,14 @@ function extractClientContext(request) {
72
100
  if (!ip && request.ip) {
73
101
  ip = validateIP(request.ip);
74
102
  }
103
+ if (options.trustedIpHeader) {
104
+ const value = headers2.get(options.trustedIpHeader);
105
+ const hop = options.trustedIpHeader === "x-forwarded-for" ? value?.split(",").at(-1)?.trim() : value;
106
+ ip = validateIP(hop);
107
+ }
75
108
  const userAgent = headers2.get("user-agent") || void 0;
76
109
  const deviceFingerprint = headers2.get("x-device-fingerprint") || void 0;
77
- const referrer = headers2.get("referer") || void 0;
110
+ const referrer = withoutAuthSecrets(headers2.get("referer") || void 0);
78
111
  const anonymousId = headers2.get("x-anonymous-id") || void 0;
79
112
  return {
80
113
  ip,
@@ -109,8 +142,8 @@ function buildClientContextHeaders(context) {
109
142
  }
110
143
 
111
144
  // src/error-context.ts
112
- function withErrorContext(error, responseData, headers2) {
113
- const enriched = { ...error };
145
+ function withErrorContext(error2, responseData, headers2) {
146
+ const enriched = { ...error2 };
114
147
  const meta = responseData?.meta;
115
148
  const requestId = meta?.request_id ?? headers2?.get("x-request-id") ?? void 0;
116
149
  if (requestId !== void 0 && enriched.requestId === void 0) {
@@ -144,6 +177,14 @@ var ScaleMuleServer = class {
144
177
  // Auth Methods
145
178
  // ==========================================================================
146
179
  this.auth = {
180
+ /** Issue a 60-second, single-use transfer code after a server OAuth callback. */
181
+ createSessionHandoff: async (sessionToken, audience) => {
182
+ return this.request("POST", "/v1/auth/session-handoff", { sessionToken, body: { session_token: sessionToken, audience } });
183
+ },
184
+ /** Exchange only on the server; write the returned session into an HTTP-only cookie. */
185
+ exchangeSessionHandoff: async (code, audience) => {
186
+ return this.request("POST", "/v1/auth/session-handoff/exchange", { body: { code, audience } });
187
+ },
147
188
  /**
148
189
  * Register a new user
149
190
  */
@@ -803,7 +844,7 @@ var ScaleMuleServer = class {
803
844
  code: `HTTP_${response.status}`,
804
845
  message: responseData?.message || text || response.statusText
805
846
  };
806
- const error = withErrorContext(baseError, responseData, response.headers);
847
+ const error2 = withErrorContext(baseError, responseData, response.headers);
807
848
  if (response.status === 401 && options.sessionToken && !options.isAutoRefresh) {
808
849
  if (this.debug) console.log("[ScaleMule Server] 401 received, attempting auto-refresh...");
809
850
  try {
@@ -826,12 +867,12 @@ var ScaleMuleServer = class {
826
867
  if (this.debug) console.error("[ScaleMule Server] Auto-refresh failed:", refreshErr);
827
868
  const refreshApiError = refreshErr instanceof ScaleMuleApiError ? { code: refreshErr.code, message: refreshErr.message } : { code: "REFRESH_FAILED", message: "Auto-refresh failed" };
828
869
  this.onAutoRefreshFailed?.(refreshApiError);
829
- throw new ScaleMuleApiError(error);
870
+ throw new ScaleMuleApiError(error2);
830
871
  } finally {
831
872
  this.onRefreshEnd?.();
832
873
  }
833
874
  }
834
- throw new ScaleMuleApiError(error);
875
+ throw new ScaleMuleApiError(error2);
835
876
  }
836
877
  const data = responseData?.data !== void 0 ? responseData.data : responseData;
837
878
  return data;
@@ -872,9 +913,10 @@ function createCookieHeader(name, value, options = {}) {
872
913
  const sameSite = options.sameSite ?? "lax";
873
914
  const path = options.path ?? "/";
874
915
  let cookie = `${name}=${encodeURIComponent(value)}; Path=${path}; Max-Age=${maxAge}; HttpOnly; SameSite=${sameSite}`;
875
- if (secure) {
916
+ if (secure || options.partitioned) {
876
917
  cookie += "; Secure";
877
918
  }
919
+ if (options.partitioned) cookie += "; Partitioned";
878
920
  if (options.domain) {
879
921
  cookie += `; Domain=${options.domain}`;
880
922
  }
@@ -885,9 +927,10 @@ function createClearCookieHeader(name, options = {}) {
885
927
  const secure = options.secure ?? process.env.NODE_ENV === "production";
886
928
  const sameSite = options.sameSite ?? "lax";
887
929
  let cookie = `${name}=; Path=${path}; Max-Age=0; HttpOnly; SameSite=${sameSite}`;
888
- if (secure) {
930
+ if (secure || options.partitioned) {
889
931
  cookie += "; Secure";
890
932
  }
933
+ if (options.partitioned) cookie += "; Partitioned";
891
934
  if (options.domain) {
892
935
  cookie += `; Domain=${options.domain}`;
893
936
  }
@@ -896,6 +939,10 @@ function createClearCookieHeader(name, options = {}) {
896
939
  function withSession(loginResponse, responseBody, options = {}) {
897
940
  const headers2 = new Headers();
898
941
  headers2.set("Content-Type", "application/json");
942
+ if (options.partitioned) {
943
+ headers2.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, { ...options, partitioned: false }));
944
+ headers2.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, { ...options, partitioned: false }));
945
+ }
899
946
  headers2.append(
900
947
  "Set-Cookie",
901
948
  createCookieHeader(SESSION_COOKIE_NAME, loginResponse.session_token, options)
@@ -912,6 +959,10 @@ function withSession(loginResponse, responseBody, options = {}) {
912
959
  function withRefreshedSession(sessionToken, userId, responseBody, options = {}) {
913
960
  const headers2 = new Headers();
914
961
  headers2.set("Content-Type", "application/json");
962
+ if (options.partitioned) {
963
+ headers2.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, { ...options, partitioned: false }));
964
+ headers2.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, { ...options, partitioned: false }));
965
+ }
915
966
  headers2.append(
916
967
  "Set-Cookie",
917
968
  createCookieHeader(SESSION_COOKIE_NAME, sessionToken, options)
@@ -928,6 +979,10 @@ function withRefreshedSession(sessionToken, userId, responseBody, options = {})
928
979
  function clearSession(responseBody, options = {}, status = 200) {
929
980
  const headers2 = new Headers();
930
981
  headers2.set("Content-Type", "application/json");
982
+ if (options.partitioned) {
983
+ headers2.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, { ...options, partitioned: false }));
984
+ headers2.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, { ...options, partitioned: false }));
985
+ }
931
986
  headers2.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, options));
932
987
  headers2.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, options));
933
988
  return new Response(JSON.stringify({ success: status < 300, data: responseBody }), {
@@ -935,7 +990,7 @@ function clearSession(responseBody, options = {}, status = 200) {
935
990
  headers: headers2
936
991
  });
937
992
  }
938
- async function getSession() {
993
+ async function getSession(options = {}) {
939
994
  const cookieStore = await cookies();
940
995
  const sessionCookie = cookieStore.get(SESSION_COOKIE_NAME);
941
996
  const userIdCookie = cookieStore.get(USER_ID_COOKIE_NAME);
@@ -947,6 +1002,7 @@ async function getSession() {
947
1002
  // Note: actual expiry is managed by ScaleMule backend
948
1003
  };
949
1004
  }
1005
+ if (options.allowBearer === false) return null;
950
1006
  const headerStore = await headers();
951
1007
  return sessionFromAuthHeaders(
952
1008
  headerStore.get("authorization"),
@@ -1152,6 +1208,139 @@ function validateCSRFToken(request) {
1152
1208
  return void 0;
1153
1209
  }
1154
1210
 
1211
+ // src/server/browser-proxy.ts
1212
+ function error(code, status) {
1213
+ return Response.json({ success: false, error: { code, message: code === "UNAUTHORIZED" ? "Authentication required" : "Request not permitted" } }, { status, headers: { "Cache-Control": "no-store" } });
1214
+ }
1215
+ function isSameOriginRequest(request) {
1216
+ const origin = request.headers.get("origin");
1217
+ const site = request.headers.get("sec-fetch-site");
1218
+ if (site) return site === "same-origin" || site === "none";
1219
+ const url = new URL(request.url);
1220
+ const host = request.headers.get("host") || url.host;
1221
+ if (origin) {
1222
+ try {
1223
+ const source = new URL(origin);
1224
+ if (!["http:", "https:"].includes(source.protocol) || source.host !== host) return false;
1225
+ } catch {
1226
+ return false;
1227
+ }
1228
+ }
1229
+ return true;
1230
+ }
1231
+ 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"]);
1232
+ var AUTH_ROUTES = /* @__PURE__ */ new Set([
1233
+ "GET me",
1234
+ "GET mfa/status",
1235
+ "GET oauth/providers",
1236
+ "PATCH profile",
1237
+ "POST change-password",
1238
+ "POST change-email",
1239
+ "POST delete-account",
1240
+ "POST export-data",
1241
+ "POST mfa/setup",
1242
+ "POST mfa/verify",
1243
+ "POST mfa/disable",
1244
+ "POST mfa/backup-codes",
1245
+ "POST oauth/start",
1246
+ "POST oauth/callback"
1247
+ ]);
1248
+ var PUBLIC_AUTH_ROUTES = /* @__PURE__ */ new Set(["POST oauth/start", "POST oauth/callback"]);
1249
+ var PUBLIC_DATA_ROUTES = /* @__PURE__ */ new Set(["POST flags/evaluate", "POST flags/evaluate/all", "POST flags/evaluate/batch", "GET feedback/items", "POST feedback/submit"]);
1250
+ var MAX_BODY_BYTES = 25 * 1024 * 1024;
1251
+ async function boundedBody(request) {
1252
+ if (request.method === "GET" || request.method === "HEAD" || !request.body) return void 0;
1253
+ const reader = request.body.getReader();
1254
+ const chunks = [];
1255
+ let size = 0;
1256
+ try {
1257
+ while (true) {
1258
+ const part = await reader.read();
1259
+ if (part.done) break;
1260
+ size += part.value.byteLength;
1261
+ if (size > MAX_BODY_BYTES) {
1262
+ await reader.cancel();
1263
+ throw new Error("BODY_TOO_LARGE");
1264
+ }
1265
+ chunks.push(part.value);
1266
+ }
1267
+ } finally {
1268
+ reader.releaseLock();
1269
+ }
1270
+ const bytes = new Uint8Array(size);
1271
+ let offset = 0;
1272
+ for (const chunk of chunks) {
1273
+ bytes.set(chunk, offset);
1274
+ offset += chunk.byteLength;
1275
+ }
1276
+ return bytes;
1277
+ }
1278
+ async function browserProxy(request, path, config) {
1279
+ if (!isSameOriginRequest(request)) return error("CSRF_ERROR", 403);
1280
+ const key = config.publishableKey || process.env.NEXT_PUBLIC_SCALEMULE_PUBLISHABLE_KEY;
1281
+ if (!key?.startsWith("sm_pb_")) return error("BROWSER_KEY_NOT_CONFIGURED", 503);
1282
+ if (request.headers.get("x-api-key") !== key) return error("CSRF_ERROR", 403);
1283
+ const authOperation = `${request.method} ${path.slice(2).join("/")}`;
1284
+ const authRoute = path[1] === "auth" && (AUTH_ROUTES.has(authOperation) || request.method === "DELETE" && path[2] === "oauth" && path[3] === "providers" && path.length === 5);
1285
+ if (path[0] !== "v1" || !(SERVICES.has(path[1]) || authRoute) || path.some((part) => !part || part === "." || part === ".." || /[\\/%\u0000-\u001f]/.test(part))) return error("NOT_FOUND", 404);
1286
+ const session = await getSession({ allowBearer: false });
1287
+ if (!session && !(authRoute && PUBLIC_AUTH_ROUTES.has(authOperation)) && !PUBLIC_DATA_ROUTES.has(`${request.method} ${path.slice(1).join("/")}`)) return error("UNAUTHORIZED", 401);
1288
+ const gateway = resolveGatewayUrl({ ...config.client, gatewayUrl: config.browserGatewayUrl || process.env.NEXT_PUBLIC_SCALEMULE_GATEWAY_URL || config.client?.gatewayUrl });
1289
+ const target = new URL(`${gateway.replace(/\/$/, "")}/${path.map(encodeURIComponent).join("/")}`);
1290
+ target.search = new URL(request.url).search;
1291
+ const headers2 = new Headers({ "x-api-key": key });
1292
+ if (session) headers2.set("Authorization", `Bearer ${session.sessionToken}`);
1293
+ for (const name of ["x-anonymous-id", "origin", "content-type", "accept", "user-agent", "range", "if-none-match", "x-idempotency-key", "x-sm-workspace-id"]) {
1294
+ const value = request.headers.get(name);
1295
+ if (value) headers2.set(name, value);
1296
+ }
1297
+ try {
1298
+ const body = await boundedBody(request);
1299
+ const upstream = await fetch(target, { method: request.method, headers: headers2, body, redirect: "error", cache: "no-store", signal: AbortSignal.timeout(6e4) });
1300
+ const outputHeaders = new Headers({ "Cache-Control": "no-store", "Vary": "Cookie" });
1301
+ for (const name of ["content-type", "content-disposition", "content-range", "accept-ranges", "etag", "retry-after", "x-request-id"]) {
1302
+ const value = upstream.headers.get(name);
1303
+ if (value) outputHeaders.set(name, value);
1304
+ }
1305
+ const rotated = upstream.headers.get("x-rotated-session-token");
1306
+ if (rotated && session) {
1307
+ const refreshed = withRefreshedSession(rotated, session.userId, {}, config.cookies);
1308
+ for (const cookie of refreshed.headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
1309
+ }
1310
+ if ([204, 205, 304].includes(upstream.status)) {
1311
+ if (authOperation === "POST delete-account" && upstream.ok) {
1312
+ for (const cookie of clearSession({}, config.cookies).headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
1313
+ }
1314
+ return new Response(null, { status: upstream.status, headers: outputHeaders });
1315
+ }
1316
+ if (authRoute) {
1317
+ const payload = await upstream.json();
1318
+ const data = payload?.data || payload;
1319
+ if (authOperation === "POST delete-account" && upstream.ok && payload.success !== false) {
1320
+ for (const cookie of clearSession({}, config.cookies).headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
1321
+ }
1322
+ const token = data?.session_token;
1323
+ if (typeof token === "string" && data?.user?.id && upstream.ok && payload.success !== false) {
1324
+ const established = withSession({ session_token: token, user: data.user }, {}, config.cookies);
1325
+ for (const cookie of established.headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
1326
+ data.authenticated = true;
1327
+ }
1328
+ if (data && typeof data === "object") {
1329
+ delete data.session_token;
1330
+ delete data.sessionToken;
1331
+ delete data.refresh_token;
1332
+ delete data.access_token;
1333
+ }
1334
+ return Response.json(payload, { status: upstream.status, headers: outputHeaders });
1335
+ }
1336
+ return new Response(upstream.body, { status: upstream.status, headers: outputHeaders });
1337
+ } catch (err) {
1338
+ if (err instanceof Error && err.message === "BODY_TOO_LARGE") return error("BODY_TOO_LARGE", 413);
1339
+ console.error("[ScaleMule] Browser proxy upstream request failed");
1340
+ return error("UPSTREAM_UNAVAILABLE", 502);
1341
+ }
1342
+ }
1343
+
1155
1344
  // src/server/routes.ts
1156
1345
  function errorResponse(code, message, status) {
1157
1346
  return new Response(
@@ -1168,6 +1357,12 @@ function successResponse(data, status = 200) {
1168
1357
  function createAuthRoutes(config = {}) {
1169
1358
  const sm = createServerClient(config.client);
1170
1359
  const cookieOptions = config.cookies || {};
1360
+ const sessionData = (user, token) => ({
1361
+ user,
1362
+ userId: user.id,
1363
+ authenticated: true,
1364
+ ...config.sessionMode === "bearer" ? { sessionToken: token } : {}
1365
+ });
1171
1366
  const POST2 = async (request, context) => {
1172
1367
  if (config.csrf) {
1173
1368
  const csrfError = validateCSRFToken(request);
@@ -1179,7 +1374,7 @@ function createAuthRoutes(config = {}) {
1179
1374
  const path = params?.scalemule?.join("/") || "";
1180
1375
  try {
1181
1376
  const body = await request.json().catch(() => ({}));
1182
- const clientContext = extractClientContext(request);
1377
+ const clientContext = extractClientContext(request, config.clientContext);
1183
1378
  switch (path) {
1184
1379
  // ==================== Register ====================
1185
1380
  case "register": {
@@ -1205,9 +1400,9 @@ function createAuthRoutes(config = {}) {
1205
1400
  try {
1206
1401
  loginData = await sm.auth.login({ email, password }, { clientContext });
1207
1402
  } catch {
1208
- return successResponse({ user: registeredUser, message: "Registration successful" }, 201);
1403
+ return successResponse({ user: registeredUser, authenticated: false, message: "Registration successful" }, 201);
1209
1404
  }
1210
- const registerResponse = withSession(loginData, { user: registeredUser, sessionToken: loginData.session_token, userId: registeredUser.id }, cookieOptions);
1405
+ const registerResponse = withSession(loginData, sessionData(registeredUser, loginData.session_token), cookieOptions);
1211
1406
  if (config.enableAccountSwitcher) {
1212
1407
  const existingKnown = getKnownAccountsCookieRaw(request);
1213
1408
  appendKnownAccountCookie(
@@ -1227,6 +1422,12 @@ function createAuthRoutes(config = {}) {
1227
1422
  }
1228
1423
  return registerResponse;
1229
1424
  }
1425
+ case "handoff/exchange": {
1426
+ if (!config.handoffAudience) return errorResponse("HANDOFF_DISABLED", "Session transfer is not configured", 404);
1427
+ if (typeof body.code !== "string" || !body.code || body.code.length > 256) return errorResponse("INVALID_HANDOFF", "Invalid sign-in transfer", 400);
1428
+ const result = await sm.auth.exchangeSessionHandoff(body.code, config.handoffAudience);
1429
+ return withRefreshedSession(result.session_token, result.user_id, { authenticated: true, userId: result.user_id }, cookieOptions);
1430
+ }
1230
1431
  case "mfa/send-code": {
1231
1432
  const { pending_token, method } = body;
1232
1433
  if (!pending_token || !["email", "sms"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token and method required", 400);
@@ -1238,7 +1439,7 @@ function createAuthRoutes(config = {}) {
1238
1439
  const result = await sm.auth.completeMfa(pending_token, code, method, { clientContext });
1239
1440
  if (!result.session_token || !result.user) return errorResponse("MFA_FAILED", "Unable to complete sign-in", 400);
1240
1441
  await config.onLogin?.({ id: result.user.id, email: result.user.email });
1241
- const response = withSession(result, { user: result.user, sessionToken: result.session_token, userId: result.user.id }, cookieOptions);
1442
+ const response = withSession(result, sessionData(result.user, result.session_token), cookieOptions);
1242
1443
  if (config.enableAccountSwitcher) {
1243
1444
  appendKnownAccountCookie(response.headers, {
1244
1445
  userId: result.user.id,
@@ -1263,7 +1464,7 @@ function createAuthRoutes(config = {}) {
1263
1464
  } catch (err) {
1264
1465
  const apiErr = err instanceof ScaleMuleApiError ? err : null;
1265
1466
  const errorCode = apiErr?.code || "LOGIN_FAILED";
1266
- let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 202 : 400;
1467
+ let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 403 : 400;
1267
1468
  if (errorCode === "CHALLENGE_RATE_LIMITED") status = 429;
1268
1469
  if (errorCode === "INVALID_CREDENTIALS" || errorCode === "UNAUTHORIZED") status = 401;
1269
1470
  if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED"].includes(errorCode)) {
@@ -1281,7 +1482,7 @@ function createAuthRoutes(config = {}) {
1281
1482
  email: loginData.user.email
1282
1483
  });
1283
1484
  }
1284
- const loginResponse = withSession(loginData, { user: loginData.user, sessionToken: loginData.session_token, userId: loginData.user.id }, cookieOptions);
1485
+ const loginResponse = withSession(loginData, sessionData(loginData.user, loginData.session_token), cookieOptions);
1285
1486
  if (config.enableAccountSwitcher) {
1286
1487
  const existingKnown = getKnownAccountsCookieRaw(request);
1287
1488
  appendKnownAccountCookie(
@@ -1303,7 +1504,7 @@ function createAuthRoutes(config = {}) {
1303
1504
  }
1304
1505
  // ==================== Logout ====================
1305
1506
  case "logout": {
1306
- const session = await getSession();
1507
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1307
1508
  let rotated = null;
1308
1509
  if (session) {
1309
1510
  try {
@@ -1367,7 +1568,7 @@ function createAuthRoutes(config = {}) {
1367
1568
  if (verifyData?.session_token && verifyData?.user) {
1368
1569
  return withSession(
1369
1570
  { session_token: verifyData.session_token, user: verifyData.user },
1370
- { message: "Email verified successfully", verified: true, user: verifyData.user, sessionToken: verifyData.session_token, userId: verifyData.user.id },
1571
+ { message: "Email verified successfully", verified: true, ...sessionData(verifyData.user, verifyData.session_token) },
1371
1572
  cookieOptions
1372
1573
  );
1373
1574
  }
@@ -1377,7 +1578,7 @@ function createAuthRoutes(config = {}) {
1377
1578
  // Supports both authenticated (session-based) and unauthenticated (email-based) resend
1378
1579
  case "resend-verification": {
1379
1580
  const { email } = body;
1380
- const session = await getSession();
1581
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1381
1582
  let rotated = null;
1382
1583
  if (email) {
1383
1584
  try {
@@ -1421,7 +1622,7 @@ function createAuthRoutes(config = {}) {
1421
1622
  }
1422
1623
  // ==================== Refresh Session ====================
1423
1624
  case "refresh": {
1424
- const session = await getSession();
1625
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1425
1626
  if (!session) {
1426
1627
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1427
1628
  }
@@ -1431,19 +1632,20 @@ function createAuthRoutes(config = {}) {
1431
1632
  } catch {
1432
1633
  return clearSession(
1433
1634
  { message: "Session expired" },
1434
- cookieOptions
1635
+ cookieOptions,
1636
+ 401
1435
1637
  );
1436
1638
  }
1437
1639
  return withRefreshedSession(
1438
1640
  refreshData.session_token,
1439
1641
  session.userId,
1440
- { message: "Session refreshed" },
1642
+ { message: "Session refreshed", ...config.sessionMode === "bearer" ? { sessionToken: refreshData.session_token, userId: session.userId } : {} },
1441
1643
  cookieOptions
1442
1644
  );
1443
1645
  }
1444
1646
  // ==================== Change Password ====================
1445
1647
  case "change-password": {
1446
- const session = await getSession();
1648
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1447
1649
  if (!session) {
1448
1650
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1449
1651
  }
@@ -1488,7 +1690,7 @@ function createAuthRoutes(config = {}) {
1488
1690
  if (!config.enableAccountSwitcher) {
1489
1691
  return errorResponse("NOT_FOUND", "Account switcher not enabled", 404);
1490
1692
  }
1491
- const session = await getSession();
1693
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1492
1694
  if (session) {
1493
1695
  try {
1494
1696
  await sm.auth.logout(session.sessionToken);
@@ -1538,6 +1740,9 @@ function createAuthRoutes(config = {}) {
1538
1740
  return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
1539
1741
  }
1540
1742
  } catch (err) {
1743
+ if (path === "handoff/exchange" && err instanceof ScaleMuleApiError) {
1744
+ return errorResponse(err.code, err.message, err.code === "HANDOFF_UNAVAILABLE" ? 503 : 401);
1745
+ }
1541
1746
  if (path.startsWith("mfa/") && err instanceof ScaleMuleApiError) {
1542
1747
  const status = ["CHALLENGE_RATE_LIMITED", "MFA_RATE_LIMITED", "MFA_MAX_ATTEMPTS"].includes(err.code) ? 429 : 400;
1543
1748
  return errorResponse(err.code, err.message, status);
@@ -1558,7 +1763,7 @@ function createAuthRoutes(config = {}) {
1558
1763
  if (normCookie) resp.headers.append("Set-Cookie", normCookie);
1559
1764
  return resp;
1560
1765
  };
1561
- const session = await getSession();
1766
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1562
1767
  if (!session) {
1563
1768
  return withNorm(errorResponse("UNAUTHORIZED", "Authentication required", 401));
1564
1769
  }
@@ -1580,15 +1785,15 @@ function createAuthRoutes(config = {}) {
1580
1785
  return withNorm(withRefreshedSession(
1581
1786
  rotated,
1582
1787
  session.userId,
1583
- { user: userData, sessionToken: rotated, userId: session.userId },
1788
+ sessionData(userData, rotated),
1584
1789
  cookieOptions
1585
1790
  ));
1586
1791
  }
1587
- return withNorm(successResponse({ user: userData, sessionToken: session.sessionToken, userId: session.userId }));
1792
+ return withNorm(successResponse(sessionData(userData, session.sessionToken)));
1588
1793
  }
1589
1794
  // ==================== Get Session Status ====================
1590
1795
  case "session": {
1591
- const session = await getSession();
1796
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1592
1797
  return successResponse({
1593
1798
  authenticated: !!session,
1594
1799
  userId: session?.userId || null
@@ -1618,7 +1823,7 @@ function createAuthRoutes(config = {}) {
1618
1823
  // ==================== Delete Account ====================
1619
1824
  case "me":
1620
1825
  case "account": {
1621
- const session = await getSession();
1826
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1622
1827
  if (!session) {
1623
1828
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1624
1829
  }
@@ -1655,7 +1860,7 @@ function createAuthRoutes(config = {}) {
1655
1860
  // ==================== Update Profile ====================
1656
1861
  case "me":
1657
1862
  case "profile": {
1658
- const session = await getSession();
1863
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1659
1864
  if (!session) {
1660
1865
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1661
1866
  }
@@ -1695,7 +1900,22 @@ function createAuthRoutes(config = {}) {
1695
1900
  return errorResponse("SERVER_ERROR", "Internal server error", 500);
1696
1901
  }
1697
1902
  };
1698
- return { GET: GET2, POST: POST2, DELETE: DELETE2, PATCH: PATCH2 };
1903
+ const wrap = (handler) => async (request, context) => {
1904
+ const params = await context.params;
1905
+ const path = params.scalemule || [];
1906
+ let response;
1907
+ if (path[0] === "client") {
1908
+ response = await browserProxy(request, path.slice(1), config);
1909
+ } else if (!["GET", "HEAD"].includes(request.method) && (!isSameOriginRequest(request) || !request.headers.get("content-type")?.toLowerCase().startsWith("application/json"))) {
1910
+ response = errorResponse("CSRF_ERROR", "Same-origin JSON request required", 403);
1911
+ } else {
1912
+ response = await handler(request, context);
1913
+ }
1914
+ response.headers.set("Cache-Control", "no-store");
1915
+ response.headers.set("Vary", "Cookie");
1916
+ return response;
1917
+ };
1918
+ return { GET: wrap(GET2), POST: wrap(POST2), DELETE: wrap(DELETE2), PATCH: wrap(PATCH2), PUT: wrap(async () => errorResponse("NOT_FOUND", "Unknown endpoint", 404)) };
1699
1919
  }
1700
1920
 
1701
1921
  // src/server/auth.ts
@@ -1703,6 +1923,6 @@ var cookieDomain = typeof process !== "undefined" ? process.env.SCALEMULE_COOKIE
1703
1923
  var handlers = createAuthRoutes({
1704
1924
  cookies: cookieDomain ? { domain: cookieDomain } : void 0
1705
1925
  });
1706
- var { GET, POST, DELETE, PATCH } = handlers;
1926
+ var { GET, POST, DELETE, PATCH, PUT } = handlers;
1707
1927
 
1708
- export { DELETE, GET, PATCH, POST };
1928
+ export { DELETE, GET, PATCH, POST, PUT };
@@ -1,6 +1,6 @@
1
- import { S as ServerConfig } from '../webhook-handler-DKt6H8FB.mjs';
2
- export { a as ScaleMuleServer, V as VideoFailedEvent, b as VideoReadyEvent, c as VideoTranscodedEvent, d as VideoUploadedEvent, W as WebhookEvent, e as WebhookRoutesConfig, f as createServerClient, g as createWebhookHandler, h as createWebhookRoutes, p as parseWebhookEvent, r as registerVideoWebhook, i as resolveGatewayUrl, v as verifyWebhookSignature } from '../webhook-handler-DKt6H8FB.mjs';
3
- import { p as ClientContext, A as ApiError } from '../index-BQgmT53x.mjs';
1
+ import { S as ServerConfig } from '../webhook-handler-DNpCXDDA.mjs';
2
+ export { a as ScaleMuleServer, V as VideoFailedEvent, b as VideoReadyEvent, c as VideoTranscodedEvent, d as VideoUploadedEvent, W as WebhookEvent, e as WebhookRoutesConfig, f as createServerClient, g as createWebhookHandler, h as createWebhookRoutes, p as parseWebhookEvent, r as registerVideoWebhook, i as resolveGatewayUrl, v as verifyWebhookSignature } from '../webhook-handler-DNpCXDDA.mjs';
3
+ import { q as ClientContext, A as ApiError } from '../index-2PnO4RAF.mjs';
4
4
  export { L as LedveryRoutesConfig, a as LedverySessionData, S as SM_LEDVERY_ACCESS_TOKEN_COOKIE, b as SM_LEDVERY_ID_TOKEN_COOKIE, c as SM_LEDVERY_NONCE_COOKIE, d as SM_LEDVERY_PKCE_VERIFIER_COOKIE, e as SM_LEDVERY_STATE_COOKIE, f as createLedveryRoutes, g as getLedverySession } from '../ledvery-CxPzZpxP.mjs';
5
5
  import { NextRequest, NextResponse } from 'next/server';
6
6
  import '@scalemule/money';
@@ -61,7 +61,11 @@ interface IncomingMessageLike {
61
61
  * }
62
62
  * ```
63
63
  */
64
- declare function extractClientContext(request: NextRequestLike): ClientContext;
64
+ interface ClientContextOptions {
65
+ /** Choose the header your ingress overwrites. ALB append mode uses the final XFF hop. */
66
+ trustedIpHeader?: 'x-forwarded-for' | 'x-real-ip' | 'cf-connecting-ip' | 'x-vercel-forwarded-for';
67
+ }
68
+ declare function extractClientContext(request: NextRequestLike, options?: ClientContextOptions): ClientContext;
65
69
  /**
66
70
  * Extract client context from a Pages Router API request.
67
71
  *
@@ -119,6 +123,8 @@ declare const USER_ID_COOKIE_NAME = "sm_user_id";
119
123
  */
120
124
  declare const KNOWN_ACCOUNTS_COOKIE_NAME = "sm_known_accounts";
121
125
  interface SessionCookieOptions {
126
+ /** Isolate an embedded session in the top-level site cookie partition (CHIPS). */
127
+ partitioned?: boolean;
122
128
  /** Cookie max age in seconds (default: 7 days) */
123
129
  maxAge?: number;
124
130
  /** Cookie domain (default: current domain) */
@@ -182,7 +188,9 @@ declare function clearSession<T extends Record<string, unknown>>(responseBody: T
182
188
  * const user = await sm.auth.me(session.sessionToken)
183
189
  * ```
184
190
  */
185
- declare function getSession(): Promise<SessionData | null>;
191
+ declare function getSession(options?: {
192
+ allowBearer?: boolean;
193
+ }): Promise<SessionData | null>;
186
194
  /**
187
195
  * Get session from a Request object (for edge/middleware)
188
196
  *
@@ -267,6 +275,16 @@ declare function requireSession(): Promise<SessionData>;
267
275
  */
268
276
 
269
277
  interface AuthRoutesConfig {
278
+ /** Fixed server-controlled audience used for OAuth-to-iframe session transfer. */
279
+ handoffAudience?: string;
280
+ /** Network boundary used to attest the browser IP on server-side auth calls. */
281
+ clientContext?: ClientContextOptions;
282
+ /** Publishable key for the cookie-authenticated browser data proxy. */
283
+ publishableKey?: string;
284
+ /** Public gateway used by the browser SDK, including WebSocket tickets. */
285
+ browserGatewayUrl?: string;
286
+ /** Explicit compatibility escape hatch. Cookie mode never returns session tokens. */
287
+ sessionMode?: 'cookie' | 'bearer';
270
288
  /** Server client config (optional if using env vars) */
271
289
  client?: Partial<ServerConfig>;
272
290
  /** Cookie options */
@@ -334,6 +352,7 @@ declare function createAuthRoutes(config?: AuthRoutesConfig): {
334
352
  POST: RouteHandler$2;
335
353
  DELETE: RouteHandler$2;
336
354
  PATCH: RouteHandler$2;
355
+ PUT: RouteHandler$2;
337
356
  };
338
357
  interface AnalyticsTrackingGateConfig {
339
358
  /** Feature flag key used to decide whether to forward analytics */