@krak-stack/auth 0.2.22 → 0.2.24

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.
@@ -4,7 +4,7 @@ import { Cause, Effect, Schema } from "effect";
4
4
  import { Atom, AsyncResult } from "effect/reactivity";
5
5
  import { Building2, Pencil, Trash2, UserCog } from "lucide-react";
6
6
  import { useEffect, useState } from "react";
7
- import { DataTable, DataTableListSummary, } from "@krak-stack/registry/data-table";
7
+ import { DataTable, } from "@krak-stack/registry/data-table";
8
8
  import { Query } from "@krak-stack/registry/query";
9
9
  import { ErrorMessage } from "@krak-stack/registry/effect-form";
10
10
  import { AppBrand } from "@krak-stack/registry/app-brand";
@@ -309,14 +309,19 @@ const organizationColumns = (m, locale, baseUrl, impersonate, impersonateAsOrgan
309
309
  {
310
310
  field: "projects",
311
311
  headerName: m.admin_column_projects,
312
- cellRenderer: ({ data }) => (_jsx(DataTableListSummary, { emptyLabel: "-", items: (data.projects ?? []).map((project) => {
312
+ type: "list",
313
+ typeOptions: {
314
+ emptyLabel: "-",
315
+ getItems: (data) => (data.projects ?? []).map((project) => {
313
316
  const logo = assetUrl(project.logo, baseUrl);
314
317
  return {
315
318
  label: project.name,
316
319
  value: project.id,
317
320
  icon: logo ? (_jsx("img", { alt: "", className: "size-full object-cover", src: logo })) : (initials(project.name)),
318
321
  };
319
- }), display: "icon" })),
322
+ }),
323
+ display: "icon",
324
+ },
320
325
  },
321
326
  {
322
327
  field: "createdAt",
@@ -4,7 +4,7 @@ import { Atom, AsyncResult } from "effect/reactivity";
4
4
  import { Effect, Schema } from "effect";
5
5
  import { Ban, Loader2, ShieldOff, UserCog, UserIcon } from "lucide-react";
6
6
  import { useEffect, useState } from "react";
7
- import { DataTable, DataTableListSummary, } from "@krak-stack/registry/data-table";
7
+ import { DataTable, } from "@krak-stack/registry/data-table";
8
8
  import { Query } from "@krak-stack/registry/query";
9
9
  import { ErrorMessage } from "@krak-stack/registry/effect-form";
10
10
  import { AppBrand } from "@krak-stack/registry/app-brand";
@@ -242,26 +242,36 @@ const userColumns = (m, baseUrl) => [
242
242
  {
243
243
  field: "organizations",
244
244
  headerName: m.admin_column_organizations,
245
- cellRenderer: ({ data }) => (_jsx(DataTableListSummary, { emptyLabel: "-", items: data.organizations.map((organization) => {
245
+ type: "list",
246
+ typeOptions: {
247
+ emptyLabel: "-",
248
+ getItems: (data) => data.organizations.map((organization) => {
246
249
  const logo = assetUrl(organization.logo, baseUrl);
247
250
  return {
248
251
  label: organization.name,
249
252
  value: organization.id,
250
253
  icon: logo ? (_jsx("img", { alt: "", className: "size-full object-cover", src: logo })) : (initials(organization.name)),
251
254
  };
252
- }), display: "icon" })),
255
+ }),
256
+ display: "icon",
257
+ },
253
258
  },
254
259
  {
255
260
  field: "projects",
256
261
  headerName: m.admin_column_projects,
257
- cellRenderer: ({ data }) => (_jsx(DataTableListSummary, { emptyLabel: "-", items: data.projects.map((project) => {
262
+ type: "list",
263
+ typeOptions: {
264
+ emptyLabel: "-",
265
+ getItems: (data) => data.projects.map((project) => {
258
266
  const logo = assetUrl(project.logo, baseUrl);
259
267
  return {
260
268
  label: project.name,
261
269
  value: project.id,
262
270
  icon: logo ? (_jsx("img", { alt: "", className: "size-full object-cover", src: logo })) : (initials(project.name)),
263
271
  };
264
- }), display: "icon" })),
272
+ }),
273
+ display: "icon",
274
+ },
265
275
  },
266
276
  {
267
277
  field: "emailVerified",
@@ -6,7 +6,7 @@ import { Effect, Option, Schema } from "effect";
6
6
  import { Atom, AsyncResult } from "effect/reactivity";
7
7
  import { HttpClientError } from "effect/http";
8
8
  import { REGEXP_ONLY_DIGITS } from "input-otp";
9
- import { KeyRound, Loader2, Mail } from "lucide-react";
9
+ import { ArrowLeft, KeyRound, Loader2, Mail } from "lucide-react";
10
10
  import { useEffect, useRef, useState } from "react";
11
11
  import { Button, buttonVariants } from "@/components/ui/button";
12
12
  import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card";
@@ -15,11 +15,14 @@ import { Field, FieldLabel } from "@/components/ui/field";
15
15
  import { InputOTP, InputOTPGroup, InputOTPSeparator, InputOTPSlot, } from "@/components/ui/input-otp";
16
16
  import { getLastUsedLoginMethod, notifyAuthChange } from "./auth-atoms.js";
17
17
  import { authClientApi, authHttpClient } from "./auth-client-api.js";
18
+ import { PasswordField } from "./password-field.js";
19
+ import { emailOtpSendsAtom, emailOtpSendState, EMAIL_OTP_RESEND_COOLDOWN_SECONDS, } from "./email-otp-state.js";
20
+ import { passwordResetSearch, passwordResetConfirmation, passwordResetConfirmationSearch, passwordResetCallbackUrl, requestPasswordResetEmail, resetPasswordAndSignOut, } from "./password-reset.js";
21
+ import { PasswordResetActions, PasswordResetFeedback, usePasswordResetRequest, } from "./password-reset-flow.js";
18
22
  import { useKrakstackAuth } from "./auth-provider.js";
19
23
  import { cn } from "./utils.js";
20
24
  import { ExtraProjectPublicConfig as ExtraProjectPublicConfigSchema, } from "../extra/schema.js";
21
25
  import { AuthBadRequest, AuthInternalServerError, AuthTooManyRequests, AuthUnauthorized, AuthRedirectURLFromString, } from "../auth/schema.js";
22
- const EMAIL_OTP_RESEND_COOLDOWN_SECONDS = 60;
23
26
  const signinFormBuilder = FormBuilder.empty
24
27
  .addField("email", Schema.String)
25
28
  .addField("password", Schema.String)
@@ -35,16 +38,22 @@ const twoFactorFormBuilder = FormBuilder.empty
35
38
  const defaultMessages = {
36
39
  en: {
37
40
  auth_continue_with_google: "Continue with Google",
38
- auth_or_continue_with: "or continue with",
41
+ auth_or_continue_with: "Or",
39
42
  auth_sign_in: "Sign in",
40
43
  field_email: "Email",
41
44
  field_password: "Password",
42
45
  forgot_password_back_to_sign_in: "Back to sign in",
46
+ forgot_password_change_email: "Change email",
43
47
  forgot_password_description: "Enter your email and we will send a reset link if an account exists.",
44
48
  forgot_password_error: "Unable to send password reset email.",
45
49
  forgot_password_submit: "Send reset link",
46
50
  forgot_password_success: "If an account exists for that email, a reset link has been sent.",
47
51
  forgot_password_title: "Reset password",
52
+ user_password_reset_title: "Check your email",
53
+ user_password_reset_sending: "Sending reset email…",
54
+ user_password_reset_resend: "Resend email",
55
+ user_password_reset_countdown: "Resend in {seconds}s",
56
+ forgot_password_success_email: "If an account exists for {email}, we’ve sent a password-reset link.",
48
57
  error_network: "We couldn't reach the server. Check your connection and try again.",
49
58
  error_rate_limited: "Too many attempts. Please wait a moment before trying again.",
50
59
  error_service_unavailable: "The authentication service is temporarily unavailable. Please try again.",
@@ -54,7 +63,7 @@ const defaultMessages = {
54
63
  reset_password_missing_token: "The password reset link is missing a token.",
55
64
  reset_password_new_password: "New password",
56
65
  reset_password_title: "Choose a new password",
57
- sign_in_change_email: "Change",
66
+ sign_in_change_email: "Back",
58
67
  sign_in_continue: "Continue",
59
68
  sign_in_description: "Enter your email to continue.",
60
69
  sign_in_email_as: "Signing in as {email}",
@@ -69,8 +78,8 @@ const defaultMessages = {
69
78
  sign_in_invalid_credentials: "The email or password is incorrect.",
70
79
  auth_invalid_code: "The code is invalid or has expired.",
71
80
  sign_in_forgot_password: "Forgot your password?",
72
- sign_in_use_email_otp: "Use email code instead",
73
- sign_in_use_password: "Use an existing password",
81
+ sign_in_use_email_otp: "Use email code",
82
+ sign_in_use_password: "Use password",
74
83
  two_factor_backup_code: "Backup code",
75
84
  two_factor_code: "Authentication code",
76
85
  two_factor_email_code: "Email verification code",
@@ -95,16 +104,22 @@ const defaultMessages = {
95
104
  },
96
105
  fr: {
97
106
  auth_continue_with_google: "Continuer avec Google",
98
- auth_or_continue_with: "ou continuez avec",
107
+ auth_or_continue_with: "Ou",
99
108
  auth_sign_in: "Se connecter",
100
109
  field_email: "Courriel",
101
110
  field_password: "Mot de passe",
102
111
  forgot_password_back_to_sign_in: "Retour à la connexion",
112
+ forgot_password_change_email: "Modifier le courriel",
103
113
  forgot_password_description: "Saisissez votre courriel et nous enverrons un lien de réinitialisation si un compte existe.",
104
114
  forgot_password_error: "Impossible d'envoyer le courriel de réinitialisation.",
105
115
  forgot_password_submit: "Envoyer le lien",
106
116
  forgot_password_success: "Si un compte existe pour ce courriel, un lien de réinitialisation a été envoyé.",
107
117
  forgot_password_title: "Réinitialiser le mot de passe",
118
+ user_password_reset_title: "Consultez votre courriel",
119
+ user_password_reset_sending: "Envoi du courriel de réinitialisation…",
120
+ user_password_reset_resend: "Renvoyer le courriel",
121
+ user_password_reset_countdown: "Renvoyer dans {seconds} s",
122
+ forgot_password_success_email: "Si un compte existe pour {email}, nous avons envoyé un lien de réinitialisation.",
108
123
  error_network: "Impossible de joindre le serveur. Vérifiez votre connexion et réessayez.",
109
124
  error_rate_limited: "Trop de tentatives. Veuillez patienter un moment avant de réessayer.",
110
125
  error_service_unavailable: "Le service d'authentification est temporairement indisponible. Veuillez réessayer.",
@@ -114,7 +129,7 @@ const defaultMessages = {
114
129
  reset_password_missing_token: "Le lien de réinitialisation du mot de passe ne contient pas de jeton.",
115
130
  reset_password_new_password: "Nouveau mot de passe",
116
131
  reset_password_title: "Choisir un nouveau mot de passe",
117
- sign_in_change_email: "Modifier",
132
+ sign_in_change_email: "Retour",
118
133
  sign_in_continue: "Continuer",
119
134
  sign_in_description: "Saisissez votre courriel pour continuer.",
120
135
  sign_in_email_as: "Connexion avec {email}",
@@ -130,7 +145,7 @@ const defaultMessages = {
130
145
  auth_invalid_code: "Le code est invalide ou a expiré.",
131
146
  sign_in_forgot_password: "Mot de passe oublié?",
132
147
  sign_in_use_email_otp: "Utiliser un code courriel",
133
- sign_in_use_password: "Utiliser un mot de passe existant",
148
+ sign_in_use_password: "Utiliser un mot de passe",
134
149
  two_factor_backup_code: "Code de secours",
135
150
  two_factor_code: "Code d'authentification",
136
151
  two_factor_email_code: "Code de vérification par courriel",
@@ -234,7 +249,6 @@ const useAuthProjectConfig = (baseUrl, searchString, projectConfig) => {
234
249
  };
235
250
  const text = (value, params) => Object.entries(params ?? {}).reduce((current, [key, replacement]) => current.replace(`{${key}}`, replacement), value);
236
251
  const authLinkClassName = cn(buttonVariants({ variant: "link", size: null }), "h-auto align-baseline");
237
- const searchObject = (searchString) => Object.fromEntries(new URLSearchParams(searchString));
238
252
  const authMethodSearch = (searchString, method, email) => {
239
253
  const search = new URLSearchParams(searchString);
240
254
  search.set("method", method);
@@ -287,6 +301,10 @@ export function Signin(props) {
287
301
  const [otpSentTo, setOtpSentTo] = useState(initialMethodStep && initialAuthMethod === "emailOtp" ? initialEmail : "");
288
302
  const [emailOtpResendAvailableAt, setEmailOtpResendAvailableAt] = useState(0);
289
303
  const [emailOtpResendSeconds, setEmailOtpResendSeconds] = useState(0);
304
+ const otpSends = useAtomValue(emailOtpSendsAtom(baseUrl ?? ""));
305
+ const persistOtpSends = useAtomSet(emailOtpSendsAtom(baseUrl ?? ""));
306
+ const otpSendsRef = useRef(otpSends);
307
+ otpSendsRef.current = otpSends;
290
308
  const [errorContext, setErrorContext] = useState("signIn");
291
309
  const selectedAuthMethod = authMethod === "password" && options.emailPassword
292
310
  ? "password"
@@ -312,13 +330,40 @@ export function Signin(props) {
312
330
  }, [emailOtpResendAvailableAt]);
313
331
  const [form] = useState(() => FormReact.make(signinFormBuilder, {
314
332
  runtime: authClientApi(baseUrl).runtime,
315
- fields: { email: TextField, password: TextField, otp: OtpField },
333
+ fields: { email: TextField, password: PasswordField, otp: OtpField },
316
334
  mode: { validation: "onSubmit" },
317
335
  onSubmit: (action, { decoded: value }) => Effect.gen(function* () {
318
336
  const email = value.email.trim();
319
- const sendEmailOtp = authHttpClient(baseUrl, locale).pipe(Effect.flatMap((client) => client.auth.sendVerificationOtp({
320
- payload: { email, type: "sign-in" },
321
- })), Effect.tap(() => Effect.sync(() => {
337
+ if (action.type === "resetPassword") {
338
+ yield* requestPasswordResetEmail({
339
+ baseUrl,
340
+ locale,
341
+ email,
342
+ redirectTo: passwordResetCallbackUrl(searchString, window.location.origin, email),
343
+ });
344
+ yield* Effect.promise(() => navigate({
345
+ to: "/reset-password",
346
+ search: passwordResetConfirmationSearch(searchString, email, Date.now()),
347
+ }));
348
+ return;
349
+ }
350
+ const previousSend = otpSendsRef.current[email];
351
+ const previousSendState = emailOtpSendState(previousSend, Date.now());
352
+ const reuseCode = previousSendState.reusable &&
353
+ (action.type !== "resendEmailOtp" ||
354
+ previousSendState.resendSeconds > 0);
355
+ const sendEmailOtp = (reuseCode
356
+ ? Effect.void
357
+ : authHttpClient(baseUrl, locale).pipe(Effect.flatMap((client) => client.auth.sendVerificationOtp({
358
+ payload: { email, type: "sign-in" },
359
+ })), Effect.asVoid, Effect.tap(() => Effect.sync(() => {
360
+ const sends = {
361
+ ...otpSendsRef.current,
362
+ [email]: Date.now(),
363
+ };
364
+ otpSendsRef.current = sends;
365
+ persistOtpSends(sends);
366
+ })))).pipe(Effect.tap(() => Effect.sync(() => {
322
367
  setAuthMethod("emailOtp");
323
368
  setEmailSubmitted(true);
324
369
  setOtpSentTo(email);
@@ -327,9 +372,11 @@ export function Signin(props) {
327
372
  search: authMethodSearch(searchString, "emailOtp", email),
328
373
  replace: true,
329
374
  });
330
- setEmailOtpResendAvailableAt(Date.now() + EMAIL_OTP_RESEND_COOLDOWN_SECONDS * 1000);
375
+ setEmailOtpResendAvailableAt((otpSendsRef.current[email] ?? 0) +
376
+ EMAIL_OTP_RESEND_COOLDOWN_SECONDS * 1000);
331
377
  })));
332
- if (action.type === "sendEmailOtp") {
378
+ if (action.type === "sendEmailOtp" ||
379
+ action.type === "resendEmailOtp") {
333
380
  yield* sendEmailOtp;
334
381
  return;
335
382
  }
@@ -411,6 +458,10 @@ export function Signin(props) {
411
458
  password: "",
412
459
  otp: "",
413
460
  }));
461
+ const lastOtpSentAt = otpSends[formValues.email.trim()];
462
+ useEffect(() => {
463
+ setEmailOtpResendAvailableAt((lastOtpSentAt ?? 0) + EMAIL_OTP_RESEND_COOLDOWN_SECONDS * 1000);
464
+ }, [lastOtpSentAt]);
414
465
  const resetForm = useAtomSet(form.reset);
415
466
  const setEmail = useAtomSet(form.getFieldAtoms(form.fields.email).setValue);
416
467
  const setPassword = useAtomSet(form.getFieldAtoms(form.fields.password).setValue);
@@ -435,8 +486,6 @@ export function Signin(props) {
435
486
  resetForm();
436
487
  setEmail(formValues.email);
437
488
  setAuthMethod("password");
438
- setOtpSentTo("");
439
- setEmailOtpResendAvailableAt(0);
440
489
  navigate({
441
490
  to: "/sign-in",
442
491
  search: authMethodSearch(searchString, "password", formValues.email),
@@ -450,10 +499,12 @@ export function Signin(props) {
450
499
  const resendEmailOtp = () => {
451
500
  setOtp("");
452
501
  setErrorContext("sendEmailOtp");
453
- submit({ type: "sendEmailOtp" });
502
+ submit({ type: "resendEmailOtp" });
454
503
  };
455
504
  const signInWithGoogle = () => startSocialSignIn(getSocialSignInDestinations(router, props.defaultRedirectTo, window.location.href));
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) => {
505
+ return (_jsxs(Card, { className: "w-full max-w-md", children: [_jsxs(CardHeader, { children: [emailSubmitted ? (_jsxs(Button, { type: "button", variant: "link", className: "w-fit justify-self-start p-0", disabled: submitResult.waiting, onClick: resetEmailStep, children: [_jsx(ArrowLeft, {}), m.sign_in_change_email] })) : null, _jsx(CardTitle, { className: "text-3xl", children: m.auth_sign_in }), _jsx(CardDescription, { children: !emailSubmitted
506
+ ? m.sign_in_description
507
+ : text(m.sign_in_email_as, { email: formValues.email }) })] }), _jsxs(CardContent, { children: [hasPrimaryAuth ? (_jsx(form.Initialize, { defaultValues: { email: initialEmail, password: "", otp: "" }, children: _jsxs("form", { className: "flex flex-col gap-4", onSubmit: (event) => {
457
508
  event.preventDefault();
458
509
  event.stopPropagation();
459
510
  setErrorContext(!emailSubmitted ||
@@ -473,29 +524,45 @@ export function Signin(props) {
473
524
  return;
474
525
  event.preventDefault();
475
526
  event.currentTarget.form?.requestSubmit();
476
- }, required: true })) : null, emailSubmitted && selectedAuthMethod === "password" ? (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(form.password, { label: m.field_password, type: "password", autoFocus: true, autoComplete: "current-password", required: true }), _jsxs("div", { className: "flex flex-wrap gap-x-4 gap-y-2 text-sm", children: [_jsx(Link, { className: authLinkClassName, to: "/reset-password", search: authMethodSearch(searchString, "password", formValues.email.trim()), 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.otp, { label: m.sign_in_email_otp_code }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.sign_in_otp_expiry }), _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
477
- ? text(m.sign_in_email_otp_resend_countdown, {
478
- seconds: String(emailOtpResendSeconds),
479
- })
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
527
+ }, required: true })) : null, emailSubmitted && selectedAuthMethod === "password" ? (_jsx("div", { className: "flex flex-col gap-2", children: _jsx(form.password, { label: m.field_password, autoFocus: true, autoComplete: "current-password", recovery: {
528
+ label: m.sign_in_forgot_password,
529
+ disabled: submitResult.waiting,
530
+ onClick: () => {
531
+ setErrorContext("resetPassword");
532
+ submit({ type: "resetPassword" });
533
+ },
534
+ }, required: true }) })) : null, emailSubmitted && selectedAuthMethod === "emailOtp" ? (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(form.otp, { label: m.sign_in_email_otp_code }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.sign_in_otp_expiry }), _jsx("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
535
+ ? text(m.sign_in_email_otp_resend_countdown, {
536
+ seconds: String(emailOtpResendSeconds),
537
+ })
538
+ : m.sign_in_email_otp_resend })) : null })] })) : null, _jsx(AuthSubmitError, { result: submitResult, labels: m, messages: {
539
+ fallback: errorContext === "resetPassword"
540
+ ? m.forgot_password_error
541
+ : errorContext === "sendEmailOtp"
542
+ ? m.sign_in_email_otp_send_error
543
+ : errorContext === "verifyEmailOtp"
544
+ ? m.sign_in_email_otp_error
545
+ : m.sign_in_error,
546
+ badRequest: errorContext === "resetPassword"
547
+ ? m.forgot_password_error
483
548
  : errorContext === "verifyEmailOtp"
484
- ? m.sign_in_email_otp_error
485
- : m.sign_in_error,
486
- badRequest: errorContext === "verifyEmailOtp"
487
- ? m.auth_invalid_code
549
+ ? m.auth_invalid_code
550
+ : errorContext === "signIn"
551
+ ? m.sign_in_invalid_credentials
552
+ : m.sign_in_email_otp_send_error,
553
+ unauthorized: errorContext === "resetPassword"
554
+ ? m.forgot_password_error
488
555
  : errorContext === "signIn"
489
556
  ? 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,
557
+ : m.sign_in_error,
494
558
  } }), _jsx("div", { children: _jsxs(Button, { type: "submit", disabled: submitResult.waiting, children: [submitResult.waiting ? (_jsx(Loader2, { className: "animate-spin", "data-icon": "inline-start" })) : null, !emailSubmitted
495
559
  ? m.sign_in_continue
496
560
  : selectedAuthMethod === "emailOtp"
497
561
  ? m.sign_in_email_otp_verify
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] })] }));
562
+ : m.auth_sign_in] }) })] }) })) : null, (emailSubmitted && canChangeAuthMethod) ||
563
+ (options.google && !emailSubmitted) ? (_jsxs("div", { className: "mt-4 flex flex-col gap-3", children: [hasPrimaryAuth ? (_jsx(Divider, { label: m.auth_or_continue_with })) : null, emailSubmitted && canChangeAuthMethod ? (_jsxs(Button, { type: "button", variant: "outline", className: "w-full", disabled: submitResult.waiting, onClick: switchAuthMethod, children: [selectedAuthMethod === "password" ? _jsx(Mail, {}) : _jsx(KeyRound, {}), selectedAuthMethod === "password"
564
+ ? m.sign_in_use_email_otp
565
+ : m.sign_in_use_password] })) : null, options.google && !emailSubmitted ? (_jsxs(_Fragment, { children: [_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] })) : null, !hasPrimaryAuth && !options.google ? (_jsx("p", { className: "text-muted-foreground text-sm", children: m.oauth_client_no_auth_methods })) : null] })] }));
499
566
  }
500
567
  export function VerifyEmail(props) {
501
568
  const { baseUrl, locale, labels: m } = useAuthFormOptions(props);
@@ -557,33 +624,45 @@ export function VerifyEmail(props) {
557
624
  }
558
625
  export function ForgotPassword(props) {
559
626
  const { baseUrl, locale, labels: m } = useAuthFormOptions(props);
627
+ const navigate = useNavigate();
560
628
  const searchString = useRouterState({
561
629
  select: (state) => state.location.searchStr,
562
630
  });
563
631
  const initialEmail = getSearchParam(searchString, "email")?.trim() ?? "";
564
- const [submitted, setSubmitted] = useState(false);
632
+ const confirmation = passwordResetConfirmation(searchString);
633
+ const passwordReset = usePasswordResetRequest(baseUrl, confirmation?.resetSentAt);
634
+ const resetEmailInput = (email) => ({
635
+ locale,
636
+ email,
637
+ redirectTo: passwordResetCallbackUrl(searchString, window.location.origin, email),
638
+ onSent: (sentAt) => navigate({
639
+ to: "/reset-password",
640
+ search: passwordResetConfirmationSearch(searchString, email, sentAt),
641
+ replace: true,
642
+ }),
643
+ });
644
+ const requestResetEmail = (email) => passwordReset.request(resetEmailInput(email));
565
645
  const [form] = useState(() => FormReact.make(forgotPasswordFormBuilder, {
566
646
  runtime: authClientApi(baseUrl).runtime,
567
647
  fields: { email: TextField },
568
648
  mode: { validation: "onSubmit" },
569
- onSubmit: (_, { decoded: value }) => Effect.gen(function* () {
570
- setSubmitted(false);
571
- yield* authHttpClient(baseUrl, locale).pipe(Effect.flatMap((client) => client.auth.requestPasswordReset({
572
- payload: {
573
- email: value.email.trim(),
574
- redirectTo: `${window.location.origin}/reset-password`,
575
- },
576
- })));
577
- setSubmitted(true);
578
- }),
649
+ onSubmit: (action, { decoded: value }) => action.requestEmail(value.email.trim()),
579
650
  }));
580
651
  const submit = useAtomSet(form.submit);
581
652
  const submitResult = useAtomValue(form.submit);
582
- return (_jsxs(Card, { className: "w-full max-w-md", children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { className: "text-3xl", children: m.forgot_password_title }), _jsx(CardDescription, { children: m.forgot_password_description })] }), _jsxs(CardContent, { children: [_jsx(form.Initialize, { defaultValues: { email: initialEmail }, children: _jsxs("form", { className: "flex flex-col gap-4", onSubmit: (event) => {
583
- event.preventDefault();
584
- event.stopPropagation();
585
- submit();
586
- }, 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 }) })] })] }));
653
+ const feedback = (_jsx(PasswordResetFeedback, { pending: passwordReset.result.waiting, sendingLabel: m.user_password_reset_sending, error: _jsx(AuthSubmitError, { result: passwordReset.result, labels: m, messages: { fallback: m.forgot_password_error } }) }));
654
+ if (confirmation) {
655
+ return (_jsxs(Card, { className: "w-full max-w-md", children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { className: "text-3xl", children: m.user_password_reset_title }), _jsx(CardDescription, { children: text(m.forgot_password_success_email, {
656
+ email: confirmation.email,
657
+ }) })] }), _jsx(CardContent, { children: _jsxs("div", { className: "flex flex-col gap-4", children: [feedback, _jsx(PasswordResetActions, { pending: passwordReset.result.waiting, resendSeconds: passwordReset.resendSeconds, onResend: () => passwordReset.send(resetEmailInput(confirmation.email)), resendLabel: m.user_password_reset_resend, countdownLabel: (seconds) => text(m.user_password_reset_countdown, {
658
+ seconds: String(seconds),
659
+ }) })] }) })] }));
660
+ }
661
+ return (_jsxs(Card, { className: "w-full max-w-md", children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { className: "text-3xl", children: m.forgot_password_title }), _jsx(CardDescription, { children: m.forgot_password_description })] }), _jsx(CardContent, { children: _jsx(form.Initialize, { defaultValues: { email: initialEmail }, children: _jsxs("form", { className: "flex flex-col gap-4", onSubmit: (event) => {
662
+ event.preventDefault();
663
+ event.stopPropagation();
664
+ submit({ requestEmail: requestResetEmail });
665
+ }, children: [_jsx(form.email, { label: m.field_email, type: "email", autoComplete: "email", required: true }), feedback, _jsxs(Button, { type: "submit", className: "self-start", disabled: submitResult.waiting || passwordReset.result.waiting, children: [submitResult.waiting || passwordReset.result.waiting ? (_jsx(Loader2, { className: "animate-spin", "data-icon": "inline-start" })) : null, m.forgot_password_submit] })] }) }, initialEmail) })] }));
587
666
  }
588
667
  export function ResetPassword(props) {
589
668
  const searchString = useRouterState({
@@ -595,18 +674,22 @@ export function ResetPassword(props) {
595
674
  function ResetPasswordForm({ token, ...props }) {
596
675
  const { baseUrl, locale, labels: m } = useAuthFormOptions(props);
597
676
  const navigate = useNavigate();
598
- const onSuccess = () => navigate({ to: "/sign-in" });
677
+ const searchString = useRouterState({
678
+ select: (state) => state.location.searchStr,
679
+ });
680
+ const onSuccess = () => navigate({ to: "/sign-in", search: passwordResetSearch(searchString) });
599
681
  const [form] = useState(() => FormReact.make(resetPasswordFormBuilder, {
600
682
  runtime: authClientApi(baseUrl).runtime,
601
- fields: { password: TextField },
683
+ fields: { password: PasswordField },
602
684
  mode: { validation: "onSubmit" },
603
685
  onSubmit: (_, { decoded: value }) => Effect.gen(function* () {
604
- yield* authHttpClient(baseUrl, locale).pipe(Effect.flatMap((client) => client.auth.resetPassword({
605
- payload: {
606
- newPassword: value.password,
607
- token,
608
- },
609
- })));
686
+ yield* resetPasswordAndSignOut({
687
+ baseUrl,
688
+ locale,
689
+ newPassword: value.password,
690
+ token,
691
+ });
692
+ notifyAuthChange();
610
693
  onSuccess();
611
694
  }),
612
695
  }));
@@ -616,7 +699,7 @@ function ResetPasswordForm({ token, ...props }) {
616
699
  event.preventDefault();
617
700
  event.stopPropagation();
618
701
  submit();
619
- }, 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] })] }) }) })] }));
702
+ }, children: [_jsx(form.password, { label: m.reset_password_new_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] })] }) }) })] }));
620
703
  }
621
704
  export function TwoFactor(props) {
622
705
  const { baseUrl, locale, labels: m } = useAuthFormOptions(props);
@@ -0,0 +1,11 @@
1
+ import { Atom } from "effect/reactivity";
2
+ export declare const EMAIL_OTP_RESEND_COOLDOWN_SECONDS = 60;
3
+ export declare const emailOtpSendsAtom: (arg: string) => Atom.Writable<{
4
+ readonly [x: string]: number;
5
+ }, {
6
+ readonly [x: string]: number;
7
+ }>;
8
+ export declare const emailOtpSendState: (sentAt: number | undefined, now: number) => {
9
+ reusable: boolean;
10
+ resendSeconds: number;
11
+ };
@@ -0,0 +1,25 @@
1
+ import { Schema } from "effect";
2
+ import { KeyValueStore } from "effect/persistence";
3
+ import { Atom } from "effect/reactivity";
4
+ export const EMAIL_OTP_RESEND_COOLDOWN_SECONDS = 60;
5
+ const EMAIL_OTP_LIFETIME_MS = 5 * 60 * 1000;
6
+ const EmailOtpSends = Schema.Record(Schema.String, Schema.Number).annotate({
7
+ identifier: "EmailOtpSends",
8
+ });
9
+ const storageRuntime = Atom.runtime(globalThis.window === undefined
10
+ ? KeyValueStore.layerMemory
11
+ : KeyValueStore.layerStorage(() => window.localStorage));
12
+ export const emailOtpSendsAtom = Atom.family((baseUrl) => Atom.kvs({
13
+ runtime: storageRuntime,
14
+ key: `krakstack-auth:email-otp-sends:v1:${baseUrl}`,
15
+ schema: EmailOtpSends,
16
+ defaultValue: () => ({}),
17
+ }));
18
+ export const emailOtpSendState = (sentAt, now) => ({
19
+ reusable: sentAt !== undefined &&
20
+ now >= sentAt &&
21
+ now - sentAt < EMAIL_OTP_LIFETIME_MS,
22
+ resendSeconds: sentAt === undefined
23
+ ? 0
24
+ : Math.max(0, Math.ceil((sentAt + EMAIL_OTP_RESEND_COOLDOWN_SECONDS * 1000 - now) / 1000)),
25
+ });
@@ -6,6 +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 { PasswordField, type PasswordFieldOptions } from "./password-field.js";
9
10
  export { AdminOrganizationsTable, adminOrganizationsMessages, } from "./admin-organizations.js";
10
11
  export { AdminOrganizationForm } from "./admin-organization-form.js";
11
12
  export { AdminUsersTable, useAdminUsersTotal } from "./admin-users.js";
@@ -6,6 +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 { PasswordField } from "./password-field.js";
9
10
  export { AdminOrganizationsTable, adminOrganizationsMessages, } from "./admin-organizations.js";
10
11
  export { AdminOrganizationForm } from "./admin-organization-form.js";
11
12
  export { AdminUsersTable, useAdminUsersTotal } from "./admin-users.js";
@@ -5,7 +5,7 @@ import { Effect, Option, Predicate, Schema } from "effect";
5
5
  import { AsyncResult, Atom } from "effect/reactivity";
6
6
  import { ArrowLeft, Building2, Check, ChevronsUpDown, Copy, KeyRound, LogOut, Mail, PencilIcon, Plus, Trash2, UserIcon, UserPlus, Users, X, } from "lucide-react";
7
7
  import { createContext, useContext, useEffect, useRef, useState, } from "react";
8
- import { DataTable, DataTableListSummary, DataTableListCell, } from "@krak-stack/registry/data-table";
8
+ import { DataTable, DataTableListCell, } from "@krak-stack/registry/data-table";
9
9
  import { CheckboxField, ImageField, SelectField, SubmitButton, SubmitError, TextAreaField, TextField, } from "@krak-stack/registry/effect-form";
10
10
  import { EditingLocaleSwitcher } from "@krak-stack/registry/editing-locale-switcher";
11
11
  import { AppBrand } from "@krak-stack/registry/app-brand";
@@ -1665,9 +1665,11 @@ const apiKeyColumns = ({ m, }) => [
1665
1665
  colId: "permissions",
1666
1666
  valueGetter: ({ data }) => data.permissions,
1667
1667
  headerName: m.user_api_key_permissions(),
1668
- cellRenderer: ({ data }) => {
1669
- const values = organizationApiKeyFormattedPermissions(data.permissions);
1670
- return (_jsx(DataTableListSummary, { emptyLabel: m.user_api_key_no_permissions(), items: values, visibleCount: 1 }));
1668
+ type: "list",
1669
+ typeOptions: {
1670
+ getItems: (data) => organizationApiKeyFormattedPermissions(data.permissions).map((label) => ({ label })),
1671
+ emptyLabel: m.user_api_key_no_permissions(),
1672
+ visibleCount: 1,
1671
1673
  },
1672
1674
  },
1673
1675
  {
@@ -0,0 +1,15 @@
1
+ import { FormReact } from "@lucas-barake/effect-form-react";
2
+ import { TextField } from "@krak-stack/registry/effect-form";
3
+ import type { ComponentProps } from "react";
4
+ export type PasswordFieldOptions = Omit<ComponentProps<typeof TextField>["props"], "type" | "autoComplete"> & ({
5
+ autoComplete: "current-password";
6
+ recovery?: {
7
+ label: string;
8
+ onClick: () => void;
9
+ disabled?: boolean;
10
+ };
11
+ } | {
12
+ autoComplete: "new-password";
13
+ recovery?: never;
14
+ });
15
+ export declare const PasswordField: FormReact.FieldComponent<string, PasswordFieldOptions>;
@@ -0,0 +1,12 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { FormReact } from "@lucas-barake/effect-form-react";
3
+ import { TextField } from "@krak-stack/registry/effect-form";
4
+ import { Button } from "@/components/ui/button";
5
+ export const PasswordField = ({ field, props }) => {
6
+ const { recovery, children, ...inputProps } = props;
7
+ return (_jsx(TextField, { field: field, props: {
8
+ ...inputProps,
9
+ type: "password",
10
+ children: (_jsxs(_Fragment, { children: [children, recovery ? (_jsx(Button, { type: "button", variant: "link", className: "ms-auto h-auto p-0 text-xs", onClick: recovery.onClick, disabled: recovery.disabled, children: recovery.label })) : null] })),
11
+ } }));
12
+ };
@@ -0,0 +1,25 @@
1
+ import { Effect } from "effect";
2
+ import { type ReactNode } from "react";
3
+ import { requestPasswordResetEmail } from "./password-reset.js";
4
+ type PasswordResetRequest = Omit<Parameters<typeof requestPasswordResetEmail>[0], "baseUrl"> & {
5
+ onSent?: (sentAt: number) => void | Promise<void>;
6
+ };
7
+ export declare const usePasswordResetRequest: (baseUrl?: string, initialSentAt?: number | null) => {
8
+ send: (value: typeof import("effect/reactivity/Atom").Reset | typeof import("effect/reactivity/Atom").Interrupt | ((value: import("effect/reactivity/AsyncResult").AsyncResult<number, import("../auth/schema.js").AuthBadRequest | import("../auth/schema.js").AuthConflict | import("../auth/schema.js").AuthExpectationFailed | import("../auth/schema.js").AuthForbidden | import("../auth/schema.js").AuthInternalServerError | import("../auth/schema.js").AuthNotFound | import("../auth/schema.js").AuthTooManyRequests | import("../auth/schema.js").AuthUnauthorized | import("effect/http/HttpClientError").HttpClientError | import("effect/Schema").SchemaError>) => typeof import("effect/reactivity/Atom").Reset | typeof import("effect/reactivity/Atom").Interrupt | PasswordResetRequest) | PasswordResetRequest) => void;
9
+ request: (input: PasswordResetRequest) => Effect.Effect<number, import("../auth/schema.js").AuthBadRequest | import("../auth/schema.js").AuthConflict | import("../auth/schema.js").AuthExpectationFailed | import("../auth/schema.js").AuthForbidden | import("../auth/schema.js").AuthInternalServerError | import("../auth/schema.js").AuthNotFound | import("../auth/schema.js").AuthTooManyRequests | import("../auth/schema.js").AuthUnauthorized | import("effect/http/HttpClientError").HttpClientError | import("effect/Schema").SchemaError, never>;
10
+ result: import("effect/reactivity/AsyncResult").AsyncResult<number, import("../auth/schema.js").AuthBadRequest | import("../auth/schema.js").AuthConflict | import("../auth/schema.js").AuthExpectationFailed | import("../auth/schema.js").AuthForbidden | import("../auth/schema.js").AuthInternalServerError | import("../auth/schema.js").AuthNotFound | import("../auth/schema.js").AuthTooManyRequests | import("../auth/schema.js").AuthUnauthorized | import("effect/http/HttpClientError").HttpClientError | import("effect/Schema").SchemaError>;
11
+ resendSeconds: number;
12
+ };
13
+ export declare const PasswordResetFeedback: ({ pending, sendingLabel, error, }: {
14
+ pending: boolean;
15
+ sendingLabel: string;
16
+ error: ReactNode;
17
+ }) => import("react").JSX.Element;
18
+ export declare const PasswordResetActions: ({ pending, resendSeconds, onResend, resendLabel, countdownLabel, }: {
19
+ pending: boolean;
20
+ resendSeconds: number;
21
+ onResend: () => void;
22
+ resendLabel: string;
23
+ countdownLabel: (seconds: number) => string;
24
+ }) => import("react").JSX.Element;
25
+ export {};