@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,15 +4,15 @@ 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
 
@@ -57,7 +57,7 @@ function validateIP(ip) {
57
57
  }
58
58
  return void 0;
59
59
  }
60
- function extractClientContext(request) {
60
+ function extractClientContext(request, options = {}) {
61
61
  const headers2 = request.headers;
62
62
  let ip;
63
63
  ip = validateIP(headers2.get("x-real-ip"));
@@ -100,6 +100,11 @@ function extractClientContext(request) {
100
100
  if (!ip && request.ip) {
101
101
  ip = validateIP(request.ip);
102
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
+ }
103
108
  const userAgent = headers2.get("user-agent") || void 0;
104
109
  const deviceFingerprint = headers2.get("x-device-fingerprint") || void 0;
105
110
  const referrer = withoutAuthSecrets(headers2.get("referer") || void 0);
@@ -137,8 +142,8 @@ function buildClientContextHeaders(context) {
137
142
  }
138
143
 
139
144
  // src/error-context.ts
140
- function withErrorContext(error, responseData, headers2) {
141
- const enriched = { ...error };
145
+ function withErrorContext(error2, responseData, headers2) {
146
+ const enriched = { ...error2 };
142
147
  const meta = responseData?.meta;
143
148
  const requestId = meta?.request_id ?? headers2?.get("x-request-id") ?? void 0;
144
149
  if (requestId !== void 0 && enriched.requestId === void 0) {
@@ -172,6 +177,14 @@ var ScaleMuleServer = class {
172
177
  // Auth Methods
173
178
  // ==========================================================================
174
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
+ },
175
188
  /**
176
189
  * Register a new user
177
190
  */
@@ -831,7 +844,7 @@ var ScaleMuleServer = class {
831
844
  code: `HTTP_${response.status}`,
832
845
  message: responseData?.message || text || response.statusText
833
846
  };
834
- const error = withErrorContext(baseError, responseData, response.headers);
847
+ const error2 = withErrorContext(baseError, responseData, response.headers);
835
848
  if (response.status === 401 && options.sessionToken && !options.isAutoRefresh) {
836
849
  if (this.debug) console.log("[ScaleMule Server] 401 received, attempting auto-refresh...");
837
850
  try {
@@ -854,12 +867,12 @@ var ScaleMuleServer = class {
854
867
  if (this.debug) console.error("[ScaleMule Server] Auto-refresh failed:", refreshErr);
855
868
  const refreshApiError = refreshErr instanceof ScaleMuleApiError ? { code: refreshErr.code, message: refreshErr.message } : { code: "REFRESH_FAILED", message: "Auto-refresh failed" };
856
869
  this.onAutoRefreshFailed?.(refreshApiError);
857
- throw new ScaleMuleApiError(error);
870
+ throw new ScaleMuleApiError(error2);
858
871
  } finally {
859
872
  this.onRefreshEnd?.();
860
873
  }
861
874
  }
862
- throw new ScaleMuleApiError(error);
875
+ throw new ScaleMuleApiError(error2);
863
876
  }
864
877
  const data = responseData?.data !== void 0 ? responseData.data : responseData;
865
878
  return data;
@@ -900,9 +913,10 @@ function createCookieHeader(name, value, options = {}) {
900
913
  const sameSite = options.sameSite ?? "lax";
901
914
  const path = options.path ?? "/";
902
915
  let cookie = `${name}=${encodeURIComponent(value)}; Path=${path}; Max-Age=${maxAge}; HttpOnly; SameSite=${sameSite}`;
903
- if (secure) {
916
+ if (secure || options.partitioned) {
904
917
  cookie += "; Secure";
905
918
  }
919
+ if (options.partitioned) cookie += "; Partitioned";
906
920
  if (options.domain) {
907
921
  cookie += `; Domain=${options.domain}`;
908
922
  }
@@ -913,9 +927,10 @@ function createClearCookieHeader(name, options = {}) {
913
927
  const secure = options.secure ?? process.env.NODE_ENV === "production";
914
928
  const sameSite = options.sameSite ?? "lax";
915
929
  let cookie = `${name}=; Path=${path}; Max-Age=0; HttpOnly; SameSite=${sameSite}`;
916
- if (secure) {
930
+ if (secure || options.partitioned) {
917
931
  cookie += "; Secure";
918
932
  }
933
+ if (options.partitioned) cookie += "; Partitioned";
919
934
  if (options.domain) {
920
935
  cookie += `; Domain=${options.domain}`;
921
936
  }
@@ -924,6 +939,10 @@ function createClearCookieHeader(name, options = {}) {
924
939
  function withSession(loginResponse, responseBody, options = {}) {
925
940
  const headers2 = new Headers();
926
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
+ }
927
946
  headers2.append(
928
947
  "Set-Cookie",
929
948
  createCookieHeader(SESSION_COOKIE_NAME, loginResponse.session_token, options)
@@ -940,6 +959,10 @@ function withSession(loginResponse, responseBody, options = {}) {
940
959
  function withRefreshedSession(sessionToken, userId, responseBody, options = {}) {
941
960
  const headers2 = new Headers();
942
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
+ }
943
966
  headers2.append(
944
967
  "Set-Cookie",
945
968
  createCookieHeader(SESSION_COOKIE_NAME, sessionToken, options)
@@ -956,6 +979,10 @@ function withRefreshedSession(sessionToken, userId, responseBody, options = {})
956
979
  function clearSession(responseBody, options = {}, status = 200) {
957
980
  const headers2 = new Headers();
958
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
+ }
959
986
  headers2.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, options));
960
987
  headers2.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, options));
961
988
  return new Response(JSON.stringify({ success: status < 300, data: responseBody }), {
@@ -963,7 +990,7 @@ function clearSession(responseBody, options = {}, status = 200) {
963
990
  headers: headers2
964
991
  });
965
992
  }
966
- async function getSession() {
993
+ async function getSession(options = {}) {
967
994
  const cookieStore = await cookies();
968
995
  const sessionCookie = cookieStore.get(SESSION_COOKIE_NAME);
969
996
  const userIdCookie = cookieStore.get(USER_ID_COOKIE_NAME);
@@ -975,6 +1002,7 @@ async function getSession() {
975
1002
  // Note: actual expiry is managed by ScaleMule backend
976
1003
  };
977
1004
  }
1005
+ if (options.allowBearer === false) return null;
978
1006
  const headerStore = await headers();
979
1007
  return sessionFromAuthHeaders(
980
1008
  headerStore.get("authorization"),
@@ -1180,6 +1208,139 @@ function validateCSRFToken(request) {
1180
1208
  return void 0;
1181
1209
  }
1182
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/widget-config", "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
+
1183
1344
  // src/server/routes.ts
1184
1345
  function errorResponse(code, message, status) {
1185
1346
  return new Response(
@@ -1196,6 +1357,12 @@ function successResponse(data, status = 200) {
1196
1357
  function createAuthRoutes(config = {}) {
1197
1358
  const sm = createServerClient(config.client);
1198
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
+ });
1199
1366
  const POST2 = async (request, context) => {
1200
1367
  if (config.csrf) {
1201
1368
  const csrfError = validateCSRFToken(request);
@@ -1207,7 +1374,7 @@ function createAuthRoutes(config = {}) {
1207
1374
  const path = params?.scalemule?.join("/") || "";
1208
1375
  try {
1209
1376
  const body = await request.json().catch(() => ({}));
1210
- const clientContext = extractClientContext(request);
1377
+ const clientContext = extractClientContext(request, config.clientContext);
1211
1378
  switch (path) {
1212
1379
  // ==================== Register ====================
1213
1380
  case "register": {
@@ -1233,9 +1400,9 @@ function createAuthRoutes(config = {}) {
1233
1400
  try {
1234
1401
  loginData = await sm.auth.login({ email, password }, { clientContext });
1235
1402
  } catch {
1236
- return successResponse({ user: registeredUser, message: "Registration successful" }, 201);
1403
+ return successResponse({ user: registeredUser, authenticated: false, message: "Registration successful" }, 201);
1237
1404
  }
1238
- 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);
1239
1406
  if (config.enableAccountSwitcher) {
1240
1407
  const existingKnown = getKnownAccountsCookieRaw(request);
1241
1408
  appendKnownAccountCookie(
@@ -1255,6 +1422,12 @@ function createAuthRoutes(config = {}) {
1255
1422
  }
1256
1423
  return registerResponse;
1257
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
+ }
1258
1431
  case "mfa/send-code": {
1259
1432
  const { pending_token, method } = body;
1260
1433
  if (!pending_token || !["email", "sms"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token and method required", 400);
@@ -1266,7 +1439,7 @@ function createAuthRoutes(config = {}) {
1266
1439
  const result = await sm.auth.completeMfa(pending_token, code, method, { clientContext });
1267
1440
  if (!result.session_token || !result.user) return errorResponse("MFA_FAILED", "Unable to complete sign-in", 400);
1268
1441
  await config.onLogin?.({ id: result.user.id, email: result.user.email });
1269
- 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);
1270
1443
  if (config.enableAccountSwitcher) {
1271
1444
  appendKnownAccountCookie(response.headers, {
1272
1445
  userId: result.user.id,
@@ -1291,7 +1464,7 @@ function createAuthRoutes(config = {}) {
1291
1464
  } catch (err) {
1292
1465
  const apiErr = err instanceof ScaleMuleApiError ? err : null;
1293
1466
  const errorCode = apiErr?.code || "LOGIN_FAILED";
1294
- let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 202 : 400;
1467
+ let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 403 : 400;
1295
1468
  if (errorCode === "CHALLENGE_RATE_LIMITED") status = 429;
1296
1469
  if (errorCode === "INVALID_CREDENTIALS" || errorCode === "UNAUTHORIZED") status = 401;
1297
1470
  if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED"].includes(errorCode)) {
@@ -1309,7 +1482,7 @@ function createAuthRoutes(config = {}) {
1309
1482
  email: loginData.user.email
1310
1483
  });
1311
1484
  }
1312
- 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);
1313
1486
  if (config.enableAccountSwitcher) {
1314
1487
  const existingKnown = getKnownAccountsCookieRaw(request);
1315
1488
  appendKnownAccountCookie(
@@ -1331,7 +1504,7 @@ function createAuthRoutes(config = {}) {
1331
1504
  }
1332
1505
  // ==================== Logout ====================
1333
1506
  case "logout": {
1334
- const session = await getSession();
1507
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1335
1508
  let rotated = null;
1336
1509
  if (session) {
1337
1510
  try {
@@ -1395,7 +1568,7 @@ function createAuthRoutes(config = {}) {
1395
1568
  if (verifyData?.session_token && verifyData?.user) {
1396
1569
  return withSession(
1397
1570
  { session_token: verifyData.session_token, user: verifyData.user },
1398
- { 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) },
1399
1572
  cookieOptions
1400
1573
  );
1401
1574
  }
@@ -1405,7 +1578,7 @@ function createAuthRoutes(config = {}) {
1405
1578
  // Supports both authenticated (session-based) and unauthenticated (email-based) resend
1406
1579
  case "resend-verification": {
1407
1580
  const { email } = body;
1408
- const session = await getSession();
1581
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1409
1582
  let rotated = null;
1410
1583
  if (email) {
1411
1584
  try {
@@ -1449,7 +1622,7 @@ function createAuthRoutes(config = {}) {
1449
1622
  }
1450
1623
  // ==================== Refresh Session ====================
1451
1624
  case "refresh": {
1452
- const session = await getSession();
1625
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1453
1626
  if (!session) {
1454
1627
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1455
1628
  }
@@ -1459,19 +1632,20 @@ function createAuthRoutes(config = {}) {
1459
1632
  } catch {
1460
1633
  return clearSession(
1461
1634
  { message: "Session expired" },
1462
- cookieOptions
1635
+ cookieOptions,
1636
+ 401
1463
1637
  );
1464
1638
  }
1465
1639
  return withRefreshedSession(
1466
1640
  refreshData.session_token,
1467
1641
  session.userId,
1468
- { message: "Session refreshed" },
1642
+ { message: "Session refreshed", ...config.sessionMode === "bearer" ? { sessionToken: refreshData.session_token, userId: session.userId } : {} },
1469
1643
  cookieOptions
1470
1644
  );
1471
1645
  }
1472
1646
  // ==================== Change Password ====================
1473
1647
  case "change-password": {
1474
- const session = await getSession();
1648
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1475
1649
  if (!session) {
1476
1650
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1477
1651
  }
@@ -1516,7 +1690,7 @@ function createAuthRoutes(config = {}) {
1516
1690
  if (!config.enableAccountSwitcher) {
1517
1691
  return errorResponse("NOT_FOUND", "Account switcher not enabled", 404);
1518
1692
  }
1519
- const session = await getSession();
1693
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1520
1694
  if (session) {
1521
1695
  try {
1522
1696
  await sm.auth.logout(session.sessionToken);
@@ -1566,6 +1740,9 @@ function createAuthRoutes(config = {}) {
1566
1740
  return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
1567
1741
  }
1568
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
+ }
1569
1746
  if (path.startsWith("mfa/") && err instanceof ScaleMuleApiError) {
1570
1747
  const status = ["CHALLENGE_RATE_LIMITED", "MFA_RATE_LIMITED", "MFA_MAX_ATTEMPTS"].includes(err.code) ? 429 : 400;
1571
1748
  return errorResponse(err.code, err.message, status);
@@ -1586,7 +1763,7 @@ function createAuthRoutes(config = {}) {
1586
1763
  if (normCookie) resp.headers.append("Set-Cookie", normCookie);
1587
1764
  return resp;
1588
1765
  };
1589
- const session = await getSession();
1766
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1590
1767
  if (!session) {
1591
1768
  return withNorm(errorResponse("UNAUTHORIZED", "Authentication required", 401));
1592
1769
  }
@@ -1608,15 +1785,15 @@ function createAuthRoutes(config = {}) {
1608
1785
  return withNorm(withRefreshedSession(
1609
1786
  rotated,
1610
1787
  session.userId,
1611
- { user: userData, sessionToken: rotated, userId: session.userId },
1788
+ sessionData(userData, rotated),
1612
1789
  cookieOptions
1613
1790
  ));
1614
1791
  }
1615
- return withNorm(successResponse({ user: userData, sessionToken: session.sessionToken, userId: session.userId }));
1792
+ return withNorm(successResponse(sessionData(userData, session.sessionToken)));
1616
1793
  }
1617
1794
  // ==================== Get Session Status ====================
1618
1795
  case "session": {
1619
- const session = await getSession();
1796
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1620
1797
  return successResponse({
1621
1798
  authenticated: !!session,
1622
1799
  userId: session?.userId || null
@@ -1646,7 +1823,7 @@ function createAuthRoutes(config = {}) {
1646
1823
  // ==================== Delete Account ====================
1647
1824
  case "me":
1648
1825
  case "account": {
1649
- const session = await getSession();
1826
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1650
1827
  if (!session) {
1651
1828
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1652
1829
  }
@@ -1683,7 +1860,7 @@ function createAuthRoutes(config = {}) {
1683
1860
  // ==================== Update Profile ====================
1684
1861
  case "me":
1685
1862
  case "profile": {
1686
- const session = await getSession();
1863
+ const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
1687
1864
  if (!session) {
1688
1865
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
1689
1866
  }
@@ -1723,7 +1900,22 @@ function createAuthRoutes(config = {}) {
1723
1900
  return errorResponse("SERVER_ERROR", "Internal server error", 500);
1724
1901
  }
1725
1902
  };
1726
- 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)) };
1727
1919
  }
1728
1920
 
1729
1921
  // src/server/auth.ts
@@ -1731,6 +1923,6 @@ var cookieDomain = typeof process !== "undefined" ? process.env.SCALEMULE_COOKIE
1731
1923
  var handlers = createAuthRoutes({
1732
1924
  cookies: cookieDomain ? { domain: cookieDomain } : void 0
1733
1925
  });
1734
- var { GET, POST, DELETE, PATCH } = handlers;
1926
+ var { GET, POST, DELETE, PATCH, PUT } = handlers;
1735
1927
 
1736
- 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 */
@@ -1,6 +1,6 @@
1
- import { S as ServerConfig } from '../webhook-handler-44RRJH-r.js';
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-44RRJH-r.js';
3
- import { p as ClientContext, A as ApiError } from '../index-BQgmT53x.js';
1
+ import { S as ServerConfig } from '../webhook-handler-1nnrmWT0.js';
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-1nnrmWT0.js';
3
+ import { q as ClientContext, A as ApiError } from '../index-2PnO4RAF.js';
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.js';
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 */