bwh-auth 0.3.2 → 0.4.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/dist/index.cjs CHANGED
@@ -30,6 +30,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ ApiCredentialsSection: () => ApiCredentialsSection,
33
34
  ChangePasswordForm: () => ChangePasswordForm,
34
35
  LoginForm: () => LoginForm,
35
36
  PasskeyLoginButton: () => PasskeyLoginButton,
@@ -41,6 +42,7 @@ __export(index_exports, {
41
42
  arrayBufferToBase64url: () => arrayBufferToBase64url,
42
43
  authenticateWithPasskey: () => authenticateWithPasskey,
43
44
  base64urlToArrayBuffer: () => base64urlToArrayBuffer,
45
+ describeDuration: () => describeDuration,
44
46
  getCsrfToken: () => getCsrfToken,
45
47
  getDefaultPasskeyName: () => getDefaultPasskeyName,
46
48
  isAbortError: () => isAbortError,
@@ -52,7 +54,7 @@ __export(index_exports, {
52
54
  module.exports = __toCommonJS(index_exports);
53
55
 
54
56
  // src/forms.tsx
55
- var React2 = __toESM(require("react"), 1);
57
+ var React3 = __toESM(require("react"), 1);
56
58
 
57
59
  // src/components.ts
58
60
  var requiredComponentKeys = [
@@ -79,10 +81,17 @@ function resolveAuthButtonComponent(components) {
79
81
  return { Button: components.Button };
80
82
  }
81
83
 
82
- // src/passkey-login-button.tsx
83
- var import_lucide_react = require("lucide-react");
84
+ // src/passkey-authentication.ts
84
85
  var React = __toESM(require("react"), 1);
85
86
 
87
+ // src/abort-utils.ts
88
+ function throwIfAborted(signal) {
89
+ if (!signal?.aborted) return;
90
+ const error = new Error("Passkey authentication was cancelled");
91
+ error.name = "AbortError";
92
+ throw error;
93
+ }
94
+
86
95
  // src/webauthn-utils.ts
87
96
  function getCsrfToken(explicitToken) {
88
97
  if (explicitToken) {
@@ -109,7 +118,7 @@ function arrayBufferToBase64url(buffer) {
109
118
  return window.btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
110
119
  }
111
120
  function isAbortError(error) {
112
- return error instanceof Error && error.name === "AbortError";
121
+ return error !== null && typeof error === "object" && "name" in error && error.name === "AbortError";
113
122
  }
114
123
  function getDefaultPasskeyName() {
115
124
  if (typeof window === "undefined") return "Passkey";
@@ -152,6 +161,7 @@ async function authenticateWithPasskey({ endpoints = {}, mediation, signal } = {
152
161
  throw new Error("Failed to get authentication options");
153
162
  }
154
163
  const options = await optRes.json();
164
+ throwIfAborted(signal);
155
165
  const publicKey = {
156
166
  ...options,
157
167
  challenge: base64urlToArrayBuffer(options.challenge),
@@ -161,6 +171,7 @@ async function authenticateWithPasskey({ endpoints = {}, mediation, signal } = {
161
171
  }))
162
172
  };
163
173
  const credential = await navigator.credentials.get({ publicKey, mediation, signal });
174
+ throwIfAborted(signal);
164
175
  if (!credential || credential.type !== "public-key") {
165
176
  throw new Error("No passkey selected");
166
177
  }
@@ -255,31 +266,87 @@ async function registerPasskey({ endpoints = {}, name, signal } = {}) {
255
266
  return { result };
256
267
  }
257
268
 
269
+ // src/passkey-authentication.ts
270
+ var PasskeyAuthenticationContext = React.createContext(null);
271
+ function usePasskeyAuthentication() {
272
+ const pending = React.useRef(null);
273
+ const cancel = React.useCallback(async (conditionalOnly = false) => {
274
+ const request = pending.current;
275
+ if (!request || conditionalOnly && !request.conditional) return;
276
+ request.controller.abort();
277
+ await request.promise.catch(() => void 0);
278
+ }, []);
279
+ const authenticate = React.useCallback(async (options = {}) => {
280
+ const previous = pending.current;
281
+ const controller = new AbortController();
282
+ previous?.controller.abort();
283
+ const promise = (async () => {
284
+ if (previous) await previous.promise.catch(() => void 0);
285
+ throwIfAborted(controller.signal);
286
+ const result = await authenticateWithPasskey({ ...options, signal: controller.signal });
287
+ throwIfAborted(controller.signal);
288
+ return result;
289
+ })();
290
+ const request = { controller, promise, conditional: options.mediation === "conditional" };
291
+ pending.current = request;
292
+ try {
293
+ return await promise;
294
+ } finally {
295
+ if (pending.current === request) pending.current = null;
296
+ }
297
+ }, []);
298
+ React.useEffect(() => () => {
299
+ void cancel();
300
+ }, [cancel]);
301
+ return React.useMemo(() => ({ authenticate, cancel }), [authenticate, cancel]);
302
+ }
303
+
258
304
  // src/passkey-login-button.tsx
305
+ var import_lucide_react = require("lucide-react");
306
+ var React2 = __toESM(require("react"), 1);
259
307
  var import_jsx_runtime = require("react/jsx-runtime");
260
- function PasskeyLoginButton({ endpoints = {}, components, className, onSuccess, onError }) {
308
+ function PasskeyLoginButton({ endpoints = {}, components, className, disabled = false, onSuccess, onError }) {
261
309
  const { Button } = resolveAuthButtonComponent(components);
262
- const [loading, setLoading] = React.useState(false);
263
- const [error, setError] = React.useState(null);
310
+ const [loading, setLoading] = React2.useState(false);
311
+ const [error, setError] = React2.useState(null);
312
+ const localAuthentication = usePasskeyAuthentication();
313
+ const authentication = React2.useContext(PasskeyAuthenticationContext) ?? localAuthentication;
314
+ const inFlight = React2.useRef(false);
315
+ const mounted = React2.useRef(true);
316
+ const callbacks = React2.useRef({ onSuccess, onError });
317
+ React2.useLayoutEffect(() => {
318
+ callbacks.current = { onSuccess, onError };
319
+ });
320
+ React2.useEffect(() => {
321
+ mounted.current = true;
322
+ return () => {
323
+ mounted.current = false;
324
+ if (inFlight.current) void authentication.cancel();
325
+ };
326
+ }, [authentication]);
264
327
  async function handlePasskeyLogin() {
328
+ if (disabled || inFlight.current) return;
329
+ inFlight.current = true;
265
330
  setError(null);
266
331
  setLoading(true);
267
332
  try {
268
- const { redirectUrl, result } = await authenticateWithPasskey({ endpoints });
269
- if (onSuccess) {
270
- onSuccess(redirectUrl, result);
333
+ const { redirectUrl, result } = await authentication.authenticate({ endpoints });
334
+ if (!mounted.current) return;
335
+ if (callbacks.current.onSuccess) {
336
+ callbacks.current.onSuccess(redirectUrl, result);
271
337
  } else {
272
338
  window.location.href = redirectUrl;
273
339
  }
274
340
  } catch (caughtError) {
275
- if (isAbortError(caughtError)) {
341
+ if (!mounted.current || isAbortError(caughtError)) {
276
342
  return;
277
343
  }
278
344
  const message = caughtError instanceof Error ? caughtError.message : "Passkey login failed";
279
- setError(message);
280
- onError?.(message);
345
+ if (callbacks.current.onError) callbacks.current.onError(message);
346
+ else setError(message);
281
347
  } finally {
282
- setLoading(false);
348
+ inFlight.current = false;
349
+ if (mounted.current) setLoading(false);
283
350
  }
284
351
  }
285
352
  if (typeof window === "undefined" || !window.PublicKeyCredential) {
@@ -287,7 +354,7 @@ function PasskeyLoginButton({ endpoints = {}, components, className, onSuccess,
287
354
  }
288
355
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className, children: [
289
356
  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: [
357
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { type: "button", variant: "outline", className: "w-full", disabled: disabled || loading, onClick: handlePasskeyLogin, children: [
291
358
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.KeyRound, { "aria-hidden": "true" }),
292
359
  loading ? "Verifying..." : "Sign in with Passkey"
293
360
  ] })
@@ -357,53 +424,70 @@ function LoginForm({
357
424
  enablePasskeyAutofill = enablePasskeys
358
425
  }) {
359
426
  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(() => ({
427
+ const [email, setEmail] = React3.useState(initialEmail);
428
+ const [password, setPassword] = React3.useState("");
429
+ const [remember, setRemember] = React3.useState(false);
430
+ const [loading, setLoading] = React3.useState(false);
431
+ const [conditionalPasskeyAvailable, setConditionalPasskeyAvailable] = React3.useState(false);
432
+ const passkeyAuthentication = usePasskeyAuthentication();
433
+ const conditionalInterrupted = React3.useRef(false);
434
+ const submitting = React3.useRef(false);
435
+ const callbacks = React3.useRef({ onError, onPasskeySuccess });
436
+ React3.useLayoutEffect(() => {
437
+ callbacks.current = { onError, onPasskeySuccess };
438
+ });
439
+ const coordinatedAuthentication = React3.useMemo(() => ({
440
+ ...passkeyAuthentication,
441
+ authenticate: (options) => {
442
+ if (options?.mediation !== "conditional") conditionalInterrupted.current = true;
443
+ return passkeyAuthentication.authenticate(options);
444
+ }
445
+ }), [passkeyAuthentication]);
446
+ const passkeyEndpoints = React3.useMemo(() => ({
366
447
  csrfToken: endpoints.csrfToken,
367
448
  passkeyAuth: endpoints.passkeyAuth,
368
449
  passkeyAuthOptions: endpoints.passkeyAuthOptions
369
450
  }), [endpoints.csrfToken, endpoints.passkeyAuth, endpoints.passkeyAuthOptions]);
370
- React2.useEffect(() => {
371
- if (!enablePasskeyAutofill) return;
372
- const abortController = new AbortController();
451
+ React3.useEffect(() => {
452
+ setConditionalPasskeyAvailable(false);
453
+ if (!enablePasskeyAutofill || conditionalInterrupted.current) return;
373
454
  let active = true;
374
455
  async function startConditionalPasskeyLogin() {
375
456
  const available = await isConditionalMediationAvailable();
376
- if (!available || !active) return;
457
+ if (!available || !active || conditionalInterrupted.current) return;
377
458
  setConditionalPasskeyAvailable(true);
378
459
  try {
379
- const { redirectUrl, result } = await authenticateWithPasskey({
460
+ const { redirectUrl, result } = await coordinatedAuthentication.authenticate({
380
461
  endpoints: passkeyEndpoints,
381
- mediation: "conditional",
382
- signal: abortController.signal
462
+ mediation: "conditional"
383
463
  });
384
464
  if (!active) return;
385
- if (onPasskeySuccess) {
386
- onPasskeySuccess(redirectUrl, result);
465
+ if (callbacks.current.onPasskeySuccess) {
466
+ callbacks.current.onPasskeySuccess(redirectUrl, result);
387
467
  } else {
388
468
  window.location.href = redirectUrl;
389
469
  }
390
470
  } catch (error) {
391
471
  if (!isAbortError(error) && active) {
392
- onError?.(error instanceof Error ? error.message : "Passkey login failed");
472
+ callbacks.current.onError?.(error instanceof Error ? error.message : "Passkey login failed");
393
473
  }
394
474
  }
395
475
  }
396
476
  void startConditionalPasskeyLogin();
397
477
  return () => {
398
478
  active = false;
399
- abortController.abort();
479
+ void coordinatedAuthentication.cancel(true);
400
480
  };
401
- }, [enablePasskeyAutofill, onError, onPasskeySuccess, passkeyEndpoints]);
481
+ }, [enablePasskeyAutofill, coordinatedAuthentication, passkeyEndpoints]);
402
482
  async function onSubmit(event) {
403
483
  event.preventDefault();
484
+ if (submitting.current) return;
485
+ submitting.current = true;
486
+ conditionalInterrupted.current = true;
404
487
  onSubmitStart?.();
405
488
  setLoading(true);
406
489
  try {
490
+ await passkeyAuthentication.cancel();
407
491
  const result = await postForm(endpoints.login ?? "/login", { email, password, remember }, endpoints.csrfToken);
408
492
  if (result.requires_2fa) {
409
493
  onTwoFactorRequired?.(result);
@@ -417,6 +501,7 @@ function LoginForm({
417
501
  } catch (error) {
418
502
  onError?.(error instanceof Error ? error.message : "Login failed");
419
503
  } finally {
504
+ submitting.current = false;
420
505
  setLoading(false);
421
506
  }
422
507
  }
@@ -460,11 +545,12 @@ function LoginForm({
460
545
  ] }),
461
546
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Button, { type: "submit", className: "w-full", disabled: loading, children: loading ? "Signing in..." : "Sign In" })
462
547
  ] }),
463
- enablePasskeys ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: "mt-4", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
548
+ 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
549
  PasskeyLoginButton,
465
550
  {
466
551
  components: { Button },
467
552
  endpoints,
553
+ disabled: loading,
468
554
  onSuccess: (redirectUrl, result) => {
469
555
  if (onPasskeySuccess) {
470
556
  onPasskeySuccess(redirectUrl, result);
@@ -474,7 +560,7 @@ function LoginForm({
474
560
  },
475
561
  onError
476
562
  }
477
- ) }) : null
563
+ ) }) }) : null
478
564
  ] })
479
565
  ] });
480
566
  }
@@ -506,11 +592,11 @@ function SignupForm({
506
592
  submittingLabel = "Creating account..."
507
593
  }) {
508
594
  const { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
509
- const [values, setValues] = React2.useState(() => Object.fromEntries(
595
+ const [values, setValues] = React3.useState(() => Object.fromEntries(
510
596
  fields.map((field) => [field.name, initialSignupValue(field, initialValues)])
511
597
  ));
512
- const [fieldErrors, setFieldErrors] = React2.useState(errors);
513
- const [loading, setLoading] = React2.useState(false);
598
+ const [fieldErrors, setFieldErrors] = React3.useState(errors);
599
+ const [loading, setLoading] = React3.useState(false);
514
600
  async function onSubmit(event) {
515
601
  setLoading(true);
516
602
  if (submitMode === "native") {
@@ -597,8 +683,8 @@ function SignupForm({
597
683
  }
598
684
  function PasswordResetRequestForm({ endpoints = {}, components, onSuccess, onError }) {
599
685
  const { Button, Input, Label } = resolveAuthComponents(components);
600
- const [email, setEmail] = React2.useState("");
601
- const [loading, setLoading] = React2.useState(false);
686
+ const [email, setEmail] = React3.useState("");
687
+ const [loading, setLoading] = React3.useState(false);
602
688
  async function onSubmit(event) {
603
689
  event.preventDefault();
604
690
  setLoading(true);
@@ -621,10 +707,10 @@ function PasswordResetRequestForm({ endpoints = {}, components, onSuccess, onErr
621
707
  }
622
708
  function ResetPasswordForm({ endpoints = {}, components, onSuccess, onError, token: initialToken = "", email: initialEmail = "" }) {
623
709
  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("");
710
+ const [email, setEmail] = React3.useState(initialEmail);
711
+ const [token, setToken] = React3.useState(initialToken);
712
+ const [password, setPassword] = React3.useState("");
713
+ const [passwordConfirmation, setPasswordConfirmation] = React3.useState("");
628
714
  async function onSubmit(event) {
629
715
  event.preventDefault();
630
716
  try {
@@ -658,10 +744,10 @@ function ResetPasswordForm({ endpoints = {}, components, onSuccess, onError, tok
658
744
  }
659
745
  function ChangePasswordForm({ endpoints = {}, components, onSuccess, onError }) {
660
746
  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);
747
+ const [currentPassword, setCurrentPassword] = React3.useState("");
748
+ const [password, setPassword] = React3.useState("");
749
+ const [passwordConfirmation, setPasswordConfirmation] = React3.useState("");
750
+ const [loading, setLoading] = React3.useState(false);
665
751
  async function onSubmit(event) {
666
752
  event.preventDefault();
667
753
  setLoading(true);
@@ -704,12 +790,12 @@ function ChangePasswordForm({ endpoints = {}, components, onSuccess, onError })
704
790
  }
705
791
  function TwoFactorForm({ endpoints = {}, components, attemptToken, appEnv, onSuccess, onError, onReportSuspicious }) {
706
792
  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]);
793
+ const [currentAttemptToken, setCurrentAttemptToken] = React3.useState(attemptToken);
794
+ const [code, setCode] = React3.useState("");
795
+ const [loading, setLoading] = React3.useState(false);
796
+ const [resending, setResending] = React3.useState(false);
797
+ const [message, setMessage] = React3.useState("");
798
+ React3.useEffect(() => setCurrentAttemptToken(attemptToken), [attemptToken]);
713
799
  async function onSubmit(event) {
714
800
  event.preventDefault();
715
801
  setLoading(true);
@@ -791,20 +877,20 @@ function TwoFactorForm({ endpoints = {}, components, attemptToken, appEnv, onSuc
791
877
 
792
878
  // src/passkey-section.tsx
793
879
  var import_lucide_react2 = require("lucide-react");
794
- var React3 = __toESM(require("react"), 1);
880
+ var React4 = __toESM(require("react"), 1);
795
881
  var import_react_dom = require("react-dom");
796
882
  var import_jsx_runtime3 = require("react/jsx-runtime");
797
883
  function PasskeySection({ endpoints = {}, components, onSuccess, onError }) {
798
884
  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("");
885
+ const [passkeys, setPasskeys] = React4.useState([]);
886
+ const [loading, setLoading] = React4.useState(true);
887
+ const [registering, setRegistering] = React4.useState(false);
888
+ const [pendingName, setPendingName] = React4.useState("");
803
889
  const listUrl = endpoints.passkeyList ?? "/api/passkeys";
804
890
  const registerOptionsUrl = endpoints.passkeyRegisterOptions ?? "/api/passkeys/register/options";
805
891
  const registerUrl = endpoints.passkeyRegister ?? "/api/passkeys/register";
806
892
  const deleteUrl = endpoints.passkeyDelete ?? ((id) => `/api/passkeys/${id}`);
807
- const fetchPasskeys = React3.useCallback(async () => {
893
+ const fetchPasskeys = React4.useCallback(async () => {
808
894
  try {
809
895
  const res = await fetch(listUrl);
810
896
  if (res.ok) {
@@ -816,7 +902,7 @@ function PasskeySection({ endpoints = {}, components, onSuccess, onError }) {
816
902
  setLoading(false);
817
903
  }
818
904
  }, [listUrl, onError]);
819
- React3.useEffect(() => {
905
+ React4.useEffect(() => {
820
906
  void fetchPasskeys();
821
907
  }, [fetchPasskeys]);
822
908
  async function registerPasskey2() {
@@ -911,8 +997,398 @@ function relyingApplicationsFrom(value) {
911
997
  return href === null ? [] : [{ key, name: name.trim(), url: href }];
912
998
  });
913
999
  }
1000
+
1001
+ // src/api-credentials-section.tsx
1002
+ var React5 = __toESM(require("react"), 1);
1003
+ var import_jsx_runtime4 = require("react/jsx-runtime");
1004
+ function ApiCredentialsSection({ indexUrl, components, links = [], csrfToken, onSuccess, onError }) {
1005
+ const { Card, CardContent, CardDescription, CardHeader, CardTitle } = resolveAuthComponents(components);
1006
+ const [index, setIndex] = React5.useState(null);
1007
+ const [issued, setIssued] = React5.useState([]);
1008
+ const issuedKey = React5.useRef(0);
1009
+ const addIssued = React5.useCallback((credential) => {
1010
+ issuedKey.current += 1;
1011
+ const key = issuedKey.current;
1012
+ setIssued((current) => [...current, { key, credential }]);
1013
+ }, []);
1014
+ const [loadError, setLoadError] = React5.useState(null);
1015
+ const onErrorRef = React5.useRef(onError);
1016
+ onErrorRef.current = onError;
1017
+ const generation = React5.useRef(0);
1018
+ const context = React5.useRef({ indexUrl, csrfToken });
1019
+ context.current = { indexUrl, csrfToken };
1020
+ const reload = React5.useCallback(async () => {
1021
+ generation.current += 1;
1022
+ const mine = generation.current;
1023
+ const { indexUrl: url, csrfToken: token } = context.current;
1024
+ const result = await credentialRequest("GET", url, void 0, token);
1025
+ if (mine !== generation.current) {
1026
+ return;
1027
+ }
1028
+ if (result.ok) {
1029
+ setIndex(result.data);
1030
+ setLoadError(null);
1031
+ } else {
1032
+ setLoadError(result.message);
1033
+ onErrorRef.current?.("api-credentials", result.message);
1034
+ }
1035
+ }, []);
1036
+ React5.useEffect(() => {
1037
+ setIndex(null);
1038
+ void reload();
1039
+ }, [indexUrl, csrfToken, reload]);
1040
+ const removeLocally = React5.useCallback((list, id) => {
1041
+ setIndex(
1042
+ (current) => current === null ? current : list === "tokens" ? { ...current, tokens: current.tokens.filter((token) => token.id !== id) } : { ...current, apps: current.apps.filter((app) => app.id !== id) }
1043
+ );
1044
+ }, []);
1045
+ const shared = { components, csrfToken, onError, onSuccess, removeLocally };
1046
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(Card, { children: [
1047
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(CardHeader, { children: [
1048
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(CardTitle, { children: "API access" }),
1049
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(CardDescription, { children: "Connect apps that use the API. Register an OAuth app for apps that sign you in, or create an API token for apps that ask for a key. Each carries only the permissions you choose, and never more than your own access." })
1050
+ ] }),
1051
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(CardContent, { children: /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "grid", gap: "1.5rem", minWidth: 0 }, children: [
1052
+ links.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("dl", { style: { display: "grid", gap: "0.5rem", minWidth: 0 }, children: links.map((link) => /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { minWidth: 0 }, children: [
1053
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("dt", { children: link.label }),
1054
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("dd", { style: { margin: 0, overflowWrap: "anywhere" }, children: [
1055
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("code", { children: link.url }),
1056
+ " ",
1057
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(CopyButton, { text: link.url, label: link.label, components })
1058
+ ] })
1059
+ ] }, link.label)) }),
1060
+ issued.map(({ key, credential }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1061
+ IssuedNotice,
1062
+ {
1063
+ issued: credential,
1064
+ components,
1065
+ onDismiss: () => setIssued((current) => current.filter((entry) => entry.key !== key))
1066
+ },
1067
+ key
1068
+ )),
1069
+ loadError !== null && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("p", { role: "alert", children: loadError }),
1070
+ index !== null && /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
1071
+ (index.issue_token_href === null || index.register_app_href === null) && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("p", { role: "status", children: "Creating new credentials is unavailable right now. You can still revoke existing ones." }),
1072
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(TokenSection, { index, ...shared, onIssued: addIssued, reload }),
1073
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(AppSection, { index, ...shared, onIssued: addIssued, reload })
1074
+ ] })
1075
+ ] }) })
1076
+ ] });
1077
+ }
1078
+ function TokenSection({ index, components, csrfToken, onIssued, reload, onSuccess, onError, removeLocally }) {
1079
+ const { Button, Input, Label } = resolveAuthComponents(components);
1080
+ const [name, setName] = React5.useState("");
1081
+ const [scopes, setScopes] = React5.useState([]);
1082
+ const [lifetime, setLifetime] = React5.useState(index.token_lifetimes[0] ?? "");
1083
+ const [busy, setBusy] = React5.useState(false);
1084
+ const [error, setError] = React5.useState(null);
1085
+ async function create(event) {
1086
+ event.preventDefault();
1087
+ if (index.issue_token_href === null) {
1088
+ return;
1089
+ }
1090
+ setBusy(true);
1091
+ const result = await credentialRequest("POST", index.issue_token_href, { name, scopes, lifetime }, csrfToken);
1092
+ setBusy(false);
1093
+ if (!result.ok) {
1094
+ setError(result.message);
1095
+ onError?.("api-tokens", result.message);
1096
+ return;
1097
+ }
1098
+ setError(null);
1099
+ setName("");
1100
+ setScopes([]);
1101
+ onIssued(result.data);
1102
+ onSuccess?.("API token created.");
1103
+ await reload();
1104
+ }
1105
+ const [pending, setPending] = React5.useState([]);
1106
+ async function revoke(token) {
1107
+ if (pending.includes(token.id)) {
1108
+ return;
1109
+ }
1110
+ setPending((current) => [...current, token.id]);
1111
+ const result = await credentialRequest("DELETE", token.revoke_href, void 0, csrfToken);
1112
+ if (!result.ok) {
1113
+ setPending((current) => current.filter((id) => id !== token.id));
1114
+ setError(result.message);
1115
+ onError?.("api-tokens", result.message);
1116
+ return;
1117
+ }
1118
+ setError(null);
1119
+ removeLocally("tokens", token.id);
1120
+ onSuccess?.("API token revoked.");
1121
+ await reload();
1122
+ setPending((current) => current.filter((id) => id !== token.id));
1123
+ }
1124
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("section", { style: { display: "grid", gap: "0.75rem", minWidth: 0 }, children: [
1125
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("h3", { children: "API tokens" }),
1126
+ index.issue_token_href !== null && /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("form", { onSubmit: create, style: { display: "grid", gap: "0.75rem" }, children: [
1127
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "grid", gap: "0.25rem" }, children: [
1128
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Label, { htmlFor: "api-token-name", children: "Token name" }),
1129
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Input, { id: "api-token-name", value: name, maxLength: 120, onChange: (event) => setName(event.target.value) })
1130
+ ] }),
1131
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(ScopePicker, { idPrefix: "api-token-scope", scopes: index.scopes, selected: scopes, onChange: setScopes }),
1132
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("fieldset", { style: { display: "grid", gap: "0.25rem", border: 0, padding: 0 }, children: [
1133
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("legend", { children: "Expires after" }),
1134
+ index.token_lifetimes.map((spec) => /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { children: [
1135
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("input", { type: "radio", name: "api-token-lifetime", checked: lifetime === spec, onChange: () => setLifetime(spec) }),
1136
+ " ",
1137
+ describeDuration(spec)
1138
+ ] }, spec))
1139
+ ] }),
1140
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Button, { type: "submit", disabled: busy || name.trim() === "" || scopes.length === 0 || lifetime === "", children: "Create API token" }) })
1141
+ ] }),
1142
+ error !== null && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("p", { role: "alert", children: error }),
1143
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("ul", { style: { display: "grid", gap: "0.5rem", listStyle: "none", padding: 0, margin: 0, minWidth: 0 }, children: index.tokens.map((token) => /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("li", { style: { minWidth: 0, overflowWrap: "anywhere" }, children: [
1144
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("strong", { children: token.name }),
1145
+ " \xB7 ",
1146
+ token.scopes.join(", "),
1147
+ token.expires_at !== null && /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
1148
+ " \xB7 expires ",
1149
+ new Date(token.expires_at).toLocaleString()
1150
+ ] }),
1151
+ " ",
1152
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Button, { type: "button", disabled: pending.includes(token.id), onClick: () => void revoke(token), children: "Revoke" })
1153
+ ] }, token.id)) })
1154
+ ] });
1155
+ }
1156
+ function AppSection({ index, components, csrfToken, onIssued, reload, onSuccess, onError, removeLocally }) {
1157
+ const { Button, Input, Label } = resolveAuthComponents(components);
1158
+ const [name, setName] = React5.useState("");
1159
+ const [redirects, setRedirects] = React5.useState("");
1160
+ const [confidential, setConfidential] = React5.useState(true);
1161
+ const [scopes, setScopes] = React5.useState([]);
1162
+ const [busy, setBusy] = React5.useState(false);
1163
+ const [error, setError] = React5.useState(null);
1164
+ const redirectUris = redirects.split("\n").map((line) => line.trim()).filter((line) => line !== "");
1165
+ async function register(event) {
1166
+ event.preventDefault();
1167
+ if (index.register_app_href === null) {
1168
+ return;
1169
+ }
1170
+ setBusy(true);
1171
+ const result = await credentialRequest(
1172
+ "POST",
1173
+ index.register_app_href,
1174
+ { name, redirect_uris: redirectUris, confidential, scopes },
1175
+ csrfToken
1176
+ );
1177
+ setBusy(false);
1178
+ if (!result.ok) {
1179
+ setError(result.message);
1180
+ onError?.("oauth-apps", result.message);
1181
+ return;
1182
+ }
1183
+ setError(null);
1184
+ setName("");
1185
+ setRedirects("");
1186
+ setScopes([]);
1187
+ onIssued(result.data);
1188
+ onSuccess?.("OAuth app registered.");
1189
+ await reload();
1190
+ }
1191
+ const [pending, setPending] = React5.useState([]);
1192
+ async function remove(app) {
1193
+ if (pending.includes(app.id)) {
1194
+ return;
1195
+ }
1196
+ setPending((current) => [...current, app.id]);
1197
+ const result = await credentialRequest("DELETE", app.delete_href, void 0, csrfToken);
1198
+ if (!result.ok) {
1199
+ setPending((current) => current.filter((id) => id !== app.id));
1200
+ setError(result.message);
1201
+ onError?.("oauth-apps", result.message);
1202
+ return;
1203
+ }
1204
+ setError(null);
1205
+ removeLocally("apps", app.id);
1206
+ onSuccess?.("OAuth app deleted and its tokens revoked.");
1207
+ await reload();
1208
+ setPending((current) => current.filter((id) => id !== app.id));
1209
+ }
1210
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("section", { style: { display: "grid", gap: "0.75rem", minWidth: 0 }, children: [
1211
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("h3", { children: "OAuth apps" }),
1212
+ index.register_app_href !== null && /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("form", { onSubmit: register, style: { display: "grid", gap: "0.75rem" }, children: [
1213
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "grid", gap: "0.25rem" }, children: [
1214
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Label, { htmlFor: "oauth-app-name", children: "App name" }),
1215
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Input, { id: "oauth-app-name", value: name, maxLength: 120, onChange: (event) => setName(event.target.value) })
1216
+ ] }),
1217
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "grid", gap: "0.25rem" }, children: [
1218
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Label, { htmlFor: "oauth-app-redirects", children: "Redirect URIs (one per line)" }),
1219
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("textarea", { id: "oauth-app-redirects", rows: 3, value: redirects, onChange: (event) => setRedirects(event.target.value) })
1220
+ ] }),
1221
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("fieldset", { style: { display: "grid", gap: "0.25rem", border: 0, padding: 0 }, children: [
1222
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("legend", { children: "Client type" }),
1223
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { children: [
1224
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("input", { type: "radio", name: "oauth-app-type", checked: confidential, onChange: () => setConfidential(true) }),
1225
+ " Confidential: the app keeps a client secret on its server"
1226
+ ] }),
1227
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { children: [
1228
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("input", { type: "radio", name: "oauth-app-type", checked: !confidential, onChange: () => setConfidential(false) }),
1229
+ " Public: no secret, PKCE only"
1230
+ ] })
1231
+ ] }),
1232
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(ScopePicker, { idPrefix: "oauth-app-scope", scopes: index.scopes, selected: scopes, onChange: setScopes }),
1233
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Button, { type: "submit", disabled: busy || name.trim() === "" || redirectUris.length === 0 || scopes.length === 0, children: "Register OAuth app" }) })
1234
+ ] }),
1235
+ error !== null && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("p", { role: "alert", children: error }),
1236
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("ul", { style: { display: "grid", gap: "0.5rem", listStyle: "none", padding: 0, margin: 0, minWidth: 0 }, children: index.apps.map((app) => /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("li", { style: { minWidth: 0, overflowWrap: "anywhere" }, children: [
1237
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("strong", { children: app.name }),
1238
+ " \xB7 client ID ",
1239
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("code", { children: app.id }),
1240
+ " \xB7 ",
1241
+ app.confidential ? "confidential" : "public",
1242
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("br", {}),
1243
+ app.redirect_uris.join(", "),
1244
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("br", {}),
1245
+ "May request: ",
1246
+ app.scopes.join(", "),
1247
+ " ",
1248
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Button, { type: "button", disabled: pending.includes(app.id), onClick: () => void remove(app), children: "Delete" })
1249
+ ] }, app.id)) })
1250
+ ] });
1251
+ }
1252
+ function ScopePicker({
1253
+ idPrefix,
1254
+ scopes,
1255
+ selected,
1256
+ onChange
1257
+ }) {
1258
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("fieldset", { style: { display: "grid", gap: "0.25rem", border: 0, padding: 0, minWidth: 0 }, children: [
1259
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("legend", { children: "Permissions" }),
1260
+ scopes.map((scope) => {
1261
+ const id = `${idPrefix}-${scope.id}`;
1262
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { htmlFor: id, style: { overflowWrap: "anywhere" }, children: [
1263
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1264
+ "input",
1265
+ {
1266
+ id,
1267
+ type: "checkbox",
1268
+ checked: selected.includes(scope.id),
1269
+ onChange: (event) => onChange(event.target.checked ? [...selected, scope.id] : selected.filter((value) => value !== scope.id))
1270
+ }
1271
+ ),
1272
+ " ",
1273
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("code", { children: scope.id }),
1274
+ " ",
1275
+ scope.description
1276
+ ] }, scope.id);
1277
+ })
1278
+ ] });
1279
+ }
1280
+ function IssuedNotice({
1281
+ issued,
1282
+ components,
1283
+ onDismiss
1284
+ }) {
1285
+ const { Button } = resolveAuthComponents(components);
1286
+ const values = issued.kind === "token" ? [{ label: "API token", url: issued.token }] : [
1287
+ { label: "Client ID", url: issued.client_id },
1288
+ ...issued.client_secret !== null ? [{ label: "Client secret", url: issued.client_secret }] : []
1289
+ ];
1290
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { role: "status", style: { display: "grid", gap: "0.5rem", minWidth: 0 }, children: [
1291
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("p", { style: { overflowWrap: "anywhere" }, children: [
1292
+ issued.kind === "token" ? `API token \u201C${issued.name}\u201D created.` : `OAuth app \u201C${issued.name}\u201D registered.`,
1293
+ " Copy it now: it will not be shown again."
1294
+ ] }),
1295
+ values.map((value) => /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { minWidth: 0, overflowWrap: "anywhere" }, children: [
1296
+ value.label,
1297
+ ": ",
1298
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("code", { children: value.url }),
1299
+ " ",
1300
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(CopyButton, { text: value.url, label: value.label, components })
1301
+ ] }, value.label)),
1302
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Button, { type: "button", onClick: onDismiss, children: "Done" }) })
1303
+ ] });
1304
+ }
1305
+ function CopyButton({ text, label, components }) {
1306
+ const { Button } = resolveAuthComponents(components);
1307
+ const [state, setState] = React5.useState("idle");
1308
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
1309
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1310
+ Button,
1311
+ {
1312
+ type: "button",
1313
+ "aria-label": `Copy ${label}`,
1314
+ onClick: async () => {
1315
+ if (typeof navigator === "undefined" || typeof navigator.clipboard?.writeText !== "function") {
1316
+ setState("failed");
1317
+ return;
1318
+ }
1319
+ try {
1320
+ await navigator.clipboard.writeText(text);
1321
+ setState("copied");
1322
+ } catch {
1323
+ setState("failed");
1324
+ }
1325
+ },
1326
+ children: state === "copied" ? "Copied" : "Copy"
1327
+ }
1328
+ ),
1329
+ state === "failed" && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { role: "status", children: " Copying is unavailable here; select the text and copy it manually." })
1330
+ ] });
1331
+ }
1332
+ function describeDuration(spec) {
1333
+ const match = /^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?)?$/.exec(spec);
1334
+ if (!match) {
1335
+ return spec;
1336
+ }
1337
+ const units = ["year", "month", "week", "day", "hour", "minute"];
1338
+ const parts = match.slice(1).map((value, position) => value ? `${Number(value)} ${units[position]}${Number(value) === 1 ? "" : "s"}` : null).filter((part) => part !== null);
1339
+ return parts.length > 0 ? parts.join(" ") : spec;
1340
+ }
1341
+ async function credentialRequest(method, url, body, csrfToken) {
1342
+ let response;
1343
+ try {
1344
+ response = await fetch(url, {
1345
+ method,
1346
+ credentials: "same-origin",
1347
+ headers: {
1348
+ Accept: "application/json",
1349
+ ...body !== void 0 ? { "Content-Type": "application/json" } : {},
1350
+ ...method !== "GET" ? { "X-CSRF-TOKEN": getCsrfToken(csrfToken) } : {}
1351
+ },
1352
+ body: body !== void 0 ? JSON.stringify(body) : void 0
1353
+ });
1354
+ } catch {
1355
+ return { ok: false, status: 0, message: "The server could not be reached. Check the connection and try again." };
1356
+ }
1357
+ const payload = await response.json().catch(() => null);
1358
+ if (response.ok) {
1359
+ const data = typeof payload === "object" && payload !== null && "data" in payload ? payload.data : payload;
1360
+ return { ok: true, status: response.status, data };
1361
+ }
1362
+ return { ok: false, status: response.status, message: refusalMessage(response.status, payload) };
1363
+ }
1364
+ function refusalMessage(status, payload) {
1365
+ if (status === 401 || status === 419) {
1366
+ return "Your session has expired. Reload the page and sign in again.";
1367
+ }
1368
+ if (typeof payload === "object" && payload !== null) {
1369
+ const errors = payload.errors;
1370
+ if (errors && typeof errors === "object") {
1371
+ const first = Object.values(errors)[0];
1372
+ if (Array.isArray(first) && typeof first[0] === "string") {
1373
+ return first[0];
1374
+ }
1375
+ }
1376
+ const message = payload.message;
1377
+ if (typeof message === "string" && message !== "") {
1378
+ return message;
1379
+ }
1380
+ }
1381
+ if (status === 403) {
1382
+ return "You do not have permission to do that.";
1383
+ }
1384
+ if (status === 404) {
1385
+ return "That credential no longer exists, or creating credentials is unavailable right now.";
1386
+ }
1387
+ return "That action could not be completed.";
1388
+ }
914
1389
  // Annotate the CommonJS export names for ESM import in node:
915
1390
  0 && (module.exports = {
1391
+ ApiCredentialsSection,
916
1392
  ChangePasswordForm,
917
1393
  LoginForm,
918
1394
  PasskeyLoginButton,
@@ -924,6 +1400,7 @@ function relyingApplicationsFrom(value) {
924
1400
  arrayBufferToBase64url,
925
1401
  authenticateWithPasskey,
926
1402
  base64urlToArrayBuffer,
1403
+ describeDuration,
927
1404
  getCsrfToken,
928
1405
  getDefaultPasskeyName,
929
1406
  isAbortError,