bwh-auth 0.6.5 → 0.7.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/LICENSE +1 -1
- package/README.md +143 -5
- package/dist/index.cjs +790 -142
- package/dist/index.d.cts +253 -6
- package/dist/index.d.ts +253 -6
- package/dist/index.js +784 -143
- package/package.json +8 -8
package/dist/index.js
CHANGED
|
@@ -1,27 +1,7 @@
|
|
|
1
1
|
import * as React from "react";
|
|
2
|
-
import { ChevronRight, Key, KeyRound, Plus, Trash2, TriangleAlert } from "lucide-react";
|
|
3
2
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { ChevronRight, Key, KeyRound, Plus, Trash2, TriangleAlert } from "lucide-react";
|
|
4
4
|
import { flushSync } from "react-dom";
|
|
5
|
-
// src/components.ts
|
|
6
|
-
const requiredComponentKeys = [
|
|
7
|
-
"Button",
|
|
8
|
-
"Card",
|
|
9
|
-
"CardContent",
|
|
10
|
-
"CardDescription",
|
|
11
|
-
"CardHeader",
|
|
12
|
-
"CardTitle",
|
|
13
|
-
"Input",
|
|
14
|
-
"Label"
|
|
15
|
-
];
|
|
16
|
-
function resolveAuthComponents(components) {
|
|
17
|
-
const missing = requiredComponentKeys.filter((key) => !components?.[key]);
|
|
18
|
-
if (missing.length > 0) throw new Error(`bwh-auth requires injected components: ${missing.join(", ")}`);
|
|
19
|
-
return components;
|
|
20
|
-
}
|
|
21
|
-
function resolveAuthButtonComponent(components) {
|
|
22
|
-
if (!components?.Button) throw new Error("bwh-auth requires an injected Button component");
|
|
23
|
-
return { Button: components.Button };
|
|
24
|
-
}
|
|
25
5
|
// src/abort-utils.ts
|
|
26
6
|
function throwIfAborted(signal) {
|
|
27
7
|
if (!signal?.aborted) return;
|
|
@@ -279,6 +259,224 @@ async function registerPasskey({ endpoints = {}, name, signal } = {}) {
|
|
|
279
259
|
throwIfAborted(signal);
|
|
280
260
|
return { result: await verifyRes.json() };
|
|
281
261
|
}
|
|
262
|
+
// src/auth-request.ts
|
|
263
|
+
/** A failed auth request, carrying what the form needs to explain it. Internal to the package. */
|
|
264
|
+
var AuthRequestError = class extends Error {
|
|
265
|
+
result;
|
|
266
|
+
status;
|
|
267
|
+
retryAfterSeconds;
|
|
268
|
+
constructor(message, result, status = null, retryAfterSeconds = null) {
|
|
269
|
+
super(message);
|
|
270
|
+
this.result = result;
|
|
271
|
+
this.status = status;
|
|
272
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
273
|
+
this.name = "AuthRequestError";
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
/**
|
|
277
|
+
* Read a `Retry-After` header as whole seconds from now.
|
|
278
|
+
*
|
|
279
|
+
* The header is either a delay in seconds or an HTTP date. Anything unreadable, or a
|
|
280
|
+
* date already in the past, yields `null` so the caller falls back to wording without
|
|
281
|
+
* a number rather than showing a wrong one.
|
|
282
|
+
*/
|
|
283
|
+
function parseRetryAfter(value, now = Date.now()) {
|
|
284
|
+
if (value === null || value === void 0) return null;
|
|
285
|
+
const trimmed = value.trim();
|
|
286
|
+
if (trimmed === "") return null;
|
|
287
|
+
if (/^\d+$/.test(trimmed)) return Number(trimmed);
|
|
288
|
+
const at = Date.parse(trimmed);
|
|
289
|
+
if (Number.isNaN(at)) return null;
|
|
290
|
+
const seconds = Math.ceil((at - now) / 1e3);
|
|
291
|
+
return seconds > 0 ? seconds : null;
|
|
292
|
+
}
|
|
293
|
+
/** The default text for an HTTP 429, naming the wait when the server sent one. */
|
|
294
|
+
function defaultRateLimitMessage(retryAfterSeconds) {
|
|
295
|
+
if (retryAfterSeconds === null) return "Too many attempts. Please wait a moment and try again.";
|
|
296
|
+
if (retryAfterSeconds < 60) return `Too many attempts. Please try again in ${retryAfterSeconds} second${retryAfterSeconds === 1 ? "" : "s"}.`;
|
|
297
|
+
const minutes = Math.ceil(retryAfterSeconds / 60);
|
|
298
|
+
return `Too many attempts. Please try again in ${minutes} minute${minutes === 1 ? "" : "s"}.`;
|
|
299
|
+
}
|
|
300
|
+
/** Replace a 429's message with `format(retryAfter)`; any other error keeps its own message. */
|
|
301
|
+
function errorMessage(error, fallback, format = null) {
|
|
302
|
+
if (format && error instanceof AuthRequestError && error.status === 429) return format(error.retryAfterSeconds);
|
|
303
|
+
return error instanceof Error ? error.message : fallback;
|
|
304
|
+
}
|
|
305
|
+
async function sendForm(url, body, csrfToken, method = "POST") {
|
|
306
|
+
const response = await fetch(url, {
|
|
307
|
+
method,
|
|
308
|
+
headers: {
|
|
309
|
+
"Content-Type": "application/json",
|
|
310
|
+
"Accept": "application/json",
|
|
311
|
+
"X-CSRF-TOKEN": getCsrfToken(csrfToken)
|
|
312
|
+
},
|
|
313
|
+
body: JSON.stringify(body)
|
|
314
|
+
});
|
|
315
|
+
const status = typeof response.status === "number" ? response.status : null;
|
|
316
|
+
const retryAfter = status === 429 ? parseRetryAfter(response.headers?.get?.("Retry-After")) : null;
|
|
317
|
+
let decoded;
|
|
318
|
+
try {
|
|
319
|
+
decoded = await response.json();
|
|
320
|
+
} catch {
|
|
321
|
+
if (status === 429) throw new AuthRequestError("Too Many Attempts.", {}, status, retryAfter);
|
|
322
|
+
throw new AuthRequestError("The server returned an unexpected response. Please try again.", {}, status);
|
|
323
|
+
}
|
|
324
|
+
if (decoded === null || typeof decoded !== "object" || Array.isArray(decoded)) throw new AuthRequestError("The server returned an unexpected response. Please try again.", {}, status);
|
|
325
|
+
const result = decoded;
|
|
326
|
+
if (!response.ok) throw new AuthRequestError(result.message || result.error || "Request failed", result, status, retryAfter);
|
|
327
|
+
return result;
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Resolve a server-sent redirect into an http(s) URL that is safe to navigate to, or `null`.
|
|
331
|
+
*
|
|
332
|
+
* Relative URLs resolve against the current page; `javascript:`, `data:` and any other
|
|
333
|
+
* scheme are refused, because a navigation to them executes rather than navigates.
|
|
334
|
+
*/
|
|
335
|
+
function safeRedirectUrl(url, base) {
|
|
336
|
+
if (typeof url !== "string" || url.trim() === "") return null;
|
|
337
|
+
const resolvedBase = base ?? (typeof window !== "undefined" ? window.location.href : void 0);
|
|
338
|
+
try {
|
|
339
|
+
const parsed = resolvedBase === void 0 ? new URL(url) : new URL(url, resolvedBase);
|
|
340
|
+
return parsed.protocol === "https:" || parsed.protocol === "http:" ? parsed.toString() : null;
|
|
341
|
+
} catch {
|
|
342
|
+
return null;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
// src/components.ts
|
|
346
|
+
const requiredComponentKeys = [
|
|
347
|
+
"Button",
|
|
348
|
+
"Card",
|
|
349
|
+
"CardContent",
|
|
350
|
+
"CardDescription",
|
|
351
|
+
"CardHeader",
|
|
352
|
+
"CardTitle",
|
|
353
|
+
"Input",
|
|
354
|
+
"Label"
|
|
355
|
+
];
|
|
356
|
+
function resolveAuthComponents(components) {
|
|
357
|
+
const missing = requiredComponentKeys.filter((key) => !components?.[key]);
|
|
358
|
+
if (missing.length > 0) throw new Error(`bwh-auth requires injected components: ${missing.join(", ")}`);
|
|
359
|
+
return components;
|
|
360
|
+
}
|
|
361
|
+
function resolveAuthButtonComponent(components) {
|
|
362
|
+
if (!components?.Button) throw new Error("bwh-auth requires an injected Button component");
|
|
363
|
+
return { Button: components.Button };
|
|
364
|
+
}
|
|
365
|
+
// src/email-code-form.tsx
|
|
366
|
+
/**
|
|
367
|
+
* A form for a code sent by email: sign-in verification, step-up before a sensitive
|
|
368
|
+
* action, or re-verifying an address. The endpoint and request body are the caller's;
|
|
369
|
+
* this owns the input, the busy state and a synchronous guard so two fast clicks or
|
|
370
|
+
* Enter presses send one request.
|
|
371
|
+
*/
|
|
372
|
+
function EmailCodeForm({ components, submitUrl, buildSubmitBody, method = "POST", resendUrl, buildResendBody, csrfToken, codeLength = 6, idPrefix = "email-code", header, unwrapped = false, hideResend = false, testCodeHint, actions, rateLimitMessage = defaultRateLimitMessage, onSubmitStart, onSuccess, onError, onResend, title = "Enter your verification code", description, codeLabel = "Verification Code", submitLabel = "Verify Code", submittingLabel = "Verifying...", resendLabel = "Send a new code", resendingLabel = "Sending...", resentMessage = "A new verification code has been sent." }) {
|
|
373
|
+
const { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Label } = resolveAuthComponents(components);
|
|
374
|
+
const [code, setCode] = React.useState("");
|
|
375
|
+
const [loading, setLoading] = React.useState(false);
|
|
376
|
+
const [resending, setResending] = React.useState(false);
|
|
377
|
+
const [message, setMessage] = React.useState("");
|
|
378
|
+
const submitting = React.useRef(false);
|
|
379
|
+
const resendInFlight = React.useRef(false);
|
|
380
|
+
const inputId = `${idPrefix}-code`;
|
|
381
|
+
async function onSubmit(event) {
|
|
382
|
+
event.preventDefault();
|
|
383
|
+
if (submitting.current) return;
|
|
384
|
+
submitting.current = true;
|
|
385
|
+
onSubmitStart?.();
|
|
386
|
+
setLoading(true);
|
|
387
|
+
setMessage("");
|
|
388
|
+
try {
|
|
389
|
+
const trimmed = code.trim();
|
|
390
|
+
const result = await sendForm(submitUrl, buildSubmitBody ? buildSubmitBody(trimmed) : { code: trimmed }, csrfToken, method);
|
|
391
|
+
onSuccess?.(result);
|
|
392
|
+
if (!onSuccess) {
|
|
393
|
+
const redirect = safeRedirectUrl(result.redirect);
|
|
394
|
+
if (redirect !== null) window.location.href = redirect;
|
|
395
|
+
}
|
|
396
|
+
} catch (error) {
|
|
397
|
+
setCode("");
|
|
398
|
+
onError?.(errorMessage(error, "Verification failed", rateLimitMessage));
|
|
399
|
+
} finally {
|
|
400
|
+
submitting.current = false;
|
|
401
|
+
setLoading(false);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
async function resend() {
|
|
405
|
+
if (!resendUrl || resendInFlight.current) return;
|
|
406
|
+
resendInFlight.current = true;
|
|
407
|
+
setResending(true);
|
|
408
|
+
setMessage("");
|
|
409
|
+
try {
|
|
410
|
+
const result = await sendForm(resendUrl, buildResendBody ? buildResendBody() : {}, csrfToken);
|
|
411
|
+
onResend?.(result);
|
|
412
|
+
setMessage(typeof result.message === "string" && result.message !== "" ? result.message : resentMessage);
|
|
413
|
+
} catch (error) {
|
|
414
|
+
onError?.(errorMessage(error, "Could not resend verification code", rateLimitMessage));
|
|
415
|
+
} finally {
|
|
416
|
+
resendInFlight.current = false;
|
|
417
|
+
setResending(false);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
const form = /* @__PURE__ */ jsxs("form", {
|
|
421
|
+
className: "space-y-4",
|
|
422
|
+
onSubmit: (event) => void onSubmit(event),
|
|
423
|
+
children: [/* @__PURE__ */ jsxs("div", {
|
|
424
|
+
className: "space-y-1",
|
|
425
|
+
children: [/* @__PURE__ */ jsx(Label, {
|
|
426
|
+
htmlFor: inputId,
|
|
427
|
+
children: codeLabel
|
|
428
|
+
}), /* @__PURE__ */ jsx(Input, {
|
|
429
|
+
id: inputId,
|
|
430
|
+
type: "text",
|
|
431
|
+
inputMode: "numeric",
|
|
432
|
+
pattern: `[0-9]{${codeLength}}`,
|
|
433
|
+
maxLength: codeLength,
|
|
434
|
+
autoComplete: "one-time-code",
|
|
435
|
+
required: true,
|
|
436
|
+
value: code,
|
|
437
|
+
onChange: (event) => setCode(event.target.value.replace(/\D/g, ""))
|
|
438
|
+
})]
|
|
439
|
+
}), /* @__PURE__ */ jsx(Button, {
|
|
440
|
+
type: "submit",
|
|
441
|
+
className: "w-full",
|
|
442
|
+
disabled: loading || code.length !== codeLength,
|
|
443
|
+
children: loading ? submittingLabel : submitLabel
|
|
444
|
+
})]
|
|
445
|
+
});
|
|
446
|
+
const renderedActions = typeof actions === "function" ? actions({
|
|
447
|
+
setMessage,
|
|
448
|
+
busy: loading || resending
|
|
449
|
+
}) : actions;
|
|
450
|
+
const footer = /* @__PURE__ */ jsxs("div", {
|
|
451
|
+
className: "mt-4 space-y-2 text-sm",
|
|
452
|
+
children: [
|
|
453
|
+
resendUrl && !hideResend ? /* @__PURE__ */ jsx(Button, {
|
|
454
|
+
type: "button",
|
|
455
|
+
variant: "outline",
|
|
456
|
+
className: "w-full",
|
|
457
|
+
disabled: resending,
|
|
458
|
+
onClick: () => void resend(),
|
|
459
|
+
children: resending ? resendingLabel : resendLabel
|
|
460
|
+
}) : null,
|
|
461
|
+
renderedActions,
|
|
462
|
+
message ? /* @__PURE__ */ jsx("p", {
|
|
463
|
+
role: "status",
|
|
464
|
+
children: message
|
|
465
|
+
}) : null,
|
|
466
|
+
testCodeHint ? /* @__PURE__ */ jsx("p", { children: testCodeHint }) : null
|
|
467
|
+
]
|
|
468
|
+
});
|
|
469
|
+
if (unwrapped) return /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
470
|
+
header,
|
|
471
|
+
form,
|
|
472
|
+
footer
|
|
473
|
+
] });
|
|
474
|
+
return /* @__PURE__ */ jsxs(Card, { children: [/* @__PURE__ */ jsxs(CardHeader, { children: [
|
|
475
|
+
header,
|
|
476
|
+
/* @__PURE__ */ jsx(CardTitle, { children: title }),
|
|
477
|
+
/* @__PURE__ */ jsx(CardDescription, { children: description ?? `Enter the ${codeLength}-digit code sent to your email address.` })
|
|
478
|
+
] }), /* @__PURE__ */ jsxs(CardContent, { children: [form, footer] })] });
|
|
479
|
+
}
|
|
282
480
|
// src/passkey-authentication.ts
|
|
283
481
|
const PasskeyAuthenticationContext = React.createContext(null);
|
|
284
482
|
function usePasskeyAuthentication() {
|
|
@@ -394,35 +592,7 @@ function PasskeyLoginButton({ endpoints = {}, components, className, disabled =
|
|
|
394
592
|
});
|
|
395
593
|
}
|
|
396
594
|
// src/forms.tsx
|
|
397
|
-
|
|
398
|
-
result;
|
|
399
|
-
constructor(message, result) {
|
|
400
|
-
super(message);
|
|
401
|
-
this.result = result;
|
|
402
|
-
this.name = "AuthRequestError";
|
|
403
|
-
}
|
|
404
|
-
};
|
|
405
|
-
async function postForm(url, body, csrfToken) {
|
|
406
|
-
const response = await fetch(url, {
|
|
407
|
-
method: "POST",
|
|
408
|
-
headers: {
|
|
409
|
-
"Content-Type": "application/json",
|
|
410
|
-
"Accept": "application/json",
|
|
411
|
-
"X-CSRF-TOKEN": getCsrfToken(csrfToken)
|
|
412
|
-
},
|
|
413
|
-
body: JSON.stringify(body)
|
|
414
|
-
});
|
|
415
|
-
let decoded;
|
|
416
|
-
try {
|
|
417
|
-
decoded = await response.json();
|
|
418
|
-
} catch {
|
|
419
|
-
throw new AuthRequestError("The server returned an unexpected response. Please try again.", {});
|
|
420
|
-
}
|
|
421
|
-
if (decoded === null || typeof decoded !== "object" || Array.isArray(decoded)) throw new AuthRequestError("The server returned an unexpected response. Please try again.", {});
|
|
422
|
-
const result = decoded;
|
|
423
|
-
if (!response.ok) throw new AuthRequestError(result.message || result.error || "Request failed", result);
|
|
424
|
-
return result;
|
|
425
|
-
}
|
|
595
|
+
const postForm = sendForm;
|
|
426
596
|
function DefaultRememberMeCheckbox({ checked, onCheckedChange, ...props }) {
|
|
427
597
|
return /* @__PURE__ */ jsx("input", {
|
|
428
598
|
...props,
|
|
@@ -748,7 +918,7 @@ function SignupForm({ endpoints = {}, components, onSuccess, onError, fields = d
|
|
|
748
918
|
]
|
|
749
919
|
}) })] });
|
|
750
920
|
}
|
|
751
|
-
function PasswordResetRequestForm({ endpoints = {}, components, onSuccess, onError, onSubmitStart, submitClassName }) {
|
|
921
|
+
function PasswordResetRequestForm({ endpoints = {}, components, onSuccess, onError, onSubmitStart, submitClassName, onRedirect, rateLimitMessage = defaultRateLimitMessage }) {
|
|
752
922
|
const { Button, Input, Label } = resolveAuthComponents(components);
|
|
753
923
|
const [email, setEmail] = React.useState("");
|
|
754
924
|
const [loading, setLoading] = React.useState(false);
|
|
@@ -762,8 +932,13 @@ function PasswordResetRequestForm({ endpoints = {}, components, onSuccess, onErr
|
|
|
762
932
|
try {
|
|
763
933
|
const result = await postForm(endpoints.forgotPassword ?? "/api/auth/forgot-password", { email }, endpoints.csrfToken);
|
|
764
934
|
onSuccess?.(result);
|
|
935
|
+
const redirect = safeRedirectUrl(result.redirect);
|
|
936
|
+
if (redirect !== null) {
|
|
937
|
+
if (onRedirect) onRedirect(redirect, result);
|
|
938
|
+
else window.location.assign(redirect);
|
|
939
|
+
}
|
|
765
940
|
} catch (error) {
|
|
766
|
-
onError?.(error
|
|
941
|
+
onError?.(errorMessage(error, "Password reset request failed", rateLimitMessage));
|
|
767
942
|
} finally {
|
|
768
943
|
submitting.current = false;
|
|
769
944
|
setLoading(false);
|
|
@@ -899,26 +1074,28 @@ function ResetPasswordForm({ endpoints = {}, components, onSuccess, onError, onS
|
|
|
899
1074
|
]
|
|
900
1075
|
});
|
|
901
1076
|
}
|
|
902
|
-
function ChangePasswordForm({ endpoints = {}, components, onSuccess, onError }) {
|
|
1077
|
+
function ChangePasswordForm({ endpoints = {}, components, onSuccess, onError, method = "POST" }) {
|
|
903
1078
|
const { Button, Input, Label } = resolveAuthComponents(components);
|
|
904
1079
|
const [currentPassword, setCurrentPassword] = React.useState("");
|
|
905
1080
|
const [password, setPassword] = React.useState("");
|
|
906
1081
|
const [passwordConfirmation, setPasswordConfirmation] = React.useState("");
|
|
907
1082
|
const [loading, setLoading] = React.useState(false);
|
|
1083
|
+
const submitting = React.useRef(false);
|
|
908
1084
|
async function onSubmit(event) {
|
|
909
1085
|
event.preventDefault();
|
|
910
|
-
|
|
1086
|
+
if (submitting.current) return;
|
|
911
1087
|
if (password !== passwordConfirmation) {
|
|
912
1088
|
onError?.("New passwords do not match.");
|
|
913
|
-
setLoading(false);
|
|
914
1089
|
return;
|
|
915
1090
|
}
|
|
1091
|
+
submitting.current = true;
|
|
1092
|
+
setLoading(true);
|
|
916
1093
|
try {
|
|
917
1094
|
const result = await postForm(endpoints.changePassword ?? "/api/change-password", {
|
|
918
1095
|
current_password: currentPassword,
|
|
919
1096
|
password,
|
|
920
1097
|
password_confirmation: passwordConfirmation
|
|
921
|
-
}, endpoints.csrfToken);
|
|
1098
|
+
}, endpoints.csrfToken, method);
|
|
922
1099
|
setCurrentPassword("");
|
|
923
1100
|
setPassword("");
|
|
924
1101
|
setPasswordConfirmation("");
|
|
@@ -926,6 +1103,7 @@ function ChangePasswordForm({ endpoints = {}, components, onSuccess, onError })
|
|
|
926
1103
|
} catch (error) {
|
|
927
1104
|
onError?.(error instanceof Error ? error.message : "Password change failed");
|
|
928
1105
|
} finally {
|
|
1106
|
+
submitting.current = false;
|
|
929
1107
|
setLoading(false);
|
|
930
1108
|
}
|
|
931
1109
|
}
|
|
@@ -985,101 +1163,62 @@ function ChangePasswordForm({ endpoints = {}, components, onSuccess, onError })
|
|
|
985
1163
|
]
|
|
986
1164
|
});
|
|
987
1165
|
}
|
|
988
|
-
function TwoFactorForm({ endpoints = {}, components, attemptToken, appEnv, onSuccess, onError, onReportSuspicious }) {
|
|
989
|
-
const { Button
|
|
1166
|
+
function TwoFactorForm({ endpoints = {}, components, attemptToken, appEnv, testCodeHint, header, hideResend = false, hideReportSuspicious = false, reportSuspiciousLabel = "This was not me", reportedMessage = "This login attempt has been reported.", rateLimitMessage = null, onSubmitStart, onSuccess, onError, onReportSuspicious, title = "Verify Your Login", ...copy }) {
|
|
1167
|
+
const { Button } = resolveAuthComponents(components);
|
|
990
1168
|
const [currentAttemptToken, setCurrentAttemptToken] = React.useState(attemptToken);
|
|
991
|
-
const
|
|
992
|
-
const [
|
|
993
|
-
const [resending, setResending] = React.useState(false);
|
|
994
|
-
const [message, setMessage] = React.useState("");
|
|
1169
|
+
const reporting = React.useRef(false);
|
|
1170
|
+
const [reportPending, setReportPending] = React.useState(false);
|
|
995
1171
|
React.useEffect(() => setCurrentAttemptToken(attemptToken), [attemptToken]);
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
const result = await postForm(endpoints.twoFactorVerify ?? "/api/auth/two-factor/verify", {
|
|
1002
|
-
attempt_token: currentAttemptToken,
|
|
1003
|
-
code: code.trim()
|
|
1004
|
-
}, endpoints.csrfToken);
|
|
1005
|
-
onSuccess?.(result);
|
|
1006
|
-
if (!onSuccess && result.redirect) window.location.href = result.redirect;
|
|
1007
|
-
} catch (error) {
|
|
1008
|
-
setCode("");
|
|
1009
|
-
onError?.(error instanceof Error ? error.message : "Verification failed");
|
|
1010
|
-
} finally {
|
|
1011
|
-
setLoading(false);
|
|
1012
|
-
}
|
|
1013
|
-
}
|
|
1014
|
-
async function resend() {
|
|
1015
|
-
setResending(true);
|
|
1016
|
-
setMessage("");
|
|
1017
|
-
try {
|
|
1018
|
-
const result = await postForm(endpoints.twoFactorResend ?? "/api/auth/two-factor/resend", { attempt_token: currentAttemptToken }, endpoints.csrfToken);
|
|
1019
|
-
if (typeof result.attempt_token === "string") setCurrentAttemptToken(result.attempt_token);
|
|
1020
|
-
setMessage(result.message ?? "A new verification code has been sent.");
|
|
1021
|
-
} catch (error) {
|
|
1022
|
-
onError?.(error instanceof Error ? error.message : "Could not resend verification code");
|
|
1023
|
-
} finally {
|
|
1024
|
-
setResending(false);
|
|
1025
|
-
}
|
|
1026
|
-
}
|
|
1027
|
-
async function reportSuspicious() {
|
|
1172
|
+
const hint = testCodeHint !== void 0 ? testCodeHint : appEnv && appEnv !== "production" ? "Dev mode: use 999999 to bypass 2FA." : null;
|
|
1173
|
+
async function reportSuspicious({ setMessage }) {
|
|
1174
|
+
if (reporting.current) return;
|
|
1175
|
+
reporting.current = true;
|
|
1176
|
+
setReportPending(true);
|
|
1028
1177
|
const url = endpoints.twoFactorReport?.(currentAttemptToken) ?? `/api/auth/two-factor/report/${encodeURIComponent(currentAttemptToken)}`;
|
|
1029
1178
|
try {
|
|
1030
1179
|
const result = await postForm(url, {}, endpoints.csrfToken);
|
|
1031
|
-
setMessage(result.message
|
|
1180
|
+
setMessage(typeof result.message === "string" && result.message !== "" ? result.message : reportedMessage);
|
|
1032
1181
|
onReportSuspicious?.(result);
|
|
1033
1182
|
} catch (error) {
|
|
1034
|
-
onError?.(error
|
|
1183
|
+
onError?.(errorMessage(error, "Could not report the login attempt", rateLimitMessage));
|
|
1184
|
+
} finally {
|
|
1185
|
+
reporting.current = false;
|
|
1186
|
+
setReportPending(false);
|
|
1035
1187
|
}
|
|
1036
1188
|
}
|
|
1037
|
-
return /* @__PURE__ */
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
onClick: () => void resend(),
|
|
1071
|
-
children: resending ? "Sending..." : "Send a new code"
|
|
1072
|
-
}),
|
|
1073
|
-
/* @__PURE__ */ jsx("button", {
|
|
1074
|
-
type: "button",
|
|
1075
|
-
className: "text-sm underline",
|
|
1076
|
-
onClick: () => void reportSuspicious(),
|
|
1077
|
-
children: "This was not me"
|
|
1078
|
-
}),
|
|
1079
|
-
message ? /* @__PURE__ */ jsx("p", { children: message }) : null,
|
|
1080
|
-
appEnv && appEnv !== "production" ? /* @__PURE__ */ jsx("p", { children: "Dev mode: use 999999 to bypass 2FA." }) : null
|
|
1081
|
-
]
|
|
1082
|
-
})] })] });
|
|
1189
|
+
return /* @__PURE__ */ jsx(EmailCodeForm, {
|
|
1190
|
+
...copy,
|
|
1191
|
+
title,
|
|
1192
|
+
components,
|
|
1193
|
+
idPrefix: "two-factor",
|
|
1194
|
+
csrfToken: endpoints.csrfToken,
|
|
1195
|
+
submitUrl: endpoints.twoFactorVerify ?? "/api/auth/two-factor/verify",
|
|
1196
|
+
buildSubmitBody: (code) => ({
|
|
1197
|
+
attempt_token: currentAttemptToken,
|
|
1198
|
+
code
|
|
1199
|
+
}),
|
|
1200
|
+
resendUrl: endpoints.twoFactorResend ?? "/api/auth/two-factor/resend",
|
|
1201
|
+
buildResendBody: () => ({ attempt_token: currentAttemptToken }),
|
|
1202
|
+
onResend: (result) => {
|
|
1203
|
+
if (typeof result.attempt_token === "string") setCurrentAttemptToken(result.attempt_token);
|
|
1204
|
+
},
|
|
1205
|
+
header,
|
|
1206
|
+
hideResend,
|
|
1207
|
+
testCodeHint: hint,
|
|
1208
|
+
rateLimitMessage,
|
|
1209
|
+
onSubmitStart,
|
|
1210
|
+
onSuccess,
|
|
1211
|
+
onError,
|
|
1212
|
+
actions: hideReportSuspicious ? void 0 : (actions) => /* @__PURE__ */ jsx(Button, {
|
|
1213
|
+
type: "button",
|
|
1214
|
+
variant: "link",
|
|
1215
|
+
size: "sm",
|
|
1216
|
+
className: "h-auto px-0 text-sm",
|
|
1217
|
+
disabled: reportPending,
|
|
1218
|
+
onClick: () => void reportSuspicious(actions),
|
|
1219
|
+
children: reportSuspiciousLabel
|
|
1220
|
+
})
|
|
1221
|
+
});
|
|
1083
1222
|
}
|
|
1084
1223
|
// src/passkey-section.tsx
|
|
1085
1224
|
function PasskeySection({ endpoints = {}, components, onSuccess, onError }) {
|
|
@@ -2510,4 +2649,506 @@ function refusalMessage(status, payload) {
|
|
|
2510
2649
|
if (status === 404) return "That credential no longer exists, or creating credentials is unavailable right now.";
|
|
2511
2650
|
return "That action could not be completed.";
|
|
2512
2651
|
}
|
|
2513
|
-
|
|
2652
|
+
// src/auth-browser-help.tsx
|
|
2653
|
+
const AUTOMATED_AGENTS = /HeadlessChrome|PhantomJS|Prerender|Google-Safety|BingPreview|Barracuda|Mimecast|Proofpoint|SkypeUriPreview/i;
|
|
2654
|
+
const IN_APP_BROWSERS = [
|
|
2655
|
+
[/FBAN\/Messenger|MessengerForiOS|MessengerLite/, "Messenger"],
|
|
2656
|
+
[/Instagram/, "Instagram"],
|
|
2657
|
+
[/FBAN|FBAV|FB_IAB|FBIOS/, "Facebook"],
|
|
2658
|
+
[/LinkedInApp/, "LinkedIn"],
|
|
2659
|
+
[/Snapchat/, "Snapchat"],
|
|
2660
|
+
[/Pinterest/, "Pinterest"],
|
|
2661
|
+
[/musical_ly|BytedanceWebview|TikTok/, "TikTok"],
|
|
2662
|
+
[/MicroMessenger/, "WeChat"],
|
|
2663
|
+
[/\bLine\//, "LINE"],
|
|
2664
|
+
[/\bTwitter\b/, "X"],
|
|
2665
|
+
[/\bGSA\//, "Google"],
|
|
2666
|
+
[/Android.*;\s?wv\)/, void 0]
|
|
2667
|
+
];
|
|
2668
|
+
const IOS_WEBVIEW = /(?:iPhone|iPod|iPad).*AppleWebKit(?!.*Safari\/)/;
|
|
2669
|
+
/** Read the current browser's environment. Returns `{}` during server rendering. */
|
|
2670
|
+
function readAuthBrowserEnvironment() {
|
|
2671
|
+
if (typeof window === "undefined" || typeof navigator === "undefined") return {};
|
|
2672
|
+
const environment = {
|
|
2673
|
+
userAgent: navigator.userAgent,
|
|
2674
|
+
webdriver: navigator.webdriver === true,
|
|
2675
|
+
cookieEnabled: navigator.cookieEnabled
|
|
2676
|
+
};
|
|
2677
|
+
try {
|
|
2678
|
+
environment.framed = window.self !== window.top;
|
|
2679
|
+
} catch {
|
|
2680
|
+
environment.framed = true;
|
|
2681
|
+
}
|
|
2682
|
+
environment.cookiesWritable = probeCookies();
|
|
2683
|
+
try {
|
|
2684
|
+
environment.standalone = navigator.standalone === true || typeof window.matchMedia === "function" && window.matchMedia("(display-mode: standalone)").matches;
|
|
2685
|
+
} catch {
|
|
2686
|
+
environment.standalone = false;
|
|
2687
|
+
}
|
|
2688
|
+
try {
|
|
2689
|
+
const key = "__bwh_auth_storage_probe";
|
|
2690
|
+
window.localStorage.setItem(key, "1");
|
|
2691
|
+
window.localStorage.removeItem(key);
|
|
2692
|
+
environment.storageAvailable = true;
|
|
2693
|
+
} catch {
|
|
2694
|
+
environment.storageAvailable = false;
|
|
2695
|
+
}
|
|
2696
|
+
return environment;
|
|
2697
|
+
}
|
|
2698
|
+
function probeCookies() {
|
|
2699
|
+
if (typeof document === "undefined") return true;
|
|
2700
|
+
const name = "__bwh_auth_cookie_probe";
|
|
2701
|
+
const secure = typeof location !== "undefined" && location.protocol === "https:" ? "; Secure" : "";
|
|
2702
|
+
try {
|
|
2703
|
+
document.cookie = `${name}=1; path=/; SameSite=Lax${secure}`;
|
|
2704
|
+
const written = document.cookie.split(";").some((part) => part.trim() === `${name}=1`);
|
|
2705
|
+
document.cookie = `${name}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax${secure}`;
|
|
2706
|
+
return written;
|
|
2707
|
+
} catch {
|
|
2708
|
+
return false;
|
|
2709
|
+
}
|
|
2710
|
+
}
|
|
2711
|
+
/** Name the conditions in `environment` that are likely to break sign-in, most fundamental first. */
|
|
2712
|
+
function detectAuthBrowserIssues(environment = readAuthBrowserEnvironment()) {
|
|
2713
|
+
const issues = [];
|
|
2714
|
+
const userAgent = environment.userAgent ?? "";
|
|
2715
|
+
if (environment.webdriver === true || AUTOMATED_AGENTS.test(userAgent)) issues.push({ kind: "automated" });
|
|
2716
|
+
if (environment.framed === true) issues.push({ kind: "framed" });
|
|
2717
|
+
const inApp = IN_APP_BROWSERS.find(([pattern]) => pattern.test(userAgent));
|
|
2718
|
+
if (inApp) issues.push(inApp[1] === void 0 ? { kind: "in-app-browser" } : {
|
|
2719
|
+
kind: "in-app-browser",
|
|
2720
|
+
app: inApp[1]
|
|
2721
|
+
});
|
|
2722
|
+
else if (environment.standalone !== true && IOS_WEBVIEW.test(userAgent)) issues.push({ kind: "in-app-browser" });
|
|
2723
|
+
if (environment.cookieEnabled === false || environment.cookiesWritable === false) issues.push({ kind: "cookies-disabled" });
|
|
2724
|
+
if (environment.storageAvailable === false) issues.push({ kind: "storage-unavailable" });
|
|
2725
|
+
return issues;
|
|
2726
|
+
}
|
|
2727
|
+
function defaultCopy(issue) {
|
|
2728
|
+
switch (issue.kind) {
|
|
2729
|
+
case "automated": return {
|
|
2730
|
+
title: "This page was opened automatically",
|
|
2731
|
+
body: "Email security scanners and link previews can open sign-in links before you do, which may use them up. If your link no longer works, request a new one and open it yourself."
|
|
2732
|
+
};
|
|
2733
|
+
case "framed": return {
|
|
2734
|
+
title: "This page is shown inside another page",
|
|
2735
|
+
body: "Signing in may not work in a preview or embedded view. Open this page in its own browser tab."
|
|
2736
|
+
};
|
|
2737
|
+
case "in-app-browser": return {
|
|
2738
|
+
title: issue.app ? `You are using ${issue.app}'s built-in browser` : "You are using an in-app browser",
|
|
2739
|
+
body: "Signing in may not work here, and you may not stay signed in. Open this page in your usual browser: use the app's menu and choose to open in the browser, or copy the link and paste it there."
|
|
2740
|
+
};
|
|
2741
|
+
case "cookies-disabled": return {
|
|
2742
|
+
title: "Cookies are blocked",
|
|
2743
|
+
body: "Signing in needs cookies for this site. Allow cookies in your browser settings, then reload this page."
|
|
2744
|
+
};
|
|
2745
|
+
case "storage-unavailable": return {
|
|
2746
|
+
title: "This browser is blocking site storage",
|
|
2747
|
+
body: "Some sign-in steps may not work in a private or restricted window. If you have trouble, try a regular browser window."
|
|
2748
|
+
};
|
|
2749
|
+
}
|
|
2750
|
+
}
|
|
2751
|
+
/**
|
|
2752
|
+
* Guidance for browsers and contexts that commonly break sign-in links and flows.
|
|
2753
|
+
*
|
|
2754
|
+
* Detection runs after mount, so server rendering and the first client render show
|
|
2755
|
+
* nothing and hydrate identically. Nothing renders when no issue applies.
|
|
2756
|
+
*/
|
|
2757
|
+
function AuthBrowserHelp({ components, issues: givenIssues, environment, ignore = [], messages = {}, url, className, onDetect }) {
|
|
2758
|
+
if (!components?.Button) throw new Error("bwh-auth requires an injected Button component");
|
|
2759
|
+
const { Button, Alert } = components;
|
|
2760
|
+
const [detected, setDetected] = React.useState([]);
|
|
2761
|
+
const [copyState, setCopyState] = React.useState("idle");
|
|
2762
|
+
const onDetectRef = React.useRef(onDetect);
|
|
2763
|
+
onDetectRef.current = onDetect;
|
|
2764
|
+
const environmentKey = environment ? JSON.stringify(environment) : "";
|
|
2765
|
+
React.useEffect(() => {
|
|
2766
|
+
if (givenIssues !== void 0) return;
|
|
2767
|
+
const found = detectAuthBrowserIssues(environment ?? readAuthBrowserEnvironment());
|
|
2768
|
+
setDetected(found);
|
|
2769
|
+
onDetectRef.current?.(found);
|
|
2770
|
+
}, [givenIssues === void 0, environmentKey]);
|
|
2771
|
+
const shown = (givenIssues ?? detected).filter((issue) => !ignore.includes(issue.kind));
|
|
2772
|
+
if (shown.length === 0) return null;
|
|
2773
|
+
function targetUrl() {
|
|
2774
|
+
return url ?? (typeof window !== "undefined" ? window.location.href : "");
|
|
2775
|
+
}
|
|
2776
|
+
async function copyLink() {
|
|
2777
|
+
try {
|
|
2778
|
+
await navigator.clipboard.writeText(targetUrl());
|
|
2779
|
+
setCopyState("copied");
|
|
2780
|
+
} catch {
|
|
2781
|
+
setCopyState("failed");
|
|
2782
|
+
}
|
|
2783
|
+
}
|
|
2784
|
+
function action(issue) {
|
|
2785
|
+
switch (issue.kind) {
|
|
2786
|
+
case "framed": return /* @__PURE__ */ jsx(Button, {
|
|
2787
|
+
type: "button",
|
|
2788
|
+
variant: "outline",
|
|
2789
|
+
size: "sm",
|
|
2790
|
+
onClick: () => window.open(targetUrl(), "_blank", "noopener,noreferrer"),
|
|
2791
|
+
children: "Open in a new tab"
|
|
2792
|
+
});
|
|
2793
|
+
case "in-app-browser": return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Button, {
|
|
2794
|
+
type: "button",
|
|
2795
|
+
variant: "outline",
|
|
2796
|
+
size: "sm",
|
|
2797
|
+
onClick: () => void copyLink(),
|
|
2798
|
+
children: copyState === "copied" ? "Link copied" : "Copy link"
|
|
2799
|
+
}), copyState === "failed" ? /* @__PURE__ */ jsx("p", {
|
|
2800
|
+
className: "text-sm",
|
|
2801
|
+
children: "Copying was blocked. Copy the address from the address bar instead."
|
|
2802
|
+
}) : null] });
|
|
2803
|
+
case "cookies-disabled": return /* @__PURE__ */ jsx(Button, {
|
|
2804
|
+
type: "button",
|
|
2805
|
+
variant: "outline",
|
|
2806
|
+
size: "sm",
|
|
2807
|
+
onClick: () => window.location.reload(),
|
|
2808
|
+
children: "Reload"
|
|
2809
|
+
});
|
|
2810
|
+
default: return null;
|
|
2811
|
+
}
|
|
2812
|
+
}
|
|
2813
|
+
return /* @__PURE__ */ jsx("div", {
|
|
2814
|
+
className: className ?? "space-y-3",
|
|
2815
|
+
"data-auth-browser-help": "",
|
|
2816
|
+
children: shown.map((issue) => {
|
|
2817
|
+
const fallback = defaultCopy(issue);
|
|
2818
|
+
const override = messages[issue.kind];
|
|
2819
|
+
const copy = {
|
|
2820
|
+
title: override?.title ?? fallback.title,
|
|
2821
|
+
body: override?.body ?? fallback.body
|
|
2822
|
+
};
|
|
2823
|
+
const content = /* @__PURE__ */ jsxs("div", {
|
|
2824
|
+
className: "space-y-2",
|
|
2825
|
+
children: [
|
|
2826
|
+
/* @__PURE__ */ jsx("p", {
|
|
2827
|
+
className: "font-medium",
|
|
2828
|
+
children: copy.title
|
|
2829
|
+
}),
|
|
2830
|
+
/* @__PURE__ */ jsx("p", {
|
|
2831
|
+
className: "text-sm",
|
|
2832
|
+
children: copy.body
|
|
2833
|
+
}),
|
|
2834
|
+
action(issue)
|
|
2835
|
+
]
|
|
2836
|
+
});
|
|
2837
|
+
return Alert ? /* @__PURE__ */ jsx(Alert, {
|
|
2838
|
+
"data-issue": issue.kind,
|
|
2839
|
+
children: content
|
|
2840
|
+
}, issue.kind) : /* @__PURE__ */ jsx("div", {
|
|
2841
|
+
role: "status",
|
|
2842
|
+
"data-issue": issue.kind,
|
|
2843
|
+
children: content
|
|
2844
|
+
}, issue.kind);
|
|
2845
|
+
})
|
|
2846
|
+
});
|
|
2847
|
+
}
|
|
2848
|
+
// src/sign-in-history.tsx
|
|
2849
|
+
/** The events `SignInHistory` shows by default: sign-in attempts and their second factor. */
|
|
2850
|
+
const SIGN_IN_AUDIT_EVENTS = [
|
|
2851
|
+
"login_succeeded",
|
|
2852
|
+
"login_failed",
|
|
2853
|
+
"login_blocked",
|
|
2854
|
+
"passkey_login_succeeded",
|
|
2855
|
+
"passkey_login_failed",
|
|
2856
|
+
"two_factor_succeeded",
|
|
2857
|
+
"two_factor_failed",
|
|
2858
|
+
"two_factor_reported_suspicious"
|
|
2859
|
+
];
|
|
2860
|
+
const DEFAULT_EVENT_LABELS = {
|
|
2861
|
+
login_succeeded: "Signed in",
|
|
2862
|
+
login_failed: "Sign-in failed",
|
|
2863
|
+
login_blocked: "Sign-in blocked",
|
|
2864
|
+
logged_out: "Signed out",
|
|
2865
|
+
two_factor_challenge_created: "Verification code sent",
|
|
2866
|
+
two_factor_succeeded: "Verification code accepted",
|
|
2867
|
+
two_factor_failed: "Verification code rejected",
|
|
2868
|
+
two_factor_reported_suspicious: "Reported as not me",
|
|
2869
|
+
passkey_registered: "Passkey added",
|
|
2870
|
+
passkey_deleted: "Passkey removed",
|
|
2871
|
+
passkey_login_succeeded: "Signed in with a passkey",
|
|
2872
|
+
passkey_login_failed: "Passkey sign-in failed",
|
|
2873
|
+
password_reset_requested: "Password reset requested",
|
|
2874
|
+
password_reset_completed: "Password reset",
|
|
2875
|
+
password_changed: "Password changed"
|
|
2876
|
+
};
|
|
2877
|
+
const DEFAULT_METHOD_LABELS = {
|
|
2878
|
+
password: "Password",
|
|
2879
|
+
passkey: "Passkey",
|
|
2880
|
+
two_factor: "Email code"
|
|
2881
|
+
};
|
|
2882
|
+
function isNullableString(value) {
|
|
2883
|
+
return value === null || typeof value === "string";
|
|
2884
|
+
}
|
|
2885
|
+
function parseEntry(value) {
|
|
2886
|
+
if (typeof value !== "object" || value === null) return null;
|
|
2887
|
+
const row = value;
|
|
2888
|
+
if (typeof row.id !== "number" || typeof row.event !== "string") return null;
|
|
2889
|
+
const metadata = typeof row.metadata === "object" && row.metadata !== null && !Array.isArray(row.metadata) ? row.metadata : null;
|
|
2890
|
+
const location = typeof row.location === "string" ? row.location : typeof metadata?.location === "string" ? metadata.location : null;
|
|
2891
|
+
return {
|
|
2892
|
+
id: row.id,
|
|
2893
|
+
user_id: typeof row.user_id === "number" ? row.user_id : null,
|
|
2894
|
+
acting_user_id: typeof row.acting_user_id === "number" ? row.acting_user_id : null,
|
|
2895
|
+
email: isNullableString(row.email) ? row.email : null,
|
|
2896
|
+
event: row.event,
|
|
2897
|
+
auth_method: isNullableString(row.auth_method) ? row.auth_method : null,
|
|
2898
|
+
succeeded: row.succeeded === true || row.succeeded === 1,
|
|
2899
|
+
reason: isNullableString(row.reason) ? row.reason : null,
|
|
2900
|
+
ip_address: isNullableString(row.ip_address) ? row.ip_address : null,
|
|
2901
|
+
user_agent: isNullableString(row.user_agent) ? row.user_agent : null,
|
|
2902
|
+
session_id: isNullableString(row.session_id) ? row.session_id : null,
|
|
2903
|
+
is_suspicious: row.is_suspicious === true || row.is_suspicious === 1,
|
|
2904
|
+
metadata,
|
|
2905
|
+
created_at: isNullableString(row.created_at) ? row.created_at : null,
|
|
2906
|
+
updated_at: isNullableString(row.updated_at) ? row.updated_at : null,
|
|
2907
|
+
location
|
|
2908
|
+
};
|
|
2909
|
+
}
|
|
2910
|
+
/**
|
|
2911
|
+
* Validate an audit-log response into a page that is safe to render, or `null` if it is not one.
|
|
2912
|
+
* Malformed rows are dropped rather than failing the whole page.
|
|
2913
|
+
*/
|
|
2914
|
+
function parseAuthAuditLogPage(payload) {
|
|
2915
|
+
if (typeof payload !== "object" || payload === null || !Array.isArray(payload.data)) return null;
|
|
2916
|
+
const page = payload;
|
|
2917
|
+
const data = page.data.flatMap((row) => {
|
|
2918
|
+
const entry = parseEntry(row);
|
|
2919
|
+
return entry === null ? [] : [entry];
|
|
2920
|
+
});
|
|
2921
|
+
const number = (value, fallback) => typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
|
2922
|
+
const currentPage = number(page.current_page, 1);
|
|
2923
|
+
return {
|
|
2924
|
+
current_page: currentPage,
|
|
2925
|
+
data,
|
|
2926
|
+
last_page: number(page.last_page, currentPage),
|
|
2927
|
+
per_page: number(page.per_page, data.length),
|
|
2928
|
+
total: number(page.total, data.length),
|
|
2929
|
+
from: typeof page.from === "number" ? page.from : null,
|
|
2930
|
+
to: typeof page.to === "number" ? page.to : null,
|
|
2931
|
+
next_page_url: typeof page.next_page_url === "string" ? page.next_page_url : null,
|
|
2932
|
+
prev_page_url: typeof page.prev_page_url === "string" ? page.prev_page_url : null
|
|
2933
|
+
};
|
|
2934
|
+
}
|
|
2935
|
+
function withQuery(url, params) {
|
|
2936
|
+
const query = new URLSearchParams(params).toString();
|
|
2937
|
+
const hashIndex = url.indexOf("#");
|
|
2938
|
+
const base = hashIndex === -1 ? url : url.slice(0, hashIndex);
|
|
2939
|
+
return `${base}${base.includes("?") ? "&" : "?"}${query}`;
|
|
2940
|
+
}
|
|
2941
|
+
function refusal(status, payload) {
|
|
2942
|
+
if (status === 401 || status === 419) return "Your session has expired. Reload the page and sign in again.";
|
|
2943
|
+
if (status === 404) return "Sign-in history is not available.";
|
|
2944
|
+
if (status === 403) return "You do not have permission to view this sign-in history.";
|
|
2945
|
+
const message = typeof payload === "object" && payload !== null ? payload.message : void 0;
|
|
2946
|
+
return typeof message === "string" && message !== "" ? message : "Sign-in history could not be loaded.";
|
|
2947
|
+
}
|
|
2948
|
+
async function loadPage(url, request) {
|
|
2949
|
+
const unreachable = "The server could not be reached. Check the connection and try again.";
|
|
2950
|
+
let status;
|
|
2951
|
+
let payload;
|
|
2952
|
+
if (request) {
|
|
2953
|
+
let result;
|
|
2954
|
+
try {
|
|
2955
|
+
result = await request(url);
|
|
2956
|
+
} catch {
|
|
2957
|
+
return {
|
|
2958
|
+
ok: false,
|
|
2959
|
+
message: unreachable
|
|
2960
|
+
};
|
|
2961
|
+
}
|
|
2962
|
+
if (!result.ok) return {
|
|
2963
|
+
ok: false,
|
|
2964
|
+
message: result.message
|
|
2965
|
+
};
|
|
2966
|
+
status = result.status;
|
|
2967
|
+
payload = result.payload;
|
|
2968
|
+
} else {
|
|
2969
|
+
let response;
|
|
2970
|
+
try {
|
|
2971
|
+
response = await fetch(url, {
|
|
2972
|
+
method: "GET",
|
|
2973
|
+
credentials: "same-origin",
|
|
2974
|
+
headers: {
|
|
2975
|
+
Accept: "application/json",
|
|
2976
|
+
"X-Requested-With": "XMLHttpRequest"
|
|
2977
|
+
}
|
|
2978
|
+
});
|
|
2979
|
+
} catch {
|
|
2980
|
+
return {
|
|
2981
|
+
ok: false,
|
|
2982
|
+
message: unreachable
|
|
2983
|
+
};
|
|
2984
|
+
}
|
|
2985
|
+
status = response.status;
|
|
2986
|
+
payload = await response.json().catch(() => null);
|
|
2987
|
+
if (!response.ok) return {
|
|
2988
|
+
ok: false,
|
|
2989
|
+
message: refusal(status, payload)
|
|
2990
|
+
};
|
|
2991
|
+
}
|
|
2992
|
+
const page = parseAuthAuditLogPage(payload);
|
|
2993
|
+
return page === null ? {
|
|
2994
|
+
ok: false,
|
|
2995
|
+
message: "The server returned an unexpected response. Please try again."
|
|
2996
|
+
} : {
|
|
2997
|
+
ok: true,
|
|
2998
|
+
page
|
|
2999
|
+
};
|
|
3000
|
+
}
|
|
3001
|
+
function defaultFormatTime(iso) {
|
|
3002
|
+
const date = new Date(iso);
|
|
3003
|
+
return Number.isNaN(date.getTime()) ? iso : date.toLocaleString();
|
|
3004
|
+
}
|
|
3005
|
+
/**
|
|
3006
|
+
* The signed-in person's recent sign-in activity, read from auth-laravel's audit-log
|
|
3007
|
+
* endpoint (`GET /api/auth/audit-log`, enabled by `bherila-auth.audit.routes_enabled`,
|
|
3008
|
+
* session-authenticated). Newest first, with "Load more" for older pages.
|
|
3009
|
+
*/
|
|
3010
|
+
function SignInHistory({ components, url = "/api/auth/audit-log", perPage = 20, events = SIGN_IN_AUDIT_EVENTS, request, formatTime = defaultFormatTime, eventLabels = {}, methodLabels = {}, emptyMessage = "No sign-in activity yet.", label = "Sign-in history", className, onError }) {
|
|
3011
|
+
if (!components?.Button) throw new Error("bwh-auth requires an injected Button component");
|
|
3012
|
+
const { Button, Alert, Badge } = components;
|
|
3013
|
+
const [rows, setRows] = React.useState([]);
|
|
3014
|
+
const [page, setPage] = React.useState(null);
|
|
3015
|
+
const [loading, setLoading] = React.useState(true);
|
|
3016
|
+
const [error, setError] = React.useState(null);
|
|
3017
|
+
const size = Math.min(Math.max(Math.trunc(perPage) || 20, 1), 100);
|
|
3018
|
+
const generation = React.useRef(0);
|
|
3019
|
+
const context = React.useRef({
|
|
3020
|
+
request,
|
|
3021
|
+
onError
|
|
3022
|
+
});
|
|
3023
|
+
context.current = {
|
|
3024
|
+
request,
|
|
3025
|
+
onError
|
|
3026
|
+
};
|
|
3027
|
+
const load = React.useCallback(async (pageNumber) => {
|
|
3028
|
+
generation.current += 1;
|
|
3029
|
+
const mine = generation.current;
|
|
3030
|
+
setLoading(true);
|
|
3031
|
+
setError(null);
|
|
3032
|
+
const result = await loadPage(withQuery(url, {
|
|
3033
|
+
per_page: String(size),
|
|
3034
|
+
page: String(pageNumber)
|
|
3035
|
+
}), context.current.request);
|
|
3036
|
+
if (mine !== generation.current) return;
|
|
3037
|
+
setLoading(false);
|
|
3038
|
+
if (!result.ok) {
|
|
3039
|
+
setError(result.message);
|
|
3040
|
+
context.current.onError?.(result.message);
|
|
3041
|
+
return;
|
|
3042
|
+
}
|
|
3043
|
+
setPage(result.page);
|
|
3044
|
+
setRows((current) => {
|
|
3045
|
+
if (pageNumber === 1) return result.page.data;
|
|
3046
|
+
const seen = new Set(current.map((row) => row.id));
|
|
3047
|
+
return [...current, ...result.page.data.filter((row) => !seen.has(row.id))];
|
|
3048
|
+
});
|
|
3049
|
+
}, [url, size]);
|
|
3050
|
+
React.useEffect(() => {
|
|
3051
|
+
setRows([]);
|
|
3052
|
+
setPage(null);
|
|
3053
|
+
load(1);
|
|
3054
|
+
return () => {
|
|
3055
|
+
generation.current += 1;
|
|
3056
|
+
};
|
|
3057
|
+
}, [load]);
|
|
3058
|
+
const shown = events === "all" ? rows : rows.filter((row) => events.includes(row.event));
|
|
3059
|
+
const showLocation = shown.some((row) => row.location);
|
|
3060
|
+
const hasMore = page !== null && page.current_page < page.last_page;
|
|
3061
|
+
const nextPage = page === null ? 1 : page.current_page + 1;
|
|
3062
|
+
const tag = (text, kind) => Badge ? /* @__PURE__ */ jsx(Badge, {
|
|
3063
|
+
"data-kind": kind,
|
|
3064
|
+
children: text
|
|
3065
|
+
}) : /* @__PURE__ */ jsx("span", {
|
|
3066
|
+
"data-kind": kind,
|
|
3067
|
+
children: text
|
|
3068
|
+
});
|
|
3069
|
+
const errorView = error === null ? null : Alert ? /* @__PURE__ */ jsx(Alert, { children: error }) : /* @__PURE__ */ jsx("p", {
|
|
3070
|
+
role: "alert",
|
|
3071
|
+
children: error
|
|
3072
|
+
});
|
|
3073
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
3074
|
+
className: className ?? "space-y-3",
|
|
3075
|
+
children: [
|
|
3076
|
+
page === null && loading ? /* @__PURE__ */ jsx("p", {
|
|
3077
|
+
role: "status",
|
|
3078
|
+
children: "Loading sign-in history..."
|
|
3079
|
+
}) : null,
|
|
3080
|
+
page !== null && shown.length === 0 && !hasMore ? /* @__PURE__ */ jsx("p", { children: emptyMessage }) : null,
|
|
3081
|
+
shown.length > 0 ? /* @__PURE__ */ jsx("div", {
|
|
3082
|
+
className: "overflow-x-auto",
|
|
3083
|
+
children: /* @__PURE__ */ jsxs("table", {
|
|
3084
|
+
className: "w-full text-sm",
|
|
3085
|
+
"aria-label": label,
|
|
3086
|
+
children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [
|
|
3087
|
+
/* @__PURE__ */ jsx("th", {
|
|
3088
|
+
scope: "col",
|
|
3089
|
+
className: "text-left",
|
|
3090
|
+
children: "Time"
|
|
3091
|
+
}),
|
|
3092
|
+
/* @__PURE__ */ jsx("th", {
|
|
3093
|
+
scope: "col",
|
|
3094
|
+
className: "text-left",
|
|
3095
|
+
children: "Activity"
|
|
3096
|
+
}),
|
|
3097
|
+
/* @__PURE__ */ jsx("th", {
|
|
3098
|
+
scope: "col",
|
|
3099
|
+
className: "text-left",
|
|
3100
|
+
children: "Method"
|
|
3101
|
+
}),
|
|
3102
|
+
/* @__PURE__ */ jsx("th", {
|
|
3103
|
+
scope: "col",
|
|
3104
|
+
className: "text-left",
|
|
3105
|
+
children: "IP address"
|
|
3106
|
+
}),
|
|
3107
|
+
showLocation ? /* @__PURE__ */ jsx("th", {
|
|
3108
|
+
scope: "col",
|
|
3109
|
+
className: "text-left",
|
|
3110
|
+
children: "Location"
|
|
3111
|
+
}) : null,
|
|
3112
|
+
/* @__PURE__ */ jsx("th", {
|
|
3113
|
+
scope: "col",
|
|
3114
|
+
className: "text-left",
|
|
3115
|
+
children: "Result"
|
|
3116
|
+
})
|
|
3117
|
+
] }) }), /* @__PURE__ */ jsx("tbody", { children: shown.map((row) => /* @__PURE__ */ jsxs("tr", {
|
|
3118
|
+
"data-event": row.event,
|
|
3119
|
+
children: [
|
|
3120
|
+
/* @__PURE__ */ jsx("td", { children: row.created_at ? /* @__PURE__ */ jsx("time", {
|
|
3121
|
+
dateTime: row.created_at,
|
|
3122
|
+
children: formatTime(row.created_at)
|
|
3123
|
+
}) : "—" }),
|
|
3124
|
+
/* @__PURE__ */ jsx("td", { children: eventLabels[row.event] ?? DEFAULT_EVENT_LABELS[row.event] ?? row.event }),
|
|
3125
|
+
/* @__PURE__ */ jsx("td", { children: row.auth_method ? methodLabels[row.auth_method] ?? DEFAULT_METHOD_LABELS[row.auth_method] ?? row.auth_method : "—" }),
|
|
3126
|
+
/* @__PURE__ */ jsx("td", { children: row.ip_address ?? "—" }),
|
|
3127
|
+
showLocation ? /* @__PURE__ */ jsx("td", { children: row.location ?? "—" }) : null,
|
|
3128
|
+
/* @__PURE__ */ jsx("td", { children: /* @__PURE__ */ jsxs("span", {
|
|
3129
|
+
className: "inline-flex flex-wrap gap-1",
|
|
3130
|
+
children: [row.event === "login_blocked" ? tag("Blocked", "blocked") : tag(row.succeeded ? "Succeeded" : "Failed", row.succeeded ? "succeeded" : "failed"), row.is_suspicious ? tag("Flagged", "suspicious") : null]
|
|
3131
|
+
}) })
|
|
3132
|
+
]
|
|
3133
|
+
}, row.id)) })]
|
|
3134
|
+
})
|
|
3135
|
+
}) : null,
|
|
3136
|
+
errorView,
|
|
3137
|
+
error !== null ? /* @__PURE__ */ jsx(Button, {
|
|
3138
|
+
type: "button",
|
|
3139
|
+
variant: "outline",
|
|
3140
|
+
size: "sm",
|
|
3141
|
+
onClick: () => void load(nextPage),
|
|
3142
|
+
children: "Try again"
|
|
3143
|
+
}) : hasMore ? /* @__PURE__ */ jsx(Button, {
|
|
3144
|
+
type: "button",
|
|
3145
|
+
variant: "outline",
|
|
3146
|
+
size: "sm",
|
|
3147
|
+
disabled: loading,
|
|
3148
|
+
onClick: () => void load(nextPage),
|
|
3149
|
+
children: loading ? "Loading..." : "Load more"
|
|
3150
|
+
}) : null
|
|
3151
|
+
]
|
|
3152
|
+
});
|
|
3153
|
+
}
|
|
3154
|
+
export { ApiCredentialsSection, AuthBrowserHelp, ChangePasswordForm, EmailCodeForm, LoginForm, PasskeyLoginButton, PasskeySection, PasswordConfirmationRequiredError, PasswordResetRequestForm, ResetPasswordForm, SIGN_IN_AUDIT_EVENTS, ScopePicker, SignInHistory, SignupForm, TwoFactorForm, arrayBufferToBase64url, authenticateWithPasskey, base64urlToArrayBuffer, closeImplications, confirmPasskey, confirmPasswordForPasskey, describeDuration, detectAuthBrowserIssues, getCsrfToken, getDefaultPasskeyName, inCatalogOrder, isAbortError, isConditionalMediationAvailable, neededBy, parseAuthAuditLogPage, readAuthBrowserEnvironment, registerPasskey, relyingApplicationsFrom, restrictImplications, safeApplicationHref, sameSelection, withScopes, withoutScopes };
|