@scalemule/nextjs 0.1.50 → 0.1.52

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.
@@ -16,6 +16,34 @@ var ScaleMuleApiError = class extends Error {
16
16
  }
17
17
  };
18
18
 
19
+ // src/url-privacy.ts
20
+ function withoutAuthSecrets(value) {
21
+ if (!value) return value;
22
+ try {
23
+ const absolute = /^[a-z][a-z0-9+.-]*:/i.test(value);
24
+ const protocolRelative = value.startsWith("//");
25
+ const url = new URL(value, "https://relative.invalid");
26
+ if (!["http:", "https:"].includes(url.protocol)) return void 0;
27
+ let changed = false;
28
+ for (const name of [...url.searchParams.keys()]) {
29
+ if (/^(token|code|state|password|new_password|access_token|refresh_token|id_token|api_key|client_secret|challenge_token|challenge_code)$/i.test(name)) {
30
+ url.searchParams.delete(name);
31
+ changed = true;
32
+ }
33
+ }
34
+ if (url.hash) {
35
+ url.hash = "";
36
+ changed = true;
37
+ }
38
+ if (!changed) return value;
39
+ if (absolute) return url.toString();
40
+ if (protocolRelative) return url.toString().replace(/^https:/, "");
41
+ return value.split(/[?#]/, 1)[0] + url.search;
42
+ } catch {
43
+ return void 0;
44
+ }
45
+ }
46
+
19
47
  // src/server/context.ts
20
48
  function validateIP(ip) {
21
49
  if (!ip) return void 0;
@@ -32,8 +60,9 @@ function validateIP(ip) {
32
60
  function extractClientContext(request) {
33
61
  const headers2 = request.headers;
34
62
  let ip;
63
+ ip = validateIP(headers2.get("x-real-ip"));
35
64
  const cfConnectingIp = headers2.get("cf-connecting-ip");
36
- if (cfConnectingIp) {
65
+ if (!ip && cfConnectingIp) {
37
66
  ip = validateIP(cfConnectingIp);
38
67
  }
39
68
  if (!ip) {
@@ -73,7 +102,7 @@ function extractClientContext(request) {
73
102
  }
74
103
  const userAgent = headers2.get("user-agent") || void 0;
75
104
  const deviceFingerprint = headers2.get("x-device-fingerprint") || void 0;
76
- const referrer = headers2.get("referer") || void 0;
105
+ const referrer = withoutAuthSecrets(headers2.get("referer") || void 0);
77
106
  const anonymousId = headers2.get("x-anonymous-id") || void 0;
78
107
  return {
79
108
  ip,
@@ -152,6 +181,12 @@ var ScaleMuleServer = class {
152
181
  /**
153
182
  * Login user - returns session token (store in HTTP-only cookie)
154
183
  */
184
+ sendMfaCode: async (pending_token, method, options) => {
185
+ return this.request("POST", "/v1/auth/mfa/send-code", { body: { pending_token, method }, clientContext: options?.clientContext });
186
+ },
187
+ completeMfa: async (pending_token, code, method, options) => {
188
+ return this.request("POST", "/v1/auth/mfa/verify", { body: { pending_token, code, method }, clientContext: options?.clientContext });
189
+ },
155
190
  login: async (data, options) => {
156
191
  return this.request("POST", "/v1/auth/login", { body: data, clientContext: options?.clientContext });
157
192
  },
@@ -791,7 +826,7 @@ var ScaleMuleServer = class {
791
826
  responseData = text ? JSON.parse(text) : null;
792
827
  } catch {
793
828
  }
794
- if (!response.ok) {
829
+ if (!response.ok || responseData?.success === false) {
795
830
  const baseError = responseData?.error || {
796
831
  code: `HTTP_${response.status}`,
797
832
  message: responseData?.message || text || response.statusText
@@ -1220,21 +1255,46 @@ function createAuthRoutes(config = {}) {
1220
1255
  }
1221
1256
  return registerResponse;
1222
1257
  }
1258
+ case "mfa/send-code": {
1259
+ const { pending_token, method } = body;
1260
+ if (!pending_token || !["email", "sms"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token and method required", 400);
1261
+ return successResponse(await sm.auth.sendMfaCode(pending_token, method, { clientContext }));
1262
+ }
1263
+ case "mfa/verify": {
1264
+ const { pending_token, code, method } = body;
1265
+ if (!pending_token || !code || !["totp", "email", "sms", "backup_code"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token, code, and valid method required", 400);
1266
+ const result = await sm.auth.completeMfa(pending_token, code, method, { clientContext });
1267
+ if (!result.session_token || !result.user) return errorResponse("MFA_FAILED", "Unable to complete sign-in", 400);
1268
+ 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);
1270
+ if (config.enableAccountSwitcher) {
1271
+ appendKnownAccountCookie(response.headers, {
1272
+ userId: result.user.id,
1273
+ email: result.user.email,
1274
+ fullName: result.user.full_name ?? void 0,
1275
+ avatarUrl: result.user.avatar_url ?? void 0,
1276
+ provider: "email",
1277
+ lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
1278
+ }, getKnownAccountsCookieRaw(request), cookieOptions, config.accountSwitcherPrivacy);
1279
+ }
1280
+ return response;
1281
+ }
1223
1282
  // ==================== Login ====================
1224
1283
  case "login": {
1225
- const { email, password, remember_me } = body;
1284
+ const { email, password, remember_me, device_fingerprint, challenge_token, challenge_code } = body;
1226
1285
  if (!email || !password) {
1227
1286
  return errorResponse("VALIDATION_ERROR", "Email and password required", 400);
1228
1287
  }
1229
1288
  let loginData;
1230
1289
  try {
1231
- loginData = await sm.auth.login({ email, password, remember_me }, { clientContext });
1290
+ loginData = await sm.auth.login({ email, password, remember_me, device_fingerprint, challenge_token, challenge_code }, { clientContext });
1232
1291
  } catch (err) {
1233
1292
  const apiErr = err instanceof ScaleMuleApiError ? err : null;
1234
1293
  const errorCode = apiErr?.code || "LOGIN_FAILED";
1235
- let status = 400;
1294
+ let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 202 : 400;
1295
+ if (errorCode === "CHALLENGE_RATE_LIMITED") status = 429;
1236
1296
  if (errorCode === "INVALID_CREDENTIALS" || errorCode === "UNAUTHORIZED") status = 401;
1237
- if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED", "MFA_REQUIRED"].includes(errorCode)) {
1297
+ if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED"].includes(errorCode)) {
1238
1298
  status = 403;
1239
1299
  }
1240
1300
  return errorResponse(
@@ -1313,7 +1373,7 @@ function createAuthRoutes(config = {}) {
1313
1373
  400
1314
1374
  );
1315
1375
  }
1316
- return successResponse({ message: "Password reset successful" });
1376
+ return clearSession({ message: "Password reset successful" }, cookieOptions);
1317
1377
  }
1318
1378
  // ==================== Verify Email ====================
1319
1379
  case "verify-email": {
@@ -1506,6 +1566,10 @@ function createAuthRoutes(config = {}) {
1506
1566
  return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
1507
1567
  }
1508
1568
  } catch (err) {
1569
+ if (path.startsWith("mfa/") && err instanceof ScaleMuleApiError) {
1570
+ const status = ["CHALLENGE_RATE_LIMITED", "MFA_RATE_LIMITED", "MFA_MAX_ATTEMPTS"].includes(err.code) ? 429 : 400;
1571
+ return errorResponse(err.code, err.message, status);
1572
+ }
1509
1573
  console.error("[ScaleMule Auth] Error:", err);
1510
1574
  return errorResponse("SERVER_ERROR", "Internal server error", 500);
1511
1575
  }
@@ -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';
@@ -23,6 +23,34 @@ var ScaleMuleApiError = class extends Error {
23
23
  }
24
24
  };
25
25
 
26
+ // src/url-privacy.ts
27
+ function withoutAuthSecrets(value) {
28
+ if (!value) return value;
29
+ try {
30
+ const absolute = /^[a-z][a-z0-9+.-]*:/i.test(value);
31
+ const protocolRelative = value.startsWith("//");
32
+ const url = new URL(value, "https://relative.invalid");
33
+ if (!["http:", "https:"].includes(url.protocol)) return void 0;
34
+ let changed = false;
35
+ for (const name of [...url.searchParams.keys()]) {
36
+ if (/^(token|code|state|password|new_password|access_token|refresh_token|id_token|api_key|client_secret|challenge_token|challenge_code)$/i.test(name)) {
37
+ url.searchParams.delete(name);
38
+ changed = true;
39
+ }
40
+ }
41
+ if (url.hash) {
42
+ url.hash = "";
43
+ changed = true;
44
+ }
45
+ if (!changed) return value;
46
+ if (absolute) return url.toString();
47
+ if (protocolRelative) return url.toString().replace(/^https:/, "");
48
+ return value.split(/[?#]/, 1)[0] + url.search;
49
+ } catch {
50
+ return void 0;
51
+ }
52
+ }
53
+
26
54
  // src/server/context.ts
27
55
  function validateIP(ip) {
28
56
  if (!ip) return void 0;
@@ -39,8 +67,9 @@ function validateIP(ip) {
39
67
  function extractClientContext(request) {
40
68
  const headers3 = request.headers;
41
69
  let ip;
70
+ ip = validateIP(headers3.get("x-real-ip"));
42
71
  const cfConnectingIp = headers3.get("cf-connecting-ip");
43
- if (cfConnectingIp) {
72
+ if (!ip && cfConnectingIp) {
44
73
  ip = validateIP(cfConnectingIp);
45
74
  }
46
75
  if (!ip) {
@@ -80,7 +109,7 @@ function extractClientContext(request) {
80
109
  }
81
110
  const userAgent = headers3.get("user-agent") || void 0;
82
111
  const deviceFingerprint = headers3.get("x-device-fingerprint") || void 0;
83
- const referrer = headers3.get("referer") || void 0;
112
+ const referrer = withoutAuthSecrets(headers3.get("referer") || void 0);
84
113
  const anonymousId = headers3.get("x-anonymous-id") || void 0;
85
114
  return {
86
115
  ip,
@@ -100,8 +129,9 @@ function extractClientContextFromReq(req) {
100
129
  return value;
101
130
  };
102
131
  let ip;
132
+ ip = validateIP(getHeader("x-real-ip"));
103
133
  const cfConnectingIp = getHeader("cf-connecting-ip");
104
- if (cfConnectingIp) {
134
+ if (!ip && cfConnectingIp) {
105
135
  ip = validateIP(cfConnectingIp);
106
136
  }
107
137
  if (!ip) {
@@ -141,7 +171,7 @@ function extractClientContextFromReq(req) {
141
171
  }
142
172
  const userAgent = getHeader("user-agent");
143
173
  const deviceFingerprint = getHeader("x-device-fingerprint");
144
- const referrer = getHeader("referer");
174
+ const referrer = withoutAuthSecrets(getHeader("referer"));
145
175
  const anonymousId = getHeader("x-anonymous-id");
146
176
  return {
147
177
  ip,
@@ -227,6 +257,12 @@ var ScaleMuleServer = class {
227
257
  /**
228
258
  * Login user - returns session token (store in HTTP-only cookie)
229
259
  */
260
+ sendMfaCode: async (pending_token, method, options) => {
261
+ return this.request("POST", "/v1/auth/mfa/send-code", { body: { pending_token, method }, clientContext: options?.clientContext });
262
+ },
263
+ completeMfa: async (pending_token, code, method, options) => {
264
+ return this.request("POST", "/v1/auth/mfa/verify", { body: { pending_token, code, method }, clientContext: options?.clientContext });
265
+ },
230
266
  login: async (data, options) => {
231
267
  return this.request("POST", "/v1/auth/login", { body: data, clientContext: options?.clientContext });
232
268
  },
@@ -866,7 +902,7 @@ var ScaleMuleServer = class {
866
902
  responseData = text ? JSON.parse(text) : null;
867
903
  } catch {
868
904
  }
869
- if (!response.ok) {
905
+ if (!response.ok || responseData?.success === false) {
870
906
  const baseError = responseData?.error || {
871
907
  code: `HTTP_${response.status}`,
872
908
  message: responseData?.message || text || response.statusText
@@ -1392,21 +1428,46 @@ function createAuthRoutes(config = {}) {
1392
1428
  }
1393
1429
  return registerResponse;
1394
1430
  }
1431
+ case "mfa/send-code": {
1432
+ const { pending_token, method } = body;
1433
+ if (!pending_token || !["email", "sms"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token and method required", 400);
1434
+ return successResponse(await sm.auth.sendMfaCode(pending_token, method, { clientContext }));
1435
+ }
1436
+ case "mfa/verify": {
1437
+ const { pending_token, code, method } = body;
1438
+ if (!pending_token || !code || !["totp", "email", "sms", "backup_code"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token, code, and valid method required", 400);
1439
+ const result = await sm.auth.completeMfa(pending_token, code, method, { clientContext });
1440
+ if (!result.session_token || !result.user) return errorResponse("MFA_FAILED", "Unable to complete sign-in", 400);
1441
+ await config.onLogin?.({ id: result.user.id, email: result.user.email });
1442
+ const response = withSession(result, { user: result.user, sessionToken: result.session_token, userId: result.user.id }, cookieOptions);
1443
+ if (config.enableAccountSwitcher) {
1444
+ appendKnownAccountCookie(response.headers, {
1445
+ userId: result.user.id,
1446
+ email: result.user.email,
1447
+ fullName: result.user.full_name ?? void 0,
1448
+ avatarUrl: result.user.avatar_url ?? void 0,
1449
+ provider: "email",
1450
+ lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
1451
+ }, getKnownAccountsCookieRaw(request), cookieOptions, config.accountSwitcherPrivacy);
1452
+ }
1453
+ return response;
1454
+ }
1395
1455
  // ==================== Login ====================
1396
1456
  case "login": {
1397
- const { email, password, remember_me } = body;
1457
+ const { email, password, remember_me, device_fingerprint, challenge_token, challenge_code } = body;
1398
1458
  if (!email || !password) {
1399
1459
  return errorResponse("VALIDATION_ERROR", "Email and password required", 400);
1400
1460
  }
1401
1461
  let loginData;
1402
1462
  try {
1403
- loginData = await sm.auth.login({ email, password, remember_me }, { clientContext });
1463
+ loginData = await sm.auth.login({ email, password, remember_me, device_fingerprint, challenge_token, challenge_code }, { clientContext });
1404
1464
  } catch (err) {
1405
1465
  const apiErr = err instanceof ScaleMuleApiError ? err : null;
1406
1466
  const errorCode = apiErr?.code || "LOGIN_FAILED";
1407
- let status = 400;
1467
+ let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 202 : 400;
1468
+ if (errorCode === "CHALLENGE_RATE_LIMITED") status = 429;
1408
1469
  if (errorCode === "INVALID_CREDENTIALS" || errorCode === "UNAUTHORIZED") status = 401;
1409
- if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED", "MFA_REQUIRED"].includes(errorCode)) {
1470
+ if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED"].includes(errorCode)) {
1410
1471
  status = 403;
1411
1472
  }
1412
1473
  return errorResponse(
@@ -1485,7 +1546,7 @@ function createAuthRoutes(config = {}) {
1485
1546
  400
1486
1547
  );
1487
1548
  }
1488
- return successResponse({ message: "Password reset successful" });
1549
+ return clearSession({ message: "Password reset successful" }, cookieOptions);
1489
1550
  }
1490
1551
  // ==================== Verify Email ====================
1491
1552
  case "verify-email": {
@@ -1678,6 +1739,10 @@ function createAuthRoutes(config = {}) {
1678
1739
  return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
1679
1740
  }
1680
1741
  } catch (err) {
1742
+ if (path.startsWith("mfa/") && err instanceof ScaleMuleApiError) {
1743
+ const status = ["CHALLENGE_RATE_LIMITED", "MFA_RATE_LIMITED", "MFA_MAX_ATTEMPTS"].includes(err.code) ? 429 : 400;
1744
+ return errorResponse(err.code, err.message, status);
1745
+ }
1681
1746
  console.error("[ScaleMule Auth] Error:", err);
1682
1747
  return errorResponse("SERVER_ERROR", "Internal server error", 500);
1683
1748
  }
@@ -21,6 +21,34 @@ var ScaleMuleApiError = class extends Error {
21
21
  }
22
22
  };
23
23
 
24
+ // src/url-privacy.ts
25
+ function withoutAuthSecrets(value) {
26
+ if (!value) return value;
27
+ try {
28
+ const absolute = /^[a-z][a-z0-9+.-]*:/i.test(value);
29
+ const protocolRelative = value.startsWith("//");
30
+ const url = new URL(value, "https://relative.invalid");
31
+ if (!["http:", "https:"].includes(url.protocol)) return void 0;
32
+ let changed = false;
33
+ for (const name of [...url.searchParams.keys()]) {
34
+ if (/^(token|code|state|password|new_password|access_token|refresh_token|id_token|api_key|client_secret|challenge_token|challenge_code)$/i.test(name)) {
35
+ url.searchParams.delete(name);
36
+ changed = true;
37
+ }
38
+ }
39
+ if (url.hash) {
40
+ url.hash = "";
41
+ changed = true;
42
+ }
43
+ if (!changed) return value;
44
+ if (absolute) return url.toString();
45
+ if (protocolRelative) return url.toString().replace(/^https:/, "");
46
+ return value.split(/[?#]/, 1)[0] + url.search;
47
+ } catch {
48
+ return void 0;
49
+ }
50
+ }
51
+
24
52
  // src/server/context.ts
25
53
  function validateIP(ip) {
26
54
  if (!ip) return void 0;
@@ -37,8 +65,9 @@ function validateIP(ip) {
37
65
  function extractClientContext(request) {
38
66
  const headers3 = request.headers;
39
67
  let ip;
68
+ ip = validateIP(headers3.get("x-real-ip"));
40
69
  const cfConnectingIp = headers3.get("cf-connecting-ip");
41
- if (cfConnectingIp) {
70
+ if (!ip && cfConnectingIp) {
42
71
  ip = validateIP(cfConnectingIp);
43
72
  }
44
73
  if (!ip) {
@@ -78,7 +107,7 @@ function extractClientContext(request) {
78
107
  }
79
108
  const userAgent = headers3.get("user-agent") || void 0;
80
109
  const deviceFingerprint = headers3.get("x-device-fingerprint") || void 0;
81
- const referrer = headers3.get("referer") || void 0;
110
+ const referrer = withoutAuthSecrets(headers3.get("referer") || void 0);
82
111
  const anonymousId = headers3.get("x-anonymous-id") || void 0;
83
112
  return {
84
113
  ip,
@@ -98,8 +127,9 @@ function extractClientContextFromReq(req) {
98
127
  return value;
99
128
  };
100
129
  let ip;
130
+ ip = validateIP(getHeader("x-real-ip"));
101
131
  const cfConnectingIp = getHeader("cf-connecting-ip");
102
- if (cfConnectingIp) {
132
+ if (!ip && cfConnectingIp) {
103
133
  ip = validateIP(cfConnectingIp);
104
134
  }
105
135
  if (!ip) {
@@ -139,7 +169,7 @@ function extractClientContextFromReq(req) {
139
169
  }
140
170
  const userAgent = getHeader("user-agent");
141
171
  const deviceFingerprint = getHeader("x-device-fingerprint");
142
- const referrer = getHeader("referer");
172
+ const referrer = withoutAuthSecrets(getHeader("referer"));
143
173
  const anonymousId = getHeader("x-anonymous-id");
144
174
  return {
145
175
  ip,
@@ -225,6 +255,12 @@ var ScaleMuleServer = class {
225
255
  /**
226
256
  * Login user - returns session token (store in HTTP-only cookie)
227
257
  */
258
+ sendMfaCode: async (pending_token, method, options) => {
259
+ return this.request("POST", "/v1/auth/mfa/send-code", { body: { pending_token, method }, clientContext: options?.clientContext });
260
+ },
261
+ completeMfa: async (pending_token, code, method, options) => {
262
+ return this.request("POST", "/v1/auth/mfa/verify", { body: { pending_token, code, method }, clientContext: options?.clientContext });
263
+ },
228
264
  login: async (data, options) => {
229
265
  return this.request("POST", "/v1/auth/login", { body: data, clientContext: options?.clientContext });
230
266
  },
@@ -864,7 +900,7 @@ var ScaleMuleServer = class {
864
900
  responseData = text ? JSON.parse(text) : null;
865
901
  } catch {
866
902
  }
867
- if (!response.ok) {
903
+ if (!response.ok || responseData?.success === false) {
868
904
  const baseError = responseData?.error || {
869
905
  code: `HTTP_${response.status}`,
870
906
  message: responseData?.message || text || response.statusText
@@ -1390,21 +1426,46 @@ function createAuthRoutes(config = {}) {
1390
1426
  }
1391
1427
  return registerResponse;
1392
1428
  }
1429
+ case "mfa/send-code": {
1430
+ const { pending_token, method } = body;
1431
+ if (!pending_token || !["email", "sms"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token and method required", 400);
1432
+ return successResponse(await sm.auth.sendMfaCode(pending_token, method, { clientContext }));
1433
+ }
1434
+ case "mfa/verify": {
1435
+ const { pending_token, code, method } = body;
1436
+ if (!pending_token || !code || !["totp", "email", "sms", "backup_code"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token, code, and valid method required", 400);
1437
+ const result = await sm.auth.completeMfa(pending_token, code, method, { clientContext });
1438
+ if (!result.session_token || !result.user) return errorResponse("MFA_FAILED", "Unable to complete sign-in", 400);
1439
+ await config.onLogin?.({ id: result.user.id, email: result.user.email });
1440
+ const response = withSession(result, { user: result.user, sessionToken: result.session_token, userId: result.user.id }, cookieOptions);
1441
+ if (config.enableAccountSwitcher) {
1442
+ appendKnownAccountCookie(response.headers, {
1443
+ userId: result.user.id,
1444
+ email: result.user.email,
1445
+ fullName: result.user.full_name ?? void 0,
1446
+ avatarUrl: result.user.avatar_url ?? void 0,
1447
+ provider: "email",
1448
+ lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
1449
+ }, getKnownAccountsCookieRaw(request), cookieOptions, config.accountSwitcherPrivacy);
1450
+ }
1451
+ return response;
1452
+ }
1393
1453
  // ==================== Login ====================
1394
1454
  case "login": {
1395
- const { email, password, remember_me } = body;
1455
+ const { email, password, remember_me, device_fingerprint, challenge_token, challenge_code } = body;
1396
1456
  if (!email || !password) {
1397
1457
  return errorResponse("VALIDATION_ERROR", "Email and password required", 400);
1398
1458
  }
1399
1459
  let loginData;
1400
1460
  try {
1401
- loginData = await sm.auth.login({ email, password, remember_me }, { clientContext });
1461
+ loginData = await sm.auth.login({ email, password, remember_me, device_fingerprint, challenge_token, challenge_code }, { clientContext });
1402
1462
  } catch (err) {
1403
1463
  const apiErr = err instanceof ScaleMuleApiError ? err : null;
1404
1464
  const errorCode = apiErr?.code || "LOGIN_FAILED";
1405
- let status = 400;
1465
+ let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 202 : 400;
1466
+ if (errorCode === "CHALLENGE_RATE_LIMITED") status = 429;
1406
1467
  if (errorCode === "INVALID_CREDENTIALS" || errorCode === "UNAUTHORIZED") status = 401;
1407
- if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED", "MFA_REQUIRED"].includes(errorCode)) {
1468
+ if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED"].includes(errorCode)) {
1408
1469
  status = 403;
1409
1470
  }
1410
1471
  return errorResponse(
@@ -1483,7 +1544,7 @@ function createAuthRoutes(config = {}) {
1483
1544
  400
1484
1545
  );
1485
1546
  }
1486
- return successResponse({ message: "Password reset successful" });
1547
+ return clearSession({ message: "Password reset successful" }, cookieOptions);
1487
1548
  }
1488
1549
  // ==================== Verify Email ====================
1489
1550
  case "verify-email": {
@@ -1676,6 +1737,10 @@ function createAuthRoutes(config = {}) {
1676
1737
  return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
1677
1738
  }
1678
1739
  } catch (err) {
1740
+ if (path.startsWith("mfa/") && err instanceof ScaleMuleApiError) {
1741
+ const status = ["CHALLENGE_RATE_LIMITED", "MFA_RATE_LIMITED", "MFA_MAX_ATTEMPTS"].includes(err.code) ? 429 : 400;
1742
+ return errorResponse(err.code, err.message, status);
1743
+ }
1679
1744
  console.error("[ScaleMule Auth] Error:", err);
1680
1745
  return errorResponse("SERVER_ERROR", "Internal server error", 500);
1681
1746
  }
@@ -1,3 +1,3 @@
1
- export { g as createWebhookHandler } from '../webhook-handler-CVmBvPFN.mjs';
1
+ export { g as createWebhookHandler } from '../webhook-handler-DKt6H8FB.mjs';
2
2
  import '@scalemule/money';
3
- import '../index-Bv1m_qQ8.mjs';
3
+ import '../index-BQgmT53x.mjs';
@@ -1,3 +1,3 @@
1
- export { g as createWebhookHandler } from '../webhook-handler-5ymVecTD.js';
1
+ export { g as createWebhookHandler } from '../webhook-handler-44RRJH-r.js';
2
2
  import '@scalemule/money';
3
- import '../index-Bv1m_qQ8.js';
3
+ import '../index-BQgmT53x.js';
@@ -1,6 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { ReactNode } from 'react';
3
- import { U as User, A as ApiError, a9 as StorageFile } from './index-Bv1m_qQ8.mjs';
3
+ import { U as User, A as ApiError, a9 as StorageFile } from './index-BQgmT53x.mjs';
4
4
 
5
5
  interface MockUserOptions {
6
6
  id?: string;
package/dist/testing.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { ReactNode } from 'react';
3
- import { U as User, A as ApiError, a9 as StorageFile } from './index-Bv1m_qQ8.js';
3
+ import { U as User, A as ApiError, a9 as StorageFile } from './index-BQgmT53x.js';
4
4
 
5
5
  interface MockUserOptions {
6
6
  id?: string;
@@ -1,5 +1,5 @@
1
1
  import { MoneyClient } from '@scalemule/money';
2
- import { A as ApiError, $ as RegisterRequest, p as ClientContext, U as User, v as LoginRequest, L as LoginResponse, c as ListFilesParams, t as ListFilesResponse, a9 as StorageFile, af as UploadResponse } from './index-Bv1m_qQ8.js';
2
+ import { A as ApiError, $ as RegisterRequest, p as ClientContext, U as User, L as LoginResponse, v as LoginRequest, c as ListFilesParams, t as ListFilesResponse, a9 as StorageFile, af as UploadResponse } from './index-BQgmT53x.js';
3
3
 
4
4
  /**
5
5
  * Server-Side ScaleMule Client
@@ -58,6 +58,14 @@ declare class ScaleMuleServer {
58
58
  /**
59
59
  * Login user - returns session token (store in HTTP-only cookie)
60
60
  */
61
+ sendMfaCode: (pending_token: string, method: string, options?: {
62
+ clientContext?: ClientContext;
63
+ }) => Promise<{
64
+ success: boolean;
65
+ }>;
66
+ completeMfa: (pending_token: string, code: string, method: string, options?: {
67
+ clientContext?: ClientContext;
68
+ }) => Promise<LoginResponse>;
61
69
  login: (data: LoginRequest, options?: {
62
70
  clientContext?: ClientContext;
63
71
  }) => Promise<LoginResponse>;
@@ -1,5 +1,5 @@
1
1
  import { MoneyClient } from '@scalemule/money';
2
- import { A as ApiError, $ as RegisterRequest, p as ClientContext, U as User, v as LoginRequest, L as LoginResponse, c as ListFilesParams, t as ListFilesResponse, a9 as StorageFile, af as UploadResponse } from './index-Bv1m_qQ8.mjs';
2
+ import { A as ApiError, $ as RegisterRequest, p as ClientContext, U as User, L as LoginResponse, v as LoginRequest, c as ListFilesParams, t as ListFilesResponse, a9 as StorageFile, af as UploadResponse } from './index-BQgmT53x.mjs';
3
3
 
4
4
  /**
5
5
  * Server-Side ScaleMule Client
@@ -58,6 +58,14 @@ declare class ScaleMuleServer {
58
58
  /**
59
59
  * Login user - returns session token (store in HTTP-only cookie)
60
60
  */
61
+ sendMfaCode: (pending_token: string, method: string, options?: {
62
+ clientContext?: ClientContext;
63
+ }) => Promise<{
64
+ success: boolean;
65
+ }>;
66
+ completeMfa: (pending_token: string, code: string, method: string, options?: {
67
+ clientContext?: ClientContext;
68
+ }) => Promise<LoginResponse>;
61
69
  login: (data: LoginRequest, options?: {
62
70
  clientContext?: ClientContext;
63
71
  }) => Promise<LoginResponse>;
@@ -11,7 +11,7 @@ React at runtime. Existing `AudioPlayer` and `NarrationPlayer` APIs are unchange
11
11
  | Client-side navigation under the same provider | The same audio element continues playing. |
12
12
  | Leaving the narrated article | Highlighting is destroyed; audio continues. |
13
13
  | Returning to that article | Highlighting resumes at the current clock if enabled. |
14
- | Moving the reader tab to another participating domain | A previously opened network player window keeps playing. The destination bar reconnects. |
14
+ | Following a network link in the original reader tab to another participating domain | A previously opened network player window keeps playing. The destination bar reconnects. |
15
15
  | Full navigation/reload without a network window | The old audio stops. An optional checkpoint restores the queue and position paused. |
16
16
  | Closing the network window | The reader restores the latest reported queue and position paused, with a Play prompt. |
17
17
  | Closing the reader tab | The network window can continue independently. |
@@ -24,8 +24,11 @@ policy. Once playing, navigation of its original reader tab does not replace its
24
24
  audio element. Browser/OS suspension can still interrupt media, especially on
25
25
  mobile. Test supported browsers before promising uninterrupted listening.
26
26
 
27
- This implementation reconnects the **original reader tab** across navigation.
28
- It does not discover unrelated tabs or synchronize devices. COOP headers that
27
+ This implementation reconnects the **original reader tab** when readers follow
28
+ links between participating sites. Direct address-bar or browser-initiated
29
+ cross-site navigation can sever the window relationship: audio continues in the
30
+ player window, but the destination bar may not reconnect. Use the player window's
31
+ controls in that case. It does not discover unrelated tabs or synchronize devices. COOP headers that
29
32
  sever `window.opener`, sandbox restrictions and popup blockers can prevent the
30
33
  connection. Failed initial connections preserve local playback and show a notice.
31
34
  An unresponsive remote player never triggers automatic local playback, which
@@ -205,8 +208,10 @@ The automated suite covers article unmounts, highlighting cleanup/return, queue
205
208
  advancement, publication identity, stale/aborted requests, signed URL refresh,
206
209
  autoplay denial, bounded recovery, blocked popups, exact origin/source checks,
207
210
  remote reconnect and host closure. Also test real media in supported browsers:
208
- start in the reader, open the network window, navigate the original tab to another
209
- allowed origin, control playback from the destination, and close the host.
211
+ start in the reader, open the network window, follow an actual network link in
212
+ the original tab to another allowed origin, control playback from the destination,
213
+ and close the host. Browser automation that changes the address directly does not
214
+ exercise the same window relationship as clicking a site link.
210
215
  Verify ad consent and publication authorization in the actual applications.
211
216
  Release the SDK, integrate layouts/routes/resolvers in the participating sites,
212
217
  then deploy through their existing release process. These SDK changes alone do
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scalemule/nextjs",
3
- "version": "0.1.50",
3
+ "version": "0.1.52",
4
4
  "description": "ScaleMule SDK for Next.js applications - authentication, storage, and user management",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -68,7 +68,7 @@
68
68
  "dependencies": {
69
69
  "@scalemule/ledvery": "^0.0.1",
70
70
  "@scalemule/money": "^0.0.1",
71
- "@scalemule/sdk": "^0.0.64"
71
+ "@scalemule/sdk": "^0.0.68"
72
72
  },
73
73
  "peerDependencies": {
74
74
  "next": ">=14.0.0",