@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.
package/README.md CHANGED
@@ -40,6 +40,35 @@ API keys never reach the browser. Session tokens are HTTP-only cookies.
40
40
 
41
41
  Need the cookie/header lifecycle or the proxy-vs-direct decision tree? See [`docs/AUTH_PROXY_PATTERN.md`](./docs/AUTH_PROXY_PATTERN.md).
42
42
 
43
+ ## Adaptive sign-in and password recovery
44
+
45
+ From 0.1.51, `useAuth().login()` handles email security challenges and enrolled MFA
46
+ through the provider's shared verification dialog. Existing login forms need no
47
+ challenge implementation. A session cookie is set only after verification succeeds.
48
+ Codes can be retried or resent; users can cancel or follow the password recovery link.
49
+
50
+ Set `passwordRecoveryUrl` on `ScaleMuleProvider` if your forgot-password page is not
51
+ `/auth/forgot-password`. For custom UI, pass an async `onSecurityChallenge` callback
52
+ that returns the entered code, `"resend"`, or `null` to cancel.
53
+
54
+ Before enabling `adaptive_email_challenges_enabled` in the application's auth settings,
55
+ deploy this SDK version to every login client and verify email delivery. The setting is
56
+ server-controlled; older clients default to observation of soft risk signals. Existing
57
+ account restrictions, abuse limits, and required MFA policies continue to apply.
58
+ Required MFA enrollment for users without a configured factor is a separate flow.
59
+
60
+ Configure the application's `public_auth_base_url` to its own auth pages, for example
61
+ `https://yourdomain.com/auth`. Configure a verified sending domain separately in
62
+ communication settings, for example `noreply@email.yourdomain.com`. The sending domain
63
+ does not determine where recovery links land. Publish SPF, DKIM, and DMARC records and
64
+ verify delivery before enabling the domain.
65
+
66
+ Your public `/auth/reset-password` page calls `useAuth().resetPassword(token, newPassword)`. Keep this page accessible even when an old session cookie exists;
67
+ set `Referrer-Policy: no-referrer` and `Cache-Control: no-store`. After success the SDK
68
+ clears the browser session and removes the reset token from the URL. The backend
69
+ invalidates other sessions and grants one subsequent password login relief from soft
70
+ risk checks for 30 minutes; it does not bypass enrolled MFA or account suspension.
71
+
43
72
  ## Environment Variables
44
73
 
45
74
  ```bash
package/dist/client.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { a8 as StorageAdapter, A as ApiError } from './index-Bv1m_qQ8.mjs';
1
+ import { a8 as StorageAdapter, A as ApiError } from './index-BQgmT53x.mjs';
2
2
 
3
3
  /**
4
4
  * ScaleMule API Client
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a8 as StorageAdapter, A as ApiError } from './index-Bv1m_qQ8.js';
1
+ import { a8 as StorageAdapter, A as ApiError } from './index-BQgmT53x.js';
2
2
 
3
3
  /**
4
4
  * ScaleMule API Client
package/dist/client.js CHANGED
@@ -611,7 +611,7 @@ var ScaleMuleClient = class {
611
611
  responseData = text ? JSON.parse(text) : null;
612
612
  } catch {
613
613
  }
614
- if (!response.ok) {
614
+ if (!response.ok || responseData?.success === false) {
615
615
  const rawError = responseData?.error;
616
616
  const baseError = rawError && typeof rawError === "object" ? rawError : { code: `HTTP_${response.status}`, message: typeof rawError === "string" ? rawError : responseData?.message || text || response.statusText };
617
617
  const error = withErrorContext(baseError, responseData, response.headers);
@@ -650,7 +650,7 @@ var ScaleMuleClient = class {
650
650
  continue;
651
651
  }
652
652
  if (this.debug) {
653
- console.error("[ScaleMule] Request failed:", error);
653
+ console.error("[ScaleMule] Request failed:", ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(error.code) ? error.code : error);
654
654
  }
655
655
  throw new ScaleMuleApiError(error);
656
656
  }
package/dist/client.mjs CHANGED
@@ -609,7 +609,7 @@ var ScaleMuleClient = class {
609
609
  responseData = text ? JSON.parse(text) : null;
610
610
  } catch {
611
611
  }
612
- if (!response.ok) {
612
+ if (!response.ok || responseData?.success === false) {
613
613
  const rawError = responseData?.error;
614
614
  const baseError = rawError && typeof rawError === "object" ? rawError : { code: `HTTP_${response.status}`, message: typeof rawError === "string" ? rawError : responseData?.message || text || response.statusText };
615
615
  const error = withErrorContext(baseError, responseData, response.headers);
@@ -648,7 +648,7 @@ var ScaleMuleClient = class {
648
648
  continue;
649
649
  }
650
650
  if (this.debug) {
651
- console.error("[ScaleMule] Request failed:", error);
651
+ console.error("[ScaleMule] Request failed:", ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(error.code) ? error.code : error);
652
652
  }
653
653
  throw new ScaleMuleApiError(error);
654
654
  }
@@ -173,6 +173,8 @@ interface RegisterRequest {
173
173
  phone?: string;
174
174
  }
175
175
  interface LoginRequest {
176
+ challenge_token?: string;
177
+ challenge_code?: string;
176
178
  email: string;
177
179
  password: string;
178
180
  remember_me?: boolean;
@@ -173,6 +173,8 @@ interface RegisterRequest {
173
173
  phone?: string;
174
174
  }
175
175
  interface LoginRequest {
176
+ challenge_token?: string;
177
+ challenge_code?: string;
176
178
  email: string;
177
179
  password: string;
178
180
  remember_me?: boolean;
package/dist/index.d.mts CHANGED
@@ -6,8 +6,8 @@ import { MoneyClient } from '@scalemule/money';
6
6
  export { MoneyClient, MoneyClientConfig, createMoneyClient } from '@scalemule/money';
7
7
  import { ScaleMuleClient } from './client.mjs';
8
8
  export { ClientConfig, RequestOptions, createClient } from './client.mjs';
9
- import { S as ScaleMuleConfig, U as User, L as LoginResponse, A as ApiError$1, a as UseAuthReturn, b as UseBillingReturn, c as ListFilesParams, d as UseContentReturn, e as UseUserReturn, f as UseAnalyticsOptions, g as UseAnalyticsReturn } from './index-Bv1m_qQ8.mjs';
10
- export { h as AccountBalance, i as AnalyticsEvent, j as ApiResponse, B as BatchTrackRequest, k as BillingPayment, l as BillingPayout, m as BillingRefund, n as BillingTransaction, C as ChangeEmailRequest, o as ChangePasswordRequest, p as ClientContext, q as ConnectedAccount, D as DeviceFingerprint, r as DeviceInfo, E as EnhancedAnalyticsEvent, F as ForgotPasswordRequest, K as KnownAccountInfo, s as LinkedAccount, t as ListFilesResponse, u as LoginDeviceInfo, v as LoginRequest, w as LoginResponseWithMFA, x as LoginRiskInfo, M as MFAChallengeResponse, y as MFAMethod, z as MFASMSSetupResponse, G as MFASetupRequest, H as MFAStatus, I as MFATOTPSetupResponse, J as MFAVerifyRequest, O as OAuthCallbackRequest, N as OAuthCallbackResponse, P as OAuthConfig, Q as OAuthProvider, R as OAuthStartResponse, T as PageViewData, V as PayoutSchedule, W as PhoneLoginRequest, X as PhoneSendCodeRequest, Y as PhoneVerifyRequest, Z as Profile, _ as RefreshResponse, $ as RegisterRequest, a0 as ResetPasswordRequest, a1 as ScaleMuleApiError, a2 as ScaleMuleEnvironment, a3 as Session, a4 as SignedUploadCompleteRequest, a5 as SignedUploadRequest, a6 as SignedUploadResponse, a7 as SignedUploadUrl, a8 as StorageAdapter, a9 as StorageFile, aa as TrackEventResponse, ab as TransactionSummary, ac as UTMParams, ad as UpdateProfileRequest, ae as UploadOptions, af as UploadResponse, ag as VerifyEmailRequest } from './index-Bv1m_qQ8.mjs';
9
+ import { S as ScaleMuleConfig, U as User, L as LoginResponse, A as ApiError$1, a as UseAuthReturn, b as UseBillingReturn, c as ListFilesParams, d as UseContentReturn, e as UseUserReturn, f as UseAnalyticsOptions, g as UseAnalyticsReturn } from './index-BQgmT53x.mjs';
10
+ export { h as AccountBalance, i as AnalyticsEvent, j as ApiResponse, B as BatchTrackRequest, k as BillingPayment, l as BillingPayout, m as BillingRefund, n as BillingTransaction, C as ChangeEmailRequest, o as ChangePasswordRequest, p as ClientContext, q as ConnectedAccount, D as DeviceFingerprint, r as DeviceInfo, E as EnhancedAnalyticsEvent, F as ForgotPasswordRequest, K as KnownAccountInfo, s as LinkedAccount, t as ListFilesResponse, u as LoginDeviceInfo, v as LoginRequest, w as LoginResponseWithMFA, x as LoginRiskInfo, M as MFAChallengeResponse, y as MFAMethod, z as MFASMSSetupResponse, G as MFASetupRequest, H as MFAStatus, I as MFATOTPSetupResponse, J as MFAVerifyRequest, O as OAuthCallbackRequest, N as OAuthCallbackResponse, P as OAuthConfig, Q as OAuthProvider, R as OAuthStartResponse, T as PageViewData, V as PayoutSchedule, W as PhoneLoginRequest, X as PhoneSendCodeRequest, Y as PhoneVerifyRequest, Z as Profile, _ as RefreshResponse, $ as RegisterRequest, a0 as ResetPasswordRequest, a1 as ScaleMuleApiError, a2 as ScaleMuleEnvironment, a3 as Session, a4 as SignedUploadCompleteRequest, a5 as SignedUploadRequest, a6 as SignedUploadResponse, a7 as SignedUploadUrl, a8 as StorageAdapter, a9 as StorageFile, aa as TrackEventResponse, ab as TransactionSummary, ac as UTMParams, ad as UpdateProfileRequest, ae as UploadOptions, af as UploadResponse, ag as VerifyEmailRequest } from './index-BQgmT53x.mjs';
11
11
 
12
12
  /**
13
13
  * Tri-state file visibility — `'private' | 'app_public' | 'anonymous_visible'`.
@@ -204,7 +204,14 @@ interface UseMediaReturn {
204
204
  */
205
205
  declare function useMedia(): UseMediaReturn;
206
206
 
207
+ interface SecurityChallenge {
208
+ method: 'email' | 'totp' | 'sms';
209
+ error?: string;
210
+ }
211
+ type SecurityChallengePrompt = (challenge: SecurityChallenge) => Promise<string | null>;
212
+
207
213
  interface ScaleMuleContextValue {
214
+ requestSecurityCode: SecurityChallengePrompt;
208
215
  /** The API client instance */
209
216
  client: ScaleMuleClient;
210
217
  /** Money client instance sharing the same session token */
@@ -269,6 +276,10 @@ interface ScaleMuleContextValue {
269
276
  bootstrapFlags?: Record<string, unknown>;
270
277
  }
271
278
  interface ScaleMuleProviderProps extends ScaleMuleConfig {
279
+ /** Recovery link in the built-in security challenge. */
280
+ passwordRecoveryUrl?: string;
281
+ /** Optional custom adaptive verification UI. */
282
+ onSecurityChallenge?: SecurityChallengePrompt;
272
283
  children: ReactNode;
273
284
  /** Called when user logs in */
274
285
  onLogin?: (user: User, response: LoginResponse) => void;
@@ -329,7 +340,7 @@ interface ScaleMuleProviderProps extends ScaleMuleConfig {
329
340
  */
330
341
  memberTokenPollMs?: number | null;
331
342
  }
332
- declare function ScaleMuleProvider({ apiKey, applicationId, environment, gatewayUrl, debug, storage, analyticsProxyUrl, authProxyUrl, telemetryEndpoint, publishableKey, enableAccountSwitcher, accountSwitcherPrivacy, children, onLogin, onLogout, onAuthError, bootstrapFlags, mediaPolicy, getToken, userResolver, memberTokenPollMs, }: ScaleMuleProviderProps): react_jsx_runtime.JSX.Element;
343
+ declare function ScaleMuleProvider({ apiKey, applicationId, environment, gatewayUrl, debug, storage, analyticsProxyUrl, authProxyUrl, telemetryEndpoint, publishableKey, enableAccountSwitcher, accountSwitcherPrivacy, children, onLogin, onLogout, onAuthError, bootstrapFlags, mediaPolicy, getToken, userResolver, memberTokenPollMs, passwordRecoveryUrl, onSecurityChallenge, }: ScaleMuleProviderProps): react_jsx_runtime.JSX.Element;
333
344
  declare function useScaleMule(): ScaleMuleContextValue;
334
345
  declare function useScaleMuleClient(): ScaleMuleClient;
335
346
  declare function useMoneyClient(): MoneyClient;
@@ -1220,4 +1231,4 @@ declare function createSafeLogger(prefix: string): {
1220
1231
  error: (message: string, data?: unknown) => void;
1221
1232
  };
1222
1233
 
1223
- export { ApiError$1 as ApiError, type AudioFile, type AudioUploadResult, type ConversationKind, type FeatureFlagEvaluation, type FeatureFlagEvaluation as FeatureFlagResult, type FeedbackItem, type FeedbackItemInput, type FeedbackPriority, type FeedbackStatus, type FeedbackType, FeedbackWidget, type FeedbackWidgetConfig, type FeedbackWidgetProps, ListFilesParams, LoginResponse, type MediaPolicy, type MediaUploadResult, NarrationPlayer, type NarrationPlayerAudio, type NarrationPlayerProps, type PasswordValidationResult, type PhoneCountry, type PhoneValidationResult, type RealtimeEvent, type RealtimeMessage, type RealtimeStatus, ScaleMuleClient, ScaleMuleConfig, ScaleMuleMedia, type ScaleMuleMediaProps, ScaleMuleProvider, type ScaleMuleProviderProps, UseAnalyticsOptions, UseAnalyticsReturn, type UseAudioReturn, type UseAudioUploadOptions, UseAuthReturn, UseBillingReturn, UseContentReturn, type UseFeatureFlagsOptions, type UseFeatureFlagsReturn, type UseFeedbackOptions, type UseFeedbackResult, type UseFileStatusOptions, type UseFileStatusReturn, type UseFeatureFlagsOptions as UseFlagsOptions, type UseFeatureFlagsReturn as UseFlagsReturn, type UseMediaReturn, type UseMediaUploadOptions, type UsePushNotificationsOptions, type UsePushNotificationsReturn, type UseRealtimeOptions, type UseRealtimeReturn, type UseShareOptions, type UseShareReturn, type UseTtsJobOptions, type UseTtsJobReturn, UseUserReturn, type UseVoteOptions, type UseVoteReturn, User, type UsernameValidationResult, VoteButton, type VoteButtonClassNames, type VoteButtonProps, type VoteState, composePhone, createSafeLogger, normalizePhone, phoneCountries, sanitizeForLog, useAnalytics, useAudio, useAuth, useBilling, useContent, useFeatureFlags, useFeedback, useFileStatus, useMedia, useMoney, useMoneyClient, usePushNotifications, useRealtime, useScaleMule, useScaleMuleClient, useShare, useTtsJob, useUser, useVote, validateForm, validators };
1234
+ export { ApiError$1 as ApiError, type AudioFile, type AudioUploadResult, type ConversationKind, type FeatureFlagEvaluation, type FeatureFlagEvaluation as FeatureFlagResult, type FeedbackItem, type FeedbackItemInput, type FeedbackPriority, type FeedbackStatus, type FeedbackType, FeedbackWidget, type FeedbackWidgetConfig, type FeedbackWidgetProps, ListFilesParams, LoginResponse, type MediaPolicy, type MediaUploadResult, NarrationPlayer, type NarrationPlayerAudio, type NarrationPlayerProps, type PasswordValidationResult, type PhoneCountry, type PhoneValidationResult, type RealtimeEvent, type RealtimeMessage, type RealtimeStatus, ScaleMuleClient, ScaleMuleConfig, ScaleMuleMedia, type ScaleMuleMediaProps, ScaleMuleProvider, type ScaleMuleProviderProps, type SecurityChallenge, type SecurityChallengePrompt, UseAnalyticsOptions, UseAnalyticsReturn, type UseAudioReturn, type UseAudioUploadOptions, UseAuthReturn, UseBillingReturn, UseContentReturn, type UseFeatureFlagsOptions, type UseFeatureFlagsReturn, type UseFeedbackOptions, type UseFeedbackResult, type UseFileStatusOptions, type UseFileStatusReturn, type UseFeatureFlagsOptions as UseFlagsOptions, type UseFeatureFlagsReturn as UseFlagsReturn, type UseMediaReturn, type UseMediaUploadOptions, type UsePushNotificationsOptions, type UsePushNotificationsReturn, type UseRealtimeOptions, type UseRealtimeReturn, type UseShareOptions, type UseShareReturn, type UseTtsJobOptions, type UseTtsJobReturn, UseUserReturn, type UseVoteOptions, type UseVoteReturn, User, type UsernameValidationResult, VoteButton, type VoteButtonClassNames, type VoteButtonProps, type VoteState, composePhone, createSafeLogger, normalizePhone, phoneCountries, sanitizeForLog, useAnalytics, useAudio, useAuth, useBilling, useContent, useFeatureFlags, useFeedback, useFileStatus, useMedia, useMoney, useMoneyClient, usePushNotifications, useRealtime, useScaleMule, useScaleMuleClient, useShare, useTtsJob, useUser, useVote, validateForm, validators };
package/dist/index.d.ts CHANGED
@@ -6,8 +6,8 @@ import { MoneyClient } from '@scalemule/money';
6
6
  export { MoneyClient, MoneyClientConfig, createMoneyClient } from '@scalemule/money';
7
7
  import { ScaleMuleClient } from './client.js';
8
8
  export { ClientConfig, RequestOptions, createClient } from './client.js';
9
- import { S as ScaleMuleConfig, U as User, L as LoginResponse, A as ApiError$1, a as UseAuthReturn, b as UseBillingReturn, c as ListFilesParams, d as UseContentReturn, e as UseUserReturn, f as UseAnalyticsOptions, g as UseAnalyticsReturn } from './index-Bv1m_qQ8.js';
10
- export { h as AccountBalance, i as AnalyticsEvent, j as ApiResponse, B as BatchTrackRequest, k as BillingPayment, l as BillingPayout, m as BillingRefund, n as BillingTransaction, C as ChangeEmailRequest, o as ChangePasswordRequest, p as ClientContext, q as ConnectedAccount, D as DeviceFingerprint, r as DeviceInfo, E as EnhancedAnalyticsEvent, F as ForgotPasswordRequest, K as KnownAccountInfo, s as LinkedAccount, t as ListFilesResponse, u as LoginDeviceInfo, v as LoginRequest, w as LoginResponseWithMFA, x as LoginRiskInfo, M as MFAChallengeResponse, y as MFAMethod, z as MFASMSSetupResponse, G as MFASetupRequest, H as MFAStatus, I as MFATOTPSetupResponse, J as MFAVerifyRequest, O as OAuthCallbackRequest, N as OAuthCallbackResponse, P as OAuthConfig, Q as OAuthProvider, R as OAuthStartResponse, T as PageViewData, V as PayoutSchedule, W as PhoneLoginRequest, X as PhoneSendCodeRequest, Y as PhoneVerifyRequest, Z as Profile, _ as RefreshResponse, $ as RegisterRequest, a0 as ResetPasswordRequest, a1 as ScaleMuleApiError, a2 as ScaleMuleEnvironment, a3 as Session, a4 as SignedUploadCompleteRequest, a5 as SignedUploadRequest, a6 as SignedUploadResponse, a7 as SignedUploadUrl, a8 as StorageAdapter, a9 as StorageFile, aa as TrackEventResponse, ab as TransactionSummary, ac as UTMParams, ad as UpdateProfileRequest, ae as UploadOptions, af as UploadResponse, ag as VerifyEmailRequest } from './index-Bv1m_qQ8.js';
9
+ import { S as ScaleMuleConfig, U as User, L as LoginResponse, A as ApiError$1, a as UseAuthReturn, b as UseBillingReturn, c as ListFilesParams, d as UseContentReturn, e as UseUserReturn, f as UseAnalyticsOptions, g as UseAnalyticsReturn } from './index-BQgmT53x.js';
10
+ export { h as AccountBalance, i as AnalyticsEvent, j as ApiResponse, B as BatchTrackRequest, k as BillingPayment, l as BillingPayout, m as BillingRefund, n as BillingTransaction, C as ChangeEmailRequest, o as ChangePasswordRequest, p as ClientContext, q as ConnectedAccount, D as DeviceFingerprint, r as DeviceInfo, E as EnhancedAnalyticsEvent, F as ForgotPasswordRequest, K as KnownAccountInfo, s as LinkedAccount, t as ListFilesResponse, u as LoginDeviceInfo, v as LoginRequest, w as LoginResponseWithMFA, x as LoginRiskInfo, M as MFAChallengeResponse, y as MFAMethod, z as MFASMSSetupResponse, G as MFASetupRequest, H as MFAStatus, I as MFATOTPSetupResponse, J as MFAVerifyRequest, O as OAuthCallbackRequest, N as OAuthCallbackResponse, P as OAuthConfig, Q as OAuthProvider, R as OAuthStartResponse, T as PageViewData, V as PayoutSchedule, W as PhoneLoginRequest, X as PhoneSendCodeRequest, Y as PhoneVerifyRequest, Z as Profile, _ as RefreshResponse, $ as RegisterRequest, a0 as ResetPasswordRequest, a1 as ScaleMuleApiError, a2 as ScaleMuleEnvironment, a3 as Session, a4 as SignedUploadCompleteRequest, a5 as SignedUploadRequest, a6 as SignedUploadResponse, a7 as SignedUploadUrl, a8 as StorageAdapter, a9 as StorageFile, aa as TrackEventResponse, ab as TransactionSummary, ac as UTMParams, ad as UpdateProfileRequest, ae as UploadOptions, af as UploadResponse, ag as VerifyEmailRequest } from './index-BQgmT53x.js';
11
11
 
12
12
  /**
13
13
  * Tri-state file visibility — `'private' | 'app_public' | 'anonymous_visible'`.
@@ -204,7 +204,14 @@ interface UseMediaReturn {
204
204
  */
205
205
  declare function useMedia(): UseMediaReturn;
206
206
 
207
+ interface SecurityChallenge {
208
+ method: 'email' | 'totp' | 'sms';
209
+ error?: string;
210
+ }
211
+ type SecurityChallengePrompt = (challenge: SecurityChallenge) => Promise<string | null>;
212
+
207
213
  interface ScaleMuleContextValue {
214
+ requestSecurityCode: SecurityChallengePrompt;
208
215
  /** The API client instance */
209
216
  client: ScaleMuleClient;
210
217
  /** Money client instance sharing the same session token */
@@ -269,6 +276,10 @@ interface ScaleMuleContextValue {
269
276
  bootstrapFlags?: Record<string, unknown>;
270
277
  }
271
278
  interface ScaleMuleProviderProps extends ScaleMuleConfig {
279
+ /** Recovery link in the built-in security challenge. */
280
+ passwordRecoveryUrl?: string;
281
+ /** Optional custom adaptive verification UI. */
282
+ onSecurityChallenge?: SecurityChallengePrompt;
272
283
  children: ReactNode;
273
284
  /** Called when user logs in */
274
285
  onLogin?: (user: User, response: LoginResponse) => void;
@@ -329,7 +340,7 @@ interface ScaleMuleProviderProps extends ScaleMuleConfig {
329
340
  */
330
341
  memberTokenPollMs?: number | null;
331
342
  }
332
- declare function ScaleMuleProvider({ apiKey, applicationId, environment, gatewayUrl, debug, storage, analyticsProxyUrl, authProxyUrl, telemetryEndpoint, publishableKey, enableAccountSwitcher, accountSwitcherPrivacy, children, onLogin, onLogout, onAuthError, bootstrapFlags, mediaPolicy, getToken, userResolver, memberTokenPollMs, }: ScaleMuleProviderProps): react_jsx_runtime.JSX.Element;
343
+ declare function ScaleMuleProvider({ apiKey, applicationId, environment, gatewayUrl, debug, storage, analyticsProxyUrl, authProxyUrl, telemetryEndpoint, publishableKey, enableAccountSwitcher, accountSwitcherPrivacy, children, onLogin, onLogout, onAuthError, bootstrapFlags, mediaPolicy, getToken, userResolver, memberTokenPollMs, passwordRecoveryUrl, onSecurityChallenge, }: ScaleMuleProviderProps): react_jsx_runtime.JSX.Element;
333
344
  declare function useScaleMule(): ScaleMuleContextValue;
334
345
  declare function useScaleMuleClient(): ScaleMuleClient;
335
346
  declare function useMoneyClient(): MoneyClient;
@@ -1220,4 +1231,4 @@ declare function createSafeLogger(prefix: string): {
1220
1231
  error: (message: string, data?: unknown) => void;
1221
1232
  };
1222
1233
 
1223
- export { ApiError$1 as ApiError, type AudioFile, type AudioUploadResult, type ConversationKind, type FeatureFlagEvaluation, type FeatureFlagEvaluation as FeatureFlagResult, type FeedbackItem, type FeedbackItemInput, type FeedbackPriority, type FeedbackStatus, type FeedbackType, FeedbackWidget, type FeedbackWidgetConfig, type FeedbackWidgetProps, ListFilesParams, LoginResponse, type MediaPolicy, type MediaUploadResult, NarrationPlayer, type NarrationPlayerAudio, type NarrationPlayerProps, type PasswordValidationResult, type PhoneCountry, type PhoneValidationResult, type RealtimeEvent, type RealtimeMessage, type RealtimeStatus, ScaleMuleClient, ScaleMuleConfig, ScaleMuleMedia, type ScaleMuleMediaProps, ScaleMuleProvider, type ScaleMuleProviderProps, UseAnalyticsOptions, UseAnalyticsReturn, type UseAudioReturn, type UseAudioUploadOptions, UseAuthReturn, UseBillingReturn, UseContentReturn, type UseFeatureFlagsOptions, type UseFeatureFlagsReturn, type UseFeedbackOptions, type UseFeedbackResult, type UseFileStatusOptions, type UseFileStatusReturn, type UseFeatureFlagsOptions as UseFlagsOptions, type UseFeatureFlagsReturn as UseFlagsReturn, type UseMediaReturn, type UseMediaUploadOptions, type UsePushNotificationsOptions, type UsePushNotificationsReturn, type UseRealtimeOptions, type UseRealtimeReturn, type UseShareOptions, type UseShareReturn, type UseTtsJobOptions, type UseTtsJobReturn, UseUserReturn, type UseVoteOptions, type UseVoteReturn, User, type UsernameValidationResult, VoteButton, type VoteButtonClassNames, type VoteButtonProps, type VoteState, composePhone, createSafeLogger, normalizePhone, phoneCountries, sanitizeForLog, useAnalytics, useAudio, useAuth, useBilling, useContent, useFeatureFlags, useFeedback, useFileStatus, useMedia, useMoney, useMoneyClient, usePushNotifications, useRealtime, useScaleMule, useScaleMuleClient, useShare, useTtsJob, useUser, useVote, validateForm, validators };
1234
+ export { ApiError$1 as ApiError, type AudioFile, type AudioUploadResult, type ConversationKind, type FeatureFlagEvaluation, type FeatureFlagEvaluation as FeatureFlagResult, type FeedbackItem, type FeedbackItemInput, type FeedbackPriority, type FeedbackStatus, type FeedbackType, FeedbackWidget, type FeedbackWidgetConfig, type FeedbackWidgetProps, ListFilesParams, LoginResponse, type MediaPolicy, type MediaUploadResult, NarrationPlayer, type NarrationPlayerAudio, type NarrationPlayerProps, type PasswordValidationResult, type PhoneCountry, type PhoneValidationResult, type RealtimeEvent, type RealtimeMessage, type RealtimeStatus, ScaleMuleClient, ScaleMuleConfig, ScaleMuleMedia, type ScaleMuleMediaProps, ScaleMuleProvider, type ScaleMuleProviderProps, type SecurityChallenge, type SecurityChallengePrompt, UseAnalyticsOptions, UseAnalyticsReturn, type UseAudioReturn, type UseAudioUploadOptions, UseAuthReturn, UseBillingReturn, UseContentReturn, type UseFeatureFlagsOptions, type UseFeatureFlagsReturn, type UseFeedbackOptions, type UseFeedbackResult, type UseFileStatusOptions, type UseFileStatusReturn, type UseFeatureFlagsOptions as UseFlagsOptions, type UseFeatureFlagsReturn as UseFlagsReturn, type UseMediaReturn, type UseMediaUploadOptions, type UsePushNotificationsOptions, type UsePushNotificationsReturn, type UseRealtimeOptions, type UseRealtimeReturn, type UseShareOptions, type UseShareReturn, type UseTtsJobOptions, type UseTtsJobReturn, UseUserReturn, type UseVoteOptions, type UseVoteReturn, User, type UsernameValidationResult, VoteButton, type VoteButtonClassNames, type VoteButtonProps, type VoteState, composePhone, createSafeLogger, normalizePhone, phoneCountries, sanitizeForLog, useAnalytics, useAudio, useAuth, useBilling, useContent, useFeatureFlags, useFeedback, useFileStatus, useMedia, useMoney, useMoneyClient, usePushNotifications, useRealtime, useScaleMule, useScaleMuleClient, useShare, useTtsJob, useUser, useVote, validateForm, validators };
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  'use strict';
2
2
 
3
3
  var React = require('react');
4
+ var jsxRuntime = require('react/jsx-runtime');
4
5
  var money = require('@scalemule/money');
5
6
  var sdk = require('@scalemule/sdk');
6
- var jsxRuntime = require('react/jsx-runtime');
7
7
 
8
8
  function _interopNamespace(e) {
9
9
  if (e && e.__esModule) return e;
@@ -25,7 +25,137 @@ function _interopNamespace(e) {
25
25
 
26
26
  var React__namespace = /*#__PURE__*/_interopNamespace(React);
27
27
 
28
- // src/provider.tsx
28
+ // src/security-challenge.tsx
29
+ function useSecurityChallenge(recoveryUrl) {
30
+ const [challenge, setChallenge] = React.useState(null);
31
+ const [code, setCode] = React.useState("");
32
+ const resolve = React.useRef(null);
33
+ const dialog = React.useRef(null);
34
+ const answer = React.useCallback((value) => {
35
+ const pending = resolve.current;
36
+ resolve.current = null;
37
+ setChallenge(null);
38
+ setCode("");
39
+ pending?.(value);
40
+ }, []);
41
+ const prompt = React.useCallback((next) => {
42
+ resolve.current?.(null);
43
+ return new Promise((done) => {
44
+ resolve.current = done;
45
+ setCode("");
46
+ setChallenge(next);
47
+ });
48
+ }, []);
49
+ React.useEffect(() => () => {
50
+ resolve.current?.(null);
51
+ resolve.current = null;
52
+ }, []);
53
+ React.useEffect(() => {
54
+ if (challenge && dialog.current && !dialog.current.open) dialog.current.showModal();
55
+ }, [challenge]);
56
+ const element = challenge ? /* @__PURE__ */ jsxRuntime.jsx(
57
+ "dialog",
58
+ {
59
+ ref: dialog,
60
+ "aria-labelledby": "sm-security-title",
61
+ "aria-describedby": "sm-security-description",
62
+ onCancel: (event) => {
63
+ event.preventDefault();
64
+ answer(null);
65
+ },
66
+ style: { border: "1px solid #d1d5db", borderRadius: 16, padding: 28, maxWidth: 420, width: "calc(100% - 48px)", color: "#111827", background: "#fff", boxSizing: "border-box" },
67
+ children: /* @__PURE__ */ jsxRuntime.jsxs("form", { onSubmit: (event) => {
68
+ event.preventDefault();
69
+ if (code.trim()) answer(code.trim());
70
+ }, children: [
71
+ /* @__PURE__ */ jsxRuntime.jsx("h2", { id: "sm-security-title", style: { marginTop: 0 }, children: "Confirm your sign-in" }),
72
+ /* @__PURE__ */ jsxRuntime.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.") }),
73
+ challenge.error && /* @__PURE__ */ jsxRuntime.jsx("p", { role: "alert", style: { color: "#b91c1c" }, children: challenge.error }),
74
+ /* @__PURE__ */ jsxRuntime.jsx("label", { htmlFor: "sm-security-code", children: "Verification code" }),
75
+ /* @__PURE__ */ jsxRuntime.jsx(
76
+ "input",
77
+ {
78
+ id: "sm-security-code",
79
+ autoFocus: true,
80
+ autoComplete: "one-time-code",
81
+ inputMode: "numeric",
82
+ value: code,
83
+ onChange: (event) => setCode(event.target.value),
84
+ maxLength: 32,
85
+ required: true,
86
+ style: { display: "block", boxSizing: "border-box", width: "100%", margin: "8px 0 20px", padding: 12, fontSize: 22, border: "1px solid #9ca3af", borderRadius: 8 }
87
+ }
88
+ ),
89
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "submit", style: { padding: "10px 20px", borderRadius: 8, border: 0, background: "#2563eb", color: "#fff", cursor: "pointer" }, children: "Continue" }),
90
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", onClick: () => answer(null), style: { marginLeft: 12 }, children: "Cancel" }),
91
+ challenge.method !== "totp" && /* @__PURE__ */ jsxRuntime.jsxs("p", { children: [
92
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", onClick: () => answer("resend"), children: "Send a new code" }),
93
+ " ",
94
+ /* @__PURE__ */ jsxRuntime.jsx("small", { children: "(wait 60 seconds between requests)" })
95
+ ] }),
96
+ /* @__PURE__ */ jsxRuntime.jsx("p", { children: /* @__PURE__ */ jsxRuntime.jsx("a", { href: recoveryUrl, onClick: () => answer(null), children: "Reset your password" }) })
97
+ ] })
98
+ }
99
+ ) : null;
100
+ return { prompt, element };
101
+ }
102
+ async function withAdaptiveChallenge(attempt, prompt, mfa) {
103
+ let proof = {};
104
+ let challengeToken;
105
+ let message;
106
+ for (; ; ) {
107
+ try {
108
+ return await attempt(proof);
109
+ } catch (error) {
110
+ const err = error;
111
+ if (err.code === "MFA_REQUIRED" && mfa) {
112
+ const details = JSON.parse(err.message || "{}");
113
+ const token = details.pending_token;
114
+ const method = details.mfa_method;
115
+ if (!token || !["totp", "email", "sms"].includes(method || "")) throw error;
116
+ let mfaError;
117
+ if (method !== "totp") {
118
+ try {
119
+ await mfa.send(token, method);
120
+ } catch (failure) {
121
+ const failed = failure;
122
+ if (failed.code !== "CHALLENGE_RATE_LIMITED") throw failure;
123
+ mfaError = failed.message;
124
+ }
125
+ }
126
+ for (; ; ) {
127
+ const code2 = await prompt({ method, error: mfaError });
128
+ if (code2 === null) throw { code: "LOGIN_CANCELLED", message: "Sign-in was cancelled." };
129
+ try {
130
+ if (code2 === "resend") {
131
+ await mfa.send(token, method);
132
+ mfaError = void 0;
133
+ continue;
134
+ }
135
+ return await mfa.verify(token, code2, method);
136
+ } catch (failure) {
137
+ const failed = failure;
138
+ if (!["INVALID_MFA_CODE", "CHALLENGE_RATE_LIMITED"].includes(failed.code || "")) throw failure;
139
+ mfaError = failed.message;
140
+ }
141
+ }
142
+ }
143
+ if (err.code === "LOGIN_CHALLENGE_REQUIRED") {
144
+ const details = JSON.parse(err.message || "{}");
145
+ if (!details.challenge_token) throw error;
146
+ challengeToken = details.challenge_token;
147
+ message = void 0;
148
+ } else if (challengeToken && ["LOGIN_CHALLENGE_INVALID", "CHALLENGE_RATE_LIMITED"].includes(err.code || "")) {
149
+ message = err.message;
150
+ } else {
151
+ throw error;
152
+ }
153
+ const code = await prompt({ method: "email", error: message });
154
+ if (code === null) throw { code: "LOGIN_CANCELLED", message: "Sign-in was cancelled." };
155
+ proof = code === "resend" ? {} : { challenge_token: challengeToken, challenge_code: code };
156
+ }
157
+ }
158
+ }
29
159
 
30
160
  // src/types/index.ts
31
161
  var ScaleMuleApiError = class extends Error {
@@ -634,7 +764,7 @@ var ScaleMuleClient = class {
634
764
  responseData = text ? JSON.parse(text) : null;
635
765
  } catch {
636
766
  }
637
- if (!response.ok) {
767
+ if (!response.ok || responseData?.success === false) {
638
768
  const rawError = responseData?.error;
639
769
  const baseError = rawError && typeof rawError === "object" ? rawError : { code: `HTTP_${response.status}`, message: typeof rawError === "string" ? rawError : responseData?.message || text || response.statusText };
640
770
  const error = withErrorContext(baseError, responseData, response.headers);
@@ -673,7 +803,7 @@ var ScaleMuleClient = class {
673
803
  continue;
674
804
  }
675
805
  if (this.debug) {
676
- console.error("[ScaleMule] Request failed:", error);
806
+ console.error("[ScaleMule] Request failed:", ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(error.code) ? error.code : error);
677
807
  }
678
808
  throw new ScaleMuleApiError(error);
679
809
  }
@@ -943,6 +1073,7 @@ function setSdkTelemetryEndpoint(url) {
943
1073
  endpoint = url;
944
1074
  }
945
1075
  function reportSdkError(payload) {
1076
+ if (["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(payload.code)) return;
946
1077
  if (!endpoint) return;
947
1078
  if (typeof fetch === "undefined") return;
948
1079
  const body = JSON.stringify({
@@ -1018,8 +1149,12 @@ function ScaleMuleProvider({
1018
1149
  mediaPolicy,
1019
1150
  getToken,
1020
1151
  userResolver,
1021
- memberTokenPollMs
1152
+ memberTokenPollMs,
1153
+ passwordRecoveryUrl = "/auth/forgot-password",
1154
+ onSecurityChallenge
1022
1155
  }) {
1156
+ const security = useSecurityChallenge(passwordRecoveryUrl);
1157
+ const requestSecurityCode = onSecurityChallenge || security.prompt;
1023
1158
  const memberMode = typeof getToken === "function";
1024
1159
  const [user, setUser] = React.useState(null);
1025
1160
  const [initializing, setInitializing] = React.useState(true);
@@ -1261,6 +1396,7 @@ function ScaleMuleProvider({
1261
1396
  );
1262
1397
  const value = React.useMemo(
1263
1398
  () => ({
1399
+ requestSecurityCode,
1264
1400
  client,
1265
1401
  money: money$1,
1266
1402
  realtime: baseClient.realtime,
@@ -1288,9 +1424,12 @@ function ScaleMuleProvider({
1288
1424
  accountSwitcherPrivacy,
1289
1425
  bootstrapFlags
1290
1426
  }),
1291
- [client, money$1, baseClient, user, handleSetUser, initializing, error, analyticsProxyUrl, authProxyUrl, publishableKey, apiKey, resolvedGatewayUrl, environment, enableAccountSwitcher, accountSwitcherPrivacy, bootstrapFlags, effectiveMediaPolicy]
1427
+ [requestSecurityCode, client, money$1, baseClient, user, handleSetUser, initializing, error, analyticsProxyUrl, authProxyUrl, publishableKey, apiKey, resolvedGatewayUrl, environment, enableAccountSwitcher, accountSwitcherPrivacy, bootstrapFlags, effectiveMediaPolicy]
1292
1428
  );
1293
- return /* @__PURE__ */ jsxRuntime.jsx(ScaleMuleContext.Provider, { value, children });
1429
+ return /* @__PURE__ */ jsxRuntime.jsxs(ScaleMuleContext.Provider, { value, children: [
1430
+ children,
1431
+ security.element
1432
+ ] });
1294
1433
  }
1295
1434
  function useScaleMule() {
1296
1435
  const context = React.useContext(ScaleMuleContext);
@@ -1402,7 +1541,7 @@ async function proxyFetch(proxyUrl, path, options = {}) {
1402
1541
  return data;
1403
1542
  }
1404
1543
  function useAuth() {
1405
- const { client, user, setUser, initializing, error, setError, authProxyUrl, enableAccountSwitcher, accountSwitcherPrivacy } = useScaleMule();
1544
+ const { client, user, setUser, initializing, error, setError, authProxyUrl, enableAccountSwitcher, accountSwitcherPrivacy, requestSecurityCode } = useScaleMule();
1406
1545
  const register = React.useCallback(
1407
1546
  async (data) => {
1408
1547
  setError(null);
@@ -1443,19 +1582,31 @@ function useAuth() {
1443
1582
  async (data) => {
1444
1583
  setError(null);
1445
1584
  if (authProxyUrl) {
1446
- const response = await proxyFetch(
1447
- authProxyUrl,
1448
- "login",
1449
- { body: data }
1450
- );
1451
- if (!response.success || !response.data) {
1452
- const err = response.error || {
1453
- code: "LOGIN_FAILED",
1454
- message: "Login failed"
1455
- };
1585
+ const response = await withAdaptiveChallenge(async (proof) => {
1586
+ const result = await proxyFetch(
1587
+ authProxyUrl,
1588
+ "login",
1589
+ { body: { ...data, ...proof } }
1590
+ );
1591
+ if (!result.success || !result.data) {
1592
+ throw result.error || { code: "LOGIN_FAILED", message: "Login failed" };
1593
+ }
1594
+ return { ...result, data: result.data };
1595
+ }, requestSecurityCode, {
1596
+ send: async (pending_token, method) => {
1597
+ const result = await proxyFetch(authProxyUrl, "mfa/send-code", { body: { pending_token, method } });
1598
+ if (!result.success) throw result.error;
1599
+ return result;
1600
+ },
1601
+ verify: async (pending_token, code, method) => {
1602
+ const result = await proxyFetch(authProxyUrl, "mfa/verify", { body: { pending_token, code, method } });
1603
+ if (!result.success || !result.data) throw result.error;
1604
+ return { ...result, data: result.data };
1605
+ }
1606
+ }).catch((err) => {
1456
1607
  setError(err);
1457
1608
  throw err;
1458
- }
1609
+ });
1459
1610
  if ("requires_mfa" in response.data && response.data.requires_mfa) {
1460
1611
  return response.data;
1461
1612
  }
@@ -1473,7 +1624,10 @@ function useAuth() {
1473
1624
  }
1474
1625
  let loginResult;
1475
1626
  try {
1476
- loginResult = await client.post("/v1/auth/login", data);
1627
+ loginResult = await withAdaptiveChallenge((proof) => client.post("/v1/auth/login", { ...data, ...proof }), requestSecurityCode, {
1628
+ send: (pending_token, method) => client.post("/v1/auth/mfa/send-code", { pending_token, method }),
1629
+ verify: (pending_token, code, method) => client.post("/v1/auth/mfa/verify", { pending_token, code, method })
1630
+ });
1477
1631
  } catch (err) {
1478
1632
  if (err instanceof ScaleMuleApiError) {
1479
1633
  setError(err);
@@ -1488,7 +1642,7 @@ function useAuth() {
1488
1642
  setUser(loginData.user);
1489
1643
  return loginData;
1490
1644
  },
1491
- [client, setUser, setError, authProxyUrl]
1645
+ [client, setUser, setError, authProxyUrl, requestSecurityCode]
1492
1646
  );
1493
1647
  const logout = React.useCallback(async () => {
1494
1648
  setError(null);
@@ -1559,8 +1713,17 @@ function useAuth() {
1559
1713
  throw err;
1560
1714
  }
1561
1715
  }
1716
+ await client.clearSession();
1717
+ setUser(null);
1718
+ if (typeof window !== "undefined") {
1719
+ const current = new URL(window.location.href);
1720
+ if (current.searchParams.get("token") === token) {
1721
+ current.searchParams.delete("token");
1722
+ window.history.replaceState(window.history.state, "", current.toString());
1723
+ }
1724
+ }
1562
1725
  },
1563
- [client, setError, authProxyUrl]
1726
+ [client, setUser, setError, authProxyUrl]
1564
1727
  );
1565
1728
  const verifyEmail = React.useCallback(
1566
1729
  async (token) => {
@@ -1841,11 +2004,15 @@ function useAuth() {
1841
2004
  setError(null);
1842
2005
  let mfaResult;
1843
2006
  try {
1844
- mfaResult = await client.post("/v1/auth/mfa/challenge", {
1845
- challenge_token: challengeToken,
1846
- code,
1847
- method
1848
- });
2007
+ if (authProxyUrl) {
2008
+ const result = await proxyFetch(authProxyUrl, "mfa/verify", { body: { pending_token: challengeToken, code, method } });
2009
+ if (!result.success || !result.data) throw result.error;
2010
+ const sessionToken = result.data.sessionToken || result.data.session_token;
2011
+ if (!sessionToken) throw new ScaleMuleApiError({ code: "MFA_FAILED", message: "Sign-in did not return a session" });
2012
+ mfaResult = { ...result.data, session_token: sessionToken };
2013
+ } else {
2014
+ mfaResult = await client.post("/v1/auth/mfa/verify", { pending_token: challengeToken, code, method });
2015
+ }
1849
2016
  } catch (err) {
1850
2017
  if (err instanceof ScaleMuleApiError) {
1851
2018
  setError(err);
@@ -1856,7 +2023,7 @@ function useAuth() {
1856
2023
  setUser(mfaResult.user);
1857
2024
  return mfaResult;
1858
2025
  },
1859
- [client, setUser, setError]
2026
+ [client, setUser, setError, authProxyUrl]
1860
2027
  );
1861
2028
  const disableMFA = React.useCallback(
1862
2029
  async (password) => {
@@ -3772,6 +3939,34 @@ function useRealtime(options) {
3772
3939
  return { status, lastMessage, disconnect, subscribe, publish };
3773
3940
  }
3774
3941
 
3942
+ // src/url-privacy.ts
3943
+ function withoutAuthSecrets(value) {
3944
+ if (!value) return value;
3945
+ try {
3946
+ const absolute = /^[a-z][a-z0-9+.-]*:/i.test(value);
3947
+ const protocolRelative = value.startsWith("//");
3948
+ const url = new URL(value, "https://relative.invalid");
3949
+ if (!["http:", "https:"].includes(url.protocol)) return void 0;
3950
+ let changed = false;
3951
+ for (const name of [...url.searchParams.keys()]) {
3952
+ if (/^(token|code|state|password|new_password|access_token|refresh_token|id_token|api_key|client_secret|challenge_token|challenge_code)$/i.test(name)) {
3953
+ url.searchParams.delete(name);
3954
+ changed = true;
3955
+ }
3956
+ }
3957
+ if (url.hash) {
3958
+ url.hash = "";
3959
+ changed = true;
3960
+ }
3961
+ if (!changed) return value;
3962
+ if (absolute) return url.toString();
3963
+ if (protocolRelative) return url.toString().replace(/^https:/, "");
3964
+ return value.split(/[?#]/, 1)[0] + url.search;
3965
+ } catch {
3966
+ return void 0;
3967
+ }
3968
+ }
3969
+
3775
3970
  // src/hooks/event-dedup.ts
3776
3971
  var DEFAULT_EVENT_DEDUP_MS = 300;
3777
3972
  var DEDUP_MAP_MAX = 200;
@@ -4041,19 +4236,20 @@ function useAnalytics(options = {}) {
4041
4236
  if (utm) setUtmParams(utm);
4042
4237
  }
4043
4238
  if (!landingPage.current) {
4044
- landingPage.current = window.location.href;
4239
+ landingPage.current = withoutAuthSecrets(window.location.href) || null;
4045
4240
  }
4046
4241
  const storage = typeof sessionStorage !== "undefined" ? sessionStorage : void 0;
4047
4242
  const storedReferrer = getStorageItem(storage, SESSION_REFERRER_KEY);
4048
4243
  if (storedReferrer) {
4049
- originalReferrerRef.current = storedReferrer;
4244
+ originalReferrerRef.current = withoutAuthSecrets(storedReferrer) || null;
4245
+ setStorageItem(storage, SESSION_REFERRER_KEY, originalReferrerRef.current || "");
4050
4246
  } else if (document.referrer) {
4051
4247
  try {
4052
4248
  const referrerUrl = new URL(document.referrer);
4053
4249
  const currentUrl = new URL(window.location.href);
4054
4250
  if (referrerUrl.hostname !== currentUrl.hostname) {
4055
- originalReferrerRef.current = document.referrer;
4056
- setStorageItem(storage, SESSION_REFERRER_KEY, document.referrer);
4251
+ originalReferrerRef.current = withoutAuthSecrets(document.referrer) || null;
4252
+ setStorageItem(storage, SESSION_REFERRER_KEY, withoutAuthSecrets(document.referrer) || "");
4057
4253
  }
4058
4254
  } catch {
4059
4255
  }
@@ -4093,10 +4289,10 @@ function useAnalytics(options = {}) {
4093
4289
  session_duration_seconds: Math.floor((Date.now() - sessionStartRef.current) / 1e3)
4094
4290
  };
4095
4291
  if (typeof window !== "undefined") {
4096
- fullEvent.page_url = window.location.href;
4292
+ fullEvent.page_url = withoutAuthSecrets(window.location.href);
4097
4293
  fullEvent.page_title = document.title;
4098
4294
  fullEvent.referrer = originalReferrerRef.current || void 0;
4099
- fullEvent.document_referrer = document.referrer || void 0;
4295
+ fullEvent.document_referrer = withoutAuthSecrets(document.referrer) || void 0;
4100
4296
  }
4101
4297
  return fullEvent;
4102
4298
  },
@@ -4179,9 +4375,9 @@ function useAnalytics(options = {}) {
4179
4375
  event_category: "navigation",
4180
4376
  properties: {
4181
4377
  ...data?.properties || {},
4182
- page_url: data?.page_url || (typeof window !== "undefined" ? window.location.href : void 0),
4378
+ page_url: withoutAuthSecrets(data?.page_url || (typeof window !== "undefined" ? window.location.href : void 0)),
4183
4379
  page_title: data?.page_title || (typeof document !== "undefined" ? document.title : void 0),
4184
- referrer: data?.referrer || originalReferrerRef.current || void 0
4380
+ referrer: withoutAuthSecrets(data?.referrer || originalReferrerRef.current || void 0)
4185
4381
  }
4186
4382
  };
4187
4383
  return trackEvent(pageEvent);