@netlify/identity 0.3.0-alpha.2 → 0.3.0-alpha.3

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/dist/index.d.cts CHANGED
@@ -1,22 +1,59 @@
1
+ /** The supported OAuth and authentication providers. */
1
2
  declare const AUTH_PROVIDERS: readonly ["google", "github", "gitlab", "bitbucket", "facebook", "saml", "email"];
3
+ /** A supported authentication provider name (e.g., `'google'`, `'github'`, `'email'`). */
2
4
  type AuthProvider = (typeof AUTH_PROVIDERS)[number];
5
+ /**
6
+ * Provider and role metadata stored in a user's `app_metadata` field.
7
+ * GoTrue sets `provider` automatically on signup; `roles` controls authorization.
8
+ * Additional keys may be present depending on your Identity configuration.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * const meta: AppMetadata = {
13
+ * provider: 'github',
14
+ * roles: ['admin'],
15
+ * custom_claim: 'value',
16
+ * }
17
+ * ```
18
+ */
3
19
  interface AppMetadata {
4
20
  provider: AuthProvider;
5
21
  roles?: string[];
6
22
  [key: string]: unknown;
7
23
  }
24
+ /**
25
+ * Identity endpoint configuration for the current environment.
26
+ * In the browser, `url` is derived from `window.location.origin`.
27
+ * On the server, `token` is the operator token for admin operations.
28
+ */
8
29
  interface IdentityConfig {
30
+ /** The GoTrue API endpoint URL (e.g., `https://example.com/.netlify/identity`). */
9
31
  url: string;
32
+ /** Operator token for server-side admin requests. Only available in Netlify Functions. */
10
33
  token?: string;
11
34
  }
35
+ /**
36
+ * Project-level Identity settings returned by {@link getSettings}.
37
+ * Reflects the configuration in your Netlify dashboard.
38
+ */
12
39
  interface Settings {
40
+ /** Whether new signups are auto-confirmed (no confirmation email sent). */
13
41
  autoconfirm: boolean;
42
+ /** Whether new signups are disabled entirely. */
14
43
  disableSignup: boolean;
44
+ /** Map of provider names to whether they are enabled. */
15
45
  providers: Record<AuthProvider, boolean>;
16
46
  }
17
47
  /**
18
48
  * Fields accepted by {@link updateUser}. All fields are optional.
19
49
  * Pass `data` to update user metadata (e.g., `{ data: { full_name: 'New Name' } }`).
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * await updateUser({ data: { full_name: 'Jane Doe' } })
54
+ * await updateUser({ email: 'new@example.com' })
55
+ * await updateUser({ password: 'new-password' })
56
+ * ```
20
57
  */
21
58
  interface UserUpdates {
22
59
  email?: string;
@@ -34,27 +71,95 @@ type SignupData = Record<string, unknown>;
34
71
  *
35
72
  * Unlike {@link UserUpdates} (used by the self-service `updateUser`), admin updates
36
73
  * can set `role`, force-confirm a user, and write to `app_metadata`.
74
+ *
75
+ * @example
76
+ * ```ts
77
+ * await admin.updateUser(userId, {
78
+ * role: 'editor',
79
+ * confirm: true,
80
+ * app_metadata: { plan: 'pro' },
81
+ * })
82
+ * ```
37
83
  */
38
84
  interface AdminUserUpdates {
39
85
  email?: string;
40
86
  password?: string;
87
+ /** The user's role (e.g., `'admin'`, `'editor'`). */
41
88
  role?: string;
89
+ /** Set to `true` to force-confirm the user's email without sending a confirmation email. */
42
90
  confirm?: boolean;
91
+ /** Server-managed metadata. Only writable via admin operations. */
43
92
  app_metadata?: Record<string, unknown>;
93
+ /** User-managed metadata (display name, avatar, preferences, etc.). */
44
94
  user_metadata?: Record<string, unknown>;
45
95
  [key: string]: unknown;
46
96
  }
97
+ /**
98
+ * Options for {@link admin.listUsers}. Only used on the server;
99
+ * pagination is ignored in the browser (gotrue-js limitation).
100
+ */
101
+ interface ListUsersOptions {
102
+ /** 1-based page number. */
103
+ page?: number;
104
+ /** Number of users per page. */
105
+ perPage?: number;
106
+ }
107
+ /**
108
+ * Parameters for {@link admin.createUser}.
109
+ *
110
+ * The optional `data` fields are spread as top-level attributes in the GoTrue
111
+ * request body (not nested under `user_metadata`). Use this to set `app_metadata`,
112
+ * `user_metadata`, `role`, or other GoTrue user fields at creation time.
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * await admin.createUser({
117
+ * email: 'jane@example.com',
118
+ * password: 'secret',
119
+ * data: { role: 'editor', user_metadata: { full_name: 'Jane Doe' } },
120
+ * })
121
+ * ```
122
+ */
123
+ interface CreateUserParams {
124
+ email: string;
125
+ password: string;
126
+ /** Additional GoTrue user fields spread into the request body. */
127
+ data?: Record<string, unknown>;
128
+ }
47
129
 
130
+ /**
131
+ * A normalized user object returned by all auth and admin functions.
132
+ * Provides a consistent shape regardless of whether the user was loaded
133
+ * from gotrue-js, a JWT cookie, or the server-side identity context.
134
+ *
135
+ * @example
136
+ * ```ts
137
+ * const user = getUser()
138
+ * if (user) {
139
+ * console.log(user.email, user.name, user.provider)
140
+ * }
141
+ * ```
142
+ */
48
143
  interface User {
144
+ /** The user's unique identifier (GoTrue UUID). */
49
145
  id: string;
146
+ /** The user's email address. */
50
147
  email?: string;
148
+ /** `true` if the user's email has been confirmed. */
51
149
  emailVerified?: boolean;
150
+ /** ISO 8601 timestamp of when the account was created. */
52
151
  createdAt?: string;
152
+ /** ISO 8601 timestamp of the last account update. */
53
153
  updatedAt?: string;
154
+ /** The authentication provider used to create the account. */
54
155
  provider?: AuthProvider;
156
+ /** Display name from `user_metadata.full_name` or `user_metadata.name`. */
55
157
  name?: string;
158
+ /** Avatar URL from `user_metadata.avatar_url`. */
56
159
  pictureUrl?: string;
160
+ /** The full `user_metadata` object. */
57
161
  metadata?: Record<string, unknown>;
162
+ /** The raw GoTrue user data, for accessing fields not mapped to this interface. */
58
163
  rawGoTrueData?: Record<string, unknown>;
59
164
  }
60
165
  /**
@@ -91,6 +196,18 @@ declare const getIdentityConfig: () => IdentityConfig | null;
91
196
  */
92
197
  declare const getSettings: () => Promise<Settings>;
93
198
 
199
+ /**
200
+ * Constants for the auth events emitted by the library.
201
+ * Use these instead of string literals when comparing event types.
202
+ *
203
+ * @example
204
+ * ```ts
205
+ * onAuthChange((event, user) => {
206
+ * if (event === AUTH_EVENTS.LOGIN) console.log('Logged in:', user)
207
+ * if (event === AUTH_EVENTS.RECOVERY) redirect('/reset-password')
208
+ * })
209
+ * ```
210
+ */
94
211
  declare const AUTH_EVENTS: {
95
212
  readonly LOGIN: "login";
96
213
  readonly LOGOUT: "logout";
@@ -98,7 +215,15 @@ declare const AUTH_EVENTS: {
98
215
  readonly USER_UPDATED: "user_updated";
99
216
  readonly RECOVERY: "recovery";
100
217
  };
218
+ /**
219
+ * Union of all auth event names: `'login' | 'logout' | 'token_refresh' | 'user_updated' | 'recovery'`.
220
+ * Passed as the first argument to {@link AuthCallback} subscribers.
221
+ */
101
222
  type AuthEvent = (typeof AUTH_EVENTS)[keyof typeof AUTH_EVENTS];
223
+ /**
224
+ * Callback function signature for {@link onAuthChange} subscribers.
225
+ * `user` is `null` on logout events.
226
+ */
102
227
  type AuthCallback = (event: AuthEvent, user: User | null) => void;
103
228
  /**
104
229
  * Subscribes to auth state changes (login, logout, token refresh, user updates,
@@ -162,9 +287,31 @@ declare const logout: () => Promise<void>;
162
287
  * @throws {AuthError} If called on the server.
163
288
  */
164
289
  declare const oauthLogin: (provider: string) => never;
290
+ /**
291
+ * Result returned by {@link handleAuthCallback} after processing a URL hash.
292
+ *
293
+ * - `'oauth'`: OAuth provider redirect completed. `user` is the authenticated user.
294
+ * - `'confirmation'`: Email confirmed via token. `user` is the confirmed user.
295
+ * - `'recovery'`: Password recovery token redeemed. `user` is logged in but must set a new password.
296
+ * - `'invite'`: Invite token found. `user` is `null`; `token` contains the invite token for {@link acceptInvite}.
297
+ * - `'email_change'`: Email change verified. `user` reflects the updated email.
298
+ *
299
+ * @example
300
+ * ```ts
301
+ * const result = await handleAuthCallback()
302
+ * if (result?.type === 'recovery') {
303
+ * redirect('/reset-password')
304
+ * } else if (result?.type === 'invite') {
305
+ * redirect(`/join?token=${result.token}`)
306
+ * }
307
+ * ```
308
+ */
165
309
  interface CallbackResult {
310
+ /** The type of auth callback that was processed. */
166
311
  type: 'oauth' | 'confirmation' | 'recovery' | 'invite' | 'email_change';
312
+ /** The authenticated user, or `null` for invite callbacks. */
167
313
  user: User | null;
314
+ /** The invite token, only present when `type` is `'invite'`. */
168
315
  token?: string;
169
316
  }
170
317
  /**
@@ -194,61 +341,53 @@ declare const handleAuthCallback: () => Promise<CallbackResult | null>;
194
341
  */
195
342
  declare const hydrateSession: () => Promise<User | null>;
196
343
 
344
+ /**
345
+ * Thrown by auth operations when something goes wrong: invalid credentials,
346
+ * network failures, missing runtime context, etc.
347
+ *
348
+ * The `status` field contains the HTTP status code from GoTrue when available
349
+ * (e.g., 401 for bad credentials, 422 for validation errors).
350
+ * The `cause` field preserves the original error for debugging.
351
+ *
352
+ * @example
353
+ * ```ts
354
+ * try {
355
+ * await login(email, password)
356
+ * } catch (error) {
357
+ * if (error instanceof AuthError) {
358
+ * console.error(error.message, error.status)
359
+ * }
360
+ * }
361
+ * ```
362
+ */
197
363
  declare class AuthError extends Error {
198
364
  name: string;
365
+ /** HTTP status code from GoTrue, if the error originated from an API response. */
199
366
  status?: number;
200
367
  cause?: unknown;
201
368
  constructor(message: string, status?: number, options?: {
202
369
  cause?: unknown;
203
370
  });
204
371
  }
372
+ /**
373
+ * Thrown when a function requires a gotrue-js client but Netlify Identity
374
+ * is not configured (no endpoint URL could be discovered).
375
+ *
376
+ * This typically means the site does not have Identity enabled, or the app
377
+ * is not running via `netlify dev` / deployed on Netlify.
378
+ */
205
379
  declare class MissingIdentityError extends Error {
206
380
  name: string;
207
381
  constructor(message?: string);
208
382
  }
209
383
 
210
384
  /**
211
- * Sends a password recovery email to the given address.
212
- *
213
- * @throws {AuthError} On network failure or if the request is rejected.
214
- */
215
- declare const requestPasswordRecovery: (email: string) => Promise<void>;
216
- /**
217
- * Redeems a recovery token and sets a new password. Logs the user in on success.
218
- *
219
- * @throws {AuthError} If the token is invalid, expired, or the update fails.
220
- */
221
- declare const recoverPassword: (token: string, newPassword: string) => Promise<User>;
222
- /**
223
- * Confirms an email address using the token from a confirmation email. Logs the user in on success.
224
- *
225
- * @throws {AuthError} If the token is invalid or expired.
226
- */
227
- declare const confirmEmail: (token: string) => Promise<User>;
228
- /**
229
- * Accepts an invite token and sets a password for the new account. Logs the user in on success.
230
- *
231
- * @throws {AuthError} If the token is invalid or expired.
232
- */
233
- declare const acceptInvite: (token: string, password: string) => Promise<User>;
234
- /**
235
- * Verifies an email change using the token from a verification email.
236
- * Auto-hydrates from auth cookies if no browser session exists. Browser only.
237
- *
238
- * @throws {AuthError} If called on the server, no user is logged in, or the token is invalid.
239
- */
240
- declare const verifyEmailChange: (token: string) => Promise<User>;
241
- /**
242
- * Updates the current user's email, password, or user metadata.
243
- * Auto-hydrates from auth cookies if no browser session exists.
385
+ * The admin namespace for privileged user management operations.
386
+ * All methods work in both server and browser contexts.
244
387
  *
245
- * @param updates - Fields to update. Pass `email` or `password` to change credentials,
246
- * or `data` to update user metadata (e.g., `{ data: { full_name: 'New Name' } }`).
247
- * @throws {AuthError} If no user is logged in or the update fails.
388
+ * **Server:** uses the operator token (automatically available in Netlify Functions).
389
+ * **Browser:** requires a logged-in user with an admin role.
248
390
  */
249
- declare const updateUser: (updates: UserUpdates) => Promise<User>;
250
-
251
- /** The admin namespace for user management operations. */
252
391
  interface Admin {
253
392
  /**
254
393
  * Lists all users. Works in both server and browser contexts.
@@ -261,10 +400,7 @@ interface Admin {
261
400
  *
262
401
  * @throws {AuthError} If the operator token is missing (server) or no admin user is logged in (browser).
263
402
  */
264
- listUsers: (options?: {
265
- page?: number;
266
- perPage?: number;
267
- }) => Promise<User[]>;
403
+ listUsers: (options?: ListUsersOptions) => Promise<User[]>;
268
404
  /**
269
405
  * Gets a single user by ID. Works in both server and browser contexts.
270
406
  *
@@ -293,11 +429,7 @@ interface Admin {
293
429
  * @throws {AuthError} If the email already exists, the operator token is missing (server),
294
430
  * or no admin user is logged in (browser).
295
431
  */
296
- createUser: (params: {
297
- email: string;
298
- password: string;
299
- data?: Record<string, unknown>;
300
- }) => Promise<User>;
432
+ createUser: (params: CreateUserParams) => Promise<User>;
301
433
  /**
302
434
  * Updates an existing user by ID. Works in both server and browser contexts.
303
435
  *
@@ -325,4 +457,45 @@ interface Admin {
325
457
  }
326
458
  declare const admin: Admin;
327
459
 
328
- export { AUTH_EVENTS, type AdminUserUpdates, type AppMetadata, type AuthCallback, AuthError, type AuthEvent, type AuthProvider, type CallbackResult, type IdentityConfig, MissingIdentityError, type Settings, type SignupData, type User, type UserUpdates, acceptInvite, admin, confirmEmail, getIdentityConfig, getSettings, getUser, handleAuthCallback, hydrateSession, isAuthenticated, login, logout, oauthLogin, onAuthChange, recoverPassword, requestPasswordRecovery, signup, updateUser, verifyEmailChange };
460
+ /**
461
+ * Sends a password recovery email to the given address.
462
+ *
463
+ * @throws {AuthError} On network failure or if the request is rejected.
464
+ */
465
+ declare const requestPasswordRecovery: (email: string) => Promise<void>;
466
+ /**
467
+ * Redeems a recovery token and sets a new password. Logs the user in on success.
468
+ *
469
+ * @throws {AuthError} If the token is invalid, expired, or the update fails.
470
+ */
471
+ declare const recoverPassword: (token: string, newPassword: string) => Promise<User>;
472
+ /**
473
+ * Confirms an email address using the token from a confirmation email. Logs the user in on success.
474
+ *
475
+ * @throws {AuthError} If the token is invalid or expired.
476
+ */
477
+ declare const confirmEmail: (token: string) => Promise<User>;
478
+ /**
479
+ * Accepts an invite token and sets a password for the new account. Logs the user in on success.
480
+ *
481
+ * @throws {AuthError} If the token is invalid or expired.
482
+ */
483
+ declare const acceptInvite: (token: string, password: string) => Promise<User>;
484
+ /**
485
+ * Verifies an email change using the token from a verification email.
486
+ * Auto-hydrates from auth cookies if no browser session exists. Browser only.
487
+ *
488
+ * @throws {AuthError} If called on the server, no user is logged in, or the token is invalid.
489
+ */
490
+ declare const verifyEmailChange: (token: string) => Promise<User>;
491
+ /**
492
+ * Updates the current user's email, password, or user metadata.
493
+ * Auto-hydrates from auth cookies if no browser session exists.
494
+ *
495
+ * @param updates - Fields to update. Pass `email` or `password` to change credentials,
496
+ * or `data` to update user metadata (e.g., `{ data: { full_name: 'New Name' } }`).
497
+ * @throws {AuthError} If no user is logged in or the update fails.
498
+ */
499
+ declare const updateUser: (updates: UserUpdates) => Promise<User>;
500
+
501
+ export { AUTH_EVENTS, type Admin, type AdminUserUpdates, type AppMetadata, type AuthCallback, AuthError, type AuthEvent, type AuthProvider, type CallbackResult, type CreateUserParams, type IdentityConfig, type ListUsersOptions, MissingIdentityError, type Settings, type SignupData, type User, type UserUpdates, acceptInvite, admin, confirmEmail, getIdentityConfig, getSettings, getUser, handleAuthCallback, hydrateSession, isAuthenticated, login, logout, oauthLogin, onAuthChange, recoverPassword, requestPasswordRecovery, signup, updateUser, verifyEmailChange };