@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.
- package/README.md +51 -5
- package/dist/client.d.mts +6 -1
- package/dist/client.d.ts +6 -1
- package/dist/client.js +24 -4
- package/dist/client.mjs +24 -4
- package/dist/{index-BQgmT53x.d.mts → index-2PnO4RAF.d.mts} +19 -5
- package/dist/{index-BQgmT53x.d.ts → index-2PnO4RAF.d.ts} +19 -5
- package/dist/index.d.mts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +136 -48
- package/dist/index.mjs +136 -48
- package/dist/server/auth.d.mts +7 -2
- package/dist/server/auth.d.ts +7 -2
- package/dist/server/auth.js +260 -39
- package/dist/server/auth.mjs +260 -40
- package/dist/server/index.d.mts +24 -5
- package/dist/server/index.d.ts +24 -5
- package/dist/server/index.js +286 -66
- package/dist/server/index.mjs +286 -66
- package/dist/server/webhook-handler.d.mts +2 -2
- package/dist/server/webhook-handler.d.ts +2 -2
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/{webhook-handler-44RRJH-r.d.ts → webhook-handler-1nnrmWT0.d.ts} +11 -1
- package/dist/{webhook-handler-DKt6H8FB.d.mts → webhook-handler-DNpCXDDA.d.mts} +11 -1
- package/docs/network-audio.md +10 -5
- package/package.json +2 -2
package/dist/server/auth.js
CHANGED
|
@@ -6,18 +6,46 @@ require('next/server');
|
|
|
6
6
|
|
|
7
7
|
// src/types/index.ts
|
|
8
8
|
var ScaleMuleApiError = class extends Error {
|
|
9
|
-
constructor(
|
|
10
|
-
super(
|
|
9
|
+
constructor(error2, status) {
|
|
10
|
+
super(error2.message);
|
|
11
11
|
this.name = "ScaleMuleApiError";
|
|
12
|
-
this.code =
|
|
13
|
-
this.field =
|
|
12
|
+
this.code = error2.code;
|
|
13
|
+
this.field = error2.field;
|
|
14
14
|
this.status = status;
|
|
15
|
-
this.requestId =
|
|
16
|
-
this.traceId =
|
|
17
|
-
this.problem =
|
|
15
|
+
this.requestId = error2.requestId;
|
|
16
|
+
this.traceId = error2.traceId;
|
|
17
|
+
this.problem = error2.problem;
|
|
18
18
|
}
|
|
19
19
|
};
|
|
20
20
|
|
|
21
|
+
// src/url-privacy.ts
|
|
22
|
+
function withoutAuthSecrets(value) {
|
|
23
|
+
if (!value) return value;
|
|
24
|
+
try {
|
|
25
|
+
const absolute = /^[a-z][a-z0-9+.-]*:/i.test(value);
|
|
26
|
+
const protocolRelative = value.startsWith("//");
|
|
27
|
+
const url = new URL(value, "https://relative.invalid");
|
|
28
|
+
if (!["http:", "https:"].includes(url.protocol)) return void 0;
|
|
29
|
+
let changed = false;
|
|
30
|
+
for (const name of [...url.searchParams.keys()]) {
|
|
31
|
+
if (/^(token|code|state|password|new_password|access_token|refresh_token|id_token|api_key|client_secret|challenge_token|challenge_code)$/i.test(name)) {
|
|
32
|
+
url.searchParams.delete(name);
|
|
33
|
+
changed = true;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
if (url.hash) {
|
|
37
|
+
url.hash = "";
|
|
38
|
+
changed = true;
|
|
39
|
+
}
|
|
40
|
+
if (!changed) return value;
|
|
41
|
+
if (absolute) return url.toString();
|
|
42
|
+
if (protocolRelative) return url.toString().replace(/^https:/, "");
|
|
43
|
+
return value.split(/[?#]/, 1)[0] + url.search;
|
|
44
|
+
} catch {
|
|
45
|
+
return void 0;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
21
49
|
// src/server/context.ts
|
|
22
50
|
function validateIP(ip) {
|
|
23
51
|
if (!ip) return void 0;
|
|
@@ -31,7 +59,7 @@ function validateIP(ip) {
|
|
|
31
59
|
}
|
|
32
60
|
return void 0;
|
|
33
61
|
}
|
|
34
|
-
function extractClientContext(request) {
|
|
62
|
+
function extractClientContext(request, options = {}) {
|
|
35
63
|
const headers2 = request.headers;
|
|
36
64
|
let ip;
|
|
37
65
|
ip = validateIP(headers2.get("x-real-ip"));
|
|
@@ -74,9 +102,14 @@ function extractClientContext(request) {
|
|
|
74
102
|
if (!ip && request.ip) {
|
|
75
103
|
ip = validateIP(request.ip);
|
|
76
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
|
+
}
|
|
77
110
|
const userAgent = headers2.get("user-agent") || void 0;
|
|
78
111
|
const deviceFingerprint = headers2.get("x-device-fingerprint") || void 0;
|
|
79
|
-
const referrer = headers2.get("referer") || void 0;
|
|
112
|
+
const referrer = withoutAuthSecrets(headers2.get("referer") || void 0);
|
|
80
113
|
const anonymousId = headers2.get("x-anonymous-id") || void 0;
|
|
81
114
|
return {
|
|
82
115
|
ip,
|
|
@@ -111,8 +144,8 @@ function buildClientContextHeaders(context) {
|
|
|
111
144
|
}
|
|
112
145
|
|
|
113
146
|
// src/error-context.ts
|
|
114
|
-
function withErrorContext(
|
|
115
|
-
const enriched = { ...
|
|
147
|
+
function withErrorContext(error2, responseData, headers2) {
|
|
148
|
+
const enriched = { ...error2 };
|
|
116
149
|
const meta = responseData?.meta;
|
|
117
150
|
const requestId = meta?.request_id ?? headers2?.get("x-request-id") ?? void 0;
|
|
118
151
|
if (requestId !== void 0 && enriched.requestId === void 0) {
|
|
@@ -146,6 +179,14 @@ var ScaleMuleServer = class {
|
|
|
146
179
|
// Auth Methods
|
|
147
180
|
// ==========================================================================
|
|
148
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
|
+
},
|
|
149
190
|
/**
|
|
150
191
|
* Register a new user
|
|
151
192
|
*/
|
|
@@ -805,7 +846,7 @@ var ScaleMuleServer = class {
|
|
|
805
846
|
code: `HTTP_${response.status}`,
|
|
806
847
|
message: responseData?.message || text || response.statusText
|
|
807
848
|
};
|
|
808
|
-
const
|
|
849
|
+
const error2 = withErrorContext(baseError, responseData, response.headers);
|
|
809
850
|
if (response.status === 401 && options.sessionToken && !options.isAutoRefresh) {
|
|
810
851
|
if (this.debug) console.log("[ScaleMule Server] 401 received, attempting auto-refresh...");
|
|
811
852
|
try {
|
|
@@ -828,12 +869,12 @@ var ScaleMuleServer = class {
|
|
|
828
869
|
if (this.debug) console.error("[ScaleMule Server] Auto-refresh failed:", refreshErr);
|
|
829
870
|
const refreshApiError = refreshErr instanceof ScaleMuleApiError ? { code: refreshErr.code, message: refreshErr.message } : { code: "REFRESH_FAILED", message: "Auto-refresh failed" };
|
|
830
871
|
this.onAutoRefreshFailed?.(refreshApiError);
|
|
831
|
-
throw new ScaleMuleApiError(
|
|
872
|
+
throw new ScaleMuleApiError(error2);
|
|
832
873
|
} finally {
|
|
833
874
|
this.onRefreshEnd?.();
|
|
834
875
|
}
|
|
835
876
|
}
|
|
836
|
-
throw new ScaleMuleApiError(
|
|
877
|
+
throw new ScaleMuleApiError(error2);
|
|
837
878
|
}
|
|
838
879
|
const data = responseData?.data !== void 0 ? responseData.data : responseData;
|
|
839
880
|
return data;
|
|
@@ -874,9 +915,10 @@ function createCookieHeader(name, value, options = {}) {
|
|
|
874
915
|
const sameSite = options.sameSite ?? "lax";
|
|
875
916
|
const path = options.path ?? "/";
|
|
876
917
|
let cookie = `${name}=${encodeURIComponent(value)}; Path=${path}; Max-Age=${maxAge}; HttpOnly; SameSite=${sameSite}`;
|
|
877
|
-
if (secure) {
|
|
918
|
+
if (secure || options.partitioned) {
|
|
878
919
|
cookie += "; Secure";
|
|
879
920
|
}
|
|
921
|
+
if (options.partitioned) cookie += "; Partitioned";
|
|
880
922
|
if (options.domain) {
|
|
881
923
|
cookie += `; Domain=${options.domain}`;
|
|
882
924
|
}
|
|
@@ -887,9 +929,10 @@ function createClearCookieHeader(name, options = {}) {
|
|
|
887
929
|
const secure = options.secure ?? process.env.NODE_ENV === "production";
|
|
888
930
|
const sameSite = options.sameSite ?? "lax";
|
|
889
931
|
let cookie = `${name}=; Path=${path}; Max-Age=0; HttpOnly; SameSite=${sameSite}`;
|
|
890
|
-
if (secure) {
|
|
932
|
+
if (secure || options.partitioned) {
|
|
891
933
|
cookie += "; Secure";
|
|
892
934
|
}
|
|
935
|
+
if (options.partitioned) cookie += "; Partitioned";
|
|
893
936
|
if (options.domain) {
|
|
894
937
|
cookie += `; Domain=${options.domain}`;
|
|
895
938
|
}
|
|
@@ -898,6 +941,10 @@ function createClearCookieHeader(name, options = {}) {
|
|
|
898
941
|
function withSession(loginResponse, responseBody, options = {}) {
|
|
899
942
|
const headers2 = new Headers();
|
|
900
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
|
+
}
|
|
901
948
|
headers2.append(
|
|
902
949
|
"Set-Cookie",
|
|
903
950
|
createCookieHeader(SESSION_COOKIE_NAME, loginResponse.session_token, options)
|
|
@@ -914,6 +961,10 @@ function withSession(loginResponse, responseBody, options = {}) {
|
|
|
914
961
|
function withRefreshedSession(sessionToken, userId, responseBody, options = {}) {
|
|
915
962
|
const headers2 = new Headers();
|
|
916
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
|
+
}
|
|
917
968
|
headers2.append(
|
|
918
969
|
"Set-Cookie",
|
|
919
970
|
createCookieHeader(SESSION_COOKIE_NAME, sessionToken, options)
|
|
@@ -930,6 +981,10 @@ function withRefreshedSession(sessionToken, userId, responseBody, options = {})
|
|
|
930
981
|
function clearSession(responseBody, options = {}, status = 200) {
|
|
931
982
|
const headers2 = new Headers();
|
|
932
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
|
+
}
|
|
933
988
|
headers2.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, options));
|
|
934
989
|
headers2.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, options));
|
|
935
990
|
return new Response(JSON.stringify({ success: status < 300, data: responseBody }), {
|
|
@@ -937,7 +992,7 @@ function clearSession(responseBody, options = {}, status = 200) {
|
|
|
937
992
|
headers: headers2
|
|
938
993
|
});
|
|
939
994
|
}
|
|
940
|
-
async function getSession() {
|
|
995
|
+
async function getSession(options = {}) {
|
|
941
996
|
const cookieStore = await headers.cookies();
|
|
942
997
|
const sessionCookie = cookieStore.get(SESSION_COOKIE_NAME);
|
|
943
998
|
const userIdCookie = cookieStore.get(USER_ID_COOKIE_NAME);
|
|
@@ -949,6 +1004,7 @@ async function getSession() {
|
|
|
949
1004
|
// Note: actual expiry is managed by ScaleMule backend
|
|
950
1005
|
};
|
|
951
1006
|
}
|
|
1007
|
+
if (options.allowBearer === false) return null;
|
|
952
1008
|
const headerStore = await headers.headers();
|
|
953
1009
|
return sessionFromAuthHeaders(
|
|
954
1010
|
headerStore.get("authorization"),
|
|
@@ -1154,6 +1210,139 @@ function validateCSRFToken(request) {
|
|
|
1154
1210
|
return void 0;
|
|
1155
1211
|
}
|
|
1156
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/items", "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
|
+
|
|
1157
1346
|
// src/server/routes.ts
|
|
1158
1347
|
function errorResponse(code, message, status) {
|
|
1159
1348
|
return new Response(
|
|
@@ -1170,6 +1359,12 @@ function successResponse(data, status = 200) {
|
|
|
1170
1359
|
function createAuthRoutes(config = {}) {
|
|
1171
1360
|
const sm = createServerClient(config.client);
|
|
1172
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
|
+
});
|
|
1173
1368
|
const POST2 = async (request, context) => {
|
|
1174
1369
|
if (config.csrf) {
|
|
1175
1370
|
const csrfError = validateCSRFToken(request);
|
|
@@ -1181,7 +1376,7 @@ function createAuthRoutes(config = {}) {
|
|
|
1181
1376
|
const path = params?.scalemule?.join("/") || "";
|
|
1182
1377
|
try {
|
|
1183
1378
|
const body = await request.json().catch(() => ({}));
|
|
1184
|
-
const clientContext = extractClientContext(request);
|
|
1379
|
+
const clientContext = extractClientContext(request, config.clientContext);
|
|
1185
1380
|
switch (path) {
|
|
1186
1381
|
// ==================== Register ====================
|
|
1187
1382
|
case "register": {
|
|
@@ -1207,9 +1402,9 @@ function createAuthRoutes(config = {}) {
|
|
|
1207
1402
|
try {
|
|
1208
1403
|
loginData = await sm.auth.login({ email, password }, { clientContext });
|
|
1209
1404
|
} catch {
|
|
1210
|
-
return successResponse({ user: registeredUser, message: "Registration successful" }, 201);
|
|
1405
|
+
return successResponse({ user: registeredUser, authenticated: false, message: "Registration successful" }, 201);
|
|
1211
1406
|
}
|
|
1212
|
-
const registerResponse = withSession(loginData,
|
|
1407
|
+
const registerResponse = withSession(loginData, sessionData(registeredUser, loginData.session_token), cookieOptions);
|
|
1213
1408
|
if (config.enableAccountSwitcher) {
|
|
1214
1409
|
const existingKnown = getKnownAccountsCookieRaw(request);
|
|
1215
1410
|
appendKnownAccountCookie(
|
|
@@ -1229,6 +1424,12 @@ function createAuthRoutes(config = {}) {
|
|
|
1229
1424
|
}
|
|
1230
1425
|
return registerResponse;
|
|
1231
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
|
+
}
|
|
1232
1433
|
case "mfa/send-code": {
|
|
1233
1434
|
const { pending_token, method } = body;
|
|
1234
1435
|
if (!pending_token || !["email", "sms"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token and method required", 400);
|
|
@@ -1240,7 +1441,7 @@ function createAuthRoutes(config = {}) {
|
|
|
1240
1441
|
const result = await sm.auth.completeMfa(pending_token, code, method, { clientContext });
|
|
1241
1442
|
if (!result.session_token || !result.user) return errorResponse("MFA_FAILED", "Unable to complete sign-in", 400);
|
|
1242
1443
|
await config.onLogin?.({ id: result.user.id, email: result.user.email });
|
|
1243
|
-
const response = withSession(result,
|
|
1444
|
+
const response = withSession(result, sessionData(result.user, result.session_token), cookieOptions);
|
|
1244
1445
|
if (config.enableAccountSwitcher) {
|
|
1245
1446
|
appendKnownAccountCookie(response.headers, {
|
|
1246
1447
|
userId: result.user.id,
|
|
@@ -1265,7 +1466,7 @@ function createAuthRoutes(config = {}) {
|
|
|
1265
1466
|
} catch (err) {
|
|
1266
1467
|
const apiErr = err instanceof ScaleMuleApiError ? err : null;
|
|
1267
1468
|
const errorCode = apiErr?.code || "LOGIN_FAILED";
|
|
1268
|
-
let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ?
|
|
1469
|
+
let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 403 : 400;
|
|
1269
1470
|
if (errorCode === "CHALLENGE_RATE_LIMITED") status = 429;
|
|
1270
1471
|
if (errorCode === "INVALID_CREDENTIALS" || errorCode === "UNAUTHORIZED") status = 401;
|
|
1271
1472
|
if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED"].includes(errorCode)) {
|
|
@@ -1283,7 +1484,7 @@ function createAuthRoutes(config = {}) {
|
|
|
1283
1484
|
email: loginData.user.email
|
|
1284
1485
|
});
|
|
1285
1486
|
}
|
|
1286
|
-
const loginResponse = withSession(loginData,
|
|
1487
|
+
const loginResponse = withSession(loginData, sessionData(loginData.user, loginData.session_token), cookieOptions);
|
|
1287
1488
|
if (config.enableAccountSwitcher) {
|
|
1288
1489
|
const existingKnown = getKnownAccountsCookieRaw(request);
|
|
1289
1490
|
appendKnownAccountCookie(
|
|
@@ -1305,7 +1506,7 @@ function createAuthRoutes(config = {}) {
|
|
|
1305
1506
|
}
|
|
1306
1507
|
// ==================== Logout ====================
|
|
1307
1508
|
case "logout": {
|
|
1308
|
-
const session = await getSession();
|
|
1509
|
+
const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
|
|
1309
1510
|
let rotated = null;
|
|
1310
1511
|
if (session) {
|
|
1311
1512
|
try {
|
|
@@ -1369,7 +1570,7 @@ function createAuthRoutes(config = {}) {
|
|
|
1369
1570
|
if (verifyData?.session_token && verifyData?.user) {
|
|
1370
1571
|
return withSession(
|
|
1371
1572
|
{ session_token: verifyData.session_token, user: verifyData.user },
|
|
1372
|
-
{ message: "Email verified successfully", verified: true,
|
|
1573
|
+
{ message: "Email verified successfully", verified: true, ...sessionData(verifyData.user, verifyData.session_token) },
|
|
1373
1574
|
cookieOptions
|
|
1374
1575
|
);
|
|
1375
1576
|
}
|
|
@@ -1379,7 +1580,7 @@ function createAuthRoutes(config = {}) {
|
|
|
1379
1580
|
// Supports both authenticated (session-based) and unauthenticated (email-based) resend
|
|
1380
1581
|
case "resend-verification": {
|
|
1381
1582
|
const { email } = body;
|
|
1382
|
-
const session = await getSession();
|
|
1583
|
+
const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
|
|
1383
1584
|
let rotated = null;
|
|
1384
1585
|
if (email) {
|
|
1385
1586
|
try {
|
|
@@ -1423,7 +1624,7 @@ function createAuthRoutes(config = {}) {
|
|
|
1423
1624
|
}
|
|
1424
1625
|
// ==================== Refresh Session ====================
|
|
1425
1626
|
case "refresh": {
|
|
1426
|
-
const session = await getSession();
|
|
1627
|
+
const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
|
|
1427
1628
|
if (!session) {
|
|
1428
1629
|
return errorResponse("UNAUTHORIZED", "Authentication required", 401);
|
|
1429
1630
|
}
|
|
@@ -1433,19 +1634,20 @@ function createAuthRoutes(config = {}) {
|
|
|
1433
1634
|
} catch {
|
|
1434
1635
|
return clearSession(
|
|
1435
1636
|
{ message: "Session expired" },
|
|
1436
|
-
cookieOptions
|
|
1637
|
+
cookieOptions,
|
|
1638
|
+
401
|
|
1437
1639
|
);
|
|
1438
1640
|
}
|
|
1439
1641
|
return withRefreshedSession(
|
|
1440
1642
|
refreshData.session_token,
|
|
1441
1643
|
session.userId,
|
|
1442
|
-
{ message: "Session refreshed" },
|
|
1644
|
+
{ message: "Session refreshed", ...config.sessionMode === "bearer" ? { sessionToken: refreshData.session_token, userId: session.userId } : {} },
|
|
1443
1645
|
cookieOptions
|
|
1444
1646
|
);
|
|
1445
1647
|
}
|
|
1446
1648
|
// ==================== Change Password ====================
|
|
1447
1649
|
case "change-password": {
|
|
1448
|
-
const session = await getSession();
|
|
1650
|
+
const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
|
|
1449
1651
|
if (!session) {
|
|
1450
1652
|
return errorResponse("UNAUTHORIZED", "Authentication required", 401);
|
|
1451
1653
|
}
|
|
@@ -1490,7 +1692,7 @@ function createAuthRoutes(config = {}) {
|
|
|
1490
1692
|
if (!config.enableAccountSwitcher) {
|
|
1491
1693
|
return errorResponse("NOT_FOUND", "Account switcher not enabled", 404);
|
|
1492
1694
|
}
|
|
1493
|
-
const session = await getSession();
|
|
1695
|
+
const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
|
|
1494
1696
|
if (session) {
|
|
1495
1697
|
try {
|
|
1496
1698
|
await sm.auth.logout(session.sessionToken);
|
|
@@ -1540,6 +1742,9 @@ function createAuthRoutes(config = {}) {
|
|
|
1540
1742
|
return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
|
|
1541
1743
|
}
|
|
1542
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
|
+
}
|
|
1543
1748
|
if (path.startsWith("mfa/") && err instanceof ScaleMuleApiError) {
|
|
1544
1749
|
const status = ["CHALLENGE_RATE_LIMITED", "MFA_RATE_LIMITED", "MFA_MAX_ATTEMPTS"].includes(err.code) ? 429 : 400;
|
|
1545
1750
|
return errorResponse(err.code, err.message, status);
|
|
@@ -1560,7 +1765,7 @@ function createAuthRoutes(config = {}) {
|
|
|
1560
1765
|
if (normCookie) resp.headers.append("Set-Cookie", normCookie);
|
|
1561
1766
|
return resp;
|
|
1562
1767
|
};
|
|
1563
|
-
const session = await getSession();
|
|
1768
|
+
const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
|
|
1564
1769
|
if (!session) {
|
|
1565
1770
|
return withNorm(errorResponse("UNAUTHORIZED", "Authentication required", 401));
|
|
1566
1771
|
}
|
|
@@ -1582,15 +1787,15 @@ function createAuthRoutes(config = {}) {
|
|
|
1582
1787
|
return withNorm(withRefreshedSession(
|
|
1583
1788
|
rotated,
|
|
1584
1789
|
session.userId,
|
|
1585
|
-
|
|
1790
|
+
sessionData(userData, rotated),
|
|
1586
1791
|
cookieOptions
|
|
1587
1792
|
));
|
|
1588
1793
|
}
|
|
1589
|
-
return withNorm(successResponse(
|
|
1794
|
+
return withNorm(successResponse(sessionData(userData, session.sessionToken)));
|
|
1590
1795
|
}
|
|
1591
1796
|
// ==================== Get Session Status ====================
|
|
1592
1797
|
case "session": {
|
|
1593
|
-
const session = await getSession();
|
|
1798
|
+
const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
|
|
1594
1799
|
return successResponse({
|
|
1595
1800
|
authenticated: !!session,
|
|
1596
1801
|
userId: session?.userId || null
|
|
@@ -1620,7 +1825,7 @@ function createAuthRoutes(config = {}) {
|
|
|
1620
1825
|
// ==================== Delete Account ====================
|
|
1621
1826
|
case "me":
|
|
1622
1827
|
case "account": {
|
|
1623
|
-
const session = await getSession();
|
|
1828
|
+
const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
|
|
1624
1829
|
if (!session) {
|
|
1625
1830
|
return errorResponse("UNAUTHORIZED", "Authentication required", 401);
|
|
1626
1831
|
}
|
|
@@ -1657,7 +1862,7 @@ function createAuthRoutes(config = {}) {
|
|
|
1657
1862
|
// ==================== Update Profile ====================
|
|
1658
1863
|
case "me":
|
|
1659
1864
|
case "profile": {
|
|
1660
|
-
const session = await getSession();
|
|
1865
|
+
const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
|
|
1661
1866
|
if (!session) {
|
|
1662
1867
|
return errorResponse("UNAUTHORIZED", "Authentication required", 401);
|
|
1663
1868
|
}
|
|
@@ -1697,7 +1902,22 @@ function createAuthRoutes(config = {}) {
|
|
|
1697
1902
|
return errorResponse("SERVER_ERROR", "Internal server error", 500);
|
|
1698
1903
|
}
|
|
1699
1904
|
};
|
|
1700
|
-
|
|
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)) };
|
|
1701
1921
|
}
|
|
1702
1922
|
|
|
1703
1923
|
// src/server/auth.ts
|
|
@@ -1705,9 +1925,10 @@ var cookieDomain = typeof process !== "undefined" ? process.env.SCALEMULE_COOKIE
|
|
|
1705
1925
|
var handlers = createAuthRoutes({
|
|
1706
1926
|
cookies: cookieDomain ? { domain: cookieDomain } : void 0
|
|
1707
1927
|
});
|
|
1708
|
-
var { GET, POST, DELETE, PATCH } = handlers;
|
|
1928
|
+
var { GET, POST, DELETE, PATCH, PUT } = handlers;
|
|
1709
1929
|
|
|
1710
1930
|
exports.DELETE = DELETE;
|
|
1711
1931
|
exports.GET = GET;
|
|
1712
1932
|
exports.PATCH = PATCH;
|
|
1713
1933
|
exports.POST = POST;
|
|
1934
|
+
exports.PUT = PUT;
|