@leancodepl/kratos 8.4.0 → 8.5.1

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
@@ -1,7 +1,371 @@
1
- # kratos
1
+ # @leancodepl/kratos
2
2
 
3
- This library was generated with [Nx](https://nx.dev).
3
+ React components and hooks for Ory Kratos authentication integration.
4
4
 
5
- ## Running unit tests
5
+ ## Features
6
6
 
7
- Run `nx test kratos` to execute the unit tests via [Jest](https://jestjs.io).
7
+ - **Complete auth flows** - Login, registration, recovery, verification, and settings flows
8
+ - **Ready-to-use components** - Login, registration, recovery, and settings cards
9
+ - **Session management** - Automatic token handling with RxJS observables
10
+ - **Customizable UI** - Override any component with your own implementation
11
+ - **Error handling** - Built-in validation and flow error management
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install @leancodepl/kratos
17
+ # or
18
+ yarn add @leancodepl/kratos
19
+ ```
20
+
21
+ ## API
22
+
23
+ ### `createKratosClient(configuration)`
24
+
25
+ Creates Ory Kratos FrontendApi client with axios and credentials configuration.
26
+
27
+ **Parameters:**
28
+
29
+ - `configuration: ConfigurationParameters` - Kratos client configuration parameters
30
+
31
+ **Returns:** Configured FrontendApi instance for Kratos operations
32
+
33
+ ### `useKratosContext()`
34
+
35
+ Access Kratos context data with components and error handling.
36
+
37
+ **Returns:** Kratos context data with initialized components
38
+
39
+ **Throws:** Error when Kratos context components are not initialized
40
+
41
+ ### `KratosContextProvider(components, useHandleFlowError, excludeScripts, children)`
42
+
43
+ Provides Kratos context to child components with customizable configuration.
44
+
45
+ **Parameters:**
46
+
47
+ - `components?: Partial<KratosComponents>` - Partial override of default Kratos UI components
48
+ - `useHandleFlowError?: UseHandleFlowError` - Custom error handler for authentication flows
49
+ - `excludeScripts?: boolean` - Whether to exclude script node execution
50
+ - `children?: ReactNode` - Child React components
51
+
52
+ **Returns:** JSX element providing Kratos context
53
+
54
+ ### `BaseSessionManager(authUrl, loginRoute)`
55
+
56
+ Manages Kratos session state with RxJS observables for authentication status.
57
+
58
+ **Parameters:**
59
+
60
+ - `authUrl: string` - Base URL for Kratos authentication endpoints
61
+ - `loginRoute: string` - Application route for login page
62
+
63
+ ### `useLoginFlow(kratosClient, returnTo, onLoggedIn, onSessionAlreadyAvailable, searchParams, updateSearchParams)`
64
+
65
+ Manages Kratos login flow state and form submission.
66
+
67
+ **Parameters:**
68
+
69
+ - `kratosClient: FrontendApi` - Configured Kratos FrontendApi client
70
+ - `returnTo?: string` - URL to redirect after successful login
71
+ - `onLoggedIn?: Function` - Callback executed when user successfully logs in
72
+ - `onSessionAlreadyAvailable?: Function` - Callback when session already exists
73
+ - `searchParams?: LoginSearchParams` - URL search parameters for flow state
74
+ - `updateSearchParams: Function` - Function to update URL search parameters
75
+
76
+ **Returns:** Object with current flow and submit function
77
+
78
+ ### `useRegistrationFlow(kratosClient, onSessionAlreadyAvailable, onContinueWith, searchParams, updateSearchParams)`
79
+
80
+ Manages Kratos registration flow state and form submission.
81
+
82
+ **Parameters:**
83
+
84
+ - `kratosClient: FrontendApi` - Configured Kratos FrontendApi client
85
+ - `onSessionAlreadyAvailable: Function` - Callback when session already exists
86
+ - `onContinueWith?: Function` - Optional callback for post-registration actions
87
+ - `searchParams?: Object` - URL search parameters for flow state
88
+ - `updateSearchParams: Function` - Function to update URL search parameters
89
+
90
+ **Returns:** Object with current flow, submit function, and registration status
91
+
92
+ ### `useRecoveryFlow(kratosClient, onSessionAlreadyAvailable, onContinueWith, searchParams, updateSearchParams)`
93
+
94
+ Manages Kratos account recovery flow state and form submission.
95
+
96
+ **Parameters:**
97
+
98
+ - `kratosClient: FrontendApi` - Configured Kratos FrontendApi client
99
+ - `onSessionAlreadyAvailable: Function` - Callback when session already exists
100
+ - `onContinueWith?: Function` - Optional callback for post-recovery actions
101
+ - `searchParams?: Object` - URL search parameters for flow state
102
+ - `updateSearchParams: Function` - Function to update URL search parameters
103
+
104
+ **Returns:** Object with current flow, submit function, and recovery status
105
+
106
+ ### `LoginCard(flow, onSubmit, className)`
107
+
108
+ Pre-built login card component for Kratos login flows.
109
+
110
+ **Parameters:**
111
+
112
+ - `flow: LoginFlow` - Kratos login flow object
113
+ - `onSubmit?: Function` - Form submission handler
114
+ - `className?: string` - Optional CSS class name
115
+
116
+ **Returns:** JSX element with login form
117
+
118
+ ### `RegistrationCard(flow, onSubmit, className)`
119
+
120
+ Pre-built registration card component for Kratos registration flows.
121
+
122
+ **Parameters:**
123
+
124
+ - `flow: RegistrationFlow` - Kratos registration flow object
125
+ - `onSubmit?: Function` - Form submission handler
126
+ - `className?: string` - Optional CSS class name
127
+
128
+ **Returns:** JSX element with registration form
129
+
130
+ ### `RecoveryCard(flow, onSubmit, className)`
131
+
132
+ Pre-built recovery card component for Kratos account recovery flows.
133
+
134
+ **Parameters:**
135
+
136
+ - `flow: RecoveryFlow` - Kratos recovery flow object
137
+ - `onSubmit?: Function` - Form submission handler
138
+ - `className?: string` - Optional CSS class name
139
+
140
+ **Returns:** JSX element with recovery form
141
+
142
+ ### `VerificationCard(flow, onSubmit, className)`
143
+
144
+ Pre-built verification card component for Kratos verification flows.
145
+
146
+ **Parameters:**
147
+
148
+ - `flow: VerificationFlow` - Kratos verification flow object
149
+ - `onSubmit?: Function` - Form submission handler
150
+ - `className?: string` - Optional CSS class name
151
+
152
+ **Returns:** JSX element with verification form
153
+
154
+ ### `useVerificationFlow(initialFlowId, kratosClient, onVerified, searchParams, updateSearchParams)`
155
+
156
+ Manages Kratos email/phone verification flow state and form submission.
157
+
158
+ **Parameters:**
159
+
160
+ - `initialFlowId?: string` - Optional initial flow ID to start with
161
+ - `kratosClient: FrontendApi` - Configured Kratos FrontendApi client
162
+ - `onVerified: Function` - Callback executed when verification is successful
163
+ - `searchParams?: Object` - URL search parameters for flow state
164
+ - `updateSearchParams: Function` - Function to update URL search parameters
165
+
166
+ **Returns:** Object with current flow, submit function, and reset function
167
+
168
+ ### `useSettingsFlow(kratosClient, params, onContinueWith, searchParams, updateSearchParams)`
169
+
170
+ Manages Kratos user settings flow state and form submission.
171
+
172
+ **Parameters:**
173
+
174
+ - `kratosClient: FrontendApi` - Configured Kratos FrontendApi client
175
+ - `params?: Object` - Optional Axios request parameters
176
+ - `onContinueWith?: Function` - Optional callback for post-settings actions
177
+ - `searchParams?: Object` - URL search parameters for flow state
178
+ - `updateSearchParams: Function` - Function to update URL search parameters
179
+
180
+ **Returns:** Object with current flow and submit function
181
+
182
+ ### `useReauthenticationFlow(kratosClient, onReauthenticated)`
183
+
184
+ Manages Kratos reauthentication flow for elevated security operations.
185
+
186
+ **Parameters:**
187
+
188
+ - `kratosClient: FrontendApi` - Configured Kratos FrontendApi client
189
+ - `onReauthenticated: Function` - Callback executed with session after successful reauthentication
190
+
191
+ **Returns:** Object with current flow and submit function
192
+
193
+ ### `useLogoutFlow(kratosClient, returnTo, onLoggedOut)`
194
+
195
+ Manages Kratos user logout flow with callback support.
196
+
197
+ **Parameters:**
198
+
199
+ - `kratosClient: FrontendApi` - Configured Kratos FrontendApi client
200
+ - `returnTo?: string` - Optional URL to redirect after logout
201
+ - `onLoggedOut?: Function` - Optional callback executed after successful logout
202
+
203
+ **Returns:** Object with logout function
204
+
205
+ ### `UserSettingsCard(flow, flowType, onSubmit, className)`
206
+
207
+ Pre-built settings card component for Kratos settings flows.
208
+
209
+ **Parameters:**
210
+
211
+ - `flow: SettingsFlow` - Kratos settings flow object
212
+ - `flowType: UserSettingsFlowType` - Type of settings flow to render
213
+ - `onSubmit?: Function` - Form submission handler
214
+ - `className?: string` - Optional CSS class name
215
+
216
+ **Returns:** JSX element with settings form or null if flow type unavailable
217
+
218
+ ## Usage Examples
219
+
220
+ ### Basic Setup
221
+
222
+ ```typescript
223
+ import { createKratosClient, KratosContextProvider } from '@leancodepl/kratos';
224
+
225
+ const kratosClient = createKratosClient({
226
+ basePath: 'https://auth.example.com'
227
+ });
228
+
229
+ function App() {
230
+ return (
231
+ <KratosContextProvider>
232
+ <Routes>
233
+ <Route path="/login" element={<LoginPage />} />
234
+ <Route path="/register" element={<RegisterPage />} />
235
+ </Routes>
236
+ </KratosContextProvider>
237
+ );
238
+ }
239
+ ```
240
+
241
+ ### Login Flow
242
+
243
+ ```typescript
244
+ import { useLoginFlow, LoginCard } from '@leancodepl/kratos';
245
+ import { useSearchParams, useNavigate } from 'react-router-dom';
246
+
247
+ function LoginPage() {
248
+ const [searchParams, setSearchParams] = useSearchParams();
249
+ const navigate = useNavigate();
250
+
251
+ const { flow, submit } = useLoginFlow({
252
+ kratosClient,
253
+ onLoggedIn: (session) => navigate('/dashboard'),
254
+ searchParams: Object.fromEntries(searchParams),
255
+ updateSearchParams: (params) => setSearchParams(params)
256
+ });
257
+
258
+ if (!flow) return <div>Loading...</div>;
259
+
260
+ return <LoginCard flow={flow} onSubmit={submit} />;
261
+ }
262
+ ```
263
+
264
+ ### Session Management
265
+
266
+ ```typescript
267
+ import { BaseSessionManager } from "@leancodepl/kratos"
268
+ import { useEffect, useState } from "react"
269
+
270
+ const sessionManager = new BaseSessionManager("https://auth.example.com", "/login")
271
+
272
+ function useAuth() {
273
+ const [isLoggedIn, setIsLoggedIn] = useState(false)
274
+ const [userId, setUserId] = useState<string>()
275
+
276
+ useEffect(() => {
277
+ const subscription = sessionManager.isLoggedIn.subscribe(setIsLoggedIn)
278
+ const userSub = sessionManager.userId$.subscribe(setUserId)
279
+
280
+ return () => {
281
+ subscription.unsubscribe()
282
+ userSub.unsubscribe()
283
+ }
284
+ }, [])
285
+
286
+ return { isLoggedIn, userId }
287
+ }
288
+ ```
289
+
290
+ ### Custom Components
291
+
292
+ ```typescript
293
+ import { KratosContextProvider, useKratosContext } from '@leancodepl/kratos';
294
+
295
+ const customComponents = {
296
+ InputComponent: ({ node, attributes }) => (
297
+ <input
298
+ className="custom-input"
299
+ {...attributes}
300
+ value={node.attributes.value}
301
+ />
302
+ ),
303
+ ButtonComponent: ({ node, attributes }) => (
304
+ <button className="custom-button" {...attributes}>
305
+ {node.meta.label}
306
+ </button>
307
+ )
308
+ };
309
+
310
+ function App() {
311
+ return (
312
+ <KratosContextProvider components={customComponents}>
313
+ <LoginForm />
314
+ </KratosContextProvider>
315
+ );
316
+ }
317
+ ```
318
+
319
+ ### Registration Flow
320
+
321
+ ```typescript
322
+ import { useRegistrationFlow, RegistrationCard } from '@leancodepl/kratos';
323
+
324
+ function RegisterPage() {
325
+ const [searchParams, setSearchParams] = useSearchParams();
326
+ const navigate = useNavigate();
327
+
328
+ const { flow, submit } = useRegistrationFlow({
329
+ kratosClient,
330
+ onRegistrationSuccess: () => navigate('/welcome'),
331
+ searchParams: Object.fromEntries(searchParams),
332
+ updateSearchParams: (params) => setSearchParams(params)
333
+ });
334
+
335
+ if (!flow) return <div>Loading...</div>;
336
+
337
+ return (
338
+ <div>
339
+ <h1>Create Account</h1>
340
+ <RegistrationCard flow={flow} onSubmit={submit} />
341
+ </div>
342
+ );
343
+ }
344
+ ```
345
+
346
+ ### Error Handling
347
+
348
+ ```typescript
349
+ import { useHandleFlowError } from '@leancodepl/kratos';
350
+
351
+ function useCustomErrorHandler() {
352
+ return useHandleFlowError({
353
+ onUnauthenticated: () => navigate('/login'),
354
+ onValidationError: (error) => {
355
+ console.error('Validation failed:', error);
356
+ toast.error('Please check your input');
357
+ },
358
+ resetFlow: () => setFlow(undefined)
359
+ });
360
+ }
361
+
362
+ function AppWithErrorHandling() {
363
+ const customErrorHandler = useCustomErrorHandler();
364
+
365
+ return (
366
+ <KratosContextProvider useHandleFlowError={customErrorHandler}>
367
+ <App />
368
+ </KratosContextProvider>
369
+ );
370
+ }
371
+ ```