@scalemule/nextjs 0.1.50 → 0.1.51

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/dist/index.mjs CHANGED
@@ -1,11 +1,133 @@
1
1
  import * as React from 'react';
2
2
  import { createContext, useState, useEffect, useMemo, useCallback, useContext, useRef } from 'react';
3
+ import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
3
4
  import { createMoneyClient } from '@scalemule/money';
4
5
  export { MoneyClient, createMoneyClient } from '@scalemule/money';
5
6
  import { STORAGE_KEYS, ensureAnonymousId, ScaleMule, WebPushManager } from '@scalemule/sdk';
6
- import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
7
7
 
8
- // src/provider.tsx
8
+ // src/security-challenge.tsx
9
+ function useSecurityChallenge(recoveryUrl) {
10
+ const [challenge, setChallenge] = useState(null);
11
+ const [code, setCode] = useState("");
12
+ const resolve = useRef(null);
13
+ const dialog = useRef(null);
14
+ const answer = useCallback((value) => {
15
+ const pending = resolve.current;
16
+ resolve.current = null;
17
+ setChallenge(null);
18
+ setCode("");
19
+ pending?.(value);
20
+ }, []);
21
+ const prompt = useCallback((next) => {
22
+ resolve.current?.(null);
23
+ return new Promise((done) => {
24
+ resolve.current = done;
25
+ setCode("");
26
+ setChallenge(next);
27
+ });
28
+ }, []);
29
+ useEffect(() => () => {
30
+ resolve.current?.(null);
31
+ resolve.current = null;
32
+ }, []);
33
+ useEffect(() => {
34
+ if (challenge && dialog.current && !dialog.current.open) dialog.current.showModal();
35
+ }, [challenge]);
36
+ const element = challenge ? /* @__PURE__ */ jsx(
37
+ "dialog",
38
+ {
39
+ ref: dialog,
40
+ "aria-labelledby": "sm-security-title",
41
+ "aria-describedby": "sm-security-description",
42
+ onCancel: (event) => {
43
+ event.preventDefault();
44
+ answer(null);
45
+ },
46
+ style: { border: "1px solid #d1d5db", borderRadius: 16, padding: 28, maxWidth: 420, width: "calc(100% - 48px)", color: "#111827", background: "#fff", boxSizing: "border-box" },
47
+ children: /* @__PURE__ */ jsxs("form", { onSubmit: (event) => {
48
+ event.preventDefault();
49
+ if (code.trim()) answer(code.trim());
50
+ }, children: [
51
+ /* @__PURE__ */ jsx("h2", { id: "sm-security-title", style: { marginTop: 0 }, children: "Confirm your sign-in" }),
52
+ /* @__PURE__ */ jsx("p", { id: "sm-security-description", children: challenge.method === "totp" ? "Enter a code from your authenticator app." : "Enter the verification code sent to your " + (challenge.method === "sms" ? "phone." : "email.") }),
53
+ challenge.error && /* @__PURE__ */ jsx("p", { role: "alert", style: { color: "#b91c1c" }, children: challenge.error }),
54
+ /* @__PURE__ */ jsx("label", { htmlFor: "sm-security-code", children: "Verification code" }),
55
+ /* @__PURE__ */ jsx(
56
+ "input",
57
+ {
58
+ id: "sm-security-code",
59
+ autoFocus: true,
60
+ autoComplete: "one-time-code",
61
+ inputMode: "numeric",
62
+ value: code,
63
+ onChange: (event) => setCode(event.target.value),
64
+ maxLength: 32,
65
+ required: true,
66
+ style: { display: "block", boxSizing: "border-box", width: "100%", margin: "8px 0 20px", padding: 12, fontSize: 22, border: "1px solid #9ca3af", borderRadius: 8 }
67
+ }
68
+ ),
69
+ /* @__PURE__ */ jsx("button", { type: "submit", style: { padding: "10px 20px", borderRadius: 8, border: 0, background: "#2563eb", color: "#fff", cursor: "pointer" }, children: "Continue" }),
70
+ /* @__PURE__ */ jsx("button", { type: "button", onClick: () => answer(null), style: { marginLeft: 12 }, children: "Cancel" }),
71
+ challenge.method !== "totp" && /* @__PURE__ */ jsxs("p", { children: [
72
+ /* @__PURE__ */ jsx("button", { type: "button", onClick: () => answer("resend"), children: "Send a new code" }),
73
+ " ",
74
+ /* @__PURE__ */ jsx("small", { children: "(wait 60 seconds between requests)" })
75
+ ] }),
76
+ /* @__PURE__ */ jsx("p", { children: /* @__PURE__ */ jsx("a", { href: recoveryUrl, onClick: () => answer(null), children: "Reset your password" }) })
77
+ ] })
78
+ }
79
+ ) : null;
80
+ return { prompt, element };
81
+ }
82
+ async function withAdaptiveChallenge(attempt, prompt, mfa) {
83
+ let proof = {};
84
+ let challengeToken;
85
+ let message;
86
+ for (; ; ) {
87
+ try {
88
+ return await attempt(proof);
89
+ } catch (error) {
90
+ const err = error;
91
+ if (err.code === "MFA_REQUIRED" && mfa) {
92
+ const details = JSON.parse(err.message || "{}");
93
+ const token = details.pending_token;
94
+ const method = details.mfa_method;
95
+ if (!token || !["totp", "email", "sms"].includes(method || "")) throw error;
96
+ if (method !== "totp") await mfa.send(token, method);
97
+ let mfaError;
98
+ for (; ; ) {
99
+ const code2 = await prompt({ method, error: mfaError });
100
+ if (code2 === null) throw { code: "LOGIN_CANCELLED", message: "Sign-in was cancelled." };
101
+ try {
102
+ if (code2 === "resend") {
103
+ await mfa.send(token, method);
104
+ mfaError = void 0;
105
+ continue;
106
+ }
107
+ return await mfa.verify(token, code2, method);
108
+ } catch (failure) {
109
+ const failed = failure;
110
+ if (!["INVALID_MFA_CODE", "CHALLENGE_RATE_LIMITED"].includes(failed.code || "")) throw failure;
111
+ mfaError = failed.message;
112
+ }
113
+ }
114
+ }
115
+ if (err.code === "LOGIN_CHALLENGE_REQUIRED") {
116
+ const details = JSON.parse(err.message || "{}");
117
+ if (!details.challenge_token) throw error;
118
+ challengeToken = details.challenge_token;
119
+ message = void 0;
120
+ } else if (challengeToken && ["LOGIN_CHALLENGE_INVALID", "CHALLENGE_RATE_LIMITED"].includes(err.code || "")) {
121
+ message = err.message;
122
+ } else {
123
+ throw error;
124
+ }
125
+ const code = await prompt({ method: "email", error: message });
126
+ if (code === null) throw { code: "LOGIN_CANCELLED", message: "Sign-in was cancelled." };
127
+ proof = code === "resend" ? {} : { challenge_token: challengeToken, challenge_code: code };
128
+ }
129
+ }
130
+ }
9
131
 
10
132
  // src/types/index.ts
11
133
  var ScaleMuleApiError = class extends Error {
@@ -614,7 +736,7 @@ var ScaleMuleClient = class {
614
736
  responseData = text ? JSON.parse(text) : null;
615
737
  } catch {
616
738
  }
617
- if (!response.ok) {
739
+ if (!response.ok || responseData?.success === false) {
618
740
  const rawError = responseData?.error;
619
741
  const baseError = rawError && typeof rawError === "object" ? rawError : { code: `HTTP_${response.status}`, message: typeof rawError === "string" ? rawError : responseData?.message || text || response.statusText };
620
742
  const error = withErrorContext(baseError, responseData, response.headers);
@@ -653,7 +775,7 @@ var ScaleMuleClient = class {
653
775
  continue;
654
776
  }
655
777
  if (this.debug) {
656
- console.error("[ScaleMule] Request failed:", error);
778
+ console.error("[ScaleMule] Request failed:", ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(error.code) ? error.code : error);
657
779
  }
658
780
  throw new ScaleMuleApiError(error);
659
781
  }
@@ -923,6 +1045,7 @@ function setSdkTelemetryEndpoint(url) {
923
1045
  endpoint = url;
924
1046
  }
925
1047
  function reportSdkError(payload) {
1048
+ if (["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(payload.code)) return;
926
1049
  if (!endpoint) return;
927
1050
  if (typeof fetch === "undefined") return;
928
1051
  const body = JSON.stringify({
@@ -998,8 +1121,12 @@ function ScaleMuleProvider({
998
1121
  mediaPolicy,
999
1122
  getToken,
1000
1123
  userResolver,
1001
- memberTokenPollMs
1124
+ memberTokenPollMs,
1125
+ passwordRecoveryUrl = "/auth/forgot-password",
1126
+ onSecurityChallenge
1002
1127
  }) {
1128
+ const security = useSecurityChallenge(passwordRecoveryUrl);
1129
+ const requestSecurityCode = onSecurityChallenge || security.prompt;
1003
1130
  const memberMode = typeof getToken === "function";
1004
1131
  const [user, setUser] = useState(null);
1005
1132
  const [initializing, setInitializing] = useState(true);
@@ -1241,6 +1368,7 @@ function ScaleMuleProvider({
1241
1368
  );
1242
1369
  const value = useMemo(
1243
1370
  () => ({
1371
+ requestSecurityCode,
1244
1372
  client,
1245
1373
  money,
1246
1374
  realtime: baseClient.realtime,
@@ -1268,9 +1396,12 @@ function ScaleMuleProvider({
1268
1396
  accountSwitcherPrivacy,
1269
1397
  bootstrapFlags
1270
1398
  }),
1271
- [client, money, baseClient, user, handleSetUser, initializing, error, analyticsProxyUrl, authProxyUrl, publishableKey, apiKey, resolvedGatewayUrl, environment, enableAccountSwitcher, accountSwitcherPrivacy, bootstrapFlags, effectiveMediaPolicy]
1399
+ [requestSecurityCode, client, money, baseClient, user, handleSetUser, initializing, error, analyticsProxyUrl, authProxyUrl, publishableKey, apiKey, resolvedGatewayUrl, environment, enableAccountSwitcher, accountSwitcherPrivacy, bootstrapFlags, effectiveMediaPolicy]
1272
1400
  );
1273
- return /* @__PURE__ */ jsx(ScaleMuleContext.Provider, { value, children });
1401
+ return /* @__PURE__ */ jsxs(ScaleMuleContext.Provider, { value, children: [
1402
+ children,
1403
+ security.element
1404
+ ] });
1274
1405
  }
1275
1406
  function useScaleMule() {
1276
1407
  const context = useContext(ScaleMuleContext);
@@ -1382,7 +1513,7 @@ async function proxyFetch(proxyUrl, path, options = {}) {
1382
1513
  return data;
1383
1514
  }
1384
1515
  function useAuth() {
1385
- const { client, user, setUser, initializing, error, setError, authProxyUrl, enableAccountSwitcher, accountSwitcherPrivacy } = useScaleMule();
1516
+ const { client, user, setUser, initializing, error, setError, authProxyUrl, enableAccountSwitcher, accountSwitcherPrivacy, requestSecurityCode } = useScaleMule();
1386
1517
  const register = useCallback(
1387
1518
  async (data) => {
1388
1519
  setError(null);
@@ -1423,19 +1554,31 @@ function useAuth() {
1423
1554
  async (data) => {
1424
1555
  setError(null);
1425
1556
  if (authProxyUrl) {
1426
- const response = await proxyFetch(
1427
- authProxyUrl,
1428
- "login",
1429
- { body: data }
1430
- );
1431
- if (!response.success || !response.data) {
1432
- const err = response.error || {
1433
- code: "LOGIN_FAILED",
1434
- message: "Login failed"
1435
- };
1557
+ const response = await withAdaptiveChallenge(async (proof) => {
1558
+ const result = await proxyFetch(
1559
+ authProxyUrl,
1560
+ "login",
1561
+ { body: { ...data, ...proof } }
1562
+ );
1563
+ if (!result.success || !result.data) {
1564
+ throw result.error || { code: "LOGIN_FAILED", message: "Login failed" };
1565
+ }
1566
+ return { ...result, data: result.data };
1567
+ }, requestSecurityCode, {
1568
+ send: async (pending_token, method) => {
1569
+ const result = await proxyFetch(authProxyUrl, "mfa/send-code", { body: { pending_token, method } });
1570
+ if (!result.success) throw result.error;
1571
+ return result;
1572
+ },
1573
+ verify: async (pending_token, code, method) => {
1574
+ const result = await proxyFetch(authProxyUrl, "mfa/verify", { body: { pending_token, code, method } });
1575
+ if (!result.success || !result.data) throw result.error;
1576
+ return { ...result, data: result.data };
1577
+ }
1578
+ }).catch((err) => {
1436
1579
  setError(err);
1437
1580
  throw err;
1438
- }
1581
+ });
1439
1582
  if ("requires_mfa" in response.data && response.data.requires_mfa) {
1440
1583
  return response.data;
1441
1584
  }
@@ -1453,7 +1596,10 @@ function useAuth() {
1453
1596
  }
1454
1597
  let loginResult;
1455
1598
  try {
1456
- loginResult = await client.post("/v1/auth/login", data);
1599
+ loginResult = await withAdaptiveChallenge((proof) => client.post("/v1/auth/login", { ...data, ...proof }), requestSecurityCode, {
1600
+ send: (pending_token, method) => client.post("/v1/auth/mfa/send-code", { pending_token, method }),
1601
+ verify: (pending_token, code, method) => client.post("/v1/auth/mfa/verify", { pending_token, code, method })
1602
+ });
1457
1603
  } catch (err) {
1458
1604
  if (err instanceof ScaleMuleApiError) {
1459
1605
  setError(err);
@@ -1468,7 +1614,7 @@ function useAuth() {
1468
1614
  setUser(loginData.user);
1469
1615
  return loginData;
1470
1616
  },
1471
- [client, setUser, setError, authProxyUrl]
1617
+ [client, setUser, setError, authProxyUrl, requestSecurityCode]
1472
1618
  );
1473
1619
  const logout = useCallback(async () => {
1474
1620
  setError(null);
@@ -1539,8 +1685,17 @@ function useAuth() {
1539
1685
  throw err;
1540
1686
  }
1541
1687
  }
1688
+ await client.clearSession();
1689
+ setUser(null);
1690
+ if (typeof window !== "undefined") {
1691
+ const current = new URL(window.location.href);
1692
+ if (current.searchParams.get("token") === token) {
1693
+ current.searchParams.delete("token");
1694
+ window.history.replaceState(window.history.state, "", current.toString());
1695
+ }
1696
+ }
1542
1697
  },
1543
- [client, setError, authProxyUrl]
1698
+ [client, setUser, setError, authProxyUrl]
1544
1699
  );
1545
1700
  const verifyEmail = useCallback(
1546
1701
  async (token) => {
@@ -1821,11 +1976,13 @@ function useAuth() {
1821
1976
  setError(null);
1822
1977
  let mfaResult;
1823
1978
  try {
1824
- mfaResult = await client.post("/v1/auth/mfa/challenge", {
1825
- challenge_token: challengeToken,
1826
- code,
1827
- method
1828
- });
1979
+ if (authProxyUrl) {
1980
+ const result = await proxyFetch(authProxyUrl, "mfa/verify", { body: { pending_token: challengeToken, code, method } });
1981
+ if (!result.success || !result.data) throw result.error;
1982
+ mfaResult = result.data;
1983
+ } else {
1984
+ mfaResult = await client.post("/v1/auth/mfa/verify", { pending_token: challengeToken, code, method });
1985
+ }
1829
1986
  } catch (err) {
1830
1987
  if (err instanceof ScaleMuleApiError) {
1831
1988
  setError(err);
@@ -1836,7 +1993,7 @@ function useAuth() {
1836
1993
  setUser(mfaResult.user);
1837
1994
  return mfaResult;
1838
1995
  },
1839
- [client, setUser, setError]
1996
+ [client, setUser, setError, authProxyUrl]
1840
1997
  );
1841
1998
  const disableMFA = useCallback(
1842
1999
  async (password) => {
@@ -34,8 +34,9 @@ function validateIP(ip) {
34
34
  function extractClientContext(request) {
35
35
  const headers2 = request.headers;
36
36
  let ip;
37
+ ip = validateIP(headers2.get("x-real-ip"));
37
38
  const cfConnectingIp = headers2.get("cf-connecting-ip");
38
- if (cfConnectingIp) {
39
+ if (!ip && cfConnectingIp) {
39
40
  ip = validateIP(cfConnectingIp);
40
41
  }
41
42
  if (!ip) {
@@ -154,6 +155,12 @@ var ScaleMuleServer = class {
154
155
  /**
155
156
  * Login user - returns session token (store in HTTP-only cookie)
156
157
  */
158
+ sendMfaCode: async (pending_token, method, options) => {
159
+ return this.request("POST", "/v1/auth/mfa/send-code", { body: { pending_token, method }, clientContext: options?.clientContext });
160
+ },
161
+ completeMfa: async (pending_token, code, method, options) => {
162
+ return this.request("POST", "/v1/auth/mfa/verify", { body: { pending_token, code, method }, clientContext: options?.clientContext });
163
+ },
157
164
  login: async (data, options) => {
158
165
  return this.request("POST", "/v1/auth/login", { body: data, clientContext: options?.clientContext });
159
166
  },
@@ -793,7 +800,7 @@ var ScaleMuleServer = class {
793
800
  responseData = text ? JSON.parse(text) : null;
794
801
  } catch {
795
802
  }
796
- if (!response.ok) {
803
+ if (!response.ok || responseData?.success === false) {
797
804
  const baseError = responseData?.error || {
798
805
  code: `HTTP_${response.status}`,
799
806
  message: responseData?.message || text || response.statusText
@@ -1222,21 +1229,46 @@ function createAuthRoutes(config = {}) {
1222
1229
  }
1223
1230
  return registerResponse;
1224
1231
  }
1232
+ case "mfa/send-code": {
1233
+ const { pending_token, method } = body;
1234
+ if (!pending_token || !["email", "sms"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token and method required", 400);
1235
+ return successResponse(await sm.auth.sendMfaCode(pending_token, method, { clientContext }));
1236
+ }
1237
+ case "mfa/verify": {
1238
+ const { pending_token, code, method } = body;
1239
+ if (!pending_token || !code || !["totp", "email", "sms", "backup_code"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token, code, and valid method required", 400);
1240
+ const result = await sm.auth.completeMfa(pending_token, code, method, { clientContext });
1241
+ if (!result.session_token || !result.user) return errorResponse("MFA_FAILED", "Unable to complete sign-in", 400);
1242
+ await config.onLogin?.({ id: result.user.id, email: result.user.email });
1243
+ const response = withSession(result, { user: result.user, sessionToken: result.session_token, userId: result.user.id }, cookieOptions);
1244
+ if (config.enableAccountSwitcher) {
1245
+ appendKnownAccountCookie(response.headers, {
1246
+ userId: result.user.id,
1247
+ email: result.user.email,
1248
+ fullName: result.user.full_name ?? void 0,
1249
+ avatarUrl: result.user.avatar_url ?? void 0,
1250
+ provider: "email",
1251
+ lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
1252
+ }, getKnownAccountsCookieRaw(request), cookieOptions, config.accountSwitcherPrivacy);
1253
+ }
1254
+ return response;
1255
+ }
1225
1256
  // ==================== Login ====================
1226
1257
  case "login": {
1227
- const { email, password, remember_me } = body;
1258
+ const { email, password, remember_me, device_fingerprint, challenge_token, challenge_code } = body;
1228
1259
  if (!email || !password) {
1229
1260
  return errorResponse("VALIDATION_ERROR", "Email and password required", 400);
1230
1261
  }
1231
1262
  let loginData;
1232
1263
  try {
1233
- loginData = await sm.auth.login({ email, password, remember_me }, { clientContext });
1264
+ loginData = await sm.auth.login({ email, password, remember_me, device_fingerprint, challenge_token, challenge_code }, { clientContext });
1234
1265
  } catch (err) {
1235
1266
  const apiErr = err instanceof ScaleMuleApiError ? err : null;
1236
1267
  const errorCode = apiErr?.code || "LOGIN_FAILED";
1237
- let status = 400;
1268
+ let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 202 : 400;
1269
+ if (errorCode === "CHALLENGE_RATE_LIMITED") status = 429;
1238
1270
  if (errorCode === "INVALID_CREDENTIALS" || errorCode === "UNAUTHORIZED") status = 401;
1239
- if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED", "MFA_REQUIRED"].includes(errorCode)) {
1271
+ if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED"].includes(errorCode)) {
1240
1272
  status = 403;
1241
1273
  }
1242
1274
  return errorResponse(
@@ -1315,7 +1347,7 @@ function createAuthRoutes(config = {}) {
1315
1347
  400
1316
1348
  );
1317
1349
  }
1318
- return successResponse({ message: "Password reset successful" });
1350
+ return clearSession({ message: "Password reset successful" }, cookieOptions);
1319
1351
  }
1320
1352
  // ==================== Verify Email ====================
1321
1353
  case "verify-email": {
@@ -1508,6 +1540,10 @@ function createAuthRoutes(config = {}) {
1508
1540
  return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
1509
1541
  }
1510
1542
  } catch (err) {
1543
+ if (path.startsWith("mfa/") && err instanceof ScaleMuleApiError) {
1544
+ const status = ["CHALLENGE_RATE_LIMITED", "MFA_RATE_LIMITED", "MFA_MAX_ATTEMPTS"].includes(err.code) ? 429 : 400;
1545
+ return errorResponse(err.code, err.message, status);
1546
+ }
1511
1547
  console.error("[ScaleMule Auth] Error:", err);
1512
1548
  return errorResponse("SERVER_ERROR", "Internal server error", 500);
1513
1549
  }
@@ -32,8 +32,9 @@ function validateIP(ip) {
32
32
  function extractClientContext(request) {
33
33
  const headers2 = request.headers;
34
34
  let ip;
35
+ ip = validateIP(headers2.get("x-real-ip"));
35
36
  const cfConnectingIp = headers2.get("cf-connecting-ip");
36
- if (cfConnectingIp) {
37
+ if (!ip && cfConnectingIp) {
37
38
  ip = validateIP(cfConnectingIp);
38
39
  }
39
40
  if (!ip) {
@@ -152,6 +153,12 @@ var ScaleMuleServer = class {
152
153
  /**
153
154
  * Login user - returns session token (store in HTTP-only cookie)
154
155
  */
156
+ sendMfaCode: async (pending_token, method, options) => {
157
+ return this.request("POST", "/v1/auth/mfa/send-code", { body: { pending_token, method }, clientContext: options?.clientContext });
158
+ },
159
+ completeMfa: async (pending_token, code, method, options) => {
160
+ return this.request("POST", "/v1/auth/mfa/verify", { body: { pending_token, code, method }, clientContext: options?.clientContext });
161
+ },
155
162
  login: async (data, options) => {
156
163
  return this.request("POST", "/v1/auth/login", { body: data, clientContext: options?.clientContext });
157
164
  },
@@ -791,7 +798,7 @@ var ScaleMuleServer = class {
791
798
  responseData = text ? JSON.parse(text) : null;
792
799
  } catch {
793
800
  }
794
- if (!response.ok) {
801
+ if (!response.ok || responseData?.success === false) {
795
802
  const baseError = responseData?.error || {
796
803
  code: `HTTP_${response.status}`,
797
804
  message: responseData?.message || text || response.statusText
@@ -1220,21 +1227,46 @@ function createAuthRoutes(config = {}) {
1220
1227
  }
1221
1228
  return registerResponse;
1222
1229
  }
1230
+ case "mfa/send-code": {
1231
+ const { pending_token, method } = body;
1232
+ if (!pending_token || !["email", "sms"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token and method required", 400);
1233
+ return successResponse(await sm.auth.sendMfaCode(pending_token, method, { clientContext }));
1234
+ }
1235
+ case "mfa/verify": {
1236
+ const { pending_token, code, method } = body;
1237
+ if (!pending_token || !code || !["totp", "email", "sms", "backup_code"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token, code, and valid method required", 400);
1238
+ const result = await sm.auth.completeMfa(pending_token, code, method, { clientContext });
1239
+ if (!result.session_token || !result.user) return errorResponse("MFA_FAILED", "Unable to complete sign-in", 400);
1240
+ 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);
1242
+ if (config.enableAccountSwitcher) {
1243
+ appendKnownAccountCookie(response.headers, {
1244
+ userId: result.user.id,
1245
+ email: result.user.email,
1246
+ fullName: result.user.full_name ?? void 0,
1247
+ avatarUrl: result.user.avatar_url ?? void 0,
1248
+ provider: "email",
1249
+ lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
1250
+ }, getKnownAccountsCookieRaw(request), cookieOptions, config.accountSwitcherPrivacy);
1251
+ }
1252
+ return response;
1253
+ }
1223
1254
  // ==================== Login ====================
1224
1255
  case "login": {
1225
- const { email, password, remember_me } = body;
1256
+ const { email, password, remember_me, device_fingerprint, challenge_token, challenge_code } = body;
1226
1257
  if (!email || !password) {
1227
1258
  return errorResponse("VALIDATION_ERROR", "Email and password required", 400);
1228
1259
  }
1229
1260
  let loginData;
1230
1261
  try {
1231
- loginData = await sm.auth.login({ email, password, remember_me }, { clientContext });
1262
+ loginData = await sm.auth.login({ email, password, remember_me, device_fingerprint, challenge_token, challenge_code }, { clientContext });
1232
1263
  } catch (err) {
1233
1264
  const apiErr = err instanceof ScaleMuleApiError ? err : null;
1234
1265
  const errorCode = apiErr?.code || "LOGIN_FAILED";
1235
- let status = 400;
1266
+ let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 202 : 400;
1267
+ if (errorCode === "CHALLENGE_RATE_LIMITED") status = 429;
1236
1268
  if (errorCode === "INVALID_CREDENTIALS" || errorCode === "UNAUTHORIZED") status = 401;
1237
- if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED", "MFA_REQUIRED"].includes(errorCode)) {
1269
+ if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED"].includes(errorCode)) {
1238
1270
  status = 403;
1239
1271
  }
1240
1272
  return errorResponse(
@@ -1313,7 +1345,7 @@ function createAuthRoutes(config = {}) {
1313
1345
  400
1314
1346
  );
1315
1347
  }
1316
- return successResponse({ message: "Password reset successful" });
1348
+ return clearSession({ message: "Password reset successful" }, cookieOptions);
1317
1349
  }
1318
1350
  // ==================== Verify Email ====================
1319
1351
  case "verify-email": {
@@ -1506,6 +1538,10 @@ function createAuthRoutes(config = {}) {
1506
1538
  return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
1507
1539
  }
1508
1540
  } catch (err) {
1541
+ if (path.startsWith("mfa/") && err instanceof ScaleMuleApiError) {
1542
+ const status = ["CHALLENGE_RATE_LIMITED", "MFA_RATE_LIMITED", "MFA_MAX_ATTEMPTS"].includes(err.code) ? 429 : 400;
1543
+ return errorResponse(err.code, err.message, status);
1544
+ }
1509
1545
  console.error("[ScaleMule Auth] Error:", err);
1510
1546
  return errorResponse("SERVER_ERROR", "Internal server error", 500);
1511
1547
  }
@@ -1,6 +1,6 @@
1
- import { S as ServerConfig } from '../webhook-handler-CVmBvPFN.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-CVmBvPFN.mjs';
3
- import { p as ClientContext, A as ApiError } from '../index-Bv1m_qQ8.mjs';
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';
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';
@@ -1,6 +1,6 @@
1
- import { S as ServerConfig } from '../webhook-handler-5ymVecTD.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-5ymVecTD.js';
3
- import { p as ClientContext, A as ApiError } from '../index-Bv1m_qQ8.js';
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';
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';
@@ -39,8 +39,9 @@ function validateIP(ip) {
39
39
  function extractClientContext(request) {
40
40
  const headers3 = request.headers;
41
41
  let ip;
42
+ ip = validateIP(headers3.get("x-real-ip"));
42
43
  const cfConnectingIp = headers3.get("cf-connecting-ip");
43
- if (cfConnectingIp) {
44
+ if (!ip && cfConnectingIp) {
44
45
  ip = validateIP(cfConnectingIp);
45
46
  }
46
47
  if (!ip) {
@@ -100,8 +101,9 @@ function extractClientContextFromReq(req) {
100
101
  return value;
101
102
  };
102
103
  let ip;
104
+ ip = validateIP(getHeader("x-real-ip"));
103
105
  const cfConnectingIp = getHeader("cf-connecting-ip");
104
- if (cfConnectingIp) {
106
+ if (!ip && cfConnectingIp) {
105
107
  ip = validateIP(cfConnectingIp);
106
108
  }
107
109
  if (!ip) {
@@ -227,6 +229,12 @@ var ScaleMuleServer = class {
227
229
  /**
228
230
  * Login user - returns session token (store in HTTP-only cookie)
229
231
  */
232
+ sendMfaCode: async (pending_token, method, options) => {
233
+ return this.request("POST", "/v1/auth/mfa/send-code", { body: { pending_token, method }, clientContext: options?.clientContext });
234
+ },
235
+ completeMfa: async (pending_token, code, method, options) => {
236
+ return this.request("POST", "/v1/auth/mfa/verify", { body: { pending_token, code, method }, clientContext: options?.clientContext });
237
+ },
230
238
  login: async (data, options) => {
231
239
  return this.request("POST", "/v1/auth/login", { body: data, clientContext: options?.clientContext });
232
240
  },
@@ -866,7 +874,7 @@ var ScaleMuleServer = class {
866
874
  responseData = text ? JSON.parse(text) : null;
867
875
  } catch {
868
876
  }
869
- if (!response.ok) {
877
+ if (!response.ok || responseData?.success === false) {
870
878
  const baseError = responseData?.error || {
871
879
  code: `HTTP_${response.status}`,
872
880
  message: responseData?.message || text || response.statusText
@@ -1392,21 +1400,46 @@ function createAuthRoutes(config = {}) {
1392
1400
  }
1393
1401
  return registerResponse;
1394
1402
  }
1403
+ case "mfa/send-code": {
1404
+ const { pending_token, method } = body;
1405
+ if (!pending_token || !["email", "sms"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token and method required", 400);
1406
+ return successResponse(await sm.auth.sendMfaCode(pending_token, method, { clientContext }));
1407
+ }
1408
+ case "mfa/verify": {
1409
+ const { pending_token, code, method } = body;
1410
+ if (!pending_token || !code || !["totp", "email", "sms", "backup_code"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token, code, and valid method required", 400);
1411
+ const result = await sm.auth.completeMfa(pending_token, code, method, { clientContext });
1412
+ if (!result.session_token || !result.user) return errorResponse("MFA_FAILED", "Unable to complete sign-in", 400);
1413
+ await config.onLogin?.({ id: result.user.id, email: result.user.email });
1414
+ const response = withSession(result, { user: result.user, sessionToken: result.session_token, userId: result.user.id }, cookieOptions);
1415
+ if (config.enableAccountSwitcher) {
1416
+ appendKnownAccountCookie(response.headers, {
1417
+ userId: result.user.id,
1418
+ email: result.user.email,
1419
+ fullName: result.user.full_name ?? void 0,
1420
+ avatarUrl: result.user.avatar_url ?? void 0,
1421
+ provider: "email",
1422
+ lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
1423
+ }, getKnownAccountsCookieRaw(request), cookieOptions, config.accountSwitcherPrivacy);
1424
+ }
1425
+ return response;
1426
+ }
1395
1427
  // ==================== Login ====================
1396
1428
  case "login": {
1397
- const { email, password, remember_me } = body;
1429
+ const { email, password, remember_me, device_fingerprint, challenge_token, challenge_code } = body;
1398
1430
  if (!email || !password) {
1399
1431
  return errorResponse("VALIDATION_ERROR", "Email and password required", 400);
1400
1432
  }
1401
1433
  let loginData;
1402
1434
  try {
1403
- loginData = await sm.auth.login({ email, password, remember_me }, { clientContext });
1435
+ loginData = await sm.auth.login({ email, password, remember_me, device_fingerprint, challenge_token, challenge_code }, { clientContext });
1404
1436
  } catch (err) {
1405
1437
  const apiErr = err instanceof ScaleMuleApiError ? err : null;
1406
1438
  const errorCode = apiErr?.code || "LOGIN_FAILED";
1407
- let status = 400;
1439
+ let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 202 : 400;
1440
+ if (errorCode === "CHALLENGE_RATE_LIMITED") status = 429;
1408
1441
  if (errorCode === "INVALID_CREDENTIALS" || errorCode === "UNAUTHORIZED") status = 401;
1409
- if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED", "MFA_REQUIRED"].includes(errorCode)) {
1442
+ if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED"].includes(errorCode)) {
1410
1443
  status = 403;
1411
1444
  }
1412
1445
  return errorResponse(
@@ -1485,7 +1518,7 @@ function createAuthRoutes(config = {}) {
1485
1518
  400
1486
1519
  );
1487
1520
  }
1488
- return successResponse({ message: "Password reset successful" });
1521
+ return clearSession({ message: "Password reset successful" }, cookieOptions);
1489
1522
  }
1490
1523
  // ==================== Verify Email ====================
1491
1524
  case "verify-email": {
@@ -1678,6 +1711,10 @@ function createAuthRoutes(config = {}) {
1678
1711
  return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
1679
1712
  }
1680
1713
  } catch (err) {
1714
+ if (path.startsWith("mfa/") && err instanceof ScaleMuleApiError) {
1715
+ const status = ["CHALLENGE_RATE_LIMITED", "MFA_RATE_LIMITED", "MFA_MAX_ATTEMPTS"].includes(err.code) ? 429 : 400;
1716
+ return errorResponse(err.code, err.message, status);
1717
+ }
1681
1718
  console.error("[ScaleMule Auth] Error:", err);
1682
1719
  return errorResponse("SERVER_ERROR", "Internal server error", 500);
1683
1720
  }