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