@nocios/crudify-ui 1.2.36 → 1.3.0

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.
@@ -0,0 +1,312 @@
1
+ # Migration Guide: Refresh Token Pattern Implementation
2
+
3
+ ## Overview
4
+
5
+ This guide helps you migrate from the standard JWT authentication to the new **Refresh Token Pattern** implementation in CRUDIFY v1.2.0+.
6
+
7
+ The Refresh Token Pattern addresses security vulnerabilities by:
8
+ - Using short-lived access tokens (15 minutes)
9
+ - Implementing long-lived refresh tokens (7 days)
10
+ - Automatic token refresh before expiration
11
+ - Secure token storage with encryption
12
+ - Session restoration on page reload
13
+
14
+ ## Prerequisites
15
+
16
+ Ensure you have the following versions installed:
17
+ - `@nocios/crudify-core` v1.2.0+
18
+ - `@nocios/crudify-ui` v1.2.0+
19
+
20
+ ```bash
21
+ npm update @nocios/crudify-core @nocios/crudify-ui
22
+ ```
23
+
24
+ ## Migration Steps
25
+
26
+ ### 1. Update Your Backend (if applicable)
27
+
28
+ If you're using the CRUDIFY backend, ensure you've deployed the refresh token endpoints. The new login response now includes:
29
+
30
+ ```typescript
31
+ {
32
+ token: string, // Access token (short-lived)
33
+ refreshToken: string, // Refresh token (long-lived)
34
+ expiresIn: number, // Access token expiration
35
+ refreshExpiresIn: number // Refresh token expiration
36
+ }
37
+ ```
38
+
39
+ ### 2. Replace SessionProvider Implementation
40
+
41
+ **BEFORE (Old implementation):**
42
+ ```tsx
43
+ import { CrudifyDataProvider } from '@nocios/crudify-ui';
44
+
45
+ function App() {
46
+ return (
47
+ <CrudifyDataProvider>
48
+ <YourApp />
49
+ </CrudifyDataProvider>
50
+ );
51
+ }
52
+ ```
53
+
54
+ **AFTER (New Refresh Token Pattern):**
55
+ ```tsx
56
+ import { SessionProvider } from '@nocios/crudify-ui';
57
+
58
+ function App() {
59
+ return (
60
+ <SessionProvider
61
+ options={{
62
+ autoRestore: true, // Restore session on page reload
63
+ enableLogging: true, // Enable debug logs
64
+ onSessionExpired: () => { // Handle session expiration
65
+ console.log('Session expired');
66
+ // Redirect to login or show modal
67
+ },
68
+ onSessionRestored: (tokens) => {
69
+ console.log('Session restored:', tokens);
70
+ }
71
+ }}
72
+ >
73
+ <YourApp />
74
+ </SessionProvider>
75
+ );
76
+ }
77
+ ```
78
+
79
+ ### 3. Update Authentication Logic
80
+
81
+ **BEFORE (Manual login handling):**
82
+ ```tsx
83
+ import { useCrudifyLogin } from '@nocios/crudify-ui';
84
+
85
+ function LoginForm() {
86
+ const { login, isLoading } = useCrudifyLogin();
87
+
88
+ const handleLogin = async () => {
89
+ const result = await login(email, password);
90
+ // Manual token handling
91
+ };
92
+ }
93
+ ```
94
+
95
+ **AFTER (Automatic session management):**
96
+ ```tsx
97
+ import { useSessionContext } from '@nocios/crudify-ui';
98
+
99
+ function LoginForm() {
100
+ const { login, isLoading, isAuthenticated, logout } = useSessionContext();
101
+
102
+ const handleLogin = async () => {
103
+ const result = await login(email, password);
104
+ // Session is managed automatically
105
+ if (result.success) {
106
+ // User is now authenticated
107
+ }
108
+ };
109
+ }
110
+ ```
111
+
112
+ ### 4. Replace Authentication Checks
113
+
114
+ **BEFORE (Manual token checking):**
115
+ ```tsx
116
+ import { getCurrentUserEmail, isTokenExpired } from '@nocios/crudify-ui';
117
+
118
+ function ProtectedComponent() {
119
+ const userEmail = getCurrentUserEmail();
120
+ const tokenExpired = isTokenExpired();
121
+
122
+ if (!userEmail || tokenExpired) {
123
+ return <LoginRequired />;
124
+ }
125
+
126
+ return <ProtectedContent />;
127
+ }
128
+ ```
129
+
130
+ **AFTER (Using ProtectedRoute):**
131
+ ```tsx
132
+ import { ProtectedRoute } from '@nocios/crudify-ui';
133
+
134
+ function ProtectedComponent() {
135
+ return (
136
+ <ProtectedRoute fallback={<LoginRequired />}>
137
+ <ProtectedContent />
138
+ </ProtectedRoute>
139
+ );
140
+ }
141
+ ```
142
+
143
+ ### 5. Update API Calls
144
+
145
+ The good news is that your existing CRUDIFY API calls **don't need to change**! The automatic refresh mechanism is built into the core library:
146
+
147
+ ```tsx
148
+ import { crudify } from '@nocios/crudify-ui';
149
+
150
+ // This automatically handles token refresh if needed
151
+ const result = await crudify.getPermissions();
152
+ ```
153
+
154
+ ## New Features Available
155
+
156
+ ### 1. Session Status Component
157
+
158
+ Display authentication status anywhere in your app:
159
+
160
+ ```tsx
161
+ import { SessionStatus } from '@nocios/crudify-ui';
162
+
163
+ function AppHeader() {
164
+ return (
165
+ <AppBar>
166
+ <Toolbar>
167
+ <Typography variant="h6">My App</Typography>
168
+ <SessionStatus /> {/* Shows auth status */}
169
+ </Toolbar>
170
+ </AppBar>
171
+ );
172
+ }
173
+ ```
174
+
175
+ ### 2. Login Component (Optional)
176
+
177
+ Ready-to-use login component with Material-UI:
178
+
179
+ ```tsx
180
+ import { LoginComponent } from '@nocios/crudify-ui';
181
+
182
+ function LoginPage() {
183
+ return <LoginComponent />;
184
+ }
185
+ ```
186
+
187
+ ### 3. Session Debug Info
188
+
189
+ For development, show detailed session information:
190
+
191
+ ```tsx
192
+ import { SessionDebugInfo } from '@nocios/crudify-ui';
193
+
194
+ function App() {
195
+ return (
196
+ <div>
197
+ <YourApp />
198
+ {process.env.NODE_ENV === 'development' && (
199
+ <SessionDebugInfo />
200
+ )}
201
+ </div>
202
+ );
203
+ }
204
+ ```
205
+
206
+ ### 4. Session Context Hook
207
+
208
+ Access session state from any component:
209
+
210
+ ```tsx
211
+ import { useSessionContext } from '@nocios/crudify-ui';
212
+
213
+ function MyComponent() {
214
+ const {
215
+ isAuthenticated,
216
+ isLoading,
217
+ tokens,
218
+ error,
219
+ login,
220
+ logout,
221
+ refreshTokens,
222
+ isExpiringSoon,
223
+ expiresIn
224
+ } = useSessionContext();
225
+
226
+ return (
227
+ <div>
228
+ {isExpiringSoon && (
229
+ <Alert>Token expires in {Math.round(expiresIn / 60000)} minutes</Alert>
230
+ )}
231
+ </div>
232
+ );
233
+ }
234
+ ```
235
+
236
+ ## Migration Checklist
237
+
238
+ - [ ] Update package versions to v1.2.0+
239
+ - [ ] Replace `CrudifyDataProvider` with `SessionProvider`
240
+ - [ ] Update login logic to use `useSessionContext`
241
+ - [ ] Replace manual auth checks with `ProtectedRoute`
242
+ - [ ] Test automatic token refresh functionality
243
+ - [ ] Test session restoration on page reload
244
+ - [ ] Update logout logic to use session context
245
+ - [ ] Remove manual token management code
246
+ - [ ] Test error handling for expired refresh tokens
247
+ - [ ] Add session debug info for development
248
+
249
+ ## Troubleshooting
250
+
251
+ ### Issue: "useSessionContext must be used within a SessionProvider"
252
+ **Solution:** Ensure your entire app is wrapped with `SessionProvider`
253
+
254
+ ### Issue: Session not restoring on page reload
255
+ **Solution:** Check that `autoRestore: true` is set in SessionProvider options
256
+
257
+ ### Issue: Automatic refresh not working
258
+ **Solution:** Verify that your backend returns refresh tokens in the login response
259
+
260
+ ### Issue: Tokens not persisting between sessions
261
+ **Solution:** Check browser storage permissions and ensure localStorage is enabled
262
+
263
+ ## Example Complete Implementation
264
+
265
+ ```tsx
266
+ // App.tsx
267
+ import React from 'react';
268
+ import { SessionProvider, ProtectedRoute } from '@nocios/crudify-ui';
269
+ import { LoginPage } from './pages/LoginPage';
270
+ import { Dashboard } from './pages/Dashboard';
271
+
272
+ function App() {
273
+ return (
274
+ <SessionProvider
275
+ options={{
276
+ autoRestore: true,
277
+ enableLogging: process.env.NODE_ENV === 'development',
278
+ onSessionExpired: () => {
279
+ console.log('Session expired - redirecting to login');
280
+ }
281
+ }}
282
+ >
283
+ <AppContent />
284
+ </SessionProvider>
285
+ );
286
+ }
287
+
288
+ function AppContent() {
289
+ return (
290
+ <div>
291
+ <LoginPage />
292
+
293
+ <ProtectedRoute fallback={null}>
294
+ <Dashboard />
295
+ </ProtectedRoute>
296
+ </div>
297
+ );
298
+ }
299
+
300
+ export default App;
301
+ ```
302
+
303
+ ## Need Help?
304
+
305
+ If you encounter issues during migration:
306
+
307
+ 1. Check the browser console for detailed error messages
308
+ 2. Enable logging with `enableLogging: true` in SessionProvider
309
+ 3. Use `<SessionDebugInfo />` to inspect session state
310
+ 4. Verify your backend is returning refresh tokens properly
311
+
312
+ The new Refresh Token Pattern provides enhanced security and better user experience with automatic session management.
package/dist/index.d.mts CHANGED
@@ -2,6 +2,7 @@ import crudify__default from '@nocios/crudify-browser';
2
2
  export * from '@nocios/crudify-browser';
3
3
  export { default as crudify } from '@nocios/crudify-browser';
4
4
  import React, { ReactNode } from 'react';
5
+ import * as react_jsx_runtime from 'react/jsx-runtime';
5
6
 
6
7
  type BoxScreenType = "login" | "signUp" | "forgotPassword" | "resetPassword" | "checkCode";
7
8
  interface CrudifyLoginConfig {
@@ -917,4 +918,236 @@ declare function parseJavaScriptError(error: unknown): ParsedError;
917
918
  */
918
919
  declare function handleCrudifyError(error: unknown): ParsedError[];
919
920
 
920
- export { type ApiError, type BoxScreenType, type CrudifyApiResponse, type CrudifyConfig, type CrudifyDataContextState, CrudifyDataProvider, type CrudifyDataProviderProps, CrudifyLogin, type CrudifyLoginConfig, type CrudifyLoginProps, type CrudifyLoginTranslations, type CrudifyTransactionResponse, type CrudifyUserData, ERROR_CODES, ERROR_SEVERITY_MAP, type ErrorCode, type ErrorSeverity, type ForgotPasswordRequest, type JWTPayload$1 as JWTPayload, type JwtPayload, type LoginRequest, type LoginResponse, type ParsedError, type ResetPasswordRequest, type ResolvedConfig, type TransactionResponseData, type UseCrudifyAuthReturn, type UseCrudifyConfigReturn, type UseCrudifyDataReturn, type UseCrudifyInstanceReturn, type UseCrudifyUserOptions, type UseCrudifyUserReturn, type UserLoginData, type UserProfile, UserProfileDisplay, type ValidateCodeRequest, type ValidationError, configurationManager, crudifyInitializer, decodeJwtSafely, getCookie, getCrudifyInstanceAsync, getCrudifyInstanceSync, getCurrentUserEmail, getErrorMessage, handleCrudifyError, isTokenExpired, parseApiError, parseJavaScriptError, parseTransactionError, secureLocalStorage, secureSessionStorage, tokenManager, useCrudifyAuth, useCrudifyConfig, useCrudifyData, useCrudifyDataContext, useCrudifyInstance, useCrudifyLogin, useCrudifyUser, useUserProfile };
921
+ type TokenData = {
922
+ accessToken: string;
923
+ refreshToken: string;
924
+ expiresAt: number;
925
+ refreshExpiresAt: number;
926
+ };
927
+ type StorageType = 'localStorage' | 'sessionStorage' | 'none';
928
+ declare class TokenStorage {
929
+ private static readonly TOKEN_KEY;
930
+ private static readonly ENCRYPTION_KEY;
931
+ private static storageType;
932
+ /**
933
+ * Configurar tipo de almacenamiento
934
+ */
935
+ static setStorageType(type: StorageType): void;
936
+ /**
937
+ * Verificar si el storage está disponible
938
+ */
939
+ private static isStorageAvailable;
940
+ /**
941
+ * Obtener instancia de storage
942
+ */
943
+ private static getStorage;
944
+ /**
945
+ * Encriptar datos sensibles
946
+ */
947
+ private static encrypt;
948
+ /**
949
+ * Desencriptar datos
950
+ */
951
+ private static decrypt;
952
+ /**
953
+ * Guardar tokens de forma segura
954
+ */
955
+ static saveTokens(tokens: TokenData): void;
956
+ /**
957
+ * Obtener tokens guardados
958
+ */
959
+ static getTokens(): TokenData | null;
960
+ /**
961
+ * Limpiar tokens almacenados
962
+ */
963
+ static clearTokens(): void;
964
+ /**
965
+ * Verificar si hay tokens válidos guardados
966
+ */
967
+ static hasValidTokens(): boolean;
968
+ /**
969
+ * Obtener información de expiración
970
+ */
971
+ static getExpirationInfo(): {
972
+ accessExpired: boolean;
973
+ refreshExpired: boolean;
974
+ accessExpiresIn: number;
975
+ refreshExpiresIn: number;
976
+ } | null;
977
+ /**
978
+ * Actualizar solo el access token (después de refresh)
979
+ */
980
+ static updateAccessToken(newAccessToken: string, newExpiresAt: number): void;
981
+ }
982
+
983
+ type SessionConfig = {
984
+ storageType?: StorageType;
985
+ autoRestore?: boolean;
986
+ enableLogging?: boolean;
987
+ onSessionExpired?: () => void;
988
+ onSessionRestored?: (tokens: TokenData) => void;
989
+ onLoginSuccess?: (tokens: TokenData) => void;
990
+ onLogout?: () => void;
991
+ };
992
+ type LoginResult = {
993
+ success: boolean;
994
+ tokens?: TokenData;
995
+ error?: string;
996
+ };
997
+ declare class SessionManager {
998
+ private static instance;
999
+ private config;
1000
+ private initialized;
1001
+ private constructor();
1002
+ static getInstance(): SessionManager;
1003
+ /**
1004
+ * Inicializar el SessionManager
1005
+ */
1006
+ initialize(config?: SessionConfig): Promise<void>;
1007
+ /**
1008
+ * Login con persistencia automática
1009
+ */
1010
+ login(email: string, password: string): Promise<LoginResult>;
1011
+ /**
1012
+ * Logout con limpieza de tokens
1013
+ */
1014
+ logout(): Promise<void>;
1015
+ /**
1016
+ * Restaurar sesión desde storage
1017
+ */
1018
+ restoreSession(): Promise<boolean>;
1019
+ /**
1020
+ * Verificar si el usuario está autenticado
1021
+ */
1022
+ isAuthenticated(): boolean;
1023
+ /**
1024
+ * Obtener información de tokens actuales
1025
+ */
1026
+ getTokenInfo(): {
1027
+ isLoggedIn: boolean;
1028
+ crudifyTokens: {
1029
+ accessToken: string;
1030
+ refreshToken: string;
1031
+ expiresAt: number;
1032
+ refreshExpiresAt: number;
1033
+ isExpired: boolean;
1034
+ isRefreshExpired: boolean;
1035
+ };
1036
+ storageInfo: {
1037
+ accessExpired: boolean;
1038
+ refreshExpired: boolean;
1039
+ accessExpiresIn: number;
1040
+ refreshExpiresIn: number;
1041
+ } | null;
1042
+ hasValidTokens: boolean;
1043
+ };
1044
+ /**
1045
+ * Refrescar tokens manualmente
1046
+ */
1047
+ refreshTokens(): Promise<boolean>;
1048
+ /**
1049
+ * Configurar interceptor de respuesta para manejo automático de errores
1050
+ */
1051
+ setupResponseInterceptor(): void;
1052
+ /**
1053
+ * Limpiar sesión completamente
1054
+ */
1055
+ clearSession(): void;
1056
+ private log;
1057
+ private formatError;
1058
+ }
1059
+
1060
+ type SessionState = {
1061
+ isAuthenticated: boolean;
1062
+ isLoading: boolean;
1063
+ isInitialized: boolean;
1064
+ tokens: TokenData | null;
1065
+ error: string | null;
1066
+ };
1067
+ type UseSessionOptions = {
1068
+ autoRestore?: boolean;
1069
+ enableLogging?: boolean;
1070
+ onSessionExpired?: () => void;
1071
+ onSessionRestored?: (tokens: TokenData) => void;
1072
+ };
1073
+ declare function useSession(options?: UseSessionOptions): {
1074
+ login: (email: string, password: string) => Promise<LoginResult>;
1075
+ logout: () => Promise<void>;
1076
+ refreshTokens: () => Promise<boolean>;
1077
+ clearError: () => void;
1078
+ getTokenInfo: () => {
1079
+ isLoggedIn: boolean;
1080
+ crudifyTokens: {
1081
+ accessToken: string;
1082
+ refreshToken: string;
1083
+ expiresAt: number;
1084
+ refreshExpiresAt: number;
1085
+ isExpired: boolean;
1086
+ isRefreshExpired: boolean;
1087
+ };
1088
+ storageInfo: {
1089
+ accessExpired: boolean;
1090
+ refreshExpired: boolean;
1091
+ accessExpiresIn: number;
1092
+ refreshExpiresIn: number;
1093
+ } | null;
1094
+ hasValidTokens: boolean;
1095
+ };
1096
+ isExpiringSoon: boolean;
1097
+ expiresIn: number;
1098
+ refreshExpiresIn: number;
1099
+ isAuthenticated: boolean;
1100
+ isLoading: boolean;
1101
+ isInitialized: boolean;
1102
+ tokens: TokenData | null;
1103
+ error: string | null;
1104
+ };
1105
+
1106
+ type SessionContextType = {
1107
+ isAuthenticated: boolean;
1108
+ isLoading: boolean;
1109
+ isInitialized: boolean;
1110
+ tokens: TokenData | null;
1111
+ error: string | null;
1112
+ login: (email: string, password: string) => Promise<LoginResult>;
1113
+ logout: () => Promise<void>;
1114
+ refreshTokens: () => Promise<boolean>;
1115
+ clearError: () => void;
1116
+ getTokenInfo: () => any;
1117
+ isExpiringSoon: boolean;
1118
+ expiresIn: number;
1119
+ refreshExpiresIn: number;
1120
+ };
1121
+ type SessionProviderProps = {
1122
+ children: ReactNode;
1123
+ options?: UseSessionOptions;
1124
+ };
1125
+ /**
1126
+ * Provider de sesión para envolver la aplicación
1127
+ */
1128
+ declare function SessionProvider({ children, options }: SessionProviderProps): react_jsx_runtime.JSX.Element;
1129
+ /**
1130
+ * Hook para usar el contexto de sesión
1131
+ */
1132
+ declare function useSessionContext(): SessionContextType;
1133
+ /**
1134
+ * HOC para proteger rutas que requieren autenticación
1135
+ */
1136
+ type ProtectedRouteProps = {
1137
+ children: ReactNode;
1138
+ fallback?: ReactNode;
1139
+ redirectTo?: () => void;
1140
+ };
1141
+ declare function ProtectedRoute({ children, fallback, redirectTo }: ProtectedRouteProps): react_jsx_runtime.JSX.Element | null;
1142
+ /**
1143
+ * Componente para mostrar información de la sesión (debug)
1144
+ */
1145
+ declare function SessionDebugInfo(): react_jsx_runtime.JSX.Element;
1146
+
1147
+ declare function LoginComponent(): react_jsx_runtime.JSX.Element;
1148
+ /**
1149
+ * Componente simple de estado de sesión para mostrar en cualquier lugar
1150
+ */
1151
+ declare function SessionStatus(): react_jsx_runtime.JSX.Element;
1152
+
1153
+ export { type ApiError, type BoxScreenType, type CrudifyApiResponse, type CrudifyConfig, type CrudifyDataContextState, CrudifyDataProvider, type CrudifyDataProviderProps, CrudifyLogin, type CrudifyLoginConfig, type CrudifyLoginProps, type CrudifyLoginTranslations, type CrudifyTransactionResponse, type CrudifyUserData, ERROR_CODES, ERROR_SEVERITY_MAP, type ErrorCode, type ErrorSeverity, type ForgotPasswordRequest, type JWTPayload$1 as JWTPayload, type JwtPayload, LoginComponent, type LoginRequest, type LoginResponse, type LoginResult, type ParsedError, ProtectedRoute, type ProtectedRouteProps, type ResetPasswordRequest, type ResolvedConfig, type SessionConfig, SessionDebugInfo, SessionManager, SessionProvider, type SessionProviderProps, type SessionState, SessionStatus, type StorageType, type TokenData, TokenStorage, type TransactionResponseData, type UseCrudifyAuthReturn, type UseCrudifyConfigReturn, type UseCrudifyDataReturn, type UseCrudifyInstanceReturn, type UseCrudifyUserOptions, type UseCrudifyUserReturn, type UseSessionOptions, type UserLoginData, type UserProfile, UserProfileDisplay, type ValidateCodeRequest, type ValidationError, configurationManager, crudifyInitializer, decodeJwtSafely, getCookie, getCrudifyInstanceAsync, getCrudifyInstanceSync, getCurrentUserEmail, getErrorMessage, handleCrudifyError, isTokenExpired, parseApiError, parseJavaScriptError, parseTransactionError, secureLocalStorage, secureSessionStorage, tokenManager, useCrudifyAuth, useCrudifyConfig, useCrudifyData, useCrudifyDataContext, useCrudifyInstance, useCrudifyLogin, useCrudifyUser, useSession, useSessionContext, useUserProfile };