@krak-stack/auth 0.1.29 → 0.1.30

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.
@@ -0,0 +1,646 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // @ts-nocheck
3
+ import { useNavigate, useRouterState } from "@tanstack/react-router";
4
+ import { REGEXP_ONLY_DIGITS } from "input-otp";
5
+ import { KeyRound, Mail } from "lucide-react";
6
+ import { useEffect, useState } from "react";
7
+ import { Button, buttonVariants } from "@/components/ui/button";
8
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card";
9
+ import { Field, FieldLabel } from "@/components/ui/field";
10
+ import { FieldError, useAppForm } from "@/components/ui/form";
11
+ import { InputOTP, InputOTPGroup, InputOTPSeparator, InputOTPSlot, } from "@/components/ui/input-otp";
12
+ import { cn } from "@/lib/utils";
13
+ import { useAuthBrandingConfig } from "@/services/auth/client/branding";
14
+ const EMAIL_OTP_RESEND_COOLDOWN_SECONDS = 60;
15
+ const defaultMessages = {
16
+ en: {
17
+ auth_continue_with_google: "Continue with Google",
18
+ auth_or_continue_with: "or continue with",
19
+ auth_sign_in: "Sign in",
20
+ auth_sign_up: "Sign up",
21
+ field_email: "Email",
22
+ field_name: "Name",
23
+ field_password: "Password",
24
+ forgot_password_back_to_sign_in: "Back to sign in",
25
+ oauth_client_no_auth_methods: "No authentication methods are enabled for this application.",
26
+ reset_password_description: "Enter a new password for your account.",
27
+ reset_password_error: "Unable to reset password.",
28
+ reset_password_missing_token: "The password reset link is missing a token.",
29
+ reset_password_new_password: "New password",
30
+ reset_password_title: "Choose a new password",
31
+ sign_in_change_email: "Change",
32
+ sign_in_continue: "Continue",
33
+ sign_in_description: "Enter your email to continue.",
34
+ sign_in_email_as: "Signing in as {email}",
35
+ sign_in_email_otp_code: "Email code",
36
+ sign_in_email_otp_error: "Unable to verify the sign-in code.",
37
+ sign_in_email_otp_resend: "Resend code",
38
+ sign_in_email_otp_resend_countdown: "Resend in {seconds}s",
39
+ sign_in_email_otp_send_error: "Unable to send the sign-in code.",
40
+ sign_in_email_otp_verify: "Verify code",
41
+ sign_in_error: "Unable to sign in.",
42
+ sign_in_forgot_password: "Forgot your password?",
43
+ sign_in_need_account: "Need an account?",
44
+ sign_in_use_email_otp: "Use email code instead",
45
+ sign_in_use_password: "Use password instead",
46
+ sign_up_description: "Enter your details to create an account.",
47
+ sign_up_disabled_description: "New account registration is currently disabled for this project.",
48
+ sign_up_disabled_title: "Sign-up is unavailable",
49
+ sign_up_error: "Unable to create account.",
50
+ sign_up_have_account: "Already have an account?",
51
+ sign_up_title: "Create account",
52
+ two_factor_backup_code: "Backup code",
53
+ two_factor_code: "Authentication code",
54
+ two_factor_email_code: "Email verification code",
55
+ two_factor_email_code_sent: "A verification code was sent to your email.",
56
+ two_factor_send_email_code: "Send email code",
57
+ two_factor_send_email_code_error: "Could not send an email verification code.",
58
+ two_factor_title: "Two-factor verification",
59
+ two_factor_trust_device: "Trust this device for 30 days",
60
+ two_factor_use_backup_code: "Use a backup code",
61
+ two_factor_use_totp: "Use authenticator code",
62
+ two_factor_verify_backup_description: "Enter one of your backup codes to continue.",
63
+ two_factor_verify_description: "Enter the code from your authenticator app to continue.",
64
+ two_factor_verify_email_description: "Enter the verification code sent to your email to continue.",
65
+ two_factor_verify_error: "Could not verify the code.",
66
+ },
67
+ fr: {
68
+ auth_continue_with_google: "Continuer avec Google",
69
+ auth_or_continue_with: "ou continuez avec",
70
+ auth_sign_in: "Se connecter",
71
+ auth_sign_up: "S'inscrire",
72
+ field_email: "Courriel",
73
+ field_name: "Nom",
74
+ field_password: "Mot de passe",
75
+ forgot_password_back_to_sign_in: "Retour à la connexion",
76
+ oauth_client_no_auth_methods: "Aucune méthode d'authentification n'est activée pour cette application.",
77
+ reset_password_description: "Saisissez un nouveau mot de passe pour votre compte.",
78
+ reset_password_error: "Impossible de réinitialiser le mot de passe.",
79
+ reset_password_missing_token: "Le lien de réinitialisation du mot de passe ne contient pas de jeton.",
80
+ reset_password_new_password: "Nouveau mot de passe",
81
+ reset_password_title: "Choisir un nouveau mot de passe",
82
+ sign_in_change_email: "Modifier",
83
+ sign_in_continue: "Continuer",
84
+ sign_in_description: "Saisissez votre courriel pour continuer.",
85
+ sign_in_email_as: "Connexion avec {email}",
86
+ sign_in_email_otp_code: "Code courriel",
87
+ sign_in_email_otp_error: "Impossible de vérifier le code de connexion.",
88
+ sign_in_email_otp_resend: "Renvoyer le code",
89
+ sign_in_email_otp_resend_countdown: "Renvoyer dans {seconds} s",
90
+ sign_in_email_otp_send_error: "Impossible d'envoyer le code de connexion.",
91
+ sign_in_email_otp_verify: "Vérifier le code",
92
+ sign_in_error: "Impossible de se connecter.",
93
+ sign_in_forgot_password: "Mot de passe oublié?",
94
+ sign_in_need_account: "Besoin d'un compte?",
95
+ sign_in_use_email_otp: "Utiliser un code courriel",
96
+ sign_in_use_password: "Utiliser le mot de passe",
97
+ sign_up_description: "Saisissez vos informations pour créer un compte.",
98
+ sign_up_disabled_description: "Les nouvelles inscriptions sont actuellement désactivées pour ce projet.",
99
+ sign_up_disabled_title: "L'inscription est indisponible",
100
+ sign_up_error: "Impossible de créer le compte.",
101
+ sign_up_have_account: "Vous avez déjà un compte?",
102
+ sign_up_title: "Créer un compte",
103
+ two_factor_backup_code: "Code de secours",
104
+ two_factor_code: "Code d'authentification",
105
+ two_factor_email_code: "Code de vérification par courriel",
106
+ two_factor_email_code_sent: "Un code de vérification a été envoyé à votre courriel.",
107
+ two_factor_send_email_code: "Envoyer un code par courriel",
108
+ two_factor_send_email_code_error: "Impossible d'envoyer un code de vérification par courriel.",
109
+ two_factor_title: "Vérification à deux facteurs",
110
+ two_factor_trust_device: "Faire confiance à cet appareil pendant 30 jours",
111
+ two_factor_use_backup_code: "Utiliser un code de secours",
112
+ two_factor_use_totp: "Utiliser le code d'authentification",
113
+ two_factor_verify_backup_description: "Saisissez l'un de vos codes de secours pour continuer.",
114
+ two_factor_verify_description: "Saisissez le code de votre application d'authentification pour continuer.",
115
+ two_factor_verify_email_description: "Saisissez le code de vérification envoyé à votre courriel pour continuer.",
116
+ two_factor_verify_error: "Impossible de vérifier le code.",
117
+ },
118
+ };
119
+ const labels = () => ({
120
+ ...defaultMessages[currentLocale()],
121
+ });
122
+ const currentLocale = () => typeof navigator !== "undefined" &&
123
+ navigator.language.toLowerCase().startsWith("fr")
124
+ ? "fr"
125
+ : "en";
126
+ const text = (value, params) => Object.entries(params ?? {}).reduce((current, [key, replacement]) => current.replace(`{${key}}`, replacement), value);
127
+ export function Signin({ authClient }) {
128
+ const navigate = useNavigate();
129
+ const searchString = useRouterState({
130
+ select: (state) => state.location.searchStr,
131
+ });
132
+ const projectConfig = useAuthBrandingConfig();
133
+ const redirectTarget = getRedirectTarget(searchString, projectConfig?.authDomain, projectConfig?.rootDomain);
134
+ const socialRedirectTarget = getSocialRedirectTarget(searchString, projectConfig?.authDomain, projectConfig?.rootDomain);
135
+ const oauthQuery = getOAuthQuery(searchString);
136
+ const authOptions = projectConfig?.authOptions ?? {};
137
+ const onNavigate = (target) => navigateTarget(target, navigate);
138
+ const onTwoFactorRedirect = (href) => navigate({ href });
139
+ const m = labels();
140
+ const options = {
141
+ emailPassword: authOptions.emailPassword ?? true,
142
+ emailOtp: authOptions.emailOtp ?? true,
143
+ google: authOptions.google ?? true,
144
+ signUp: authOptions.signUp ?? true,
145
+ };
146
+ const [emailSubmitted, setEmailSubmitted] = useState(false);
147
+ const [authMethod, setAuthMethod] = useState("password");
148
+ const [otpSentTo, setOtpSentTo] = useState("");
149
+ const [emailOtpResendAvailableAt, setEmailOtpResendAvailableAt] = useState(0);
150
+ const [emailOtpResendSeconds, setEmailOtpResendSeconds] = useState(0);
151
+ const selectedAuthMethod = authMethod === "password" && options.emailPassword
152
+ ? "password"
153
+ : options.emailOtp
154
+ ? "emailOtp"
155
+ : "password";
156
+ const hasPrimaryAuth = options.emailPassword || options.emailOtp;
157
+ const canChangeAuthMethod = options.emailPassword && options.emailOtp;
158
+ useEffect(() => {
159
+ if (!emailOtpResendAvailableAt) {
160
+ setEmailOtpResendSeconds(0);
161
+ return;
162
+ }
163
+ const updateResendSeconds = () => {
164
+ const seconds = Math.max(0, Math.ceil((emailOtpResendAvailableAt - Date.now()) / 1000));
165
+ setEmailOtpResendSeconds(seconds);
166
+ if (seconds === 0)
167
+ setEmailOtpResendAvailableAt(0);
168
+ };
169
+ updateResendSeconds();
170
+ const interval = window.setInterval(updateResendSeconds, 1000);
171
+ return () => window.clearInterval(interval);
172
+ }, [emailOtpResendAvailableAt]);
173
+ const form = useAppForm({
174
+ defaultValues: { email: "", password: "", otp: "" },
175
+ onSubmit: async ({ value, formApi }) => {
176
+ formApi.setErrorMap({ onSubmit: undefined });
177
+ const email = value.email.trim();
178
+ if (!emailSubmitted) {
179
+ if (selectedAuthMethod === "emailOtp") {
180
+ await sendEmailOtp(email, (message) => formApi.setErrorMap({ onSubmit: { form: message, fields: {} } }));
181
+ return;
182
+ }
183
+ setEmailSubmitted(true);
184
+ return;
185
+ }
186
+ try {
187
+ if (selectedAuthMethod === "emailOtp") {
188
+ if (!otpSentTo) {
189
+ await sendEmailOtp(email, (message) => formApi.setErrorMap({ onSubmit: { form: message, fields: {} } }));
190
+ return;
191
+ }
192
+ const result = await authClient.signIn.emailOtp({
193
+ email,
194
+ otp: value.otp.trim(),
195
+ });
196
+ if (result.error) {
197
+ formApi.setErrorMap({
198
+ onSubmit: {
199
+ form: result.error.message ?? m.sign_in_email_otp_error,
200
+ fields: {},
201
+ },
202
+ });
203
+ return;
204
+ }
205
+ onNavigate(redirectTarget);
206
+ return;
207
+ }
208
+ const result = await authClient.signIn.email({
209
+ email,
210
+ password: value.password,
211
+ callbackURL: redirectTarget,
212
+ ...(oauthQuery ? { oauth_query: oauthQuery } : {}),
213
+ });
214
+ if (result.error) {
215
+ formApi.setErrorMap({
216
+ onSubmit: {
217
+ form: result.error.message ?? m.sign_in_error,
218
+ fields: {},
219
+ },
220
+ });
221
+ return;
222
+ }
223
+ if (hasTwoFactorRedirect(result.data)) {
224
+ onTwoFactorRedirect(`/2fa${oauthQuery ? `?${oauthQuery}` : `?callbackURL=${encodeURIComponent(redirectTarget)}`}`);
225
+ return;
226
+ }
227
+ onNavigate(result.data?.url ?? redirectTarget);
228
+ }
229
+ catch {
230
+ formApi.setErrorMap({
231
+ onSubmit: {
232
+ form: selectedAuthMethod === "emailOtp"
233
+ ? m.sign_in_email_otp_error
234
+ : m.sign_in_error,
235
+ fields: {},
236
+ },
237
+ });
238
+ }
239
+ },
240
+ });
241
+ const sendEmailOtp = async (email, setError) => {
242
+ try {
243
+ const result = await authClient.emailOtp.sendVerificationOtp({
244
+ email,
245
+ type: "sign-in",
246
+ });
247
+ if (result.error) {
248
+ setError(result.error.message ?? m.sign_in_email_otp_send_error);
249
+ return;
250
+ }
251
+ setAuthMethod("emailOtp");
252
+ setEmailSubmitted(true);
253
+ setOtpSentTo(email);
254
+ setEmailOtpResendAvailableAt(Date.now() + EMAIL_OTP_RESEND_COOLDOWN_SECONDS * 1000);
255
+ }
256
+ catch {
257
+ setError(m.sign_in_email_otp_send_error);
258
+ }
259
+ };
260
+ const resetEmailStep = () => {
261
+ setEmailSubmitted(false);
262
+ setOtpSentTo("");
263
+ setEmailOtpResendAvailableAt(0);
264
+ form.setFieldValue("password", "");
265
+ form.setFieldValue("otp", "");
266
+ form.setErrorMap({ onSubmit: undefined });
267
+ };
268
+ const switchAuthMethod = async () => {
269
+ form.setErrorMap({ onSubmit: undefined });
270
+ form.setFieldValue("password", "");
271
+ form.setFieldValue("otp", "");
272
+ if (selectedAuthMethod === "emailOtp") {
273
+ setAuthMethod("password");
274
+ setOtpSentTo("");
275
+ setEmailOtpResendAvailableAt(0);
276
+ return;
277
+ }
278
+ await sendEmailOtp(form.state.values.email.trim(), (message) => form.setErrorMap({ onSubmit: { form: message, fields: {} } }));
279
+ };
280
+ const resendEmailOtp = async () => {
281
+ form.setErrorMap({ onSubmit: undefined });
282
+ form.setFieldValue("otp", "");
283
+ await sendEmailOtp(form.state.values.email.trim(), (message) => form.setErrorMap({ onSubmit: { form: message, fields: {} } }));
284
+ };
285
+ const signInWithGoogle = async () => {
286
+ try {
287
+ const result = await authClient.signIn.social({
288
+ provider: "google",
289
+ callbackURL: socialRedirectTarget,
290
+ errorCallbackURL: "/sign-in",
291
+ ...(oauthQuery ? { additionalData: { query: oauthQuery } } : {}),
292
+ ...(oauthQuery ? { oauth_query: oauthQuery } : {}),
293
+ });
294
+ if (result.error) {
295
+ form.setErrorMap({
296
+ onSubmit: {
297
+ form: result.error.message ?? m.sign_in_error,
298
+ fields: {},
299
+ },
300
+ });
301
+ return;
302
+ }
303
+ if (result.data?.url)
304
+ onNavigate(result.data.url);
305
+ }
306
+ catch {
307
+ form.setErrorMap({ onSubmit: { form: m.sign_in_error, fields: {} } });
308
+ }
309
+ };
310
+ 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: form.state.values.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.AppForm, { children: _jsxs("form", { className: "flex flex-col gap-4", onSubmit: (event) => {
311
+ event.preventDefault();
312
+ event.stopPropagation();
313
+ form.handleSubmit();
314
+ }, children: [!emailSubmitted ? (_jsx(form.AppField, { name: "email", children: (field) => (_jsx(field.TextField, { label: m.field_email, type: "email", autoComplete: "email", required: true })) })) : null, emailSubmitted && selectedAuthMethod === "password" ? (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(form.AppField, { name: "password", children: (field) => (_jsx(field.TextField, { label: m.field_password, type: "password", autoComplete: "current-password", required: true })) }), _jsxs("div", { className: "flex flex-wrap gap-x-4 gap-y-2 text-sm", children: [_jsx("a", { className: cn(buttonVariants({ variant: "link" }), "h-auto px-0"), href: `/forgot-password${searchString}`, children: m.sign_in_forgot_password }), canChangeAuthMethod ? (_jsxs(Button, { type: "button", variant: "link", className: "h-auto px-0", onClick: switchAuthMethod, children: [_jsx(Mail, {}), m.sign_in_use_email_otp] })) : null] })] })) : null, emailSubmitted && selectedAuthMethod === "emailOtp" ? (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(form.AppField, { name: "otp", children: (field) => (_jsx(OtpInput, { field: field, label: m.sign_in_email_otp_code })) }), _jsxs("div", { className: "flex flex-wrap gap-x-4 gap-y-2 text-sm", children: [otpSentTo ? (_jsx(Button, { type: "button", variant: "link", className: "h-auto px-0", disabled: emailOtpResendSeconds > 0, onClick: resendEmailOtp, children: emailOtpResendSeconds > 0
315
+ ? text(m.sign_in_email_otp_resend_countdown, {
316
+ seconds: String(emailOtpResendSeconds),
317
+ })
318
+ : 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(form.FormError, {}), _jsx("div", { children: _jsx(form.SubmitButton, { children: !emailSubmitted
319
+ ? m.sign_in_continue
320
+ : selectedAuthMethod === "emailOtp"
321
+ ? m.sign_in_email_otp_verify
322
+ : 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", onClick: signInWithGoogle, children: [_jsx(GoogleLogo, {}), m.auth_continue_with_google] })] })) : null, !hasPrimaryAuth && !options.google ? (_jsx("p", { className: "text-muted-foreground text-sm", children: m.oauth_client_no_auth_methods })) : null, options.signUp ? (_jsxs("p", { className: "text-muted-foreground mt-6 text-center text-sm", children: [m.sign_in_need_account, " ", _jsx("a", { className: cn(buttonVariants({ variant: "link" }), "h-auto px-0"), href: `/sign-up${searchString}`, children: m.auth_sign_up })] })) : null] })] }));
323
+ }
324
+ export function Signup({ authClient }) {
325
+ const navigate = useNavigate();
326
+ const searchString = useRouterState({
327
+ select: (state) => state.location.searchStr,
328
+ });
329
+ const projectConfig = useAuthBrandingConfig();
330
+ const redirectTarget = getRedirectTarget(searchString, projectConfig?.authDomain, projectConfig?.rootDomain);
331
+ const authOptions = projectConfig?.authOptions ?? {};
332
+ const onNavigate = (target) => navigate({ href: target });
333
+ const onVerifyEmail = (email) => navigate({ to: "/verify-email", search: { email } });
334
+ const m = labels();
335
+ const options = {
336
+ google: authOptions.google ?? true,
337
+ signUp: authOptions.signUp ?? true,
338
+ signUpName: authOptions.signUpName ?? true,
339
+ };
340
+ const form = useAppForm({
341
+ defaultValues: { name: "", email: "", password: "" },
342
+ onSubmit: async ({ value, formApi }) => {
343
+ formApi.setErrorMap({ onSubmit: undefined });
344
+ if (!options.signUp) {
345
+ formApi.setErrorMap({
346
+ onSubmit: { form: m.sign_up_disabled_description, fields: {} },
347
+ });
348
+ return;
349
+ }
350
+ try {
351
+ const result = await authClient.signUp.email({
352
+ name: options.signUpName
353
+ ? value.name.trim()
354
+ : nameFromEmail(value.email),
355
+ email: value.email.trim(),
356
+ password: value.password,
357
+ });
358
+ if (result.error) {
359
+ formApi.setErrorMap({
360
+ onSubmit: {
361
+ form: result.error.message ?? m.sign_up_error,
362
+ fields: {},
363
+ },
364
+ });
365
+ return;
366
+ }
367
+ onVerifyEmail(value.email.trim());
368
+ }
369
+ catch {
370
+ formApi.setErrorMap({
371
+ onSubmit: { form: m.sign_up_error, fields: {} },
372
+ });
373
+ }
374
+ },
375
+ });
376
+ const signUpWithGoogle = async () => {
377
+ try {
378
+ const result = await authClient.signIn.social({
379
+ provider: "google",
380
+ callbackURL: redirectTarget,
381
+ errorCallbackURL: "/sign-up",
382
+ });
383
+ if (result.error) {
384
+ form.setErrorMap({
385
+ onSubmit: {
386
+ form: result.error.message ?? m.sign_up_error,
387
+ fields: {},
388
+ },
389
+ });
390
+ return;
391
+ }
392
+ if (result.data?.url)
393
+ onNavigate(result.data.url);
394
+ }
395
+ catch {
396
+ form.setErrorMap({ onSubmit: { form: m.sign_up_error, fields: {} } });
397
+ }
398
+ };
399
+ if (!options.signUp) {
400
+ return (_jsxs(Card, { className: "w-full max-w-md", children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { className: "text-3xl", children: m.sign_up_disabled_title }), _jsx(CardDescription, { children: m.sign_up_disabled_description })] }), _jsx(CardContent, { children: _jsxs("p", { className: "text-muted-foreground text-center text-sm", children: [m.sign_up_have_account, " ", _jsx("a", { className: "text-foreground font-medium underline-offset-4 hover:underline", href: `/sign-in${searchString}`, children: m.auth_sign_in })] }) })] }));
401
+ }
402
+ return (_jsxs(Card, { className: "w-full max-w-md", children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { className: "text-3xl", children: m.sign_up_title }), _jsx(CardDescription, { children: m.sign_up_description })] }), _jsxs(CardContent, { children: [_jsx(form.AppForm, { children: _jsxs("form", { className: "flex flex-col gap-4", onSubmit: (event) => {
403
+ event.preventDefault();
404
+ event.stopPropagation();
405
+ form.handleSubmit();
406
+ }, children: [options.signUpName ? (_jsx(form.AppField, { name: "name", children: (field) => (_jsx(field.TextField, { label: m.field_name, autoComplete: "name", required: true })) })) : null, _jsx(form.AppField, { name: "email", children: (field) => (_jsx(field.TextField, { label: m.field_email, type: "email", autoComplete: "email", required: true })) }), _jsx(form.AppField, { name: "password", children: (field) => (_jsx(field.TextField, { label: m.field_password, type: "password", autoComplete: "new-password", minLength: 8, required: true })) }), _jsx(form.FormError, {}), _jsx(form.SubmitButton, {})] }) }), options.google ? (_jsxs("div", { className: "mt-4 flex flex-col gap-3", children: [_jsx(Divider, { label: m.auth_or_continue_with }), _jsxs(Button, { type: "button", variant: "outline", className: "w-full", onClick: signUpWithGoogle, children: [_jsx(GoogleLogo, {}), m.auth_continue_with_google] })] })) : null, _jsxs("p", { className: "text-muted-foreground mt-6 text-center text-sm", children: [m.sign_up_have_account, " ", _jsx("a", { className: "text-foreground font-medium underline-offset-4 hover:underline", href: `/sign-in${searchString}`, children: m.auth_sign_in })] })] })] }));
407
+ }
408
+ export function ResetPassword({ authClient }) {
409
+ const navigate = useNavigate();
410
+ const searchString = useRouterState({
411
+ select: (state) => state.location.searchStr,
412
+ });
413
+ const token = getSearchParam(searchString, "token") ?? "";
414
+ const onSuccess = () => navigate({ to: "/sign-in" });
415
+ const m = labels();
416
+ const form = useAppForm({
417
+ defaultValues: { password: "" },
418
+ onSubmit: async ({ value, formApi }) => {
419
+ formApi.setErrorMap({ onSubmit: undefined });
420
+ if (!token) {
421
+ formApi.setErrorMap({
422
+ onSubmit: { form: m.reset_password_missing_token, fields: {} },
423
+ });
424
+ return;
425
+ }
426
+ const result = await authClient.resetPassword({
427
+ newPassword: value.password,
428
+ token,
429
+ });
430
+ if (result.error) {
431
+ formApi.setErrorMap({
432
+ onSubmit: {
433
+ form: result.error.message ?? m.reset_password_error,
434
+ fields: {},
435
+ },
436
+ });
437
+ return;
438
+ }
439
+ onSuccess();
440
+ },
441
+ });
442
+ return (_jsxs(Card, { className: "w-full max-w-md", children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { className: "text-3xl", children: m.reset_password_title }), _jsx(CardDescription, { children: m.reset_password_description })] }), _jsx(CardContent, { children: _jsx(form.AppForm, { children: _jsxs("form", { className: "flex flex-col gap-4", onSubmit: (event) => {
443
+ event.preventDefault();
444
+ event.stopPropagation();
445
+ form.handleSubmit();
446
+ }, children: [_jsx(form.AppField, { name: "password", children: (field) => (_jsx(field.TextField, { label: m.reset_password_new_password, type: "password", autoComplete: "new-password", minLength: 8, required: true })) }), _jsx(form.FormError, {}), _jsx(form.SubmitButton, {})] }) }) })] }));
447
+ }
448
+ export function TwoFactor({ authClient }) {
449
+ const navigate = useNavigate();
450
+ const searchString = useRouterState({
451
+ select: (state) => state.location.searchStr,
452
+ });
453
+ const projectConfig = useAuthBrandingConfig();
454
+ const redirectTarget = getRedirectTarget(searchString, projectConfig?.authDomain, projectConfig?.rootDomain);
455
+ const oauthQuery = getOAuthQuery(searchString);
456
+ const onNavigate = (target) => navigateTarget(target, navigate);
457
+ const m = labels();
458
+ const [mode, setMode] = useState("totp");
459
+ const [emailCodeSent, setEmailCodeSent] = useState(false);
460
+ const form = useAppForm({
461
+ defaultValues: { code: "", trustDevice: true },
462
+ onSubmit: async ({ value, formApi }) => {
463
+ formApi.setErrorMap({ onSubmit: undefined });
464
+ const code = value.code.trim();
465
+ const result = mode === "backup"
466
+ ? await authClient.twoFactor.verifyBackupCode({
467
+ code,
468
+ trustDevice: value.trustDevice,
469
+ ...(oauthQuery ? { oauth_query: oauthQuery } : {}),
470
+ })
471
+ : mode === "email"
472
+ ? await authClient.twoFactor.verifyOtp({
473
+ code,
474
+ trustDevice: value.trustDevice,
475
+ ...(oauthQuery ? { oauth_query: oauthQuery } : {}),
476
+ })
477
+ : await authClient.twoFactor.verifyTotp({
478
+ code,
479
+ trustDevice: value.trustDevice,
480
+ ...(oauthQuery ? { oauth_query: oauthQuery } : {}),
481
+ });
482
+ if (result.error) {
483
+ formApi.setErrorMap({
484
+ onSubmit: {
485
+ form: result.error.message ?? m.two_factor_verify_error,
486
+ fields: {},
487
+ },
488
+ });
489
+ return;
490
+ }
491
+ onNavigate(getResultRedirectUrl(result.data) ?? redirectTarget);
492
+ },
493
+ });
494
+ const sendEmailCode = async () => {
495
+ form.setErrorMap({ onSubmit: undefined });
496
+ const result = await authClient.twoFactor.sendOtp();
497
+ if (result.error) {
498
+ form.setErrorMap({
499
+ onSubmit: {
500
+ form: result.error.message ?? m.two_factor_send_email_code_error,
501
+ fields: {},
502
+ },
503
+ });
504
+ return;
505
+ }
506
+ setEmailCodeSent(true);
507
+ setMode("email");
508
+ };
509
+ 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"
510
+ ? m.two_factor_verify_backup_description
511
+ : mode === "email"
512
+ ? m.two_factor_verify_email_description
513
+ : m.two_factor_verify_description })] }), _jsx(CardContent, { children: _jsx(form.AppForm, { children: _jsxs("form", { className: "flex flex-col gap-4", onSubmit: (event) => {
514
+ event.preventDefault();
515
+ event.stopPropagation();
516
+ form.handleSubmit();
517
+ }, children: [_jsx(form.AppField, { name: "code", children: (field) => mode === "backup" ? (_jsx(field.TextField, { label: m.two_factor_backup_code, autoComplete: "one-time-code", required: true })) : (_jsx(OtpInput, { field: field, label: mode === "email"
518
+ ? m.two_factor_email_code
519
+ : m.two_factor_code })) }), _jsx(form.AppField, { name: "trustDevice", children: (field) => (_jsx(field.CheckboxField, { label: m.two_factor_trust_device })) }), _jsx(form.FormError, {}), 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: [_jsx(form.SubmitButton, {}), _jsx(Button, { type: "button", variant: "ghost", onClick: sendEmailCode, children: m.two_factor_send_email_code }), _jsx(Button, { type: "button", variant: "ghost", onClick: () => setMode(mode === "backup" ? "totp" : "backup"), children: mode === "backup"
520
+ ? m.two_factor_use_totp
521
+ : m.two_factor_use_backup_code })] })] }) }) })] }));
522
+ }
523
+ const OtpInput = ({ field, label }) => {
524
+ const invalid = !field.state.meta.isValid;
525
+ return (_jsxs(Field, { "data-invalid": invalid, children: [_jsx(FieldLabel, { htmlFor: field.name, children: label }), _jsxs(InputOTP, { id: field.name, name: field.name, maxLength: 6, value: field.state.value ?? "", onChange: (value) => field.handleChange(value), onBlur: field.handleBlur, autoComplete: "one-time-code", inputMode: "numeric", pattern: REGEXP_ONLY_DIGITS, required: true, children: [_jsxs(InputOTPGroup, { children: [_jsx(InputOTPSlot, { index: 0, "aria-invalid": invalid }), _jsx(InputOTPSlot, { index: 1, "aria-invalid": invalid }), _jsx(InputOTPSlot, { index: 2, "aria-invalid": invalid })] }), _jsx(InputOTPSeparator, {}), _jsxs(InputOTPGroup, { children: [_jsx(InputOTPSlot, { index: 3, "aria-invalid": invalid }), _jsx(InputOTPSlot, { index: 4, "aria-invalid": invalid }), _jsx(InputOTPSlot, { index: 5, "aria-invalid": invalid })] })] }), _jsx(FieldError, { errors: field.getMeta().errors })] }));
526
+ };
527
+ const Divider = ({ label }) => (_jsxs("div", { className: "text-muted-foreground flex items-center gap-3 text-xs", children: [_jsx("span", { className: "bg-border h-px flex-1" }), label, _jsx("span", { className: "bg-border h-px flex-1" })] }));
528
+ const GoogleLogo = () => (_jsxs("svg", { "aria-hidden": "true", className: "size-[18px]", viewBox: "0 0 18 18", xmlns: "http://www.w3.org/2000/svg", children: [_jsx("path", { d: "M17.64 9.204c0-.638-.057-1.252-.164-1.84H9v3.481h4.844a4.14 4.14 0 0 1-1.796 2.716v2.259h2.908c1.702-1.567 2.684-3.874 2.684-6.616Z", fill: "#4285F4" }), _jsx("path", { d: "M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.583-5.036-3.711H.957v2.332A8.997 8.997 0 0 0 9 18Z", fill: "#34A853" }), _jsx("path", { d: "M3.964 10.71A5.41 5.41 0 0 1 3.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 0 0 0 9c0 1.452.348 2.827.957 4.042l3.007-2.332Z", fill: "#FBBC05" }), _jsx("path", { d: "M9 3.58c1.321 0 2.508.454 3.44 1.346l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 0 0 .957 4.958L3.964 7.29C4.672 5.162 6.656 3.58 9 3.58Z", fill: "#EA4335" })] }));
529
+ const hasTwoFactorRedirect = (data) => typeof data === "object" &&
530
+ data !== null &&
531
+ "twoFactorRedirect" in data &&
532
+ data.twoFactorRedirect === true;
533
+ const getResultRedirectUrl = (data) => {
534
+ if (typeof data !== "object" || data === null || !("url" in data))
535
+ return null;
536
+ const url = data.url;
537
+ return typeof url === "string" ? url : null;
538
+ };
539
+ const getRedirectTarget = (searchString, projectAuthDomain, projectRootDomain) => {
540
+ const oauthTarget = getOAuthAuthorizeTarget(searchString);
541
+ if (oauthTarget)
542
+ return oauthTarget;
543
+ return (getAuthRedirectParam(searchString) ??
544
+ getDefaultAuthRedirectTarget(projectAuthDomain, projectRootDomain));
545
+ };
546
+ const getSocialRedirectTarget = (searchString, projectAuthDomain, projectRootDomain) => {
547
+ const oauthTarget = getOAuthAuthorizeTargetWithoutPromptLogin(searchString);
548
+ if (oauthTarget)
549
+ return oauthTarget;
550
+ return getRedirectTarget(searchString, projectAuthDomain, projectRootDomain);
551
+ };
552
+ const getOAuthAuthorizeTarget = (searchString) => {
553
+ if (!searchString)
554
+ return null;
555
+ const search = new URLSearchParams(searchString);
556
+ if (!search.has("sig"))
557
+ return null;
558
+ return `/api/auth/oauth2/authorize${searchString}`;
559
+ };
560
+ const getOAuthAuthorizeTargetWithoutPromptLogin = (searchString) => {
561
+ if (!searchString)
562
+ return null;
563
+ const search = new URLSearchParams(searchString);
564
+ if (!search.has("sig"))
565
+ return null;
566
+ const prompts = search
567
+ .get("prompt")
568
+ ?.split(" ")
569
+ .filter((prompt) => prompt && prompt !== "login");
570
+ if (prompts?.length) {
571
+ search.set("prompt", prompts.join(" "));
572
+ }
573
+ else {
574
+ search.delete("prompt");
575
+ }
576
+ const nextSearchString = search.toString();
577
+ return `/api/auth/oauth2/authorize${nextSearchString ? `?${nextSearchString}` : ""}`;
578
+ };
579
+ const getOAuthQuery = (searchString) => {
580
+ if (!searchString)
581
+ return null;
582
+ const search = new URLSearchParams(searchString);
583
+ if (!search.has("sig"))
584
+ return null;
585
+ const signedSearch = new URLSearchParams();
586
+ for (const [key, value] of search.entries()) {
587
+ signedSearch.append(key, value);
588
+ if (key === "sig")
589
+ break;
590
+ }
591
+ return signedSearch.toString();
592
+ };
593
+ const getAuthRedirectParam = (searchString) => {
594
+ const search = new URLSearchParams(searchString);
595
+ return (search.get("callbackURL") ??
596
+ search.get("redirect") ??
597
+ search.get("redirectTo") ??
598
+ search.get("returnTo"));
599
+ };
600
+ const getDefaultAuthRedirectTarget = (projectAuthDomain, projectRootDomain) => {
601
+ if (typeof window === "undefined")
602
+ return "/admin";
603
+ const currentHost = normalizeAuthHost(window.location.host);
604
+ const isProjectDomain = normalizeAuthHost(projectAuthDomain) === currentHost;
605
+ if (!isProjectDomain)
606
+ return "/admin";
607
+ const rootDomain = normalizeAuthHost(projectRootDomain);
608
+ if (!rootDomain)
609
+ return "/admin";
610
+ return `${window.location.protocol}//${rootDomain}`;
611
+ };
612
+ const normalizeAuthHost = (value) => {
613
+ const raw = value?.trim().toLowerCase();
614
+ if (!raw)
615
+ return null;
616
+ try {
617
+ return new URL(raw.includes("://") ? raw : `https://${raw}`).host;
618
+ }
619
+ catch {
620
+ return raw.split("/")[0]?.trim() || null;
621
+ }
622
+ };
623
+ const getSearchParam = (searchString, key) => new URLSearchParams(searchString).get(key);
624
+ const navigateTarget = (target, navigate) => {
625
+ if (shouldUseDocumentRedirect(target)) {
626
+ navigate({ href: target });
627
+ }
628
+ else {
629
+ navigate({ to: target });
630
+ }
631
+ };
632
+ const shouldUseDocumentRedirect = (target) => {
633
+ if (target.startsWith("/api/"))
634
+ return true;
635
+ if (target.startsWith("/"))
636
+ return false;
637
+ if (target.startsWith(window.location.origin)) {
638
+ return target.slice(window.location.origin.length).startsWith("/api/");
639
+ }
640
+ return target.startsWith("http://") || target.startsWith("https://");
641
+ };
642
+ const nameFromEmail = (email) => {
643
+ const trimmed = email.trim();
644
+ const localPart = trimmed.split("@")[0]?.trim();
645
+ return localPart || trimmed;
646
+ };
@@ -0,0 +1 @@
1
+ export declare const useOpenedOnce: (open: boolean) => boolean;
@@ -0,0 +1,9 @@
1
+ import { useEffect, useState } from "react";
2
+ export const useOpenedOnce = (open) => {
3
+ const [opened, setOpened] = useState(open);
4
+ useEffect(() => {
5
+ if (open)
6
+ setOpened(true);
7
+ }, [open]);
8
+ return opened;
9
+ };