@krak-stack/auth 0.2.12 → 0.2.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/admin/api.group.d.ts +4 -0
- package/dist/admin/schema.d.ts +3 -0
- package/dist/admin/schema.js +4 -1
- package/dist/api.d.ts +1394 -1380
- package/dist/auth/api.group.d.ts +46 -46
- package/dist/components/admin-organizations.d.ts +111 -1
- package/dist/components/admin-organizations.js +142 -26
- package/dist/components/admin-users.js +54 -78
- package/dist/components/associated-projects-notice.d.ts +6 -0
- package/dist/components/associated-projects-notice.js +24 -0
- package/dist/components/auth-atoms.d.ts +3 -3
- package/dist/components/auth-client-api.d.ts +55 -45
- package/dist/components/auth-forms.d.ts +1 -1
- package/dist/components/auth-forms.js +115 -33
- package/dist/components/auth-provider.d.ts +23 -0
- package/dist/components/auth-provider.js +68 -19
- package/dist/components/index.d.ts +4 -3
- package/dist/components/index.js +2 -2
- package/dist/components/organization-switcher.d.ts +4 -0
- package/dist/components/organization-switcher.js +47 -41
- package/dist/components/scrollable-dialog.d.ts +13 -0
- package/dist/components/scrollable-dialog.js +12 -0
- package/dist/components/user-button.d.ts +4 -0
- package/dist/components/user-button.js +75 -69
- package/dist/extra/api.group.d.ts +6 -1
- package/dist/extra/api.group.js +14 -1
- package/dist/extra/schema.d.ts +12 -0
- package/dist/extra/schema.js +18 -0
- package/dist/server/actor.d.ts +2 -1
- package/dist/service.d.ts +102 -90
- package/package.json +3 -3
|
@@ -4,12 +4,13 @@ import { FormBuilder, FormReact } from "@lucas-barake/effect-form-react";
|
|
|
4
4
|
import { Link, useNavigate, useRouterState } from "@tanstack/react-router";
|
|
5
5
|
import { Effect, Option, Schema } from "effect";
|
|
6
6
|
import { Atom, AsyncResult } from "effect/unstable/reactivity";
|
|
7
|
+
import { HttpClientError } from "effect/unstable/http";
|
|
7
8
|
import { REGEXP_ONLY_DIGITS } from "input-otp";
|
|
8
9
|
import { KeyRound, Loader2, Mail } from "lucide-react";
|
|
9
10
|
import { useEffect, useRef, useState } from "react";
|
|
10
11
|
import { Button, buttonVariants } from "@/components/ui/button";
|
|
11
12
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card";
|
|
12
|
-
import { CheckboxField, ErrorMessage,
|
|
13
|
+
import { CheckboxField, ErrorMessage, TextField, effectFormMessages, } from "@krak-stack/registry/effect-form";
|
|
13
14
|
import { Field, FieldLabel } from "@/components/ui/field";
|
|
14
15
|
import { InputOTP, InputOTPGroup, InputOTPSeparator, InputOTPSlot, } from "@/components/ui/input-otp";
|
|
15
16
|
import { getLastUsedLoginMethod, notifyAuthChange } from "./auth-atoms.js";
|
|
@@ -17,6 +18,7 @@ import { authClientApi, authHttpClient } from "./auth-client-api.js";
|
|
|
17
18
|
import { useKrakstackAuth } from "./auth-provider.js";
|
|
18
19
|
import { cn } from "./utils.js";
|
|
19
20
|
import { ExtraProjectPublicConfig as ExtraProjectPublicConfigSchema, } from "../extra/schema.js";
|
|
21
|
+
import { AuthBadRequest, AuthInternalServerError, AuthTooManyRequests, AuthUnauthorized, } from "../auth/schema.js";
|
|
20
22
|
const EMAIL_OTP_RESEND_COOLDOWN_SECONDS = 60;
|
|
21
23
|
const signinFormBuilder = FormBuilder.empty
|
|
22
24
|
.addField("email", Schema.String)
|
|
@@ -43,6 +45,9 @@ const defaultMessages = {
|
|
|
43
45
|
forgot_password_submit: "Send reset link",
|
|
44
46
|
forgot_password_success: "If an account exists for that email, a reset link has been sent.",
|
|
45
47
|
forgot_password_title: "Reset password",
|
|
48
|
+
error_network: "We couldn't reach the server. Check your connection and try again.",
|
|
49
|
+
error_rate_limited: "Too many attempts. Please wait a moment before trying again.",
|
|
50
|
+
error_service_unavailable: "The authentication service is temporarily unavailable. Please try again.",
|
|
46
51
|
oauth_client_no_auth_methods: "No authentication methods are enabled for this application.",
|
|
47
52
|
reset_password_description: "Enter a new password for your account.",
|
|
48
53
|
reset_password_error: "Unable to reset password.",
|
|
@@ -61,6 +66,8 @@ const defaultMessages = {
|
|
|
61
66
|
sign_in_email_otp_send_error: "Unable to send the sign-in code.",
|
|
62
67
|
sign_in_email_otp_verify: "Verify code",
|
|
63
68
|
sign_in_error: "Unable to sign in.",
|
|
69
|
+
sign_in_invalid_credentials: "The email or password is incorrect.",
|
|
70
|
+
auth_invalid_code: "The code is invalid or has expired.",
|
|
64
71
|
sign_in_forgot_password: "Forgot your password?",
|
|
65
72
|
sign_in_use_email_otp: "Use email code instead",
|
|
66
73
|
sign_in_use_password: "Use an existing password",
|
|
@@ -98,6 +105,9 @@ const defaultMessages = {
|
|
|
98
105
|
forgot_password_submit: "Envoyer le lien",
|
|
99
106
|
forgot_password_success: "Si un compte existe pour ce courriel, un lien de réinitialisation a été envoyé.",
|
|
100
107
|
forgot_password_title: "Réinitialiser le mot de passe",
|
|
108
|
+
error_network: "Impossible de joindre le serveur. Vérifiez votre connexion et réessayez.",
|
|
109
|
+
error_rate_limited: "Trop de tentatives. Veuillez patienter un moment avant de réessayer.",
|
|
110
|
+
error_service_unavailable: "Le service d'authentification est temporairement indisponible. Veuillez réessayer.",
|
|
101
111
|
oauth_client_no_auth_methods: "Aucune méthode d'authentification n'est activée pour cette application.",
|
|
102
112
|
reset_password_description: "Saisissez un nouveau mot de passe pour votre compte.",
|
|
103
113
|
reset_password_error: "Impossible de réinitialiser le mot de passe.",
|
|
@@ -116,6 +126,8 @@ const defaultMessages = {
|
|
|
116
126
|
sign_in_email_otp_send_error: "Impossible d'envoyer le code de connexion.",
|
|
117
127
|
sign_in_email_otp_verify: "Vérifier le code",
|
|
118
128
|
sign_in_error: "Impossible de se connecter.",
|
|
129
|
+
sign_in_invalid_credentials: "Le courriel ou le mot de passe est incorrect.",
|
|
130
|
+
auth_invalid_code: "Le code est invalide ou a expiré.",
|
|
119
131
|
sign_in_forgot_password: "Mot de passe oublié?",
|
|
120
132
|
sign_in_use_email_otp: "Utiliser un code courriel",
|
|
121
133
|
sign_in_use_password: "Utiliser un mot de passe existant",
|
|
@@ -145,6 +157,37 @@ const defaultMessages = {
|
|
|
145
157
|
const labels = (locale) => ({
|
|
146
158
|
...defaultMessages[locale],
|
|
147
159
|
});
|
|
160
|
+
const AuthSubmitError = ({ result, labels: m, messages, }) => {
|
|
161
|
+
const error = Option.getOrUndefined(AsyncResult.error(result));
|
|
162
|
+
if (!error)
|
|
163
|
+
return null;
|
|
164
|
+
let message = messages.fallback;
|
|
165
|
+
if (error instanceof AuthBadRequest) {
|
|
166
|
+
message = messages.badRequest ?? messages.fallback;
|
|
167
|
+
}
|
|
168
|
+
else if (error instanceof AuthUnauthorized) {
|
|
169
|
+
message = messages.unauthorized ?? messages.fallback;
|
|
170
|
+
}
|
|
171
|
+
else if (error instanceof AuthTooManyRequests) {
|
|
172
|
+
message = m.error_rate_limited;
|
|
173
|
+
}
|
|
174
|
+
else if (error instanceof AuthInternalServerError) {
|
|
175
|
+
message = m.error_service_unavailable;
|
|
176
|
+
}
|
|
177
|
+
else if (HttpClientError.isHttpClientError(error)) {
|
|
178
|
+
message =
|
|
179
|
+
error.reason._tag === "TransportError"
|
|
180
|
+
? m.error_network
|
|
181
|
+
: error.reason._tag === "StatusCodeError" &&
|
|
182
|
+
error.reason.response.status === 429
|
|
183
|
+
? m.error_rate_limited
|
|
184
|
+
: m.error_service_unavailable;
|
|
185
|
+
}
|
|
186
|
+
else if (Schema.isSchemaError(error)) {
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
return _jsx(ErrorMessage, { text: message });
|
|
190
|
+
};
|
|
148
191
|
const useAuthFormOptions = ({ baseUrl, locale }) => {
|
|
149
192
|
const auth = useKrakstackAuth();
|
|
150
193
|
const resolvedLocale = locale ?? auth?.locale ?? "en";
|
|
@@ -244,6 +287,7 @@ export function Signin(props) {
|
|
|
244
287
|
const [otpSentTo, setOtpSentTo] = useState(initialMethodStep && initialAuthMethod === "emailOtp" ? initialEmail : "");
|
|
245
288
|
const [emailOtpResendAvailableAt, setEmailOtpResendAvailableAt] = useState(0);
|
|
246
289
|
const [emailOtpResendSeconds, setEmailOtpResendSeconds] = useState(0);
|
|
290
|
+
const [errorContext, setErrorContext] = useState("signIn");
|
|
247
291
|
const selectedAuthMethod = authMethod === "password" && options.emailPassword
|
|
248
292
|
? "password"
|
|
249
293
|
: options.emailOtp
|
|
@@ -337,16 +381,7 @@ export function Signin(props) {
|
|
|
337
381
|
}
|
|
338
382
|
notifyAuthChange();
|
|
339
383
|
onNavigate(result.url ?? redirectTarget);
|
|
340
|
-
})
|
|
341
|
-
? cause
|
|
342
|
-
: new Error(action.type === "sendEmailOtp" ||
|
|
343
|
-
(action.type === "submit" &&
|
|
344
|
-
action.method === "emailOtp" &&
|
|
345
|
-
(!action.emailSubmitted || !action.otpSent))
|
|
346
|
-
? m.sign_in_email_otp_send_error
|
|
347
|
-
: action.type === "submit" && action.method === "emailOtp"
|
|
348
|
-
? m.sign_in_email_otp_error
|
|
349
|
-
: m.sign_in_error))),
|
|
384
|
+
}),
|
|
350
385
|
}));
|
|
351
386
|
const submit = useAtomSet(form.submit);
|
|
352
387
|
const submitResult = useAtomValue(form.submit);
|
|
@@ -368,7 +403,7 @@ export function Signin(props) {
|
|
|
368
403
|
notifyAuthChange();
|
|
369
404
|
if (result.url)
|
|
370
405
|
onNavigate(result.url);
|
|
371
|
-
})
|
|
406
|
+
})));
|
|
372
407
|
const startSocialSignIn = useAtomSet(socialSignIn);
|
|
373
408
|
const socialSignInResult = useAtomValue(socialSignIn);
|
|
374
409
|
const formValues = Option.getOrElse(useAtomValue(form.values), () => ({
|
|
@@ -409,16 +444,24 @@ export function Signin(props) {
|
|
|
409
444
|
});
|
|
410
445
|
return;
|
|
411
446
|
}
|
|
447
|
+
setErrorContext("sendEmailOtp");
|
|
412
448
|
submit({ type: "sendEmailOtp" });
|
|
413
449
|
};
|
|
414
450
|
const resendEmailOtp = () => {
|
|
415
451
|
setOtp("");
|
|
452
|
+
setErrorContext("sendEmailOtp");
|
|
416
453
|
submit({ type: "sendEmailOtp" });
|
|
417
454
|
};
|
|
418
455
|
const signInWithGoogle = () => startSocialSignIn("google");
|
|
419
456
|
return (_jsxs(Card, { className: "w-full max-w-md", children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { className: "text-3xl", children: m.auth_sign_in }), _jsx(CardDescription, { children: !emailSubmitted ? (m.sign_in_description) : (_jsxs(_Fragment, { children: [text(m.sign_in_email_as, { email: formValues.email }), " ", _jsx(Button, { type: "button", variant: "link", className: "h-auto px-0", onClick: resetEmailStep, children: m.sign_in_change_email })] })) })] }), _jsxs(CardContent, { children: [hasPrimaryAuth ? (_jsx(form.Initialize, { defaultValues: { email: initialEmail, password: "", otp: "" }, children: _jsxs("form", { className: "flex flex-col gap-4", onSubmit: (event) => {
|
|
420
457
|
event.preventDefault();
|
|
421
458
|
event.stopPropagation();
|
|
459
|
+
setErrorContext(!emailSubmitted ||
|
|
460
|
+
(selectedAuthMethod === "emailOtp" && !otpSentTo)
|
|
461
|
+
? "sendEmailOtp"
|
|
462
|
+
: selectedAuthMethod === "emailOtp"
|
|
463
|
+
? "verifyEmailOtp"
|
|
464
|
+
: "signIn");
|
|
422
465
|
submit({
|
|
423
466
|
type: "submit",
|
|
424
467
|
emailSubmitted,
|
|
@@ -434,11 +477,25 @@ export function Signin(props) {
|
|
|
434
477
|
? text(m.sign_in_email_otp_resend_countdown, {
|
|
435
478
|
seconds: String(emailOtpResendSeconds),
|
|
436
479
|
})
|
|
437
|
-
: m.sign_in_email_otp_resend })) : null, canChangeAuthMethod ? (_jsxs(Button, { type: "button", variant: "link", className: "h-auto px-0", onClick: switchAuthMethod, children: [_jsx(KeyRound, {}), m.sign_in_use_password] })) : null] })] })) : null, _jsx(
|
|
480
|
+
: m.sign_in_email_otp_resend })) : null, canChangeAuthMethod ? (_jsxs(Button, { type: "button", variant: "link", className: "h-auto px-0", onClick: switchAuthMethod, children: [_jsx(KeyRound, {}), m.sign_in_use_password] })) : null] })] })) : null, _jsx(AuthSubmitError, { result: submitResult, labels: m, messages: {
|
|
481
|
+
fallback: errorContext === "sendEmailOtp"
|
|
482
|
+
? m.sign_in_email_otp_send_error
|
|
483
|
+
: errorContext === "verifyEmailOtp"
|
|
484
|
+
? m.sign_in_email_otp_error
|
|
485
|
+
: m.sign_in_error,
|
|
486
|
+
badRequest: errorContext === "verifyEmailOtp"
|
|
487
|
+
? m.auth_invalid_code
|
|
488
|
+
: errorContext === "signIn"
|
|
489
|
+
? m.sign_in_invalid_credentials
|
|
490
|
+
: m.sign_in_email_otp_send_error,
|
|
491
|
+
unauthorized: errorContext === "signIn"
|
|
492
|
+
? m.sign_in_invalid_credentials
|
|
493
|
+
: m.sign_in_error,
|
|
494
|
+
} }), _jsx("div", { children: _jsxs(Button, { type: "submit", disabled: submitResult.waiting, children: [submitResult.waiting ? (_jsx(Loader2, { className: "animate-spin", "data-icon": "inline-start" })) : null, !emailSubmitted
|
|
438
495
|
? m.sign_in_continue
|
|
439
496
|
: selectedAuthMethod === "emailOtp"
|
|
440
497
|
? m.sign_in_email_otp_verify
|
|
441
|
-
: m.auth_sign_in] }) })] }) })) : null, options.google && !emailSubmitted ? (_jsxs("div", { className: "mt-4 flex flex-col gap-3", children: [hasPrimaryAuth ? (_jsx(Divider, { label: m.auth_or_continue_with })) : null, _jsxs(Button, { type: "button", variant: "outline", className: "w-full", disabled: submitResult.waiting, onClick: signInWithGoogle, children: [_jsx(GoogleLogo, {}), m.auth_continue_with_google] }), _jsx(
|
|
498
|
+
: m.auth_sign_in] }) })] }) })) : null, options.google && !emailSubmitted ? (_jsxs("div", { className: "mt-4 flex flex-col gap-3", children: [hasPrimaryAuth ? (_jsx(Divider, { label: m.auth_or_continue_with })) : null, _jsxs(Button, { type: "button", variant: "outline", className: "w-full", disabled: submitResult.waiting, onClick: signInWithGoogle, children: [_jsx(GoogleLogo, {}), m.auth_continue_with_google] }), _jsx(AuthSubmitError, { result: socialSignInResult, labels: m, messages: { fallback: m.sign_in_error } })] })) : null, !hasPrimaryAuth && !options.google ? (_jsx("p", { className: "text-muted-foreground text-sm", children: m.oauth_client_no_auth_methods })) : null] })] }));
|
|
442
499
|
}
|
|
443
500
|
export function VerifyEmail(props) {
|
|
444
501
|
const { baseUrl, locale, labels: m, projectConfig: providedProjectConfig, } = useAuthFormOptions(props);
|
|
@@ -450,6 +507,7 @@ export function VerifyEmail(props) {
|
|
|
450
507
|
const redirectTarget = getRedirectTarget(searchString, projectConfig?.authDomain, projectConfig?.rootDomain);
|
|
451
508
|
const onNavigate = (target) => navigateTarget(target, navigate);
|
|
452
509
|
const [resent, setResent] = useState(false);
|
|
510
|
+
const [lastAction, setLastAction] = useState("verify");
|
|
453
511
|
const [form] = useState(() => FormReact.make(verifyEmailFormBuilder, {
|
|
454
512
|
runtime: authClientApi(baseUrl).runtime,
|
|
455
513
|
fields: { email: TextField, otp: OtpField },
|
|
@@ -473,23 +531,30 @@ export function VerifyEmail(props) {
|
|
|
473
531
|
})));
|
|
474
532
|
notifyAuthChange();
|
|
475
533
|
onNavigate(redirectTarget);
|
|
476
|
-
})
|
|
477
|
-
? cause
|
|
478
|
-
: new Error(action === "resend"
|
|
479
|
-
? m.verify_email_resend_error
|
|
480
|
-
: m.verify_email_error))),
|
|
534
|
+
}),
|
|
481
535
|
}));
|
|
482
536
|
const submit = useAtomSet(form.submit);
|
|
483
537
|
const submitResult = useAtomValue(form.submit);
|
|
484
|
-
const resendCode = () =>
|
|
538
|
+
const resendCode = () => {
|
|
539
|
+
setLastAction("resend");
|
|
540
|
+
submit("resend");
|
|
541
|
+
};
|
|
485
542
|
return (_jsxs(Card, { className: "w-full max-w-md", children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { className: "text-3xl", children: m.verify_email_title }), _jsx(CardDescription, { children: m.verify_email_description })] }), _jsxs(CardContent, { children: [_jsx(form.Initialize, { defaultValues: {
|
|
486
543
|
email: getSearchParam(searchString, "email") ?? "",
|
|
487
544
|
otp: "",
|
|
488
545
|
}, children: _jsxs("form", { className: "flex flex-col gap-4", onSubmit: (event) => {
|
|
489
546
|
event.preventDefault();
|
|
490
547
|
event.stopPropagation();
|
|
548
|
+
setLastAction("verify");
|
|
491
549
|
submit("verify");
|
|
492
|
-
}, children: [_jsx(form.email, { label: m.field_email, type: "email", autoComplete: "email", required: true }), _jsx(form.otp, { label: m.verify_email_code }), _jsx(
|
|
550
|
+
}, children: [_jsx(form.email, { label: m.field_email, type: "email", autoComplete: "email", required: true }), _jsx(form.otp, { label: m.verify_email_code }), _jsx(AuthSubmitError, { result: submitResult, labels: m, messages: {
|
|
551
|
+
fallback: lastAction === "resend"
|
|
552
|
+
? m.verify_email_resend_error
|
|
553
|
+
: m.verify_email_error,
|
|
554
|
+
badRequest: lastAction === "verify"
|
|
555
|
+
? m.auth_invalid_code
|
|
556
|
+
: m.verify_email_resend_error,
|
|
557
|
+
} }), resent ? (_jsx("p", { className: "text-muted-foreground text-sm", children: m.verify_email_resent })) : null, _jsxs("div", { className: "flex flex-wrap items-center gap-3", children: [_jsxs(Button, { type: "submit", disabled: submitResult.waiting, children: [submitResult.waiting ? (_jsx(Loader2, { className: "animate-spin", "data-icon": "inline-start" })) : null, effectFormMessages().submit] }), _jsx(Button, { type: "button", variant: "ghost", disabled: submitResult.waiting, onClick: resendCode, children: m.verify_email_resend })] })] }) }), _jsx("p", { className: "text-muted-foreground mt-6 text-center text-sm", children: _jsx(Link, { className: authLinkClassName, to: "/sign-in", children: m.forgot_password_back_to_sign_in }) })] })] }));
|
|
493
558
|
}
|
|
494
559
|
export function ForgotPassword(props) {
|
|
495
560
|
const { baseUrl, locale, labels: m } = useAuthFormOptions(props);
|
|
@@ -511,7 +576,7 @@ export function ForgotPassword(props) {
|
|
|
511
576
|
},
|
|
512
577
|
})));
|
|
513
578
|
setSubmitted(true);
|
|
514
|
-
})
|
|
579
|
+
}),
|
|
515
580
|
}));
|
|
516
581
|
const submit = useAtomSet(form.submit);
|
|
517
582
|
const submitResult = useAtomValue(form.submit);
|
|
@@ -519,7 +584,7 @@ export function ForgotPassword(props) {
|
|
|
519
584
|
event.preventDefault();
|
|
520
585
|
event.stopPropagation();
|
|
521
586
|
submit();
|
|
522
|
-
}, children: [_jsx(form.email, { label: m.field_email, type: "email", autoComplete: "email", required: true }), _jsx(
|
|
587
|
+
}, children: [_jsx(form.email, { label: m.field_email, type: "email", autoComplete: "email", required: true }), _jsx(AuthSubmitError, { result: submitResult, labels: m, messages: { fallback: m.forgot_password_error } }), submitted ? (_jsx("p", { className: "bg-card text-card-foreground rounded-lg border px-4 py-3 text-sm shadow-xs", children: m.forgot_password_success })) : null, _jsxs(Button, { type: "submit", disabled: submitResult.waiting, children: [submitResult.waiting ? (_jsx(Loader2, { className: "animate-spin", "data-icon": "inline-start" })) : null, m.forgot_password_submit] })] }) }), _jsx("p", { className: "text-muted-foreground mt-6 text-center text-sm", children: _jsx(Link, { className: authLinkClassName, to: "/sign-in", search: searchObject(searchString), children: m.forgot_password_back_to_sign_in }) })] })] }));
|
|
523
588
|
}
|
|
524
589
|
export function ResetPassword(props) {
|
|
525
590
|
const searchString = useRouterState({
|
|
@@ -544,7 +609,7 @@ function ResetPasswordForm({ token, ...props }) {
|
|
|
544
609
|
},
|
|
545
610
|
})));
|
|
546
611
|
onSuccess();
|
|
547
|
-
})
|
|
612
|
+
}),
|
|
548
613
|
}));
|
|
549
614
|
const submit = useAtomSet(form.submit);
|
|
550
615
|
const submitResult = useAtomValue(form.submit);
|
|
@@ -552,7 +617,7 @@ function ResetPasswordForm({ token, ...props }) {
|
|
|
552
617
|
event.preventDefault();
|
|
553
618
|
event.stopPropagation();
|
|
554
619
|
submit();
|
|
555
|
-
}, children: [_jsx(form.password, { label: m.reset_password_new_password, type: "password", autoComplete: "new-password", minLength: 8, required: true }), _jsx(
|
|
620
|
+
}, children: [_jsx(form.password, { label: m.reset_password_new_password, type: "password", autoComplete: "new-password", minLength: 8, required: true }), _jsx(AuthSubmitError, { result: submitResult, labels: m, messages: { fallback: m.reset_password_error } }), _jsxs(Button, { type: "submit", disabled: submitResult.waiting, children: [submitResult.waiting ? (_jsx(Loader2, { className: "animate-spin", "data-icon": "inline-start" })) : null, effectFormMessages().submit] })] }) }) })] }));
|
|
556
621
|
}
|
|
557
622
|
export function TwoFactor(props) {
|
|
558
623
|
const { baseUrl, locale, labels: m, projectConfig: providedProjectConfig, } = useAuthFormOptions(props);
|
|
@@ -566,6 +631,7 @@ export function TwoFactor(props) {
|
|
|
566
631
|
const onNavigate = (target) => navigateTarget(target, navigate);
|
|
567
632
|
const [mode, setMode] = useState("totp");
|
|
568
633
|
const [emailCodeSent, setEmailCodeSent] = useState(false);
|
|
634
|
+
const [lastAction, setLastAction] = useState("verify");
|
|
569
635
|
const [form] = useState(() => FormReact.make(twoFactorFormBuilder, {
|
|
570
636
|
runtime: authClientApi(baseUrl).runtime,
|
|
571
637
|
fields: { code: AuthCodeField, trustDevice: CheckboxField },
|
|
@@ -598,15 +664,14 @@ export function TwoFactor(props) {
|
|
|
598
664
|
})));
|
|
599
665
|
notifyAuthChange();
|
|
600
666
|
onNavigate(getResultRedirectUrl(result) ?? redirectTarget);
|
|
601
|
-
})
|
|
602
|
-
? cause
|
|
603
|
-
: new Error(action.type === "sendEmailCode"
|
|
604
|
-
? m.two_factor_send_email_code_error
|
|
605
|
-
: m.two_factor_verify_error))),
|
|
667
|
+
}),
|
|
606
668
|
}));
|
|
607
669
|
const submit = useAtomSet(form.submit);
|
|
608
670
|
const submitResult = useAtomValue(form.submit);
|
|
609
|
-
const sendEmailCode = () =>
|
|
671
|
+
const sendEmailCode = () => {
|
|
672
|
+
setLastAction("sendEmailCode");
|
|
673
|
+
submit({ type: "sendEmailCode" });
|
|
674
|
+
};
|
|
610
675
|
return (_jsxs(Card, { className: "w-full max-w-md", children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { className: "text-3xl", children: m.two_factor_title }), _jsx(CardDescription, { children: mode === "backup"
|
|
611
676
|
? m.two_factor_verify_backup_description
|
|
612
677
|
: mode === "email"
|
|
@@ -614,12 +679,20 @@ export function TwoFactor(props) {
|
|
|
614
679
|
: m.two_factor_verify_description })] }), _jsx(CardContent, { children: _jsx(form.Initialize, { defaultValues: { code: "", trustDevice: true }, children: _jsxs("form", { className: "flex flex-col gap-4", onSubmit: (event) => {
|
|
615
680
|
event.preventDefault();
|
|
616
681
|
event.stopPropagation();
|
|
682
|
+
setLastAction("verify");
|
|
617
683
|
submit({ type: "verify", mode });
|
|
618
684
|
}, children: [_jsx(form.code, { autoComplete: "one-time-code", label: mode === "backup"
|
|
619
685
|
? m.two_factor_backup_code
|
|
620
686
|
: mode === "email"
|
|
621
687
|
? m.two_factor_email_code
|
|
622
|
-
: m.two_factor_code, otp: mode !== "backup", required: true }), _jsx(form.trustDevice, { label: m.two_factor_trust_device }), _jsx(
|
|
688
|
+
: m.two_factor_code, otp: mode !== "backup", required: true }), _jsx(form.trustDevice, { label: m.two_factor_trust_device }), _jsx(AuthSubmitError, { result: submitResult, labels: m, messages: {
|
|
689
|
+
fallback: lastAction === "sendEmailCode"
|
|
690
|
+
? m.two_factor_send_email_code_error
|
|
691
|
+
: m.two_factor_verify_error,
|
|
692
|
+
badRequest: lastAction === "verify"
|
|
693
|
+
? m.auth_invalid_code
|
|
694
|
+
: m.two_factor_send_email_code_error,
|
|
695
|
+
} }), emailCodeSent && mode === "email" ? (_jsx("p", { className: "text-muted-foreground text-sm", children: m.two_factor_email_code_sent })) : null, _jsxs("div", { className: "flex flex-wrap items-center gap-3", children: [_jsxs(Button, { type: "submit", disabled: submitResult.waiting, children: [submitResult.waiting ? (_jsx(Loader2, { className: "animate-spin", "data-icon": "inline-start" })) : null, effectFormMessages().submit] }), _jsx(Button, { type: "button", variant: "ghost", disabled: submitResult.waiting, onClick: sendEmailCode, children: m.two_factor_send_email_code }), _jsx(Button, { type: "button", variant: "ghost", onClick: () => setMode(mode === "backup" ? "totp" : "backup"), children: mode === "backup"
|
|
623
696
|
? m.two_factor_use_totp
|
|
624
697
|
: m.two_factor_use_backup_code })] })] }) }) })] }));
|
|
625
698
|
}
|
|
@@ -709,7 +782,16 @@ const getBrowserAuthHost = () => globalThis.window?.location.host ?? null;
|
|
|
709
782
|
export const navigateTarget = (target, navigate) => {
|
|
710
783
|
// Return destinations are complete URLs, including any search and hash.
|
|
711
784
|
// API callbacks must reach the server rather than the client route tree.
|
|
712
|
-
|
|
785
|
+
if (target.startsWith("/api/") || URL.canParse(target)) {
|
|
786
|
+
globalThis.window.location.href = target;
|
|
787
|
+
return;
|
|
788
|
+
}
|
|
789
|
+
const url = new URL(target, "http://localhost");
|
|
790
|
+
return navigate({
|
|
791
|
+
to: url.pathname,
|
|
792
|
+
search: Object.fromEntries(url.searchParams),
|
|
793
|
+
hash: url.hash.slice(1),
|
|
794
|
+
});
|
|
713
795
|
};
|
|
714
796
|
const nameFromEmail = (email) => {
|
|
715
797
|
const trimmed = email.trim();
|
|
@@ -1,7 +1,16 @@
|
|
|
1
|
+
import { Cause, Schema } from "effect";
|
|
2
|
+
import { AsyncResult } from "effect/unstable/reactivity";
|
|
1
3
|
import { type ReactNode } from "react";
|
|
2
4
|
import type { ExtraProjectPublicConfig } from "../extra/schema.js";
|
|
3
5
|
import type { ProjectAccessCatalog, ProjectAccessLabelCatalog } from "../access.js";
|
|
4
6
|
export type KrakstackAuthLocale = "en" | "fr";
|
|
7
|
+
export type KrakstackAuthStatus = "loading" | "ready" | "degraded" | "error";
|
|
8
|
+
declare const KrakstackAuthUnavailableError_base: Schema.Class<KrakstackAuthUnavailableError, Schema.TaggedStruct<"KrakstackAuthUnavailableError", {
|
|
9
|
+
readonly cause: Schema.Defect;
|
|
10
|
+
}>, Cause.YieldableError>;
|
|
11
|
+
export declare class KrakstackAuthUnavailableError extends KrakstackAuthUnavailableError_base {
|
|
12
|
+
readonly status = 503;
|
|
13
|
+
}
|
|
5
14
|
export type KrakstackAuthProviderProps = {
|
|
6
15
|
children: ReactNode;
|
|
7
16
|
locale?: KrakstackAuthLocale | undefined;
|
|
@@ -14,10 +23,18 @@ export type KrakstackAuthContextValue = {
|
|
|
14
23
|
locale: KrakstackAuthLocale;
|
|
15
24
|
baseUrl?: string | undefined;
|
|
16
25
|
projectId?: string | null | undefined;
|
|
26
|
+
status: KrakstackAuthStatus;
|
|
27
|
+
error: KrakstackAuthUnavailableError | null;
|
|
17
28
|
projectConfig: ExtraProjectPublicConfig | null;
|
|
18
29
|
access: ProjectAccessCatalog | null;
|
|
19
30
|
accessLabels: ProjectAccessLabelCatalog | null;
|
|
20
31
|
};
|
|
32
|
+
type ProjectConfigState = {
|
|
33
|
+
status: KrakstackAuthStatus;
|
|
34
|
+
error: KrakstackAuthUnavailableError | null;
|
|
35
|
+
projectConfig: ExtraProjectPublicConfig | null;
|
|
36
|
+
};
|
|
37
|
+
export declare const resolveProjectConfigState: (result: AsyncResult.AsyncResult<ExtraProjectPublicConfig | null, unknown>) => ProjectConfigState;
|
|
21
38
|
export declare function KrakstackAuthProvider({ children, locale, baseUrl, projectId, access, accessLabels, }: KrakstackAuthProviderProps): import("react").JSX.Element;
|
|
22
39
|
export declare const useKrakstackAuth: () => KrakstackAuthContextValue | null;
|
|
23
40
|
export declare const useKrakstackAuthProjectConfig: () => {
|
|
@@ -33,6 +50,11 @@ export declare const useKrakstackAuthProjectConfig: () => {
|
|
|
33
50
|
readonly google: boolean;
|
|
34
51
|
};
|
|
35
52
|
} | null;
|
|
53
|
+
export type KrakstackAuthRequiredProps = {
|
|
54
|
+
children: ReactNode;
|
|
55
|
+
fallback?: ReactNode | undefined;
|
|
56
|
+
};
|
|
57
|
+
export declare const KrakstackAuthRequired: ({ children, fallback, }: KrakstackAuthRequiredProps) => ReactNode;
|
|
36
58
|
export declare const usePermissions: () => {
|
|
37
59
|
loading: boolean;
|
|
38
60
|
permissions: Set<string>;
|
|
@@ -40,3 +62,4 @@ export declare const usePermissions: () => {
|
|
|
40
62
|
canAll: (required: ReadonlyArray<string>) => boolean;
|
|
41
63
|
canAny: (required: ReadonlyArray<string>) => boolean;
|
|
42
64
|
};
|
|
65
|
+
export {};
|
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
-
import {
|
|
2
|
+
import { useAtomValue } from "@effect/atom-react";
|
|
3
3
|
import { useRouterState } from "@tanstack/react-router";
|
|
4
|
-
import {
|
|
4
|
+
import { Cause, Option, Schema } from "effect";
|
|
5
|
+
import { HttpApiError } from "effect/unstable/httpapi";
|
|
6
|
+
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
|
5
7
|
import { createContext, useContext, useEffect, useMemo, useRef, } from "react";
|
|
6
8
|
import { activeAuthOrganizationAtom, authSessionAtom } from "./auth-atoms.js";
|
|
7
9
|
import { authClientApi } from "./auth-client-api.js";
|
|
8
10
|
import { parseRoleList } from "../roles.js";
|
|
11
|
+
export class KrakstackAuthUnavailableError extends Schema.TaggedError()("KrakstackAuthUnavailableError", {
|
|
12
|
+
cause: Schema.Defect(),
|
|
13
|
+
}) {
|
|
14
|
+
status = 503;
|
|
15
|
+
}
|
|
9
16
|
const KrakstackAuthContext = createContext(null);
|
|
10
17
|
const PROJECT_CONTEXT_COOKIE = "krakstack-auth.project_context";
|
|
11
18
|
const setProjectContextCookie = (projectId) => {
|
|
@@ -42,7 +49,28 @@ const getRedirectHost = (searchString) => {
|
|
|
42
49
|
return null;
|
|
43
50
|
}
|
|
44
51
|
};
|
|
45
|
-
const
|
|
52
|
+
const serverProjectConfigAtom = Atom.make(AsyncResult.initial());
|
|
53
|
+
export const resolveProjectConfigState = (result) => {
|
|
54
|
+
if (AsyncResult.isFailure(result)) {
|
|
55
|
+
const projectConfig = AsyncResult.getOrElse(result, () => null);
|
|
56
|
+
return {
|
|
57
|
+
status: Option.isSome(result.previousSuccess) ? "degraded" : "error",
|
|
58
|
+
error: new KrakstackAuthUnavailableError({
|
|
59
|
+
cause: Cause.squash(result.cause),
|
|
60
|
+
}),
|
|
61
|
+
projectConfig,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
if (AsyncResult.isSuccess(result)) {
|
|
65
|
+
return {
|
|
66
|
+
status: "ready",
|
|
67
|
+
error: null,
|
|
68
|
+
projectConfig: result.value,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
return { status: "loading", error: null, projectConfig: null };
|
|
72
|
+
};
|
|
73
|
+
const useProjectConfigState = (baseUrl, providedProjectId) => {
|
|
46
74
|
const searchString = useRouterState({
|
|
47
75
|
select: (state) => state.location.searchStr,
|
|
48
76
|
});
|
|
@@ -59,26 +87,29 @@ const useProjectConfig = (baseUrl, providedProjectId) => {
|
|
|
59
87
|
query.host = host;
|
|
60
88
|
if (rootHost)
|
|
61
89
|
query.rootHost = rootHost;
|
|
62
|
-
const
|
|
63
|
-
query,
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
90
|
+
const projectConfigAtom = globalThis.window
|
|
91
|
+
? authClientApi(baseUrl).query("authExtra", "getProjectPublicConfig", {
|
|
92
|
+
query,
|
|
93
|
+
timeToLive: "5 minutes",
|
|
94
|
+
reactivityKeys: [
|
|
95
|
+
"project-public-config",
|
|
96
|
+
...(projectId ? [`project:${projectId}`] : []),
|
|
97
|
+
...(clientId ? [`client:${clientId}`] : []),
|
|
98
|
+
...(host ? [`host:${host}`] : []),
|
|
99
|
+
...(rootHost ? [`root-host:${rootHost}`] : []),
|
|
100
|
+
],
|
|
101
|
+
serializationKey: `project-public-config:${projectId ?? ""}:${clientId ?? ""}:${host ?? ""}:${rootHost ?? ""}`,
|
|
102
|
+
})
|
|
103
|
+
: serverProjectConfigAtom;
|
|
104
|
+
const result = useAtomValue(projectConfigAtom);
|
|
105
|
+
return useMemo(() => resolveProjectConfigState(result), [result]);
|
|
75
106
|
};
|
|
76
107
|
export function KrakstackAuthProvider({ children, locale = "en", baseUrl, projectId, access, accessLabels, }) {
|
|
77
108
|
const searchString = useRouterState({
|
|
78
109
|
select: (state) => state.location.searchStr,
|
|
79
110
|
});
|
|
80
111
|
const resolvedProjectId = projectId ?? getSearchParam(searchString, "projectId");
|
|
81
|
-
const
|
|
112
|
+
const projectConfigState = useProjectConfigState(baseUrl, projectId);
|
|
82
113
|
const sessionAtom = authSessionAtom(baseUrl);
|
|
83
114
|
const sessionResult = useAtomValue(sessionAtom);
|
|
84
115
|
const wasAuthenticated = useRef(false);
|
|
@@ -101,14 +132,32 @@ export function KrakstackAuthProvider({ children, locale = "en", baseUrl, projec
|
|
|
101
132
|
baseUrl,
|
|
102
133
|
locale,
|
|
103
134
|
projectId: resolvedProjectId,
|
|
104
|
-
|
|
135
|
+
...projectConfigState,
|
|
105
136
|
access: access ?? null,
|
|
106
137
|
accessLabels: accessLabels ?? null,
|
|
107
|
-
}), [
|
|
138
|
+
}), [
|
|
139
|
+
baseUrl,
|
|
140
|
+
locale,
|
|
141
|
+
resolvedProjectId,
|
|
142
|
+
projectConfigState,
|
|
143
|
+
access,
|
|
144
|
+
accessLabels,
|
|
145
|
+
]);
|
|
108
146
|
return (_jsx(KrakstackAuthContext.Provider, { value: value, children: children }));
|
|
109
147
|
}
|
|
110
148
|
export const useKrakstackAuth = () => useContext(KrakstackAuthContext);
|
|
111
149
|
export const useKrakstackAuthProjectConfig = () => useKrakstackAuth()?.projectConfig ?? null;
|
|
150
|
+
export const KrakstackAuthRequired = ({ children, fallback = null, }) => {
|
|
151
|
+
const auth = useKrakstackAuth();
|
|
152
|
+
if (!auth) {
|
|
153
|
+
throw new Error("KrakstackAuthProvider is required to use KrakstackAuthRequired.");
|
|
154
|
+
}
|
|
155
|
+
if (auth.status === "loading")
|
|
156
|
+
return fallback;
|
|
157
|
+
if (auth.status === "error")
|
|
158
|
+
throw auth.error;
|
|
159
|
+
return children;
|
|
160
|
+
};
|
|
112
161
|
export const usePermissions = () => {
|
|
113
162
|
const auth = useKrakstackAuth();
|
|
114
163
|
if (!auth) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { KrakstackAuthProvider, useKrakstackAuth, useKrakstackAuthProjectConfig, usePermissions, } from "./auth-provider.js";
|
|
1
|
+
export { KrakstackAuthProvider, KrakstackAuthRequired, KrakstackAuthUnavailableError, useKrakstackAuth, useKrakstackAuthProjectConfig, usePermissions, } from "./auth-provider.js";
|
|
2
2
|
export { activeAuthOrganizationAtom, authOrganizationsAtom, authSessionAtom, } from "./auth-atoms.js";
|
|
3
3
|
export { OrganizationSwitcher } from "./organization-switcher.js";
|
|
4
4
|
export { MemberRequired } from "./member-required.js";
|
|
@@ -6,14 +6,15 @@ export { HasPermission, useHasPermission } from "./has-permission.js";
|
|
|
6
6
|
export { ProjectAccessMatrix } from "./project-access-matrix.js";
|
|
7
7
|
export { ForgotPassword, ResetPassword, Signin, TwoFactor, VerifyEmail, } from "./auth-forms.js";
|
|
8
8
|
export { UserButton } from "./user-button.js";
|
|
9
|
-
export { AdminOrganizationsTable } from "./admin-organizations.js";
|
|
9
|
+
export { AdminOrganizationsTable, adminOrganizationsMessages, } from "./admin-organizations.js";
|
|
10
10
|
export { AdminOrganizationForm } from "./admin-organization-form.js";
|
|
11
11
|
export { AdminUsersTable, useAdminUsersTotal } from "./admin-users.js";
|
|
12
12
|
export { assetUrl } from "./utils.js";
|
|
13
13
|
export { ApiKeyPermissionGrant, CurrentActor, Forbidden, all, actorUserId, any, defineProjectAccess, defineProjectAccessLabels, permission, policy, withPolicy, } from "../access.js";
|
|
14
14
|
export type { ApiKeyOwner, ApiKeyActor, Actor, Policy, ProjectAccessConfig, ProjectAccessCatalog, ProjectAccessLabelCatalog, ProjectAccessDefinition, ProjectAccessLabels, UserActor, } from "../access.js";
|
|
15
15
|
export type { ProjectAccessMatrixAccess, ProjectAccessMatrixMessages, } from "./project-access-matrix.js";
|
|
16
|
-
export type {
|
|
16
|
+
export type { AdminOrganizationsMessages } from "./admin-organizations.js";
|
|
17
|
+
export type { KrakstackAuthContextValue, KrakstackAuthLocale, KrakstackAuthProviderProps, KrakstackAuthRequiredProps, KrakstackAuthStatus, } from "./auth-provider.js";
|
|
17
18
|
export type { OrganizationSwitcherDialog, OrganizationSwitcherFeatures, OrganizationSwitcherProps, } from "./organization-switcher.js";
|
|
18
19
|
export type { UserButtonDialog, UserButtonProps } from "./user-button.js";
|
|
19
20
|
export type { MemberRequiredMessages, MemberRequiredProps, } from "./member-required.js";
|
package/dist/components/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { KrakstackAuthProvider, useKrakstackAuth, useKrakstackAuthProjectConfig, usePermissions, } from "./auth-provider.js";
|
|
1
|
+
export { KrakstackAuthProvider, KrakstackAuthRequired, KrakstackAuthUnavailableError, useKrakstackAuth, useKrakstackAuthProjectConfig, usePermissions, } from "./auth-provider.js";
|
|
2
2
|
export { activeAuthOrganizationAtom, authOrganizationsAtom, authSessionAtom, } from "./auth-atoms.js";
|
|
3
3
|
export { OrganizationSwitcher } from "./organization-switcher.js";
|
|
4
4
|
export { MemberRequired } from "./member-required.js";
|
|
@@ -6,7 +6,7 @@ export { HasPermission, useHasPermission } from "./has-permission.js";
|
|
|
6
6
|
export { ProjectAccessMatrix } from "./project-access-matrix.js";
|
|
7
7
|
export { ForgotPassword, ResetPassword, Signin, TwoFactor, VerifyEmail, } from "./auth-forms.js";
|
|
8
8
|
export { UserButton } from "./user-button.js";
|
|
9
|
-
export { AdminOrganizationsTable } from "./admin-organizations.js";
|
|
9
|
+
export { AdminOrganizationsTable, adminOrganizationsMessages, } from "./admin-organizations.js";
|
|
10
10
|
export { AdminOrganizationForm } from "./admin-organization-form.js";
|
|
11
11
|
export { AdminUsersTable, useAdminUsersTotal } from "./admin-users.js";
|
|
12
12
|
export { assetUrl } from "./utils.js";
|
|
@@ -23,6 +23,8 @@ declare const messages: {
|
|
|
23
23
|
readonly organization_create_slug_conflict: "That organization slug is already in use. Choose a different slug.";
|
|
24
24
|
readonly organization_create_title: "Create organization";
|
|
25
25
|
readonly organization_edit_description: "Update the active organization's localized profile.";
|
|
26
|
+
readonly organization_projects_summary: "Used by {count} projects.";
|
|
27
|
+
readonly organization_projects_view: "View";
|
|
26
28
|
readonly organization_invitation_cancel: "Cancel invitation";
|
|
27
29
|
readonly organization_invitation_cancel_error: "Could not cancel the invitation.";
|
|
28
30
|
readonly organization_invitation_accept: "Accept invitation";
|
|
@@ -162,6 +164,8 @@ declare const messages: {
|
|
|
162
164
|
readonly organization_create_slug_conflict: "Ce slug d'organisation est déjà utilisé. Choisissez un autre slug.";
|
|
163
165
|
readonly organization_create_title: "Créer une organisation";
|
|
164
166
|
readonly organization_edit_description: "Mettez à jour le profil localisé de l'organisation active.";
|
|
167
|
+
readonly organization_projects_summary: "Utilisée dans {count} projets.";
|
|
168
|
+
readonly organization_projects_view: "Voir";
|
|
165
169
|
readonly organization_invitation_cancel: "Annuler l'invitation";
|
|
166
170
|
readonly organization_invitation_cancel_error: "Impossible d'annuler l'invitation.";
|
|
167
171
|
readonly organization_invitation_accept: "Accepter l'invitation";
|