@b3dotfun/sdk 0.1.69-alpha.17 → 0.1.69-alpha.18

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.
Files changed (71) hide show
  1. package/dist/cjs/anyspend/utils/chain.js +1 -1
  2. package/dist/cjs/global-account/better-auth-client.d.ts +1883 -0
  3. package/dist/cjs/global-account/better-auth-client.js +17 -0
  4. package/dist/cjs/global-account/react/components/B3Provider/B3ConfigProvider.d.ts +4 -1
  5. package/dist/cjs/global-account/react/components/B3Provider/B3ConfigProvider.js +2 -1
  6. package/dist/cjs/global-account/react/components/B3Provider/B3Provider.d.ts +4 -1
  7. package/dist/cjs/global-account/react/components/B3Provider/B3Provider.js +3 -2
  8. package/dist/cjs/global-account/react/components/B3Provider/BetterAuthProvider.d.ts +16 -0
  9. package/dist/cjs/global-account/react/components/B3Provider/BetterAuthProvider.js +120 -0
  10. package/dist/cjs/global-account/react/components/SignInWithB3/BetterAuthResetPassword.d.ts +21 -0
  11. package/dist/cjs/global-account/react/components/SignInWithB3/BetterAuthResetPassword.js +67 -0
  12. package/dist/cjs/global-account/react/components/SignInWithB3/BetterAuthSignIn.d.ts +34 -0
  13. package/dist/cjs/global-account/react/components/SignInWithB3/BetterAuthSignIn.js +149 -0
  14. package/dist/cjs/global-account/react/components/SignInWithB3/SignInWithB3Flow.js +9 -3
  15. package/dist/cjs/global-account/react/components/SignInWithB3/steps/LoginStepBetterAuth.d.ts +6 -0
  16. package/dist/cjs/global-account/react/components/SignInWithB3/steps/LoginStepBetterAuth.js +123 -0
  17. package/dist/cjs/global-account/react/components/SignInWithB3/utils/signInUtils.js +5 -1
  18. package/dist/cjs/global-account/react/components/index.d.ts +3 -0
  19. package/dist/cjs/global-account/react/components/index.js +7 -3
  20. package/dist/cjs/global-account/react/hooks/index.d.ts +1 -0
  21. package/dist/cjs/global-account/react/hooks/index.js +4 -2
  22. package/dist/cjs/global-account/react/hooks/useBetterAuth.d.ts +969 -0
  23. package/dist/cjs/global-account/react/hooks/useBetterAuth.js +142 -0
  24. package/dist/esm/anyspend/utils/chain.js +1 -1
  25. package/dist/esm/global-account/better-auth-client.d.ts +1883 -0
  26. package/dist/esm/global-account/better-auth-client.js +13 -0
  27. package/dist/esm/global-account/react/components/B3Provider/B3ConfigProvider.d.ts +4 -1
  28. package/dist/esm/global-account/react/components/B3Provider/B3ConfigProvider.js +2 -1
  29. package/dist/esm/global-account/react/components/B3Provider/B3Provider.d.ts +4 -1
  30. package/dist/esm/global-account/react/components/B3Provider/B3Provider.js +3 -2
  31. package/dist/esm/global-account/react/components/B3Provider/BetterAuthProvider.d.ts +16 -0
  32. package/dist/esm/global-account/react/components/B3Provider/BetterAuthProvider.js +115 -0
  33. package/dist/esm/global-account/react/components/SignInWithB3/BetterAuthResetPassword.d.ts +21 -0
  34. package/dist/esm/global-account/react/components/SignInWithB3/BetterAuthResetPassword.js +64 -0
  35. package/dist/esm/global-account/react/components/SignInWithB3/BetterAuthSignIn.d.ts +34 -0
  36. package/dist/esm/global-account/react/components/SignInWithB3/BetterAuthSignIn.js +146 -0
  37. package/dist/esm/global-account/react/components/SignInWithB3/SignInWithB3Flow.js +9 -3
  38. package/dist/esm/global-account/react/components/SignInWithB3/steps/LoginStepBetterAuth.d.ts +6 -0
  39. package/dist/esm/global-account/react/components/SignInWithB3/steps/LoginStepBetterAuth.js +120 -0
  40. package/dist/esm/global-account/react/components/SignInWithB3/utils/signInUtils.js +5 -1
  41. package/dist/esm/global-account/react/components/index.d.ts +3 -0
  42. package/dist/esm/global-account/react/components/index.js +2 -0
  43. package/dist/esm/global-account/react/hooks/index.d.ts +1 -0
  44. package/dist/esm/global-account/react/hooks/index.js +1 -0
  45. package/dist/esm/global-account/react/hooks/useBetterAuth.d.ts +969 -0
  46. package/dist/esm/global-account/react/hooks/useBetterAuth.js +136 -0
  47. package/dist/styles/index.css +1 -1
  48. package/dist/types/global-account/better-auth-client.d.ts +1883 -0
  49. package/dist/types/global-account/react/components/B3Provider/B3ConfigProvider.d.ts +4 -1
  50. package/dist/types/global-account/react/components/B3Provider/B3Provider.d.ts +4 -1
  51. package/dist/types/global-account/react/components/B3Provider/BetterAuthProvider.d.ts +16 -0
  52. package/dist/types/global-account/react/components/SignInWithB3/BetterAuthResetPassword.d.ts +21 -0
  53. package/dist/types/global-account/react/components/SignInWithB3/BetterAuthSignIn.d.ts +34 -0
  54. package/dist/types/global-account/react/components/SignInWithB3/steps/LoginStepBetterAuth.d.ts +6 -0
  55. package/dist/types/global-account/react/components/index.d.ts +3 -0
  56. package/dist/types/global-account/react/hooks/index.d.ts +1 -0
  57. package/dist/types/global-account/react/hooks/useBetterAuth.d.ts +969 -0
  58. package/package.json +2 -1
  59. package/src/anyspend/utils/chain.ts +1 -2
  60. package/src/global-account/better-auth-client.ts +17 -0
  61. package/src/global-account/react/components/B3Provider/B3ConfigProvider.tsx +6 -0
  62. package/src/global-account/react/components/B3Provider/B3Provider.tsx +15 -5
  63. package/src/global-account/react/components/B3Provider/BetterAuthProvider.tsx +127 -0
  64. package/src/global-account/react/components/SignInWithB3/BetterAuthResetPassword.tsx +146 -0
  65. package/src/global-account/react/components/SignInWithB3/BetterAuthSignIn.tsx +375 -0
  66. package/src/global-account/react/components/SignInWithB3/SignInWithB3Flow.tsx +9 -3
  67. package/src/global-account/react/components/SignInWithB3/steps/LoginStepBetterAuth.tsx +263 -0
  68. package/src/global-account/react/components/SignInWithB3/utils/signInUtils.ts +5 -1
  69. package/src/global-account/react/components/index.ts +3 -0
  70. package/src/global-account/react/hooks/index.ts +1 -0
  71. package/src/global-account/react/hooks/useBetterAuth.ts +177 -0
@@ -0,0 +1,13 @@
1
+ import { createAuthClient } from "better-auth/client";
2
+ import { B3_API_URL } from "../app.shared.js";
3
+ export function createB3BetterAuthClient(baseURL = B3_API_URL) {
4
+ return createAuthClient({
5
+ baseURL,
6
+ basePath: "/auth",
7
+ fetchOptions: {
8
+ credentials: "include",
9
+ },
10
+ });
11
+ }
12
+ // Default singleton for standard usage
13
+ export const betterAuthClient = createB3BetterAuthClient();
@@ -3,6 +3,7 @@ import { CreateOrderParams } from "../../../../anyspend/react/hooks/useAnyspendC
3
3
  import { PermissionsConfig } from "../../../../global-account/types/permissions";
4
4
  import { Account } from "thirdweb/wallets";
5
5
  import { ClientType } from "../../../client-manager";
6
+ export type AuthStrategy = "thirdweb" | "better-auth";
6
7
  export interface B3ConfigContextType {
7
8
  accountOverride?: Account;
8
9
  automaticallySetFirstEoa: boolean;
@@ -13,8 +14,9 @@ export interface B3ConfigContextType {
13
14
  partnerId: string;
14
15
  stripePublishableKey?: string;
15
16
  createClientReferenceId?: (params: CreateOrderParams | CreateOnrampOrderParams) => Promise<string>;
17
+ authStrategy: AuthStrategy;
16
18
  }
17
- export declare function B3ConfigProvider({ children, accountOverride, environment, defaultPermissions, automaticallySetFirstEoa, theme, clientType, partnerId, stripePublishableKey, createClientReferenceId, }: {
19
+ export declare function B3ConfigProvider({ children, accountOverride, environment, defaultPermissions, automaticallySetFirstEoa, theme, clientType, partnerId, stripePublishableKey, createClientReferenceId, authStrategy, }: {
18
20
  children: React.ReactNode;
19
21
  accountOverride?: Account;
20
22
  environment?: "development" | "production";
@@ -25,5 +27,6 @@ export declare function B3ConfigProvider({ children, accountOverride, environmen
25
27
  partnerId: string;
26
28
  stripePublishableKey?: string;
27
29
  createClientReferenceId?: (params: CreateOrderParams | CreateOnrampOrderParams) => Promise<string>;
30
+ authStrategy?: AuthStrategy;
28
31
  }): import("react/jsx-runtime").JSX.Element;
29
32
  export declare function useB3Config(): B3ConfigContextType;
@@ -10,7 +10,7 @@ const DEFAULT_PERMISSIONS = {
10
10
  endDate: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365), // 1 year from now
11
11
  };
12
12
  const B3ConfigContext = createContext(null);
13
- export function B3ConfigProvider({ children, accountOverride, environment = "development", defaultPermissions = DEFAULT_PERMISSIONS, automaticallySetFirstEoa = false, theme = "light", clientType = "rest", partnerId, stripePublishableKey, createClientReferenceId, }) {
13
+ export function B3ConfigProvider({ children, accountOverride, environment = "development", defaultPermissions = DEFAULT_PERMISSIONS, automaticallySetFirstEoa = false, theme = "light", clientType = "rest", partnerId, stripePublishableKey, createClientReferenceId, authStrategy = "thirdweb", }) {
14
14
  return (_jsx(B3ConfigContext.Provider, { value: {
15
15
  accountOverride,
16
16
  environment,
@@ -21,6 +21,7 @@ export function B3ConfigProvider({ children, accountOverride, environment = "dev
21
21
  partnerId,
22
22
  stripePublishableKey,
23
23
  createClientReferenceId,
24
+ authStrategy,
24
25
  }, children: children }));
25
26
  }
26
27
  export function useB3Config() {
@@ -1,6 +1,7 @@
1
1
  import { CreateOnrampOrderParams } from "../../../../anyspend/react/hooks/useAnyspendCreateOnrampOrder";
2
2
  import { CreateOrderParams } from "../../../../anyspend/react/hooks/useAnyspendCreateOrder";
3
3
  import { PermissionsConfig } from "../../../../global-account/types/permissions";
4
+ import type { AuthStrategy } from "./B3ConfigProvider";
4
5
  import "@relayprotocol/relay-kit-ui/styles.css";
5
6
  import { QueryClient } from "@tanstack/react-query";
6
7
  import { Account, EIP1193, Wallet } from "thirdweb/wallets";
@@ -9,7 +10,7 @@ import { ClientType } from "../../../client-manager";
9
10
  /**
10
11
  * Main B3Provider component
11
12
  */
12
- export declare function B3Provider({ theme, children, accountOverride, environment, automaticallySetFirstEoa, defaultEoaProvider, simDuneApiKey, toaster: _toaster, clientType, rpcUrls, partnerId, stripePublishableKey, onConnect, onLogout, connectors, overrideDefaultConnectors, createClientReferenceId, defaultPermissions, disableBSMNTAuthentication, queryClient, }: {
13
+ export declare function B3Provider({ theme, children, accountOverride, environment, automaticallySetFirstEoa, defaultEoaProvider, simDuneApiKey, toaster: _toaster, clientType, rpcUrls, partnerId, stripePublishableKey, onConnect, onLogout, connectors, overrideDefaultConnectors, createClientReferenceId, defaultPermissions, disableBSMNTAuthentication, queryClient, authStrategy, }: {
13
14
  theme: "light" | "dark";
14
15
  children: React.ReactNode;
15
16
  accountOverride?: Account;
@@ -36,4 +37,6 @@ export declare function B3Provider({ theme, children, accountOverride, environme
36
37
  disableBSMNTAuthentication?: boolean;
37
38
  /** Provide your own QueryClient for React Query. If omitted, WalletProvider creates one internally. */
38
39
  queryClient?: QueryClient;
40
+ /** Auth strategy: "thirdweb" (default, ecosystem wallet) or "better-auth" (email/password via Better Auth) */
41
+ authStrategy?: AuthStrategy;
39
42
  }): import("react/jsx-runtime").JSX.Element;
@@ -10,13 +10,14 @@ import { StyleRoot } from "../StyleRoot.js";
10
10
  import { setToastContext, ToastProvider, useToastContext } from "../Toast/index.js";
11
11
  import AuthenticationProvider from "./AuthenticationProvider.js";
12
12
  import { B3ConfigProvider } from "./B3ConfigProvider.js";
13
+ import BetterAuthProvider from "./BetterAuthProvider.js";
13
14
  import { LocalSDKProvider } from "./LocalSDKProvider.js";
14
15
  /**
15
16
  * Main B3Provider component
16
17
  */
17
18
  export function B3Provider({ theme = "light", children, accountOverride, environment, automaticallySetFirstEoa, defaultEoaProvider, simDuneApiKey,
18
19
  // deprecated since v0.0.87
19
- toaster: _toaster, clientType = "rest", rpcUrls, partnerId, stripePublishableKey, onConnect, onLogout, connectors, overrideDefaultConnectors = false, createClientReferenceId, defaultPermissions, disableBSMNTAuthentication = false, queryClient, }) {
20
+ toaster: _toaster, clientType = "rest", rpcUrls, partnerId, stripePublishableKey, onConnect, onLogout, connectors, overrideDefaultConnectors = false, createClientReferenceId, defaultPermissions, disableBSMNTAuthentication = false, queryClient, authStrategy = "thirdweb", }) {
20
21
  // Initialize Google Analytics on mount
21
22
  useEffect(() => {
22
23
  loadGA4Script();
@@ -26,7 +27,7 @@ toaster: _toaster, clientType = "rest", rpcUrls, partnerId, stripePublishableKey
26
27
  setClientType(clientType);
27
28
  }, [clientType]);
28
29
  const wagmiConfig = useMemo(() => createWagmiConfig({ partnerId, rpcUrls, connectors, overrideDefaultConnectors }), [partnerId, rpcUrls, connectors, overrideDefaultConnectors]);
29
- return (_jsx(WalletProvider, { wagmiConfig: wagmiConfig, queryClient: queryClient, children: _jsx(TooltipProvider, { children: _jsx(ToastProvider, { children: _jsx(LocalSDKProvider, { onConnectCallback: onConnect, onLogoutCallback: onLogout, disableBSMNTAuthentication: disableBSMNTAuthentication, children: _jsxs(B3ConfigProvider, { accountOverride: accountOverride, environment: environment, automaticallySetFirstEoa: !!automaticallySetFirstEoa, theme: theme, clientType: clientType, partnerId: partnerId, stripePublishableKey: stripePublishableKey, createClientReferenceId: createClientReferenceId, defaultPermissions: defaultPermissions, children: [_jsx(ToastContextConnector, {}), _jsxs(RelayKitProviderWrapper, { simDuneApiKey: simDuneApiKey, children: [children, _jsx(StyleRoot, { id: "b3-root" })] }), _jsx(AuthenticationProvider, { partnerId: partnerId, automaticallySetFirstEoa: !!automaticallySetFirstEoa, defaultEoaProvider: defaultEoaProvider })] }) }) }) }) }));
30
+ return (_jsx(WalletProvider, { wagmiConfig: wagmiConfig, queryClient: queryClient, children: _jsx(TooltipProvider, { children: _jsx(ToastProvider, { children: _jsx(LocalSDKProvider, { onConnectCallback: onConnect, onLogoutCallback: onLogout, disableBSMNTAuthentication: disableBSMNTAuthentication, children: _jsxs(B3ConfigProvider, { accountOverride: accountOverride, environment: environment, automaticallySetFirstEoa: !!automaticallySetFirstEoa, theme: theme, clientType: clientType, partnerId: partnerId, stripePublishableKey: stripePublishableKey, createClientReferenceId: createClientReferenceId, defaultPermissions: defaultPermissions, authStrategy: authStrategy, children: [_jsx(ToastContextConnector, {}), _jsxs(RelayKitProviderWrapper, { simDuneApiKey: simDuneApiKey, children: [children, _jsx(StyleRoot, { id: "b3-root" })] }), authStrategy === "better-auth" ? (_jsx(BetterAuthProvider, { partnerId: partnerId })) : (_jsx(AuthenticationProvider, { partnerId: partnerId, automaticallySetFirstEoa: !!automaticallySetFirstEoa, defaultEoaProvider: defaultEoaProvider }))] }) }) }) }) }));
30
31
  }
31
32
  /**
32
33
  * Component to connect the toast context to the global toast API
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Parallel to AuthenticationProvider for Better Auth strategy.
3
+ *
4
+ * Manages the isAuthenticating lifecycle for Better Auth:
5
+ * 1. On mount, try to restore an existing Feathers JWT (from a previous login)
6
+ * 2. If no Feathers JWT, check for a Better Auth session (e.g. after OAuth redirect)
7
+ * and exchange it for a Feathers JWT
8
+ * 3. If neither exists, set isAuthenticating: false so the login UI renders
9
+ *
10
+ * Also patches app.logout() so any code path that calls it (useAuthentication,
11
+ * useAuth, SignIn component, etc.) automatically clears the Better Auth session.
12
+ */
13
+ declare const BetterAuthProvider: ({ partnerId }: {
14
+ partnerId: string;
15
+ }) => null;
16
+ export default BetterAuthProvider;
@@ -0,0 +1,115 @@
1
+ import app from "../../../../global-account/app.js";
2
+ import { useAuthStore } from "../../../../global-account/react/index.js";
3
+ import { B3_AUTH_COOKIE_NAME } from "../../../../shared/constants/index.js";
4
+ import { debugB3React } from "../../../../shared/utils/debug.js";
5
+ import Cookies from "js-cookie";
6
+ import { useEffect, useRef } from "react";
7
+ import { betterAuthClient } from "../../../better-auth-client.js";
8
+ import { useUserQuery } from "../../hooks/useUserQuery.js";
9
+ const debug = debugB3React("BetterAuthProvider");
10
+ /**
11
+ * Parallel to AuthenticationProvider for Better Auth strategy.
12
+ *
13
+ * Manages the isAuthenticating lifecycle for Better Auth:
14
+ * 1. On mount, try to restore an existing Feathers JWT (from a previous login)
15
+ * 2. If no Feathers JWT, check for a Better Auth session (e.g. after OAuth redirect)
16
+ * and exchange it for a Feathers JWT
17
+ * 3. If neither exists, set isAuthenticating: false so the login UI renders
18
+ *
19
+ * Also patches app.logout() so any code path that calls it (useAuthentication,
20
+ * useAuth, SignIn component, etc.) automatically clears the Better Auth session.
21
+ */
22
+ const BetterAuthProvider = ({ partnerId }) => {
23
+ const setIsAuthenticated = useAuthStore(state => state.setIsAuthenticated);
24
+ const setIsAuthenticating = useAuthStore(state => state.setIsAuthenticating);
25
+ const setIsConnected = useAuthStore(state => state.setIsConnected);
26
+ const { setUser } = useUserQuery();
27
+ const hasAttemptedRestore = useRef(false);
28
+ const hasPatched = useRef(false);
29
+ // Patch app.logout() to also clear the Better Auth session.
30
+ // This ensures any existing logout path (useAuthentication, useAuth, SignIn
31
+ // dropdown, etc.) clears both the Feathers JWT and the Better Auth session.
32
+ // Patch app.logout() to also clear the Better Auth session.
33
+ // Only handles Better Auth signOut — state cleanup (isAuthenticated, isConnected,
34
+ // setUser, localStorage) is handled by useAuthentication/useAuth's own logout.
35
+ useEffect(() => {
36
+ if (hasPatched.current)
37
+ return;
38
+ hasPatched.current = true;
39
+ const originalLogout = app.logout.bind(app);
40
+ app.logout = async () => {
41
+ debug("Patched logout: clearing Better Auth session");
42
+ try {
43
+ await betterAuthClient.signOut();
44
+ }
45
+ catch {
46
+ debug("Better Auth signOut failed (non-critical)");
47
+ }
48
+ return originalLogout();
49
+ };
50
+ return () => {
51
+ app.logout = originalLogout;
52
+ hasPatched.current = false;
53
+ };
54
+ }, []);
55
+ // Session restore on mount
56
+ useEffect(() => {
57
+ if (hasAttemptedRestore.current)
58
+ return;
59
+ hasAttemptedRestore.current = true;
60
+ const restoreSession = async () => {
61
+ debug("Attempting session restore");
62
+ // 1. Try existing Feathers JWT first (fastest — no network call to Better Auth)
63
+ try {
64
+ const response = await app.reAuthenticate();
65
+ if (response?.user) {
66
+ debug("Feathers JWT restored", { userId: response.user.userId });
67
+ setUser(response.user);
68
+ setIsAuthenticated(true);
69
+ setIsConnected(true);
70
+ setIsAuthenticating(false);
71
+ return;
72
+ }
73
+ }
74
+ catch {
75
+ debug("No existing Feathers JWT");
76
+ }
77
+ // 2. Check for a Better Auth session (e.g. after OAuth redirect sets a cookie)
78
+ try {
79
+ const session = await betterAuthClient.getSession();
80
+ if (session.data?.session?.token) {
81
+ debug("Better Auth session found, exchanging for Feathers JWT", {
82
+ betterAuthUserId: session.data.user?.id,
83
+ });
84
+ const response = await app.authenticate({
85
+ strategy: "better-auth",
86
+ accessToken: session.data.session.token,
87
+ partnerId,
88
+ });
89
+ if (response.accessToken) {
90
+ Cookies.set(B3_AUTH_COOKIE_NAME, response.accessToken, {
91
+ secure: true,
92
+ sameSite: "Lax",
93
+ });
94
+ }
95
+ if (response.user) {
96
+ setUser(response.user);
97
+ setIsAuthenticated(true);
98
+ setIsConnected(true);
99
+ }
100
+ debug("OAuth session exchanged for Feathers JWT", { userId: response.user?.userId });
101
+ setIsAuthenticating(false);
102
+ return;
103
+ }
104
+ }
105
+ catch {
106
+ debug("No Better Auth session to restore");
107
+ }
108
+ // 3. Nothing found — show login UI
109
+ setIsAuthenticating(false);
110
+ };
111
+ restoreSession();
112
+ }, [setIsAuthenticated, setIsAuthenticating, setIsConnected, setUser, partnerId]);
113
+ return null;
114
+ };
115
+ export default BetterAuthProvider;
@@ -0,0 +1,21 @@
1
+ export interface BetterAuthResetPasswordProps {
2
+ /** The reset token from the URL query param */
3
+ token: string;
4
+ /** Called after password is successfully reset */
5
+ onSuccess?: () => void;
6
+ /** Called on error */
7
+ onError?: (error: Error) => void;
8
+ /** Optional class name */
9
+ className?: string;
10
+ }
11
+ /**
12
+ * Standalone reset password form. Render this on your reset password page.
13
+ * Reads the token from props (extract it from the URL query string).
14
+ *
15
+ * Usage:
16
+ * ```tsx
17
+ * const token = new URLSearchParams(window.location.search).get("token");
18
+ * <BetterAuthResetPassword token={token} onSuccess={() => navigate("/login")} />
19
+ * ```
20
+ */
21
+ export declare function BetterAuthResetPassword({ token, onSuccess, onError, className }: BetterAuthResetPasswordProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,64 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Button, Input } from "../../../../global-account/react/index.js";
3
+ import { debugB3React } from "../../../../shared/utils/debug.js";
4
+ import { useState } from "react";
5
+ import { useBetterAuth } from "../../hooks/useBetterAuth.js";
6
+ const debug = debugB3React("BetterAuthResetPassword");
7
+ /**
8
+ * Standalone reset password form. Render this on your reset password page.
9
+ * Reads the token from props (extract it from the URL query string).
10
+ *
11
+ * Usage:
12
+ * ```tsx
13
+ * const token = new URLSearchParams(window.location.search).get("token");
14
+ * <BetterAuthResetPassword token={token} onSuccess={() => navigate("/login")} />
15
+ * ```
16
+ */
17
+ export function BetterAuthResetPassword({ token, onSuccess, onError, className }) {
18
+ const { resetPassword } = useBetterAuth();
19
+ const [password, setPassword] = useState("");
20
+ const [confirmPassword, setConfirmPassword] = useState("");
21
+ const [isLoading, setIsLoading] = useState(false);
22
+ const [error, setError] = useState(null);
23
+ const [success, setSuccess] = useState(false);
24
+ const handleSubmit = async () => {
25
+ if (!password) {
26
+ setError("Please enter a new password");
27
+ return;
28
+ }
29
+ if (password.length < 8) {
30
+ setError("Password must be at least 8 characters");
31
+ return;
32
+ }
33
+ if (password !== confirmPassword) {
34
+ setError("Passwords do not match");
35
+ return;
36
+ }
37
+ try {
38
+ setIsLoading(true);
39
+ setError(null);
40
+ await resetPassword(password, token);
41
+ setSuccess(true);
42
+ debug("Password reset successful");
43
+ onSuccess?.();
44
+ }
45
+ catch (err) {
46
+ const message = err instanceof Error ? err.message : "Password reset failed";
47
+ setError(message);
48
+ debug("Password reset failed", err);
49
+ onError?.(err);
50
+ }
51
+ finally {
52
+ setPassword("");
53
+ setConfirmPassword("");
54
+ setIsLoading(false);
55
+ }
56
+ };
57
+ if (!token) {
58
+ return (_jsx("div", { className: `w-full max-w-[400px] px-6 text-center ${className || ""}`, children: _jsx("p", { className: "text-sm text-red-500", children: "Invalid or missing reset token." }) }));
59
+ }
60
+ return (_jsxs("div", { className: `w-full max-w-[400px] px-6 ${className || ""}`, children: [_jsxs("div", { className: "mb-10 text-center", children: [_jsx("h1", { className: "text-[28px] font-semibold tracking-tight text-gray-900 dark:text-gray-100", children: success ? "Password reset" : "Set new password" }), _jsx("p", { className: "mt-3 text-[15px] text-gray-500 dark:text-gray-400", children: success ? "Your password has been updated." : "Enter your new password below." })] }), success ? (_jsx("div", { className: "space-y-4 text-center", children: _jsx("div", { className: "mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-green-100", children: _jsx("svg", { className: "h-6 w-6 text-green-600", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", children: _jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M5 13l4 4L19 7" }) }) }) })) : (_jsxs("div", { className: "space-y-5", children: [_jsxs("div", { children: [_jsx("label", { className: "mb-2 block text-xs font-medium uppercase tracking-wide text-gray-700 dark:text-gray-300", children: "New password" }), _jsx(Input, { type: "password", placeholder: "At least 8 characters", value: password, onChange: e => setPassword(e.target.value), disabled: isLoading, className: "h-11 px-4 text-[15px]" })] }), _jsxs("div", { children: [_jsx("label", { className: "mb-2 block text-xs font-medium uppercase tracking-wide text-gray-700 dark:text-gray-300", children: "Confirm password" }), _jsx(Input, { type: "password", placeholder: "Repeat your password", value: confirmPassword, onChange: e => setConfirmPassword(e.target.value), disabled: isLoading, onKeyDown: e => {
61
+ if (e.key === "Enter")
62
+ handleSubmit();
63
+ }, className: "h-11 px-4 text-[15px]" })] }), error && _jsx("p", { className: "text-sm text-red-500", children: error }), _jsx(Button, { onClick: handleSubmit, disabled: isLoading, className: "h-11 w-full bg-gray-900 text-[15px] font-medium text-white hover:bg-gray-800 dark:bg-white dark:text-gray-900 dark:hover:bg-gray-100", children: isLoading ? "Resetting..." : "Reset password" })] }))] }));
64
+ }
@@ -0,0 +1,34 @@
1
+ import { type BetterAuthSocialProvider } from "../../hooks/useBetterAuth";
2
+ export interface BetterAuthSignInProps {
3
+ /** Title displayed above the form. Default: "Welcome back" for sign-in, "Create an account" for sign-up */
4
+ title?: string;
5
+ /** Subtitle displayed below the title */
6
+ subtitle?: string;
7
+ /** Which social providers to show. Defaults to all. Pass empty array to hide. */
8
+ socialProviders?: BetterAuthSocialProvider[];
9
+ /** Show email/password form. Default: true */
10
+ showEmail?: boolean;
11
+ /** URL to redirect to after password reset link is clicked. Token is appended as ?token=... */
12
+ passwordResetRedirectTo?: string;
13
+ /** Called after successful authentication */
14
+ onSuccess?: () => void;
15
+ /** Called on authentication error */
16
+ onError?: (error: Error) => void;
17
+ /** Optional class name for the root container */
18
+ className?: string;
19
+ }
20
+ /**
21
+ * Standalone inline sign-in component for Better Auth.
22
+ *
23
+ * Renders directly — no modal, no button wrapper. Designed for full-page
24
+ * sign-in layouts (e.g., B3OS web with branding on the left, form on the right).
25
+ *
26
+ * Usage:
27
+ * ```tsx
28
+ * <BetterAuthSignIn
29
+ * socialProviders={["google", "github"]}
30
+ * onSuccess={() => router.push("/dashboard")}
31
+ * />
32
+ * ```
33
+ */
34
+ export declare function BetterAuthSignIn({ title, subtitle, socialProviders, showEmail, passwordResetRedirectTo, onSuccess, onError, className, }: BetterAuthSignInProps): import("react/jsx-runtime").JSX.Element | null;
@@ -0,0 +1,146 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { Button, Input, useAuthStore } from "../../../../global-account/react/index.js";
3
+ import { debugB3React } from "../../../../shared/utils/debug.js";
4
+ import { useState } from "react";
5
+ import { useBetterAuth } from "../../hooks/useBetterAuth.js";
6
+ import { strategyIcons, strategyLabels } from "./utils/signInUtils.js";
7
+ const debug = debugB3React("BetterAuthSignIn");
8
+ const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
9
+ const DEFAULT_SOCIAL_PROVIDERS = [
10
+ { id: "google", label: "Google" },
11
+ { id: "github", label: "GitHub" },
12
+ { id: "discord", label: "Discord" },
13
+ { id: "microsoft", label: "Microsoft" },
14
+ { id: "slack", label: "Slack" },
15
+ ];
16
+ /**
17
+ * Standalone inline sign-in component for Better Auth.
18
+ *
19
+ * Renders directly — no modal, no button wrapper. Designed for full-page
20
+ * sign-in layouts (e.g., B3OS web with branding on the left, form on the right).
21
+ *
22
+ * Usage:
23
+ * ```tsx
24
+ * <BetterAuthSignIn
25
+ * socialProviders={["google", "github"]}
26
+ * onSuccess={() => router.push("/dashboard")}
27
+ * />
28
+ * ```
29
+ */
30
+ export function BetterAuthSignIn({ title, subtitle = "Enter your credentials to access your account", socialProviders = DEFAULT_SOCIAL_PROVIDERS.map(p => p.id), showEmail = true, passwordResetRedirectTo, onSuccess, onError, className, }) {
31
+ const { signInWithEmail, signUpWithEmail, signInWithSocial, requestPasswordReset } = useBetterAuth();
32
+ const isAuthenticated = useAuthStore(state => state.isAuthenticated);
33
+ const [mode, setMode] = useState("sign-in");
34
+ const [email, setEmail] = useState("");
35
+ const [password, setPassword] = useState("");
36
+ const [name, setName] = useState("");
37
+ const [isLoading, setIsLoading] = useState(false);
38
+ const [loadingProvider, setLoadingProvider] = useState(null);
39
+ const [error, setError] = useState(null);
40
+ const [resetEmailSent, setResetEmailSent] = useState(false);
41
+ const resolvedTitle = title ||
42
+ (mode === "forgot-password" ? "Reset password" : mode === "sign-in" ? "Welcome back" : "Create an account");
43
+ const resolvedSubtitle = mode === "forgot-password"
44
+ ? "Enter your email and we'll send you a reset link"
45
+ : subtitle || "Enter your credentials to access your account";
46
+ const handleForgotPassword = async () => {
47
+ const normalizedEmail = email.trim().toLowerCase();
48
+ if (!EMAIL_REGEX.test(normalizedEmail)) {
49
+ setError("Please enter a valid email address");
50
+ return;
51
+ }
52
+ try {
53
+ setIsLoading(true);
54
+ setError(null);
55
+ await requestPasswordReset(normalizedEmail, passwordResetRedirectTo);
56
+ setResetEmailSent(true);
57
+ }
58
+ catch (err) {
59
+ const message = err instanceof Error ? err.message : "Failed to send reset email";
60
+ setError(message);
61
+ }
62
+ finally {
63
+ setIsLoading(false);
64
+ }
65
+ };
66
+ const providers = socialProviders
67
+ .map(id => DEFAULT_SOCIAL_PROVIDERS.find(p => p.id === id))
68
+ .filter((p) => !!p);
69
+ if (isAuthenticated) {
70
+ return null;
71
+ }
72
+ const handleEmailSubmit = async () => {
73
+ const normalizedEmail = email.trim().toLowerCase();
74
+ if (!EMAIL_REGEX.test(normalizedEmail)) {
75
+ setError("Please enter a valid email address");
76
+ return;
77
+ }
78
+ if (!password) {
79
+ setError("Please enter a password");
80
+ return;
81
+ }
82
+ if (mode === "sign-up" && !name.trim()) {
83
+ setError("Please enter your name");
84
+ return;
85
+ }
86
+ try {
87
+ setIsLoading(true);
88
+ setError(null);
89
+ if (mode === "sign-up") {
90
+ await signUpWithEmail(normalizedEmail, password, name.trim());
91
+ }
92
+ else {
93
+ await signInWithEmail(normalizedEmail, password);
94
+ }
95
+ debug("Auth successful");
96
+ onSuccess?.();
97
+ }
98
+ catch (err) {
99
+ const message = err instanceof Error ? err.message : "Authentication failed";
100
+ setError(message);
101
+ debug("Auth failed", err);
102
+ onError?.(err);
103
+ }
104
+ finally {
105
+ setPassword("");
106
+ setIsLoading(false);
107
+ }
108
+ };
109
+ const handleSocialSignIn = async (provider) => {
110
+ try {
111
+ setIsLoading(true);
112
+ setLoadingProvider(provider);
113
+ setError(null);
114
+ await signInWithSocial(provider);
115
+ }
116
+ catch (err) {
117
+ const message = err instanceof Error ? err.message : `Sign in failed`;
118
+ setError(message);
119
+ onError?.(err);
120
+ setIsLoading(false);
121
+ setLoadingProvider(null);
122
+ }
123
+ };
124
+ return (_jsxs("div", { className: `w-full max-w-[400px] px-6 ${className || ""}`, children: [_jsxs("div", { className: "mb-10 text-center", children: [_jsx("h1", { className: "text-[28px] font-semibold tracking-tight text-gray-900 dark:text-gray-100", children: resolvedTitle }), _jsx("p", { className: "mt-3 text-[15px] text-gray-500 dark:text-gray-400", children: resolvedSubtitle })] }), mode === "forgot-password" && (_jsxs("div", { className: "space-y-5", children: [resetEmailSent ? (_jsxs("div", { className: "space-y-4 text-center", children: [_jsx("div", { className: "mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-green-100", children: _jsx("svg", { className: "h-6 w-6 text-green-600", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", children: _jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M5 13l4 4L19 7" }) }) }), _jsx("p", { className: "text-[15px] text-gray-600 dark:text-gray-300", children: "Check your email for a reset link." })] })) : (_jsxs(_Fragment, { children: [_jsxs("div", { children: [_jsx("label", { className: "mb-2 block text-xs font-medium uppercase tracking-wide text-gray-700 dark:text-gray-300", children: "Email" }), _jsx(Input, { type: "email", placeholder: "name@company.com", value: email, onChange: e => setEmail(e.target.value), disabled: isLoading, onKeyDown: e => {
125
+ if (e.key === "Enter")
126
+ handleForgotPassword();
127
+ }, className: "h-11 px-4 text-[15px]" })] }), error && _jsx("p", { className: "text-sm text-red-500", children: error }), _jsx(Button, { onClick: handleForgotPassword, disabled: isLoading, className: "h-11 w-full bg-gray-900 text-[15px] font-medium text-white hover:bg-gray-800 dark:bg-white dark:text-gray-900 dark:hover:bg-gray-100", children: isLoading ? "Sending..." : "Send reset link" })] })), _jsx("p", { className: "mt-8 text-center text-[14px] text-gray-500 dark:text-gray-400", children: _jsx("button", { onClick: () => {
128
+ setMode("sign-in");
129
+ setError(null);
130
+ setResetEmailSent(false);
131
+ }, className: "font-medium text-blue-600 hover:text-blue-500 dark:text-blue-400", children: "Back to sign in" }) })] })), showEmail && mode !== "forgot-password" && (_jsxs("div", { className: "space-y-5", children: [mode === "sign-up" && (_jsxs("div", { children: [_jsx("label", { className: "mb-2 block text-xs font-medium uppercase tracking-wide text-gray-700 dark:text-gray-300", children: "Name" }), _jsx(Input, { type: "text", placeholder: "Your name", value: name, onChange: e => setName(e.target.value), disabled: isLoading, className: "h-11 px-4 text-[15px]" })] })), _jsxs("div", { children: [_jsx("label", { className: "mb-2 block text-xs font-medium uppercase tracking-wide text-gray-700 dark:text-gray-300", children: "Email" }), _jsx(Input, { type: "email", placeholder: "name@company.com", value: email, onChange: e => setEmail(e.target.value), disabled: isLoading, className: "h-11 px-4 text-[15px]" })] }), _jsxs("div", { children: [_jsxs("div", { className: "mb-2 flex items-center justify-between", children: [_jsx("label", { className: "block text-xs font-medium uppercase tracking-wide text-gray-700 dark:text-gray-300", children: "Password" }), mode === "sign-in" && (_jsx("button", { type: "button", onClick: () => {
132
+ setMode("forgot-password");
133
+ setError(null);
134
+ }, className: "text-xs font-medium text-blue-600 hover:text-blue-500 dark:text-blue-400", children: "Forgot password?" }))] }), _jsx(Input, { type: "password", placeholder: "Password", value: password, onChange: e => setPassword(e.target.value), disabled: isLoading, onKeyDown: e => {
135
+ if (e.key === "Enter")
136
+ handleEmailSubmit();
137
+ }, className: "h-11 px-4 text-[15px]" })] }), error && _jsx("p", { className: "text-sm text-red-500", children: error }), _jsx(Button, { onClick: handleEmailSubmit, disabled: isLoading, className: "h-11 w-full bg-gray-900 text-[15px] font-medium text-white hover:bg-gray-800 dark:bg-white dark:text-gray-900 dark:hover:bg-gray-100", children: isLoading ? "Loading..." : mode === "sign-in" ? "Sign in" : "Sign up" })] })), providers.length > 0 && mode !== "forgot-password" && (_jsxs(_Fragment, { children: [showEmail && (_jsxs("div", { className: "my-8 flex items-center gap-4", children: [_jsx("div", { className: "h-px flex-1 bg-gray-200 dark:bg-gray-700" }), _jsx("span", { className: "text-xs text-gray-400", children: "Or continue with" }), _jsx("div", { className: "h-px flex-1 bg-gray-200 dark:bg-gray-700" })] })), _jsx("div", { className: "space-y-4", children: providers.map(provider => {
138
+ const icon = strategyIcons[provider.id];
139
+ const label = strategyLabels[provider.id] || provider.label;
140
+ const isProviderLoading = loadingProvider === provider.id;
141
+ return (_jsxs("button", { onClick: () => handleSocialSignIn(provider.id), disabled: isLoading, style: { paddingTop: "12px", paddingBottom: "12px" }, className: "flex w-full items-center justify-center gap-3 rounded-lg border border-gray-200 bg-white px-4 text-[14px] font-medium text-gray-700 transition-colors hover:bg-gray-50 disabled:opacity-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200 dark:hover:bg-gray-700", children: [isProviderLoading ? (_jsxs("svg", { className: "h-5 w-5 animate-spin text-gray-400", viewBox: "0 0 24 24", fill: "none", children: [_jsx("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "4" }), _jsx("path", { className: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" })] })) : (icon && _jsx("img", { src: icon, alt: "", className: "h-5 w-5" })), _jsx("span", { children: isProviderLoading ? "Redirecting..." : label })] }, provider.id));
142
+ }) })] })), showEmail && mode !== "forgot-password" && (_jsxs("p", { className: "mt-8 text-center text-[14px] text-gray-500 dark:text-gray-400", children: [mode === "sign-in" ? "Don't have an account? " : "Already have an account? ", _jsx("button", { onClick: () => {
143
+ setMode(mode === "sign-in" ? "sign-up" : "sign-in");
144
+ setError(null);
145
+ }, disabled: isLoading, className: "font-medium text-blue-600 hover:text-blue-500 dark:text-blue-400", children: mode === "sign-in" ? "Sign up" : "Sign in" })] }))] }));
146
+ }
@@ -1,5 +1,6 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { Loading, useAuthentication, useAuthStore, useB3Config, useGetAllTWSigners, useModalStore, } from "../../../../global-account/react/index.js";
3
+ import { LoginStepBetterAuth } from "./steps/LoginStepBetterAuth.js";
3
4
  import { debugB3React } from "../../../../shared/utils/debug.js";
4
5
  import { useCallback, useEffect, useRef, useState } from "react";
5
6
  import { useActiveAccount } from "thirdweb/react";
@@ -13,18 +14,20 @@ const MAX_REFETCH_ATTEMPTS = 20;
13
14
  * Handles different login providers, authentication steps, and session key management
14
15
  */
15
16
  export function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySuccess, onError, chain, sessionKeyAddress, partnerId, closeAfterLogin = false, source = "signInWithB3Button", signersEnabled = false, }) {
16
- const { automaticallySetFirstEoa } = useB3Config();
17
+ const { automaticallySetFirstEoa, authStrategy } = useB3Config();
17
18
  // skipAutoConnect: this component intentionally logs out on mount to show a fresh login screen.
18
19
  // AuthenticationProvider is the sole owner of useAutoConnect to avoid competing auth cycles.
19
20
  const { user, logout } = useAuthentication(partnerId, { skipAutoConnect: true });
20
21
  // Tracks whether the pre-login logout has finished.
21
22
  // We must not render ConnectEmbed until logout (wallet disconnect) completes,
22
23
  // otherwise the wallet state disrupts ConnectEmbed causing a blank modal.
23
- const [readyToShowLogin, setReadyToShowLogin] = useState(source === "requestPermissions");
24
+ const [readyToShowLogin, setReadyToShowLogin] = useState(source === "requestPermissions" || authStrategy === "better-auth");
24
25
  const hasLoggedOutRef = useRef(false);
25
26
  useEffect(() => {
26
27
  if (hasLoggedOutRef.current)
27
28
  return;
29
+ if (authStrategy === "better-auth")
30
+ return;
28
31
  if (source !== "requestPermissions") {
29
32
  debug("Logging out before login");
30
33
  hasLoggedOutRef.current = true;
@@ -32,7 +35,7 @@ export function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySucce
32
35
  setReadyToShowLogin(true);
33
36
  });
34
37
  }
35
- }, [source, logout]);
38
+ }, [source, logout, authStrategy]);
36
39
  const [step, setStep] = useState(source === "requestPermissions" ? null : "login");
37
40
  const [sessionKeyAdded, setSessionKeyAdded] = useState(source === "requestPermissions" ? true : false);
38
41
  const { setB3ModalContentType, setB3ModalOpen, isOpen, contentType } = useModalStore();
@@ -240,6 +243,9 @@ export function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySucce
240
243
  if (!readyToShowLogin || isAuthenticating || isFetchingSigners) {
241
244
  content = (_jsx(LoginStepContainer, { partnerId: partnerId, children: _jsx("div", { className: "my-8 flex min-h-[350px] items-center justify-center", children: _jsx(Loading, { variant: "white", size: "lg" }) }) }));
242
245
  }
246
+ else if (authStrategy === "better-auth") {
247
+ content = _jsx(LoginStepBetterAuth, { onSuccess: () => handleLoginSuccess({}), onError: onError });
248
+ }
243
249
  else {
244
250
  // Custom strategy
245
251
  if (strategies?.[0] === "privy") {
@@ -0,0 +1,6 @@
1
+ interface LoginStepBetterAuthProps {
2
+ onSuccess?: () => void;
3
+ onError?: (error: Error) => Promise<void>;
4
+ }
5
+ export declare function LoginStepBetterAuth({ onSuccess, onError }: LoginStepBetterAuthProps): import("react/jsx-runtime").JSX.Element;
6
+ export {};