@teamhanko/hanko-frontend-sdk 1.5.2 → 2.1.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.
- package/README.md +453 -97
- package/dist/Hanko.d.ts +57 -29
- package/dist/index.d.ts +16 -9
- package/dist/lib/Cookie.d.ts +2 -2
- package/dist/lib/Dto.d.ts +11 -184
- package/dist/lib/client/HttpClient.d.ts +7 -9
- package/dist/lib/client/SessionClient.d.ts +0 -11
- package/dist/lib/client/UserClient.d.ts +1 -35
- package/dist/lib/events/CustomEvents.d.ts +25 -0
- package/dist/lib/events/Dispatcher.d.ts +9 -1
- package/dist/lib/events/Listener.d.ts +3 -1
- package/dist/lib/events/Relay.d.ts +3 -3
- package/dist/lib/flow-api/State.d.ts +192 -62
- package/dist/lib/flow-api/WebauthnManager.d.ts +47 -0
- package/dist/lib/flow-api/auto-steps.d.ts +2 -0
- package/dist/lib/flow-api/passkey-autofill-activation.d.ts +2 -0
- package/dist/lib/flow-api/types/action.d.ts +4 -2
- package/dist/lib/flow-api/types/flow.d.ts +25 -0
- package/dist/lib/flow-api/types/{error.d.ts → flowError.d.ts} +1 -2
- package/dist/lib/flow-api/types/input.d.ts +6 -4
- package/dist/lib/flow-api/types/payload.d.ts +5 -0
- package/dist/lib/flow-api/types/{state-handling.d.ts → state.d.ts} +0 -7
- package/dist/sdk.cjs +1 -1
- package/dist/sdk.cjs.map +1 -1
- package/dist/sdk.modern.js +1 -1
- package/dist/sdk.modern.js.map +1 -1
- package/dist/sdk.module.js +1 -1
- package/dist/sdk.module.js.map +1 -1
- package/dist/sdk.umd.js +1 -1
- package/dist/sdk.umd.js.map +1 -1
- package/package.json +1 -1
- package/dist/lib/client/EmailClient.d.ts +0 -58
- package/dist/lib/client/EnterpriseClient.d.ts +0 -41
- package/dist/lib/client/ThirdPartyClient.d.ts +0 -28
- package/dist/lib/client/TokenClient.d.ts +0 -21
- package/dist/lib/flow-api/BrowserFlowStorage.d.ts +0 -6
- package/dist/lib/flow-api/Flow.d.ts +0 -41
- package/dist/lib/state/State.d.ts +0 -50
package/README.md
CHANGED
|
@@ -3,6 +3,32 @@
|
|
|
3
3
|
This package utilizes the [Hanko API](https://github.com/teamhanko/hanko/blob/main/backend/README.md) to provide
|
|
4
4
|
functionality that allows an easier UI integration. It is meant for use in browsers only.
|
|
5
5
|
|
|
6
|
+
- [Installation](#installation)
|
|
7
|
+
- [Usage](#usage)
|
|
8
|
+
- [Options](#options)
|
|
9
|
+
- [Session Events](#session-events)
|
|
10
|
+
- [Session Management](#session-management)
|
|
11
|
+
- [Getting the User Object](#getting-the-user-object)
|
|
12
|
+
- [Validating a Session](#validating-a-session)
|
|
13
|
+
- [Getting the Session Token](#getting-the-session-token)
|
|
14
|
+
- [Logging out a User](#logging-out-a-user)
|
|
15
|
+
- [Translation of Outgoing Emails](#translation-of-outgoing-emails)
|
|
16
|
+
- [Custom Session Claim Type Safety](#custom-session-claim-type-safety)
|
|
17
|
+
- [FlowAPI](#flowapi)
|
|
18
|
+
- [Initializing a New Flow](#initializing-a-new-flow)
|
|
19
|
+
- [Understanding the State Object](#understanding-the-state-object)
|
|
20
|
+
- [Action Availability](#action-availability)
|
|
21
|
+
- [Accessing Action Inputs](#accessing-action-inputs)
|
|
22
|
+
- [Running an Action](#running-an-action)
|
|
23
|
+
- [Event Handlers](#event-handlers)
|
|
24
|
+
- [Controlling the AfterStateChanged Event](#controlling-the-afterstatechanged-event)
|
|
25
|
+
- [Auto-Steps](#auto-steps)
|
|
26
|
+
- [Error Handling](#error-handling)
|
|
27
|
+
- [Caching Flow State](#caching-flow-state)
|
|
28
|
+
- [Bugs](#bugs)
|
|
29
|
+
- [Documentation](#documentation)
|
|
30
|
+
- [License](#license)
|
|
31
|
+
|
|
6
32
|
## Installation
|
|
7
33
|
|
|
8
34
|
```shell
|
|
@@ -53,103 +79,7 @@ const defaultOptions = {
|
|
|
53
79
|
const hanko = new Hanko("http://localhost:3000", defaultOptions);
|
|
54
80
|
```
|
|
55
81
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
To see the latest documentation, please click [here](https://teamhanko.github.io/hanko/jsdoc/hanko-frontend-sdk/).
|
|
59
|
-
|
|
60
|
-
## Exports
|
|
61
|
-
|
|
62
|
-
### SDK
|
|
63
|
-
|
|
64
|
-
- `Hanko` - A class that bundles all functionalities.
|
|
65
|
-
|
|
66
|
-
### Client Classes
|
|
67
|
-
|
|
68
|
-
- `UserClient` - A class to manage users.
|
|
69
|
-
- `ThirdPartyClient` - A class to handle social logins.
|
|
70
|
-
- `TokenClient` - A class that handles the exchange of one time tokens for session JWTs.
|
|
71
|
-
|
|
72
|
-
### Utility Classes
|
|
73
|
-
|
|
74
|
-
- `WebauthnSupport` - A class to check the browser's WebAuthn support.
|
|
75
|
-
|
|
76
|
-
### DTO Interfaces
|
|
77
|
-
|
|
78
|
-
- `PasswordConfig`
|
|
79
|
-
- `EmailConfig`
|
|
80
|
-
- `AccountConfig`
|
|
81
|
-
- `Config`
|
|
82
|
-
- `WebauthnFinalized`
|
|
83
|
-
- `TokenFinalized`
|
|
84
|
-
- `UserInfo`
|
|
85
|
-
- `Me`
|
|
86
|
-
- `Credential`
|
|
87
|
-
- `User`
|
|
88
|
-
- `UserCreated`
|
|
89
|
-
- `Passcode`
|
|
90
|
-
- `WebauthnTransports`
|
|
91
|
-
- `Attestation`
|
|
92
|
-
- `Email`
|
|
93
|
-
- `Emails`
|
|
94
|
-
- `WebauthnCredential`
|
|
95
|
-
- `WebauthnCredentials`
|
|
96
|
-
- `Identity`
|
|
97
|
-
|
|
98
|
-
### Event Interfaces
|
|
99
|
-
|
|
100
|
-
- `SessionDetail`
|
|
101
|
-
|
|
102
|
-
### Event Types
|
|
103
|
-
|
|
104
|
-
- `CustomEventWithDetail`
|
|
105
|
-
- `sessionCreatedType`
|
|
106
|
-
- `sessionExpiredType`
|
|
107
|
-
- `userLoggedOutType`
|
|
108
|
-
- `userDeletedType`
|
|
109
|
-
|
|
110
|
-
### Error Classes
|
|
111
|
-
|
|
112
|
-
- `HankoError`
|
|
113
|
-
- `TechnicalError`
|
|
114
|
-
- `ConflictError`
|
|
115
|
-
- `RequestTimeoutError`
|
|
116
|
-
- `WebauthnRequestCancelledError`
|
|
117
|
-
- `InvalidPasswordError`
|
|
118
|
-
- `InvalidPasscodeError`
|
|
119
|
-
- `InvalidWebauthnCredentialError`
|
|
120
|
-
- `PasscodeExpiredError`
|
|
121
|
-
- `MaxNumOfPasscodeAttemptsReachedError`
|
|
122
|
-
- `NotFoundError`
|
|
123
|
-
- `TooManyRequestsError`
|
|
124
|
-
- `UnauthorizedError`
|
|
125
|
-
|
|
126
|
-
## Examples
|
|
127
|
-
|
|
128
|
-
### Get the current user / Validate the JWT against the Hanko API
|
|
129
|
-
|
|
130
|
-
The Hanko API issues a JWT when a user logs in. For certain actions, like obtaining the user object, a valid JWT is
|
|
131
|
-
required. The following example shows how to get the user object of the current user, or to identify that the user is
|
|
132
|
-
not logged in:
|
|
133
|
-
|
|
134
|
-
```typescript
|
|
135
|
-
import { Hanko, UnauthorizedError } from "@teamhanko/hanko-frontend-sdk"
|
|
136
|
-
|
|
137
|
-
const hanko = new Hanko("https://[HANKO_API_URL]")
|
|
138
|
-
|
|
139
|
-
try {
|
|
140
|
-
const user = await hanko.user.getCurrent()
|
|
141
|
-
|
|
142
|
-
// A valid JWT is in place so that the user object was able to be fetched.
|
|
143
|
-
} catch (e) {
|
|
144
|
-
if (e instanceof UnauthorizedError) {
|
|
145
|
-
// Display an error or prompt the user to login again. After a successful call to `hanko.webauthn.login()`,
|
|
146
|
-
// `hanko.password.login()` or `hanko.passcode.finalize()` a JWT will be issued and `hanko.user.getCurrent()`
|
|
147
|
-
// would succeed.
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
```
|
|
151
|
-
|
|
152
|
-
### Custom Events
|
|
82
|
+
### Session Events
|
|
153
83
|
|
|
154
84
|
You can bind callback functions to different custom events. The callback function will be called when the event happens
|
|
155
85
|
and an object will be passed in, containing event details. The event binding works as follows:
|
|
@@ -208,6 +138,111 @@ hanko.onUserDeleted(() => {
|
|
|
208
138
|
|
|
209
139
|
Please Take a look into the [docs](https://teamhanko.github.io/hanko/jsdoc/hanko-frontend-sdk/) for more details.
|
|
210
140
|
|
|
141
|
+
### Session Management
|
|
142
|
+
|
|
143
|
+
The SDK provides methods to manage user sessions and retrieve user information.
|
|
144
|
+
|
|
145
|
+
#### Getting the User Object
|
|
146
|
+
|
|
147
|
+
Fetches the current user's profile information.
|
|
148
|
+
|
|
149
|
+
- **Returns**: A `User` object containing the user’s profile details. The object includes:
|
|
150
|
+
- `user_id`: A unique string identifier for the user.
|
|
151
|
+
- `passkeys`: An optional array of WebAuthn credentials (passkey-based authentication).
|
|
152
|
+
- `security_keys`: An optional array of WebAuthn credentials (security key-based authentication).
|
|
153
|
+
- `mfa_config`: An optional configuration object for multi-factor authentication settings.
|
|
154
|
+
- `emails`: An optional array of email objects (e.g., `{ address: string, is_primary: boolean, is_verified: boolean }`).
|
|
155
|
+
- `username`: An optional username object (e.g., `{ id: string, username: string }`).
|
|
156
|
+
- `created_at`: A string timestamp (ISO 8601) of when the user was created.
|
|
157
|
+
- `updated_at`: A string timestamp (ISO 8601) of when the user was last updated.
|
|
158
|
+
- **Errors**: `UnauthorizedError` (invalid or expired session), `TechnicalError` (server or network issues).
|
|
159
|
+
|
|
160
|
+
```typescript
|
|
161
|
+
try {
|
|
162
|
+
const user = await hanko.getUser();
|
|
163
|
+
console.log("User profile:", user);
|
|
164
|
+
// Example output:
|
|
165
|
+
// {
|
|
166
|
+
// user_id: "123e4567-e89b-12d3-a456-426614174000",
|
|
167
|
+
// emails: [{ address: "user@example.com", is_primary: true, is_verified: true }],
|
|
168
|
+
// username: { id: "f2882293-3c39-451d-a7cb-4cf3375e0c66", username: "johndoe" },
|
|
169
|
+
// created_at: "2025-01-01T10:00:00Z",
|
|
170
|
+
// updated_at: "2025-04-01T12:00:00Z"
|
|
171
|
+
// }
|
|
172
|
+
} catch (error) {
|
|
173
|
+
console.error("Failed to fetch user profile:", error);
|
|
174
|
+
// Handle UnauthorizedError or TechnicalError
|
|
175
|
+
}
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
#### Validating a Session
|
|
179
|
+
|
|
180
|
+
Checks the validity of the current session.
|
|
181
|
+
|
|
182
|
+
- **Returns**: A SessionCheckResponse object containing:
|
|
183
|
+
- `is_valid`: A boolean indicating whether the session is valid.
|
|
184
|
+
- `claims`: An optional object with session details, including:
|
|
185
|
+
- `subject`: The user ID or session identifier.
|
|
186
|
+
- `session_id`: The unique session identifier.
|
|
187
|
+
- `expiration`: A string timestamp (ISO 8601) when the session expires.
|
|
188
|
+
- `email`: An optional object with email details (e.g., `{ address: string, is_primary: boolean, is_verified: boolean }`).
|
|
189
|
+
- `username`: An optional string with the user’s username.
|
|
190
|
+
- `issued_at`, `audience`, `issuer`: Optional metadata about the session token.
|
|
191
|
+
- Custom claims (defined by the application).
|
|
192
|
+
- **Errors**: TechnicalError (server or network issues).
|
|
193
|
+
|
|
194
|
+
```typescript
|
|
195
|
+
try {
|
|
196
|
+
const sessionStatus = await hanko.validateSession();
|
|
197
|
+
console.log("Session status:", sessionStatus);
|
|
198
|
+
// Example output:
|
|
199
|
+
// {
|
|
200
|
+
// is_valid: true,
|
|
201
|
+
// claims: {
|
|
202
|
+
// subject: "123e4567-e89b-12d3-a456-426614174000",
|
|
203
|
+
// session_id: "789abc",
|
|
204
|
+
// expiration: "2025-04-25T12:00:00Z",
|
|
205
|
+
// email: { address: "user@example.com", is_primary: true, is_verified: true },
|
|
206
|
+
// custom_field: "value"
|
|
207
|
+
// }
|
|
208
|
+
// }
|
|
209
|
+
} catch (error) {
|
|
210
|
+
console.error("Failed to validate session:", error);
|
|
211
|
+
// Handle TechnicalError
|
|
212
|
+
}
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
#### Getting the Session Token
|
|
216
|
+
|
|
217
|
+
Retrieves the current session token from the authentication cookie.
|
|
218
|
+
|
|
219
|
+
- **Returns**: A string containing the JWT session token or `null` if no session exists.
|
|
220
|
+
- **Note**: This method does not throw errors; check for `null` to handle missing sessions.
|
|
221
|
+
|
|
222
|
+
```typescript
|
|
223
|
+
const token = hanko.getSessionToken();
|
|
224
|
+
console.log("Session token:", token);
|
|
225
|
+
// Example output: "eyJhbGciOiJIUzI1NiIs..."
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
#### Logging out a User
|
|
229
|
+
|
|
230
|
+
Logs out the current user by invalidating the session.
|
|
231
|
+
|
|
232
|
+
- **Returns**: A promise that resolves with no value on successful logout or throws an error.
|
|
233
|
+
- **Errors**: `TechnicalError` (server or network issues).
|
|
234
|
+
- **Note**: If no session exists, the method resolves without error.
|
|
235
|
+
|
|
236
|
+
```typescript
|
|
237
|
+
try {
|
|
238
|
+
await hanko.logout();
|
|
239
|
+
console.log("User logged out");
|
|
240
|
+
} catch (error) {
|
|
241
|
+
console.error("Failed to fetch user logout:", error);
|
|
242
|
+
// Handle TechnicalError
|
|
243
|
+
}
|
|
244
|
+
```
|
|
245
|
+
|
|
211
246
|
### Translation of outgoing emails
|
|
212
247
|
|
|
213
248
|
If you use the main `Hanko` client provided by the Frontend SDK, you can use the `lang` parameter in the options when
|
|
@@ -216,10 +251,331 @@ language to use for outgoing emails. If you have disabled email delivery through
|
|
|
216
251
|
`email.send` event, the value for the `lang` parameter is reflected in the JWT payload of the token contained in the
|
|
217
252
|
webhook request in the "Language" claim.
|
|
218
253
|
|
|
254
|
+
### Custom session claim type safety
|
|
255
|
+
|
|
256
|
+
The Hanko backend allows you to define custom claims that are added to issued session JWTs
|
|
257
|
+
(see [here](https://github.com/teamhanko/hanko/blob/main/backend/README.md#session-jwt-templates) for more info).
|
|
258
|
+
|
|
259
|
+
To allow for IDE autocompletion and to maintain type safety for your custom claims:
|
|
260
|
+
|
|
261
|
+
1. Create a TypeScript definition file (`*.d.ts`) in your project (alternatively, modify an existing one).
|
|
262
|
+
2. Import the `Claims` type from the frontend SDK.
|
|
263
|
+
3. Declare a custom type that extends the `Claims` type.
|
|
264
|
+
4. Add your custom claims to your custom type.
|
|
265
|
+
|
|
266
|
+
```ts
|
|
267
|
+
import type { Claims } from "@teamhanko/hanko-frontend-sdk" // 2.
|
|
268
|
+
// import type { Claims } from "@teamhanko/elements" // alternatively, if you use Hanko Elements, which
|
|
269
|
+
// re-exports most SDK types
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
type CustomClaims = Claims<{ // 3.
|
|
273
|
+
custom_claim?: string // 4.
|
|
274
|
+
}>;
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
5. Use your custom type when accessing claims, e.g. in session details received in event callbacks or when accessing
|
|
278
|
+
claims in responses from session validation
|
|
279
|
+
[endpoints](https://docs.hanko.io/api-reference/public/session-management/validate-a-session):
|
|
280
|
+
|
|
281
|
+
```ts
|
|
282
|
+
import type { CustomClaims } from "..."; // path to your type declaration file
|
|
283
|
+
|
|
284
|
+
hanko.onSessionCreated((sessionDetail) => {
|
|
285
|
+
const claims = sessionDetail.claims as CustomClaims;
|
|
286
|
+
console.info("My custom claim:", claims.custom_claim);
|
|
287
|
+
});
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
```ts
|
|
291
|
+
import type { CustomClaims } from "..."; // path to your type declaration file
|
|
292
|
+
|
|
293
|
+
async function session() {
|
|
294
|
+
const session = await hanko.validateSession();
|
|
295
|
+
const claims = session.claims as CustomClaims;
|
|
296
|
+
console.info("My custom claim:", claims.custom_claim);
|
|
297
|
+
};
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
## FlowAPI
|
|
301
|
+
|
|
302
|
+
The SDK offers a TypeScript-based interface for managing authentication and profile flows with Hanko, enabling the
|
|
303
|
+
development of custom frontends with the Hanko FlowAPI. It handles state transitions, action execution, input
|
|
304
|
+
validation, and event dispatching, while also providing built-in support for auto-stepping and passkey autofill.
|
|
305
|
+
This guide explores its core functionality and usage patterns.
|
|
306
|
+
|
|
307
|
+
### Initializing a New Flow
|
|
308
|
+
|
|
309
|
+
Start a new authentication or profile flow using the `createState` method on a Hanko instance. Options allow you to control
|
|
310
|
+
event dispatching and auto-step behavior.
|
|
311
|
+
|
|
312
|
+
```typescript
|
|
313
|
+
const state = await hanko.createState("login", {
|
|
314
|
+
dispatchAfterStateChangeEvent: true,
|
|
315
|
+
excludeAutoSteps: [],
|
|
316
|
+
loadFromCache: true,
|
|
317
|
+
cacheKey: "hanko-flow-state",
|
|
318
|
+
});
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
#### Parameters
|
|
322
|
+
|
|
323
|
+
- **flowName**: The name of the flow (e.g., "login", "register" or "profile").
|
|
324
|
+
- **options**:
|
|
325
|
+
- **dispatchAfterStateChangeEvent**: `boolean` - Whether to dispatch the onAfterStateChange event after state changes (default: true).
|
|
326
|
+
- **excludeAutoSteps**: `AutoStepExclusion` - Array of state names or "all" to skip specific or all auto-steps (default: null).
|
|
327
|
+
- **loadFromCache**: `boolean` - Whether to attempt loading a cached state from localStorage (default: true).
|
|
328
|
+
- **cacheKey**: `string` - The key used for localStorage caching (default: "hanko-flow-state").
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
### Understanding the State Object
|
|
332
|
+
|
|
333
|
+
The `state` object represents the current step in the flow. It contains properties and methods to interact with the flow.
|
|
334
|
+
|
|
335
|
+
#### Structure
|
|
336
|
+
|
|
337
|
+
- **name**: `StateName` - The current state’s name (e.g., "login_init", "login_password", "success").
|
|
338
|
+
- **flowName**: `FlowName` - The name of the flow (e.g., "login").
|
|
339
|
+
- **error**: `Error | undefined` - An error object if an action or request fails (e.g., invalid input, network error).
|
|
340
|
+
- **payload**: `Payloads[StateName] | undefined` - State-specific data returned by the API.
|
|
341
|
+
- **actions**: `ActionMap<StateName>` - An object mapping action names to Action instances.
|
|
342
|
+
- **csrfToken**: `string` - CSRF token for secure requests.
|
|
343
|
+
- **status**: `number` - HTTP status code of the last response.
|
|
344
|
+
- **invokedAction**: `ActionInfo | undefined` - Details of the last action run on this state, if any.
|
|
345
|
+
- **previousAction**: `ActionInfo | undefined` - Details of the action that led to this state, if any.
|
|
346
|
+
- **isCached**: `boolean` - Whether the state was loaded from localStorage.
|
|
347
|
+
- **cacheKey**: `string` - The key used for localStorage caching.
|
|
348
|
+
- **excludeAutoSteps**: `AutoStepExclusion` - An array of `StateNames` excluded from auto-stepping.
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
### Action Availability
|
|
352
|
+
|
|
353
|
+
Actions can be enabled or disabled based on the backend configuration or the user's state and properties. You can check
|
|
354
|
+
whether a specific action is enabled by accessing its `enabled` property:
|
|
355
|
+
|
|
356
|
+
```typescript
|
|
357
|
+
if (state.actions.example_action.enabled) {
|
|
358
|
+
await state.actions.example_action.run();
|
|
359
|
+
} else {
|
|
360
|
+
console.log("Action is disabled");
|
|
361
|
+
}
|
|
362
|
+
```
|
|
363
|
+
|
|
364
|
+
### Accessing Action Inputs
|
|
365
|
+
|
|
366
|
+
Each action in `state.actions` has an `inputs` property defining expected input fields.
|
|
367
|
+
|
|
368
|
+
```typescript
|
|
369
|
+
console.log(state.actions.continue_with_login_identifier.inputs);
|
|
370
|
+
// Example output:
|
|
371
|
+
// {
|
|
372
|
+
// username: {
|
|
373
|
+
// required: true,
|
|
374
|
+
// type: "string",
|
|
375
|
+
// minLength: 3,
|
|
376
|
+
// maxLength: 20,
|
|
377
|
+
// description: "User’s login name"
|
|
378
|
+
// }
|
|
379
|
+
// }
|
|
380
|
+
```
|
|
381
|
+
|
|
382
|
+
### Running an Action
|
|
383
|
+
|
|
384
|
+
Actions transition the flow to a new state. Use the `run` method on an action, passing input values and optional configuration.
|
|
385
|
+
|
|
386
|
+
#### Basic Example with Type Narrowing
|
|
387
|
+
|
|
388
|
+
```typescript
|
|
389
|
+
if (state.name === "login_init") {
|
|
390
|
+
const newState = await state.actions.continue_with_login_identifier.run({
|
|
391
|
+
username: "user1",
|
|
392
|
+
});
|
|
393
|
+
// Triggers `onBeforeStateChange` and `onAfterStateChange` events
|
|
394
|
+
// `newState` is the next state in the flow (e.g., "login_password")
|
|
395
|
+
}
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
#### Additional Considerations
|
|
399
|
+
|
|
400
|
+
- **Type Narrowing**: Check `state.name` to ensure the action exists and inputs are valid for that state.
|
|
401
|
+
- **Events**: By default, `run` triggers `onBeforeStateChange` before the action and `onAfterStateChange` after the new state is loaded.
|
|
402
|
+
- **Validation Errors**: If the action fails due to invalid input (e.g., wrong format or length), `newState.error` will be set to "invalid_form_data", and specific errors will be attached to the related input fields (see "Error Handling" below).
|
|
403
|
+
|
|
404
|
+
### Event Handlers
|
|
405
|
+
|
|
406
|
+
The SDK dispatches events via the Hanko instance to track state changes.
|
|
407
|
+
|
|
408
|
+
#### `onBeforeStateChange`
|
|
409
|
+
|
|
410
|
+
Fires before an action is executed, useful for showing loading states.
|
|
411
|
+
|
|
412
|
+
```typescript
|
|
413
|
+
hanko.onBeforeStateChange(({ state }) => {
|
|
414
|
+
console.log("Action loading:", state.invokedAction);
|
|
415
|
+
});
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
#### `onAfterStateChange`
|
|
419
|
+
|
|
420
|
+
Fires after a new state is loaded, ideal for rendering UI or handling state-specific logic.
|
|
421
|
+
|
|
422
|
+
```typescript
|
|
423
|
+
hanko.onAfterStateChange(({ state }) => {
|
|
424
|
+
console.log("Action load finished:", state.invokedAction);
|
|
425
|
+
|
|
426
|
+
switch (state.name) {
|
|
427
|
+
case "login_init":
|
|
428
|
+
state.passkeyAutofillActivation(); // Special handler for passkey autofill; requires an <input> field on the page with `autocomplete="username webauthn"` (e.g., <input type="text" name="username" autocomplete="username webauthn" />) so the browser can suggest and autofill passkeys when the user interacts with it.
|
|
429
|
+
break;
|
|
430
|
+
case "login_password":
|
|
431
|
+
// Render password input UI
|
|
432
|
+
if (state.error) {
|
|
433
|
+
console.log("Error:", state.error); // e.g., "invalid_form_data"
|
|
434
|
+
}
|
|
435
|
+
break;
|
|
436
|
+
case "error":
|
|
437
|
+
// Handle network errors or 5xx responses
|
|
438
|
+
console.error("Flow error:", state.error);
|
|
439
|
+
break;
|
|
440
|
+
}
|
|
441
|
+
});
|
|
442
|
+
```
|
|
443
|
+
|
|
444
|
+
### Controlling the AfterStateChanged Event
|
|
445
|
+
|
|
446
|
+
You can disable the automatic `onAfterStateChange` event and dispatch it manually after custom logic.
|
|
447
|
+
|
|
448
|
+
```typescript
|
|
449
|
+
if (state.name === "login_init") {
|
|
450
|
+
const newState = await state.actions.continue_with_login_identifier.run(
|
|
451
|
+
{ username: "user1" },
|
|
452
|
+
{ dispatchAfterStateChangeEvent: false }, // Disable automatic dispatch
|
|
453
|
+
);
|
|
454
|
+
// Only `onBeforeStateChange` is triggered here
|
|
455
|
+
|
|
456
|
+
await doSomething(); // Your custom async logic
|
|
457
|
+
newState.dispatchAfterStateChangeEvent(); // Manually trigger the event
|
|
458
|
+
}
|
|
459
|
+
```
|
|
460
|
+
|
|
461
|
+
### Auto-Steps
|
|
462
|
+
|
|
463
|
+
Auto-steps automatically advance the flow for certain states, reducing manual intervention.
|
|
464
|
+
|
|
465
|
+
#### Supported States
|
|
466
|
+
|
|
467
|
+
- `preflight`
|
|
468
|
+
- `login_passkey`
|
|
469
|
+
- `onboarding_verify_passkey_attestation`
|
|
470
|
+
- `webauthn_credential_verification`
|
|
471
|
+
- `thirdparty`
|
|
472
|
+
- `success`
|
|
473
|
+
- `account_deleted`
|
|
474
|
+
|
|
475
|
+
#### Disabling Auto-Steps
|
|
476
|
+
|
|
477
|
+
Prevent auto-steps by specifying states in `excludeAutoSteps`:
|
|
478
|
+
|
|
479
|
+
```typescript
|
|
480
|
+
const state = await hanko.createState("login", {
|
|
481
|
+
excludeAutoSteps: ["success"], // Skip auto-step for "success"
|
|
482
|
+
});
|
|
483
|
+
```
|
|
484
|
+
|
|
485
|
+
#### Manual Auto-Step Execution
|
|
486
|
+
|
|
487
|
+
```typescript
|
|
488
|
+
hanko.onAfterStateChange(({ state }) => {
|
|
489
|
+
if (state.name === "success") {
|
|
490
|
+
console.log("Flow completed");
|
|
491
|
+
await state.autoStep();
|
|
492
|
+
}
|
|
493
|
+
});
|
|
494
|
+
```
|
|
495
|
+
|
|
496
|
+
### Error Handling
|
|
497
|
+
|
|
498
|
+
#### Input Errors
|
|
499
|
+
|
|
500
|
+
If an action fails due to invalid inputs:
|
|
501
|
+
|
|
502
|
+
```typescript
|
|
503
|
+
if (state.name === "login_password" && state.error === "invalid_form_data") {
|
|
504
|
+
const passwordError = state.actions.password_login.inputs.password.error;
|
|
505
|
+
console.log("Password error:", passwordError);
|
|
506
|
+
}
|
|
507
|
+
```
|
|
508
|
+
|
|
509
|
+
#### Network/API Errors
|
|
510
|
+
|
|
511
|
+
For network issues or `5xx` responses, the `error` state is entered with details in `state.error`.
|
|
512
|
+
|
|
513
|
+
```typescript
|
|
514
|
+
if (state.name === "error") {
|
|
515
|
+
console.error("Flow error:", state.error);
|
|
516
|
+
}
|
|
517
|
+
```
|
|
518
|
+
|
|
519
|
+
### Caching Flow State
|
|
520
|
+
|
|
521
|
+
Persist and recover flow state using `localStorage`.
|
|
522
|
+
|
|
523
|
+
#### Saving State
|
|
524
|
+
|
|
525
|
+
Save the current flow state to `localStorage` using `saveToLocalStorage()`.
|
|
526
|
+
|
|
527
|
+
```typescript
|
|
528
|
+
state.saveToLocalStorage(); // Stores under `state.cacheKey` (default: "hanko-flow-state")
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
Please note that the `localStorage` entry will be removed automatically when an action is invoked on the saved state.
|
|
532
|
+
|
|
533
|
+
#### Loading State
|
|
534
|
+
|
|
535
|
+
Recover a cached state or start a new flow:
|
|
536
|
+
|
|
537
|
+
```typescript
|
|
538
|
+
const state = await hanko.createState("login", {
|
|
539
|
+
loadFromCache: true, // Attempts to load from `cacheKey`
|
|
540
|
+
cacheKey: "hanko-flow-state",
|
|
541
|
+
});
|
|
542
|
+
```
|
|
543
|
+
|
|
544
|
+
#### Clearing State
|
|
545
|
+
|
|
546
|
+
Remove the cached state:
|
|
547
|
+
|
|
548
|
+
```typescript
|
|
549
|
+
state.removeFromLocalStorage(); // Deletes from `state.cacheKey`
|
|
550
|
+
```
|
|
551
|
+
|
|
552
|
+
#### Advanced Serialization
|
|
553
|
+
|
|
554
|
+
For custom persistence:
|
|
555
|
+
|
|
556
|
+
```typescript
|
|
557
|
+
import { State } from "@teamhanko/hanko-frontend-sdk";
|
|
558
|
+
|
|
559
|
+
const serialized = state.serialize(); // Returns a `SerializedState` object
|
|
560
|
+
// Store `serialized` in your storage system
|
|
561
|
+
|
|
562
|
+
// Later, deserialize it
|
|
563
|
+
const recoveredState = await State.deserialize(hanko, serialized, {
|
|
564
|
+
cacheKey: "custom-key",
|
|
565
|
+
});
|
|
566
|
+
```
|
|
567
|
+
|
|
568
|
+
This allows integration with other storage mechanisms.
|
|
569
|
+
|
|
570
|
+
|
|
219
571
|
## Bugs
|
|
220
572
|
|
|
221
573
|
Found a bug? Please report on our [GitHub](https://github.com/teamhanko/hanko/issues) page.
|
|
222
574
|
|
|
575
|
+
## Documentation
|
|
576
|
+
|
|
577
|
+
To see the latest documentation, please click [here](https://teamhanko.github.io/hanko/jsdoc/hanko-frontend-sdk/).
|
|
578
|
+
|
|
223
579
|
## License
|
|
224
580
|
|
|
225
581
|
The `hanko-frontend-sdk` project is licensed under the [MIT License](LICENSE).
|
package/dist/Hanko.d.ts
CHANGED
|
@@ -1,14 +1,11 @@
|
|
|
1
|
-
import { EnterpriseClient } from "./lib/client/EnterpriseClient";
|
|
2
|
-
import { UserClient } from "./lib/client/UserClient";
|
|
3
|
-
import { EmailClient } from "./lib/client/EmailClient";
|
|
4
|
-
import { ThirdPartyClient } from "./lib/client/ThirdPartyClient";
|
|
5
|
-
import { TokenClient } from "./lib/client/TokenClient";
|
|
6
1
|
import { Listener } from "./lib/events/Listener";
|
|
7
2
|
import { Relay } from "./lib/events/Relay";
|
|
8
3
|
import { CookieSameSite } from "./lib/Cookie";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
4
|
+
import { HttpClient, SessionTokenLocation } from "./lib/client/HttpClient";
|
|
5
|
+
import { FlowName } from "./lib/flow-api/types/flow";
|
|
6
|
+
import { StateCreateConfig } from "./lib/flow-api/State";
|
|
7
|
+
import { SessionCheckResponse } from "./lib/Dto";
|
|
8
|
+
import { User } from "./lib/flow-api/types/payload";
|
|
12
9
|
/**
|
|
13
10
|
* The options for the Hanko class
|
|
14
11
|
*
|
|
@@ -47,16 +44,11 @@ export interface HankoOptions {
|
|
|
47
44
|
* @param {HankoOptions=} options - The options that can be used
|
|
48
45
|
*/
|
|
49
46
|
declare class Hanko extends Listener {
|
|
50
|
-
|
|
51
|
-
user
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
token: TokenClient;
|
|
56
|
-
sessionClient: SessionClient;
|
|
57
|
-
session: Session;
|
|
58
|
-
relay: Relay;
|
|
59
|
-
flow: Flow;
|
|
47
|
+
private readonly session;
|
|
48
|
+
private readonly user;
|
|
49
|
+
private readonly cookie;
|
|
50
|
+
readonly client: HttpClient;
|
|
51
|
+
readonly relay: Relay;
|
|
60
52
|
constructor(api: string, options?: HankoOptions);
|
|
61
53
|
/**
|
|
62
54
|
* Sets the preferred language on the underlying sub-clients. The clients'
|
|
@@ -67,16 +59,52 @@ declare class Hanko extends Listener {
|
|
|
67
59
|
* @param lang {string} - The preferred language to convey to the API.
|
|
68
60
|
*/
|
|
69
61
|
setLang(lang: string): void;
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
62
|
+
/**
|
|
63
|
+
* Creates a new flow state for the specified flow.
|
|
64
|
+
*
|
|
65
|
+
* This method initializes a state by either loading from cache (if configured) or fetching from the server.
|
|
66
|
+
* It uses the provided configuration to control caching, event dispatching, and auto-step behavior.
|
|
67
|
+
*
|
|
68
|
+
* @param {FlowName} flowName - The name of the flow to create a state for.
|
|
69
|
+
* @param {StateCreateConfig} [config={}] - Configuration options for state creation.
|
|
70
|
+
* @param {boolean} [config.dispatchAfterStateChangeEvent=true] - Whether to dispatch an event after the state changes.
|
|
71
|
+
* @param {AutoStepExclusion} [config.excludeAutoSteps=null] - States to exclude from auto-step processing, or `"all"` to skip all auto-steps.
|
|
72
|
+
* @param {string} [config.cacheKey="hanko-flow-state"] - Key used for caching the state in localStorage.
|
|
73
|
+
* @param {boolean} [config.loadFromCache=true] - Whether to attempt loading the state from cache.
|
|
74
|
+
* @returns {Promise<AnyState>} A promise that resolves to the created flow state.
|
|
75
|
+
* @category SDK
|
|
76
|
+
* @subcategory FlowAPI
|
|
77
|
+
*/
|
|
78
|
+
createState(flowName: FlowName, config?: StateCreateConfig): Promise<import("./lib/flow-api/types/flow").AnyState>;
|
|
79
|
+
/**
|
|
80
|
+
* Retrieves the current user's profile information.
|
|
81
|
+
*
|
|
82
|
+
* @public
|
|
83
|
+
* @returns {Promise<User>} A promise that resolves to the user object
|
|
84
|
+
* @throws {UnauthorizedError} If the user is not authenticated
|
|
85
|
+
* @throws {TechnicalError} If an unexpected error occurs
|
|
86
|
+
*/
|
|
87
|
+
getUser(): Promise<User>;
|
|
88
|
+
/**
|
|
89
|
+
* Validates the current session.
|
|
90
|
+
*
|
|
91
|
+
* @public
|
|
92
|
+
* @returns {Promise<SessionCheckResponse>} A promise that resolves to the session check response
|
|
93
|
+
*/
|
|
94
|
+
validateSession(): Promise<SessionCheckResponse>;
|
|
95
|
+
/**
|
|
96
|
+
* Retrieves the current session token from the authentication cookie.
|
|
97
|
+
*
|
|
98
|
+
* @public
|
|
99
|
+
* @returns {string} The session token
|
|
100
|
+
*/
|
|
101
|
+
getSessionToken(): string;
|
|
102
|
+
/**
|
|
103
|
+
* Logs out the current user by invalidating the session.
|
|
104
|
+
*
|
|
105
|
+
* @public
|
|
106
|
+
* @returns {Promise<void>} A promise that resolves when the logout is complete
|
|
107
|
+
*/
|
|
108
|
+
logout(): Promise<void>;
|
|
81
109
|
}
|
|
82
110
|
export { Hanko };
|