@netlify/identity 0.1.1-alpha.22 → 0.1.1-alpha.24

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.js CHANGED
@@ -23,7 +23,7 @@ var AuthError = class extends Error {
23
23
  }
24
24
  };
25
25
  var MissingIdentityError = class extends Error {
26
- constructor(message = "Netlify Identity is not available. Enable Identity in your site dashboard and use `netlify dev` for local development.") {
26
+ constructor(message = "Netlify Identity is not available.") {
27
27
  super(message);
28
28
  this.name = "MissingIdentityError";
29
29
  }
@@ -301,22 +301,15 @@ var getSettings = async () => {
301
301
  }
302
302
  };
303
303
 
304
- // src/auth.ts
305
- var getCookies = () => {
306
- const cookies = globalThis.Netlify?.context?.cookies;
307
- if (!cookies) {
308
- throw new AuthError("Server-side auth requires Netlify Functions runtime");
309
- }
310
- return cookies;
311
- };
312
- var getServerIdentityUrl = () => {
313
- const ctx = getIdentityContext();
314
- if (!ctx?.url) {
315
- throw new AuthError("Could not determine the Identity endpoint URL on the server");
316
- }
317
- return ctx.url;
304
+ // src/events.ts
305
+ var AUTH_EVENTS = {
306
+ LOGIN: "login",
307
+ LOGOUT: "logout",
308
+ TOKEN_REFRESH: "token_refresh",
309
+ USER_UPDATED: "user_updated",
310
+ RECOVERY: "recovery"
318
311
  };
319
- var persistSession = true;
312
+ var GOTRUE_STORAGE_KEY = "gotrue.user";
320
313
  var listeners = /* @__PURE__ */ new Set();
321
314
  var emitAuthEvent = (event, user) => {
322
315
  for (const listener of listeners) {
@@ -326,19 +319,18 @@ var emitAuthEvent = (event, user) => {
326
319
  }
327
320
  }
328
321
  };
329
- var GOTRUE_STORAGE_KEY = "gotrue.user";
330
322
  var storageListenerAttached = false;
331
323
  var attachStorageListener = () => {
332
- if (storageListenerAttached) return;
324
+ if (storageListenerAttached || !isBrowser()) return;
333
325
  storageListenerAttached = true;
334
326
  window.addEventListener("storage", (event) => {
335
327
  if (event.key !== GOTRUE_STORAGE_KEY) return;
336
328
  if (event.newValue) {
337
329
  const client = getGoTrueClient();
338
330
  const currentUser = client?.currentUser();
339
- emitAuthEvent("login", currentUser ? toUser(currentUser) : null);
331
+ emitAuthEvent(AUTH_EVENTS.LOGIN, currentUser ? toUser(currentUser) : null);
340
332
  } else {
341
- emitAuthEvent("logout", null);
333
+ emitAuthEvent(AUTH_EVENTS.LOGOUT, null);
342
334
  }
343
335
  });
344
336
  };
@@ -353,6 +345,23 @@ var onAuthChange = (callback) => {
353
345
  listeners.delete(callback);
354
346
  };
355
347
  };
348
+
349
+ // src/auth.ts
350
+ var getCookies = () => {
351
+ const cookies = globalThis.Netlify?.context?.cookies;
352
+ if (!cookies) {
353
+ throw new AuthError("Server-side auth requires Netlify Functions runtime");
354
+ }
355
+ return cookies;
356
+ };
357
+ var getServerIdentityUrl = () => {
358
+ const ctx = getIdentityContext();
359
+ if (!ctx?.url) {
360
+ throw new AuthError("Could not determine the Identity endpoint URL on the server");
361
+ }
362
+ return ctx.url;
363
+ };
364
+ var persistSession = true;
356
365
  var login = async (email, password) => {
357
366
  if (!isBrowser()) {
358
367
  const identityUrl = getServerIdentityUrl();
@@ -374,10 +383,7 @@ var login = async (email, password) => {
374
383
  }
375
384
  if (!res.ok) {
376
385
  const errorBody = await res.json().catch(() => ({}));
377
- throw new AuthError(
378
- errorBody.msg || errorBody.error_description || `Login failed (${res.status})`,
379
- res.status
380
- );
386
+ throw new AuthError(errorBody.msg || errorBody.error_description || `Login failed (${res.status})`, res.status);
381
387
  }
382
388
  const data = await res.json();
383
389
  const accessToken = data.access_token;
@@ -391,10 +397,7 @@ var login = async (email, password) => {
391
397
  }
392
398
  if (!userRes.ok) {
393
399
  const errorBody = await userRes.json().catch(() => ({}));
394
- throw new AuthError(
395
- errorBody.msg || `Failed to fetch user data (${userRes.status})`,
396
- userRes.status
397
- );
400
+ throw new AuthError(errorBody.msg || `Failed to fetch user data (${userRes.status})`, userRes.status);
398
401
  }
399
402
  const userData = await userRes.json();
400
403
  const user = toUser(userData);
@@ -407,7 +410,7 @@ var login = async (email, password) => {
407
410
  const jwt = await gotrueUser.jwt();
408
411
  setBrowserAuthCookies(jwt);
409
412
  const user = toUser(gotrueUser);
410
- emitAuthEvent("login", user);
413
+ emitAuthEvent(AUTH_EVENTS.LOGIN, user);
411
414
  return user;
412
415
  } catch (error) {
413
416
  throw new AuthError(error.message, void 0, { cause: error });
@@ -434,10 +437,9 @@ var signup = async (email, password, data) => {
434
437
  const responseData = await res.json();
435
438
  const user = toUser(responseData);
436
439
  if (responseData.confirmed_at) {
437
- const responseRecord = responseData;
438
- const accessToken = responseRecord.access_token;
440
+ const accessToken = responseData.access_token;
439
441
  if (accessToken) {
440
- setAuthCookies(cookies, accessToken, responseRecord.refresh_token);
442
+ setAuthCookies(cookies, accessToken, responseData.refresh_token);
441
443
  }
442
444
  }
443
445
  return user;
@@ -451,7 +453,7 @@ var signup = async (email, password, data) => {
451
453
  if (jwt) {
452
454
  setBrowserAuthCookies(jwt);
453
455
  }
454
- emitAuthEvent("login", user);
456
+ emitAuthEvent(AUTH_EVENTS.LOGIN, user);
455
457
  }
456
458
  return user;
457
459
  } catch (error) {
@@ -482,7 +484,7 @@ var logout = async () => {
482
484
  await currentUser.logout();
483
485
  }
484
486
  deleteBrowserAuthCookies();
485
- emitAuthEvent("logout", null);
487
+ emitAuthEvent(AUTH_EVENTS.LOGOUT, null);
486
488
  } catch (error) {
487
489
  throw new AuthError(error.message, void 0, { cause: error });
488
490
  }
@@ -500,87 +502,92 @@ var handleAuthCallback = async () => {
500
502
  const hash = window.location.hash.substring(1);
501
503
  if (!hash) return null;
502
504
  const client = getClient();
505
+ const params = new URLSearchParams(hash);
503
506
  try {
504
- const params = new URLSearchParams(hash);
505
507
  const accessToken = params.get("access_token");
506
- if (accessToken) {
507
- const refreshToken = params.get("refresh_token") ?? "";
508
- const gotrueUser = await client.createUser(
509
- {
510
- access_token: accessToken,
511
- token_type: params.get("token_type") ?? "bearer",
512
- expires_in: Number(params.get("expires_in")),
513
- expires_at: Number(params.get("expires_at")),
514
- refresh_token: refreshToken
515
- },
516
- persistSession
517
- );
518
- setBrowserAuthCookies(accessToken, refreshToken || void 0);
519
- const user = toUser(gotrueUser);
520
- clearHash();
521
- emitAuthEvent("login", user);
522
- return { type: "oauth", user };
523
- }
508
+ if (accessToken) return await handleOAuthCallback(client, params, accessToken);
524
509
  const confirmationToken = params.get("confirmation_token");
525
- if (confirmationToken) {
526
- const gotrueUser = await client.confirm(confirmationToken, persistSession);
527
- const jwt = await gotrueUser.jwt();
528
- setBrowserAuthCookies(jwt);
529
- const user = toUser(gotrueUser);
530
- clearHash();
531
- emitAuthEvent("login", user);
532
- return { type: "confirmation", user };
533
- }
510
+ if (confirmationToken) return await handleConfirmationCallback(client, confirmationToken);
534
511
  const recoveryToken = params.get("recovery_token");
535
- if (recoveryToken) {
536
- const gotrueUser = await client.recover(recoveryToken, persistSession);
537
- const jwt = await gotrueUser.jwt();
538
- setBrowserAuthCookies(jwt);
539
- const user = toUser(gotrueUser);
540
- clearHash();
541
- emitAuthEvent("login", user);
542
- return { type: "recovery", user };
543
- }
512
+ if (recoveryToken) return await handleRecoveryCallback(client, recoveryToken);
544
513
  const inviteToken = params.get("invite_token");
545
- if (inviteToken) {
546
- clearHash();
547
- return { type: "invite", user: null, token: inviteToken };
548
- }
514
+ if (inviteToken) return handleInviteCallback(inviteToken);
549
515
  const emailChangeToken = params.get("email_change_token");
550
- if (emailChangeToken) {
551
- const currentUser = client.currentUser();
552
- if (!currentUser) {
553
- throw new AuthError("Email change verification requires an active browser session");
554
- }
555
- const jwt = await currentUser.jwt();
556
- const identityUrl = `${window.location.origin}${IDENTITY_PATH}`;
557
- const emailChangeRes = await fetch(`${identityUrl}/user`, {
558
- method: "PUT",
559
- headers: {
560
- "Content-Type": "application/json",
561
- Authorization: `Bearer ${jwt}`
562
- },
563
- body: JSON.stringify({ email_change_token: emailChangeToken })
564
- });
565
- if (!emailChangeRes.ok) {
566
- const errorBody = await emailChangeRes.json().catch(() => ({}));
567
- throw new AuthError(
568
- errorBody.msg || `Email change verification failed (${emailChangeRes.status})`,
569
- emailChangeRes.status
570
- );
571
- }
572
- const emailChangeData = await emailChangeRes.json();
573
- const user = toUser(emailChangeData);
574
- clearHash();
575
- emitAuthEvent("user_updated", user);
576
- return { type: "email_change", user };
577
- }
516
+ if (emailChangeToken) return await handleEmailChangeCallback(client, emailChangeToken);
578
517
  return null;
579
518
  } catch (error) {
580
519
  if (error instanceof AuthError) throw error;
581
520
  throw new AuthError(error.message, void 0, { cause: error });
582
521
  }
583
522
  };
523
+ var handleOAuthCallback = async (client, params, accessToken) => {
524
+ const refreshToken = params.get("refresh_token") ?? "";
525
+ const gotrueUser = await client.createUser(
526
+ {
527
+ access_token: accessToken,
528
+ token_type: params.get("token_type") ?? "bearer",
529
+ expires_in: Number(params.get("expires_in")),
530
+ expires_at: Number(params.get("expires_at")),
531
+ refresh_token: refreshToken
532
+ },
533
+ persistSession
534
+ );
535
+ setBrowserAuthCookies(accessToken, refreshToken || void 0);
536
+ const user = toUser(gotrueUser);
537
+ clearHash();
538
+ emitAuthEvent(AUTH_EVENTS.LOGIN, user);
539
+ return { type: "oauth", user };
540
+ };
541
+ var handleConfirmationCallback = async (client, token) => {
542
+ const gotrueUser = await client.confirm(token, persistSession);
543
+ const jwt = await gotrueUser.jwt();
544
+ setBrowserAuthCookies(jwt);
545
+ const user = toUser(gotrueUser);
546
+ clearHash();
547
+ emitAuthEvent(AUTH_EVENTS.LOGIN, user);
548
+ return { type: "confirmation", user };
549
+ };
550
+ var handleRecoveryCallback = async (client, token) => {
551
+ const gotrueUser = await client.recover(token, persistSession);
552
+ const jwt = await gotrueUser.jwt();
553
+ setBrowserAuthCookies(jwt);
554
+ const user = toUser(gotrueUser);
555
+ clearHash();
556
+ emitAuthEvent(AUTH_EVENTS.RECOVERY, user);
557
+ return { type: "recovery", user };
558
+ };
559
+ var handleInviteCallback = (token) => {
560
+ clearHash();
561
+ return { type: "invite", user: null, token };
562
+ };
563
+ var handleEmailChangeCallback = async (client, emailChangeToken) => {
564
+ const currentUser = client.currentUser();
565
+ if (!currentUser) {
566
+ throw new AuthError("Email change verification requires an active browser session");
567
+ }
568
+ const jwt = await currentUser.jwt();
569
+ const identityUrl = `${window.location.origin}${IDENTITY_PATH}`;
570
+ const emailChangeRes = await fetch(`${identityUrl}/user`, {
571
+ method: "PUT",
572
+ headers: {
573
+ "Content-Type": "application/json",
574
+ Authorization: `Bearer ${jwt}`
575
+ },
576
+ body: JSON.stringify({ email_change_token: emailChangeToken })
577
+ });
578
+ if (!emailChangeRes.ok) {
579
+ const errorBody = await emailChangeRes.json().catch(() => ({}));
580
+ throw new AuthError(
581
+ errorBody.msg || `Email change verification failed (${emailChangeRes.status})`,
582
+ emailChangeRes.status
583
+ );
584
+ }
585
+ const emailChangeData = await emailChangeRes.json();
586
+ const user = toUser(emailChangeData);
587
+ clearHash();
588
+ emitAuthEvent(AUTH_EVENTS.USER_UPDATED, user);
589
+ return { type: "email_change", user };
590
+ };
584
591
  var clearHash = () => {
585
592
  history.replaceState(null, "", window.location.pathname + window.location.search);
586
593
  };
@@ -606,12 +613,12 @@ var hydrateSession = async () => {
606
613
  persistSession
607
614
  );
608
615
  const user = toUser(gotrueUser);
609
- emitAuthEvent("login", user);
616
+ emitAuthEvent(AUTH_EVENTS.LOGIN, user);
610
617
  return user;
611
618
  };
612
619
 
613
620
  // src/account.ts
614
- var ensureCurrentUser = async () => {
621
+ var resolveCurrentUser = async () => {
615
622
  const client = getClient();
616
623
  let currentUser = client.currentUser();
617
624
  if (!currentUser && isBrowser()) {
@@ -638,7 +645,7 @@ var recoverPassword = async (token, newPassword) => {
638
645
  const gotrueUser = await client.recover(token, persistSession);
639
646
  const updatedUser = await gotrueUser.update({ password: newPassword });
640
647
  const user = toUser(updatedUser);
641
- emitAuthEvent("login", user);
648
+ emitAuthEvent(AUTH_EVENTS.LOGIN, user);
642
649
  return user;
643
650
  } catch (error) {
644
651
  throw new AuthError(error.message, void 0, { cause: error });
@@ -649,7 +656,7 @@ var confirmEmail = async (token) => {
649
656
  try {
650
657
  const gotrueUser = await client.confirm(token, persistSession);
651
658
  const user = toUser(gotrueUser);
652
- emitAuthEvent("login", user);
659
+ emitAuthEvent(AUTH_EVENTS.LOGIN, user);
653
660
  return user;
654
661
  } catch (error) {
655
662
  throw new AuthError(error.message, void 0, { cause: error });
@@ -660,7 +667,7 @@ var acceptInvite = async (token, password) => {
660
667
  try {
661
668
  const gotrueUser = await client.acceptInvite(token, password, persistSession);
662
669
  const user = toUser(gotrueUser);
663
- emitAuthEvent("login", user);
670
+ emitAuthEvent(AUTH_EVENTS.LOGIN, user);
664
671
  return user;
665
672
  } catch (error) {
666
673
  throw new AuthError(error.message, void 0, { cause: error });
@@ -668,7 +675,7 @@ var acceptInvite = async (token, password) => {
668
675
  };
669
676
  var verifyEmailChange = async (token) => {
670
677
  if (!isBrowser()) throw new AuthError("verifyEmailChange() is only available in the browser");
671
- const currentUser = await ensureCurrentUser();
678
+ const currentUser = await resolveCurrentUser();
672
679
  const jwt = await currentUser.jwt();
673
680
  const identityUrl = `${window.location.origin}${IDENTITY_PATH}`;
674
681
  try {
@@ -682,14 +689,11 @@ var verifyEmailChange = async (token) => {
682
689
  });
683
690
  if (!res.ok) {
684
691
  const errorBody = await res.json().catch(() => ({}));
685
- throw new AuthError(
686
- errorBody.msg || `Email change verification failed (${res.status})`,
687
- res.status
688
- );
692
+ throw new AuthError(errorBody.msg || `Email change verification failed (${res.status})`, res.status);
689
693
  }
690
694
  const userData = await res.json();
691
695
  const user = toUser(userData);
692
- emitAuthEvent("user_updated", user);
696
+ emitAuthEvent(AUTH_EVENTS.USER_UPDATED, user);
693
697
  return user;
694
698
  } catch (error) {
695
699
  if (error instanceof AuthError) throw error;
@@ -697,17 +701,18 @@ var verifyEmailChange = async (token) => {
697
701
  }
698
702
  };
699
703
  var updateUser = async (updates) => {
700
- const currentUser = await ensureCurrentUser();
704
+ const currentUser = await resolveCurrentUser();
701
705
  try {
702
706
  const updatedUser = await currentUser.update(updates);
703
707
  const user = toUser(updatedUser);
704
- emitAuthEvent("user_updated", user);
708
+ emitAuthEvent(AUTH_EVENTS.USER_UPDATED, user);
705
709
  return user;
706
710
  } catch (error) {
707
711
  throw new AuthError(error.message, void 0, { cause: error });
708
712
  }
709
713
  };
710
714
  export {
715
+ AUTH_EVENTS,
711
716
  AuthError,
712
717
  MissingIdentityError,
713
718
  acceptInvite,