bwh-auth 0.3.2 → 0.3.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/README.md CHANGED
@@ -169,6 +169,10 @@ import { SignupForm, registerPasskey } from 'bwh-auth'
169
169
  />
170
170
  ```
171
171
 
172
+ Within `LoginForm`, explicit passkey login cancels and waits for conditional autofill before requesting a credential. Password submission and unmount also cancel pending passkey authentication. Autofill pauses after a manual sign-in attempt until the form is remounted. Changing consumer callbacks does not restart autofill.
173
+
174
+ When `PasskeyLoginButton` receives `onError`, the consumer owns error display; without it, the button displays its own error.
175
+
172
176
  Consumers can preserve app-specific login state and design-system checkboxes
173
177
  without rebuilding the form:
174
178
 
package/dist/index.cjs CHANGED
@@ -52,7 +52,7 @@ __export(index_exports, {
52
52
  module.exports = __toCommonJS(index_exports);
53
53
 
54
54
  // src/forms.tsx
55
- var React2 = __toESM(require("react"), 1);
55
+ var React3 = __toESM(require("react"), 1);
56
56
 
57
57
  // src/components.ts
58
58
  var requiredComponentKeys = [
@@ -79,10 +79,17 @@ function resolveAuthButtonComponent(components) {
79
79
  return { Button: components.Button };
80
80
  }
81
81
 
82
- // src/passkey-login-button.tsx
83
- var import_lucide_react = require("lucide-react");
82
+ // src/passkey-authentication.ts
84
83
  var React = __toESM(require("react"), 1);
85
84
 
85
+ // src/abort-utils.ts
86
+ function throwIfAborted(signal) {
87
+ if (!signal?.aborted) return;
88
+ const error = new Error("Passkey authentication was cancelled");
89
+ error.name = "AbortError";
90
+ throw error;
91
+ }
92
+
86
93
  // src/webauthn-utils.ts
87
94
  function getCsrfToken(explicitToken) {
88
95
  if (explicitToken) {
@@ -109,7 +116,7 @@ function arrayBufferToBase64url(buffer) {
109
116
  return window.btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
110
117
  }
111
118
  function isAbortError(error) {
112
- return error instanceof Error && error.name === "AbortError";
119
+ return error !== null && typeof error === "object" && "name" in error && error.name === "AbortError";
113
120
  }
114
121
  function getDefaultPasskeyName() {
115
122
  if (typeof window === "undefined") return "Passkey";
@@ -152,6 +159,7 @@ async function authenticateWithPasskey({ endpoints = {}, mediation, signal } = {
152
159
  throw new Error("Failed to get authentication options");
153
160
  }
154
161
  const options = await optRes.json();
162
+ throwIfAborted(signal);
155
163
  const publicKey = {
156
164
  ...options,
157
165
  challenge: base64urlToArrayBuffer(options.challenge),
@@ -161,6 +169,7 @@ async function authenticateWithPasskey({ endpoints = {}, mediation, signal } = {
161
169
  }))
162
170
  };
163
171
  const credential = await navigator.credentials.get({ publicKey, mediation, signal });
172
+ throwIfAborted(signal);
164
173
  if (!credential || credential.type !== "public-key") {
165
174
  throw new Error("No passkey selected");
166
175
  }
@@ -255,31 +264,87 @@ async function registerPasskey({ endpoints = {}, name, signal } = {}) {
255
264
  return { result };
256
265
  }
257
266
 
267
+ // src/passkey-authentication.ts
268
+ var PasskeyAuthenticationContext = React.createContext(null);
269
+ function usePasskeyAuthentication() {
270
+ const pending = React.useRef(null);
271
+ const cancel = React.useCallback(async (conditionalOnly = false) => {
272
+ const request = pending.current;
273
+ if (!request || conditionalOnly && !request.conditional) return;
274
+ request.controller.abort();
275
+ await request.promise.catch(() => void 0);
276
+ }, []);
277
+ const authenticate = React.useCallback(async (options = {}) => {
278
+ const previous = pending.current;
279
+ const controller = new AbortController();
280
+ previous?.controller.abort();
281
+ const promise = (async () => {
282
+ if (previous) await previous.promise.catch(() => void 0);
283
+ throwIfAborted(controller.signal);
284
+ const result = await authenticateWithPasskey({ ...options, signal: controller.signal });
285
+ throwIfAborted(controller.signal);
286
+ return result;
287
+ })();
288
+ const request = { controller, promise, conditional: options.mediation === "conditional" };
289
+ pending.current = request;
290
+ try {
291
+ return await promise;
292
+ } finally {
293
+ if (pending.current === request) pending.current = null;
294
+ }
295
+ }, []);
296
+ React.useEffect(() => () => {
297
+ void cancel();
298
+ }, [cancel]);
299
+ return React.useMemo(() => ({ authenticate, cancel }), [authenticate, cancel]);
300
+ }
301
+
258
302
  // src/passkey-login-button.tsx
303
+ var import_lucide_react = require("lucide-react");
304
+ var React2 = __toESM(require("react"), 1);
259
305
  var import_jsx_runtime = require("react/jsx-runtime");
260
- function PasskeyLoginButton({ endpoints = {}, components, className, onSuccess, onError }) {
306
+ function PasskeyLoginButton({ endpoints = {}, components, className, disabled = false, onSuccess, onError }) {
261
307
  const { Button } = resolveAuthButtonComponent(components);
262
- const [loading, setLoading] = React.useState(false);
263
- const [error, setError] = React.useState(null);
308
+ const [loading, setLoading] = React2.useState(false);
309
+ const [error, setError] = React2.useState(null);
310
+ const localAuthentication = usePasskeyAuthentication();
311
+ const authentication = React2.useContext(PasskeyAuthenticationContext) ?? localAuthentication;
312
+ const inFlight = React2.useRef(false);
313
+ const mounted = React2.useRef(true);
314
+ const callbacks = React2.useRef({ onSuccess, onError });
315
+ React2.useLayoutEffect(() => {
316
+ callbacks.current = { onSuccess, onError };
317
+ });
318
+ React2.useEffect(() => {
319
+ mounted.current = true;
320
+ return () => {
321
+ mounted.current = false;
322
+ if (inFlight.current) void authentication.cancel();
323
+ };
324
+ }, [authentication]);
264
325
  async function handlePasskeyLogin() {
326
+ if (disabled || inFlight.current) return;
327
+ inFlight.current = true;
265
328
  setError(null);
266
329
  setLoading(true);
267
330
  try {
268
- const { redirectUrl, result } = await authenticateWithPasskey({ endpoints });
269
- if (onSuccess) {
270
- onSuccess(redirectUrl, result);
331
+ const { redirectUrl, result } = await authentication.authenticate({ endpoints });
332
+ if (!mounted.current) return;
333
+ if (callbacks.current.onSuccess) {
334
+ callbacks.current.onSuccess(redirectUrl, result);
271
335
  } else {
272
336
  window.location.href = redirectUrl;
273
337
  }
274
338
  } catch (caughtError) {
275
- if (isAbortError(caughtError)) {
339
+ if (!mounted.current || isAbortError(caughtError)) {
276
340
  return;
277
341
  }
278
342
  const message = caughtError instanceof Error ? caughtError.message : "Passkey login failed";
279
- setError(message);
280
- onError?.(message);
343
+ if (callbacks.current.onError) callbacks.current.onError(message);
344
+ else setError(message);
281
345
  } finally {
282
- setLoading(false);
346
+ inFlight.current = false;
347
+ if (mounted.current) setLoading(false);
283
348
  }
284
349
  }
285
350
  if (typeof window === "undefined" || !window.PublicKeyCredential) {
@@ -287,7 +352,7 @@ function PasskeyLoginButton({ endpoints = {}, components, className, onSuccess,
287
352
  }
288
353
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className, children: [
289
354
  error ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "mb-2 text-sm text-destructive", children: error }) : null,
290
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { type: "button", variant: "outline", className: "w-full", disabled: loading, onClick: handlePasskeyLogin, children: [
355
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { type: "button", variant: "outline", className: "w-full", disabled: disabled || loading, onClick: handlePasskeyLogin, children: [
291
356
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.KeyRound, { "aria-hidden": "true" }),
292
357
  loading ? "Verifying..." : "Sign in with Passkey"
293
358
  ] })
@@ -357,53 +422,70 @@ function LoginForm({
357
422
  enablePasskeyAutofill = enablePasskeys
358
423
  }) {
359
424
  const { Button, Card, CardContent, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
360
- const [email, setEmail] = React2.useState(initialEmail);
361
- const [password, setPassword] = React2.useState("");
362
- const [remember, setRemember] = React2.useState(false);
363
- const [loading, setLoading] = React2.useState(false);
364
- const [conditionalPasskeyAvailable, setConditionalPasskeyAvailable] = React2.useState(false);
365
- const passkeyEndpoints = React2.useMemo(() => ({
425
+ const [email, setEmail] = React3.useState(initialEmail);
426
+ const [password, setPassword] = React3.useState("");
427
+ const [remember, setRemember] = React3.useState(false);
428
+ const [loading, setLoading] = React3.useState(false);
429
+ const [conditionalPasskeyAvailable, setConditionalPasskeyAvailable] = React3.useState(false);
430
+ const passkeyAuthentication = usePasskeyAuthentication();
431
+ const conditionalInterrupted = React3.useRef(false);
432
+ const submitting = React3.useRef(false);
433
+ const callbacks = React3.useRef({ onError, onPasskeySuccess });
434
+ React3.useLayoutEffect(() => {
435
+ callbacks.current = { onError, onPasskeySuccess };
436
+ });
437
+ const coordinatedAuthentication = React3.useMemo(() => ({
438
+ ...passkeyAuthentication,
439
+ authenticate: (options) => {
440
+ if (options?.mediation !== "conditional") conditionalInterrupted.current = true;
441
+ return passkeyAuthentication.authenticate(options);
442
+ }
443
+ }), [passkeyAuthentication]);
444
+ const passkeyEndpoints = React3.useMemo(() => ({
366
445
  csrfToken: endpoints.csrfToken,
367
446
  passkeyAuth: endpoints.passkeyAuth,
368
447
  passkeyAuthOptions: endpoints.passkeyAuthOptions
369
448
  }), [endpoints.csrfToken, endpoints.passkeyAuth, endpoints.passkeyAuthOptions]);
370
- React2.useEffect(() => {
371
- if (!enablePasskeyAutofill) return;
372
- const abortController = new AbortController();
449
+ React3.useEffect(() => {
450
+ setConditionalPasskeyAvailable(false);
451
+ if (!enablePasskeyAutofill || conditionalInterrupted.current) return;
373
452
  let active = true;
374
453
  async function startConditionalPasskeyLogin() {
375
454
  const available = await isConditionalMediationAvailable();
376
- if (!available || !active) return;
455
+ if (!available || !active || conditionalInterrupted.current) return;
377
456
  setConditionalPasskeyAvailable(true);
378
457
  try {
379
- const { redirectUrl, result } = await authenticateWithPasskey({
458
+ const { redirectUrl, result } = await coordinatedAuthentication.authenticate({
380
459
  endpoints: passkeyEndpoints,
381
- mediation: "conditional",
382
- signal: abortController.signal
460
+ mediation: "conditional"
383
461
  });
384
462
  if (!active) return;
385
- if (onPasskeySuccess) {
386
- onPasskeySuccess(redirectUrl, result);
463
+ if (callbacks.current.onPasskeySuccess) {
464
+ callbacks.current.onPasskeySuccess(redirectUrl, result);
387
465
  } else {
388
466
  window.location.href = redirectUrl;
389
467
  }
390
468
  } catch (error) {
391
469
  if (!isAbortError(error) && active) {
392
- onError?.(error instanceof Error ? error.message : "Passkey login failed");
470
+ callbacks.current.onError?.(error instanceof Error ? error.message : "Passkey login failed");
393
471
  }
394
472
  }
395
473
  }
396
474
  void startConditionalPasskeyLogin();
397
475
  return () => {
398
476
  active = false;
399
- abortController.abort();
477
+ void coordinatedAuthentication.cancel(true);
400
478
  };
401
- }, [enablePasskeyAutofill, onError, onPasskeySuccess, passkeyEndpoints]);
479
+ }, [enablePasskeyAutofill, coordinatedAuthentication, passkeyEndpoints]);
402
480
  async function onSubmit(event) {
403
481
  event.preventDefault();
482
+ if (submitting.current) return;
483
+ submitting.current = true;
484
+ conditionalInterrupted.current = true;
404
485
  onSubmitStart?.();
405
486
  setLoading(true);
406
487
  try {
488
+ await passkeyAuthentication.cancel();
407
489
  const result = await postForm(endpoints.login ?? "/login", { email, password, remember }, endpoints.csrfToken);
408
490
  if (result.requires_2fa) {
409
491
  onTwoFactorRequired?.(result);
@@ -417,6 +499,7 @@ function LoginForm({
417
499
  } catch (error) {
418
500
  onError?.(error instanceof Error ? error.message : "Login failed");
419
501
  } finally {
502
+ submitting.current = false;
420
503
  setLoading(false);
421
504
  }
422
505
  }
@@ -460,11 +543,12 @@ function LoginForm({
460
543
  ] }),
461
544
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Button, { type: "submit", className: "w-full", disabled: loading, children: loading ? "Signing in..." : "Sign In" })
462
545
  ] }),
463
- enablePasskeys ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: "mt-4", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
546
+ enablePasskeys ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: "mt-4", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(PasskeyAuthenticationContext.Provider, { value: coordinatedAuthentication, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
464
547
  PasskeyLoginButton,
465
548
  {
466
549
  components: { Button },
467
550
  endpoints,
551
+ disabled: loading,
468
552
  onSuccess: (redirectUrl, result) => {
469
553
  if (onPasskeySuccess) {
470
554
  onPasskeySuccess(redirectUrl, result);
@@ -474,7 +558,7 @@ function LoginForm({
474
558
  },
475
559
  onError
476
560
  }
477
- ) }) : null
561
+ ) }) }) : null
478
562
  ] })
479
563
  ] });
480
564
  }
@@ -506,11 +590,11 @@ function SignupForm({
506
590
  submittingLabel = "Creating account..."
507
591
  }) {
508
592
  const { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
509
- const [values, setValues] = React2.useState(() => Object.fromEntries(
593
+ const [values, setValues] = React3.useState(() => Object.fromEntries(
510
594
  fields.map((field) => [field.name, initialSignupValue(field, initialValues)])
511
595
  ));
512
- const [fieldErrors, setFieldErrors] = React2.useState(errors);
513
- const [loading, setLoading] = React2.useState(false);
596
+ const [fieldErrors, setFieldErrors] = React3.useState(errors);
597
+ const [loading, setLoading] = React3.useState(false);
514
598
  async function onSubmit(event) {
515
599
  setLoading(true);
516
600
  if (submitMode === "native") {
@@ -597,8 +681,8 @@ function SignupForm({
597
681
  }
598
682
  function PasswordResetRequestForm({ endpoints = {}, components, onSuccess, onError }) {
599
683
  const { Button, Input, Label } = resolveAuthComponents(components);
600
- const [email, setEmail] = React2.useState("");
601
- const [loading, setLoading] = React2.useState(false);
684
+ const [email, setEmail] = React3.useState("");
685
+ const [loading, setLoading] = React3.useState(false);
602
686
  async function onSubmit(event) {
603
687
  event.preventDefault();
604
688
  setLoading(true);
@@ -621,10 +705,10 @@ function PasswordResetRequestForm({ endpoints = {}, components, onSuccess, onErr
621
705
  }
622
706
  function ResetPasswordForm({ endpoints = {}, components, onSuccess, onError, token: initialToken = "", email: initialEmail = "" }) {
623
707
  const { Button, Input, Label } = resolveAuthComponents(components);
624
- const [email, setEmail] = React2.useState(initialEmail);
625
- const [token, setToken] = React2.useState(initialToken);
626
- const [password, setPassword] = React2.useState("");
627
- const [passwordConfirmation, setPasswordConfirmation] = React2.useState("");
708
+ const [email, setEmail] = React3.useState(initialEmail);
709
+ const [token, setToken] = React3.useState(initialToken);
710
+ const [password, setPassword] = React3.useState("");
711
+ const [passwordConfirmation, setPasswordConfirmation] = React3.useState("");
628
712
  async function onSubmit(event) {
629
713
  event.preventDefault();
630
714
  try {
@@ -658,10 +742,10 @@ function ResetPasswordForm({ endpoints = {}, components, onSuccess, onError, tok
658
742
  }
659
743
  function ChangePasswordForm({ endpoints = {}, components, onSuccess, onError }) {
660
744
  const { Button, Input, Label } = resolveAuthComponents(components);
661
- const [currentPassword, setCurrentPassword] = React2.useState("");
662
- const [password, setPassword] = React2.useState("");
663
- const [passwordConfirmation, setPasswordConfirmation] = React2.useState("");
664
- const [loading, setLoading] = React2.useState(false);
745
+ const [currentPassword, setCurrentPassword] = React3.useState("");
746
+ const [password, setPassword] = React3.useState("");
747
+ const [passwordConfirmation, setPasswordConfirmation] = React3.useState("");
748
+ const [loading, setLoading] = React3.useState(false);
665
749
  async function onSubmit(event) {
666
750
  event.preventDefault();
667
751
  setLoading(true);
@@ -704,12 +788,12 @@ function ChangePasswordForm({ endpoints = {}, components, onSuccess, onError })
704
788
  }
705
789
  function TwoFactorForm({ endpoints = {}, components, attemptToken, appEnv, onSuccess, onError, onReportSuspicious }) {
706
790
  const { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
707
- const [currentAttemptToken, setCurrentAttemptToken] = React2.useState(attemptToken);
708
- const [code, setCode] = React2.useState("");
709
- const [loading, setLoading] = React2.useState(false);
710
- const [resending, setResending] = React2.useState(false);
711
- const [message, setMessage] = React2.useState("");
712
- React2.useEffect(() => setCurrentAttemptToken(attemptToken), [attemptToken]);
791
+ const [currentAttemptToken, setCurrentAttemptToken] = React3.useState(attemptToken);
792
+ const [code, setCode] = React3.useState("");
793
+ const [loading, setLoading] = React3.useState(false);
794
+ const [resending, setResending] = React3.useState(false);
795
+ const [message, setMessage] = React3.useState("");
796
+ React3.useEffect(() => setCurrentAttemptToken(attemptToken), [attemptToken]);
713
797
  async function onSubmit(event) {
714
798
  event.preventDefault();
715
799
  setLoading(true);
@@ -791,20 +875,20 @@ function TwoFactorForm({ endpoints = {}, components, attemptToken, appEnv, onSuc
791
875
 
792
876
  // src/passkey-section.tsx
793
877
  var import_lucide_react2 = require("lucide-react");
794
- var React3 = __toESM(require("react"), 1);
878
+ var React4 = __toESM(require("react"), 1);
795
879
  var import_react_dom = require("react-dom");
796
880
  var import_jsx_runtime3 = require("react/jsx-runtime");
797
881
  function PasskeySection({ endpoints = {}, components, onSuccess, onError }) {
798
882
  const { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
799
- const [passkeys, setPasskeys] = React3.useState([]);
800
- const [loading, setLoading] = React3.useState(true);
801
- const [registering, setRegistering] = React3.useState(false);
802
- const [pendingName, setPendingName] = React3.useState("");
883
+ const [passkeys, setPasskeys] = React4.useState([]);
884
+ const [loading, setLoading] = React4.useState(true);
885
+ const [registering, setRegistering] = React4.useState(false);
886
+ const [pendingName, setPendingName] = React4.useState("");
803
887
  const listUrl = endpoints.passkeyList ?? "/api/passkeys";
804
888
  const registerOptionsUrl = endpoints.passkeyRegisterOptions ?? "/api/passkeys/register/options";
805
889
  const registerUrl = endpoints.passkeyRegister ?? "/api/passkeys/register";
806
890
  const deleteUrl = endpoints.passkeyDelete ?? ((id) => `/api/passkeys/${id}`);
807
- const fetchPasskeys = React3.useCallback(async () => {
891
+ const fetchPasskeys = React4.useCallback(async () => {
808
892
  try {
809
893
  const res = await fetch(listUrl);
810
894
  if (res.ok) {
@@ -816,7 +900,7 @@ function PasskeySection({ endpoints = {}, components, onSuccess, onError }) {
816
900
  setLoading(false);
817
901
  }
818
902
  }, [listUrl, onError]);
819
- React3.useEffect(() => {
903
+ React4.useEffect(() => {
820
904
  void fetchPasskeys();
821
905
  }, [fetchPasskeys]);
822
906
  async function registerPasskey2() {
package/dist/index.d.cts CHANGED
@@ -136,10 +136,11 @@ interface PasskeyLoginButtonProps {
136
136
  endpoints?: AuthEndpointConfig;
137
137
  components: AuthButtonComponentInput;
138
138
  className?: string;
139
+ disabled?: boolean;
139
140
  onSuccess?: (redirectUrl: string, result: AuthJsonResponse) => void;
140
141
  onError?: (message: string) => void;
141
142
  }
142
- declare function PasskeyLoginButton({ endpoints, components, className, onSuccess, onError }: PasskeyLoginButtonProps): React.JSX.Element | null;
143
+ declare function PasskeyLoginButton({ endpoints, components, className, disabled, onSuccess, onError }: PasskeyLoginButtonProps): React.JSX.Element | null;
143
144
 
144
145
  interface PasskeySectionProps {
145
146
  endpoints?: AuthEndpointConfig;
package/dist/index.d.ts CHANGED
@@ -136,10 +136,11 @@ interface PasskeyLoginButtonProps {
136
136
  endpoints?: AuthEndpointConfig;
137
137
  components: AuthButtonComponentInput;
138
138
  className?: string;
139
+ disabled?: boolean;
139
140
  onSuccess?: (redirectUrl: string, result: AuthJsonResponse) => void;
140
141
  onError?: (message: string) => void;
141
142
  }
142
- declare function PasskeyLoginButton({ endpoints, components, className, onSuccess, onError }: PasskeyLoginButtonProps): React.JSX.Element | null;
143
+ declare function PasskeyLoginButton({ endpoints, components, className, disabled, onSuccess, onError }: PasskeyLoginButtonProps): React.JSX.Element | null;
143
144
 
144
145
  interface PasskeySectionProps {
145
146
  endpoints?: AuthEndpointConfig;
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/forms.tsx
2
- import * as React2 from "react";
2
+ import * as React3 from "react";
3
3
 
4
4
  // src/components.ts
5
5
  var requiredComponentKeys = [
@@ -26,10 +26,17 @@ function resolveAuthButtonComponent(components) {
26
26
  return { Button: components.Button };
27
27
  }
28
28
 
29
- // src/passkey-login-button.tsx
30
- import { KeyRound } from "lucide-react";
29
+ // src/passkey-authentication.ts
31
30
  import * as React from "react";
32
31
 
32
+ // src/abort-utils.ts
33
+ function throwIfAborted(signal) {
34
+ if (!signal?.aborted) return;
35
+ const error = new Error("Passkey authentication was cancelled");
36
+ error.name = "AbortError";
37
+ throw error;
38
+ }
39
+
33
40
  // src/webauthn-utils.ts
34
41
  function getCsrfToken(explicitToken) {
35
42
  if (explicitToken) {
@@ -56,7 +63,7 @@ function arrayBufferToBase64url(buffer) {
56
63
  return window.btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
57
64
  }
58
65
  function isAbortError(error) {
59
- return error instanceof Error && error.name === "AbortError";
66
+ return error !== null && typeof error === "object" && "name" in error && error.name === "AbortError";
60
67
  }
61
68
  function getDefaultPasskeyName() {
62
69
  if (typeof window === "undefined") return "Passkey";
@@ -99,6 +106,7 @@ async function authenticateWithPasskey({ endpoints = {}, mediation, signal } = {
99
106
  throw new Error("Failed to get authentication options");
100
107
  }
101
108
  const options = await optRes.json();
109
+ throwIfAborted(signal);
102
110
  const publicKey = {
103
111
  ...options,
104
112
  challenge: base64urlToArrayBuffer(options.challenge),
@@ -108,6 +116,7 @@ async function authenticateWithPasskey({ endpoints = {}, mediation, signal } = {
108
116
  }))
109
117
  };
110
118
  const credential = await navigator.credentials.get({ publicKey, mediation, signal });
119
+ throwIfAborted(signal);
111
120
  if (!credential || credential.type !== "public-key") {
112
121
  throw new Error("No passkey selected");
113
122
  }
@@ -202,31 +211,87 @@ async function registerPasskey({ endpoints = {}, name, signal } = {}) {
202
211
  return { result };
203
212
  }
204
213
 
214
+ // src/passkey-authentication.ts
215
+ var PasskeyAuthenticationContext = React.createContext(null);
216
+ function usePasskeyAuthentication() {
217
+ const pending = React.useRef(null);
218
+ const cancel = React.useCallback(async (conditionalOnly = false) => {
219
+ const request = pending.current;
220
+ if (!request || conditionalOnly && !request.conditional) return;
221
+ request.controller.abort();
222
+ await request.promise.catch(() => void 0);
223
+ }, []);
224
+ const authenticate = React.useCallback(async (options = {}) => {
225
+ const previous = pending.current;
226
+ const controller = new AbortController();
227
+ previous?.controller.abort();
228
+ const promise = (async () => {
229
+ if (previous) await previous.promise.catch(() => void 0);
230
+ throwIfAborted(controller.signal);
231
+ const result = await authenticateWithPasskey({ ...options, signal: controller.signal });
232
+ throwIfAborted(controller.signal);
233
+ return result;
234
+ })();
235
+ const request = { controller, promise, conditional: options.mediation === "conditional" };
236
+ pending.current = request;
237
+ try {
238
+ return await promise;
239
+ } finally {
240
+ if (pending.current === request) pending.current = null;
241
+ }
242
+ }, []);
243
+ React.useEffect(() => () => {
244
+ void cancel();
245
+ }, [cancel]);
246
+ return React.useMemo(() => ({ authenticate, cancel }), [authenticate, cancel]);
247
+ }
248
+
205
249
  // src/passkey-login-button.tsx
250
+ import { KeyRound } from "lucide-react";
251
+ import * as React2 from "react";
206
252
  import { jsx, jsxs } from "react/jsx-runtime";
207
- function PasskeyLoginButton({ endpoints = {}, components, className, onSuccess, onError }) {
253
+ function PasskeyLoginButton({ endpoints = {}, components, className, disabled = false, onSuccess, onError }) {
208
254
  const { Button } = resolveAuthButtonComponent(components);
209
- const [loading, setLoading] = React.useState(false);
210
- const [error, setError] = React.useState(null);
255
+ const [loading, setLoading] = React2.useState(false);
256
+ const [error, setError] = React2.useState(null);
257
+ const localAuthentication = usePasskeyAuthentication();
258
+ const authentication = React2.useContext(PasskeyAuthenticationContext) ?? localAuthentication;
259
+ const inFlight = React2.useRef(false);
260
+ const mounted = React2.useRef(true);
261
+ const callbacks = React2.useRef({ onSuccess, onError });
262
+ React2.useLayoutEffect(() => {
263
+ callbacks.current = { onSuccess, onError };
264
+ });
265
+ React2.useEffect(() => {
266
+ mounted.current = true;
267
+ return () => {
268
+ mounted.current = false;
269
+ if (inFlight.current) void authentication.cancel();
270
+ };
271
+ }, [authentication]);
211
272
  async function handlePasskeyLogin() {
273
+ if (disabled || inFlight.current) return;
274
+ inFlight.current = true;
212
275
  setError(null);
213
276
  setLoading(true);
214
277
  try {
215
- const { redirectUrl, result } = await authenticateWithPasskey({ endpoints });
216
- if (onSuccess) {
217
- onSuccess(redirectUrl, result);
278
+ const { redirectUrl, result } = await authentication.authenticate({ endpoints });
279
+ if (!mounted.current) return;
280
+ if (callbacks.current.onSuccess) {
281
+ callbacks.current.onSuccess(redirectUrl, result);
218
282
  } else {
219
283
  window.location.href = redirectUrl;
220
284
  }
221
285
  } catch (caughtError) {
222
- if (isAbortError(caughtError)) {
286
+ if (!mounted.current || isAbortError(caughtError)) {
223
287
  return;
224
288
  }
225
289
  const message = caughtError instanceof Error ? caughtError.message : "Passkey login failed";
226
- setError(message);
227
- onError?.(message);
290
+ if (callbacks.current.onError) callbacks.current.onError(message);
291
+ else setError(message);
228
292
  } finally {
229
- setLoading(false);
293
+ inFlight.current = false;
294
+ if (mounted.current) setLoading(false);
230
295
  }
231
296
  }
232
297
  if (typeof window === "undefined" || !window.PublicKeyCredential) {
@@ -234,7 +299,7 @@ function PasskeyLoginButton({ endpoints = {}, components, className, onSuccess,
234
299
  }
235
300
  return /* @__PURE__ */ jsxs("div", { className, children: [
236
301
  error ? /* @__PURE__ */ jsx("p", { className: "mb-2 text-sm text-destructive", children: error }) : null,
237
- /* @__PURE__ */ jsxs(Button, { type: "button", variant: "outline", className: "w-full", disabled: loading, onClick: handlePasskeyLogin, children: [
302
+ /* @__PURE__ */ jsxs(Button, { type: "button", variant: "outline", className: "w-full", disabled: disabled || loading, onClick: handlePasskeyLogin, children: [
238
303
  /* @__PURE__ */ jsx(KeyRound, { "aria-hidden": "true" }),
239
304
  loading ? "Verifying..." : "Sign in with Passkey"
240
305
  ] })
@@ -304,53 +369,70 @@ function LoginForm({
304
369
  enablePasskeyAutofill = enablePasskeys
305
370
  }) {
306
371
  const { Button, Card, CardContent, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
307
- const [email, setEmail] = React2.useState(initialEmail);
308
- const [password, setPassword] = React2.useState("");
309
- const [remember, setRemember] = React2.useState(false);
310
- const [loading, setLoading] = React2.useState(false);
311
- const [conditionalPasskeyAvailable, setConditionalPasskeyAvailable] = React2.useState(false);
312
- const passkeyEndpoints = React2.useMemo(() => ({
372
+ const [email, setEmail] = React3.useState(initialEmail);
373
+ const [password, setPassword] = React3.useState("");
374
+ const [remember, setRemember] = React3.useState(false);
375
+ const [loading, setLoading] = React3.useState(false);
376
+ const [conditionalPasskeyAvailable, setConditionalPasskeyAvailable] = React3.useState(false);
377
+ const passkeyAuthentication = usePasskeyAuthentication();
378
+ const conditionalInterrupted = React3.useRef(false);
379
+ const submitting = React3.useRef(false);
380
+ const callbacks = React3.useRef({ onError, onPasskeySuccess });
381
+ React3.useLayoutEffect(() => {
382
+ callbacks.current = { onError, onPasskeySuccess };
383
+ });
384
+ const coordinatedAuthentication = React3.useMemo(() => ({
385
+ ...passkeyAuthentication,
386
+ authenticate: (options) => {
387
+ if (options?.mediation !== "conditional") conditionalInterrupted.current = true;
388
+ return passkeyAuthentication.authenticate(options);
389
+ }
390
+ }), [passkeyAuthentication]);
391
+ const passkeyEndpoints = React3.useMemo(() => ({
313
392
  csrfToken: endpoints.csrfToken,
314
393
  passkeyAuth: endpoints.passkeyAuth,
315
394
  passkeyAuthOptions: endpoints.passkeyAuthOptions
316
395
  }), [endpoints.csrfToken, endpoints.passkeyAuth, endpoints.passkeyAuthOptions]);
317
- React2.useEffect(() => {
318
- if (!enablePasskeyAutofill) return;
319
- const abortController = new AbortController();
396
+ React3.useEffect(() => {
397
+ setConditionalPasskeyAvailable(false);
398
+ if (!enablePasskeyAutofill || conditionalInterrupted.current) return;
320
399
  let active = true;
321
400
  async function startConditionalPasskeyLogin() {
322
401
  const available = await isConditionalMediationAvailable();
323
- if (!available || !active) return;
402
+ if (!available || !active || conditionalInterrupted.current) return;
324
403
  setConditionalPasskeyAvailable(true);
325
404
  try {
326
- const { redirectUrl, result } = await authenticateWithPasskey({
405
+ const { redirectUrl, result } = await coordinatedAuthentication.authenticate({
327
406
  endpoints: passkeyEndpoints,
328
- mediation: "conditional",
329
- signal: abortController.signal
407
+ mediation: "conditional"
330
408
  });
331
409
  if (!active) return;
332
- if (onPasskeySuccess) {
333
- onPasskeySuccess(redirectUrl, result);
410
+ if (callbacks.current.onPasskeySuccess) {
411
+ callbacks.current.onPasskeySuccess(redirectUrl, result);
334
412
  } else {
335
413
  window.location.href = redirectUrl;
336
414
  }
337
415
  } catch (error) {
338
416
  if (!isAbortError(error) && active) {
339
- onError?.(error instanceof Error ? error.message : "Passkey login failed");
417
+ callbacks.current.onError?.(error instanceof Error ? error.message : "Passkey login failed");
340
418
  }
341
419
  }
342
420
  }
343
421
  void startConditionalPasskeyLogin();
344
422
  return () => {
345
423
  active = false;
346
- abortController.abort();
424
+ void coordinatedAuthentication.cancel(true);
347
425
  };
348
- }, [enablePasskeyAutofill, onError, onPasskeySuccess, passkeyEndpoints]);
426
+ }, [enablePasskeyAutofill, coordinatedAuthentication, passkeyEndpoints]);
349
427
  async function onSubmit(event) {
350
428
  event.preventDefault();
429
+ if (submitting.current) return;
430
+ submitting.current = true;
431
+ conditionalInterrupted.current = true;
351
432
  onSubmitStart?.();
352
433
  setLoading(true);
353
434
  try {
435
+ await passkeyAuthentication.cancel();
354
436
  const result = await postForm(endpoints.login ?? "/login", { email, password, remember }, endpoints.csrfToken);
355
437
  if (result.requires_2fa) {
356
438
  onTwoFactorRequired?.(result);
@@ -364,6 +446,7 @@ function LoginForm({
364
446
  } catch (error) {
365
447
  onError?.(error instanceof Error ? error.message : "Login failed");
366
448
  } finally {
449
+ submitting.current = false;
367
450
  setLoading(false);
368
451
  }
369
452
  }
@@ -407,11 +490,12 @@ function LoginForm({
407
490
  ] }),
408
491
  /* @__PURE__ */ jsx2(Button, { type: "submit", className: "w-full", disabled: loading, children: loading ? "Signing in..." : "Sign In" })
409
492
  ] }),
410
- enablePasskeys ? /* @__PURE__ */ jsx2("div", { className: "mt-4", children: /* @__PURE__ */ jsx2(
493
+ enablePasskeys ? /* @__PURE__ */ jsx2("div", { className: "mt-4", children: /* @__PURE__ */ jsx2(PasskeyAuthenticationContext.Provider, { value: coordinatedAuthentication, children: /* @__PURE__ */ jsx2(
411
494
  PasskeyLoginButton,
412
495
  {
413
496
  components: { Button },
414
497
  endpoints,
498
+ disabled: loading,
415
499
  onSuccess: (redirectUrl, result) => {
416
500
  if (onPasskeySuccess) {
417
501
  onPasskeySuccess(redirectUrl, result);
@@ -421,7 +505,7 @@ function LoginForm({
421
505
  },
422
506
  onError
423
507
  }
424
- ) }) : null
508
+ ) }) }) : null
425
509
  ] })
426
510
  ] });
427
511
  }
@@ -453,11 +537,11 @@ function SignupForm({
453
537
  submittingLabel = "Creating account..."
454
538
  }) {
455
539
  const { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
456
- const [values, setValues] = React2.useState(() => Object.fromEntries(
540
+ const [values, setValues] = React3.useState(() => Object.fromEntries(
457
541
  fields.map((field) => [field.name, initialSignupValue(field, initialValues)])
458
542
  ));
459
- const [fieldErrors, setFieldErrors] = React2.useState(errors);
460
- const [loading, setLoading] = React2.useState(false);
543
+ const [fieldErrors, setFieldErrors] = React3.useState(errors);
544
+ const [loading, setLoading] = React3.useState(false);
461
545
  async function onSubmit(event) {
462
546
  setLoading(true);
463
547
  if (submitMode === "native") {
@@ -544,8 +628,8 @@ function SignupForm({
544
628
  }
545
629
  function PasswordResetRequestForm({ endpoints = {}, components, onSuccess, onError }) {
546
630
  const { Button, Input, Label } = resolveAuthComponents(components);
547
- const [email, setEmail] = React2.useState("");
548
- const [loading, setLoading] = React2.useState(false);
631
+ const [email, setEmail] = React3.useState("");
632
+ const [loading, setLoading] = React3.useState(false);
549
633
  async function onSubmit(event) {
550
634
  event.preventDefault();
551
635
  setLoading(true);
@@ -568,10 +652,10 @@ function PasswordResetRequestForm({ endpoints = {}, components, onSuccess, onErr
568
652
  }
569
653
  function ResetPasswordForm({ endpoints = {}, components, onSuccess, onError, token: initialToken = "", email: initialEmail = "" }) {
570
654
  const { Button, Input, Label } = resolveAuthComponents(components);
571
- const [email, setEmail] = React2.useState(initialEmail);
572
- const [token, setToken] = React2.useState(initialToken);
573
- const [password, setPassword] = React2.useState("");
574
- const [passwordConfirmation, setPasswordConfirmation] = React2.useState("");
655
+ const [email, setEmail] = React3.useState(initialEmail);
656
+ const [token, setToken] = React3.useState(initialToken);
657
+ const [password, setPassword] = React3.useState("");
658
+ const [passwordConfirmation, setPasswordConfirmation] = React3.useState("");
575
659
  async function onSubmit(event) {
576
660
  event.preventDefault();
577
661
  try {
@@ -605,10 +689,10 @@ function ResetPasswordForm({ endpoints = {}, components, onSuccess, onError, tok
605
689
  }
606
690
  function ChangePasswordForm({ endpoints = {}, components, onSuccess, onError }) {
607
691
  const { Button, Input, Label } = resolveAuthComponents(components);
608
- const [currentPassword, setCurrentPassword] = React2.useState("");
609
- const [password, setPassword] = React2.useState("");
610
- const [passwordConfirmation, setPasswordConfirmation] = React2.useState("");
611
- const [loading, setLoading] = React2.useState(false);
692
+ const [currentPassword, setCurrentPassword] = React3.useState("");
693
+ const [password, setPassword] = React3.useState("");
694
+ const [passwordConfirmation, setPasswordConfirmation] = React3.useState("");
695
+ const [loading, setLoading] = React3.useState(false);
612
696
  async function onSubmit(event) {
613
697
  event.preventDefault();
614
698
  setLoading(true);
@@ -651,12 +735,12 @@ function ChangePasswordForm({ endpoints = {}, components, onSuccess, onError })
651
735
  }
652
736
  function TwoFactorForm({ endpoints = {}, components, attemptToken, appEnv, onSuccess, onError, onReportSuspicious }) {
653
737
  const { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
654
- const [currentAttemptToken, setCurrentAttemptToken] = React2.useState(attemptToken);
655
- const [code, setCode] = React2.useState("");
656
- const [loading, setLoading] = React2.useState(false);
657
- const [resending, setResending] = React2.useState(false);
658
- const [message, setMessage] = React2.useState("");
659
- React2.useEffect(() => setCurrentAttemptToken(attemptToken), [attemptToken]);
738
+ const [currentAttemptToken, setCurrentAttemptToken] = React3.useState(attemptToken);
739
+ const [code, setCode] = React3.useState("");
740
+ const [loading, setLoading] = React3.useState(false);
741
+ const [resending, setResending] = React3.useState(false);
742
+ const [message, setMessage] = React3.useState("");
743
+ React3.useEffect(() => setCurrentAttemptToken(attemptToken), [attemptToken]);
660
744
  async function onSubmit(event) {
661
745
  event.preventDefault();
662
746
  setLoading(true);
@@ -738,20 +822,20 @@ function TwoFactorForm({ endpoints = {}, components, attemptToken, appEnv, onSuc
738
822
 
739
823
  // src/passkey-section.tsx
740
824
  import { Key, Plus, Trash2 } from "lucide-react";
741
- import * as React3 from "react";
825
+ import * as React4 from "react";
742
826
  import { flushSync } from "react-dom";
743
827
  import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
744
828
  function PasskeySection({ endpoints = {}, components, onSuccess, onError }) {
745
829
  const { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
746
- const [passkeys, setPasskeys] = React3.useState([]);
747
- const [loading, setLoading] = React3.useState(true);
748
- const [registering, setRegistering] = React3.useState(false);
749
- const [pendingName, setPendingName] = React3.useState("");
830
+ const [passkeys, setPasskeys] = React4.useState([]);
831
+ const [loading, setLoading] = React4.useState(true);
832
+ const [registering, setRegistering] = React4.useState(false);
833
+ const [pendingName, setPendingName] = React4.useState("");
750
834
  const listUrl = endpoints.passkeyList ?? "/api/passkeys";
751
835
  const registerOptionsUrl = endpoints.passkeyRegisterOptions ?? "/api/passkeys/register/options";
752
836
  const registerUrl = endpoints.passkeyRegister ?? "/api/passkeys/register";
753
837
  const deleteUrl = endpoints.passkeyDelete ?? ((id) => `/api/passkeys/${id}`);
754
- const fetchPasskeys = React3.useCallback(async () => {
838
+ const fetchPasskeys = React4.useCallback(async () => {
755
839
  try {
756
840
  const res = await fetch(listUrl);
757
841
  if (res.ok) {
@@ -763,7 +847,7 @@ function PasskeySection({ endpoints = {}, components, onSuccess, onError }) {
763
847
  setLoading(false);
764
848
  }
765
849
  }, [listUrl, onError]);
766
- React3.useEffect(() => {
850
+ React4.useEffect(() => {
767
851
  void fetchPasskeys();
768
852
  }, [fetchPasskeys]);
769
853
  async function registerPasskey2() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bwh-auth",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "Shared React auth UI and browser WebAuthn helpers for BWH applications.",
5
5
  "license": "MIT",
6
6
  "type": "module",