@krak-stack/auth 0.2.28 → 0.2.29

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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @krak-stack/auth
2
2
 
3
+ ## 0.2.29
4
+
5
+ ### Patch Changes
6
+
7
+ - Keep email-code send history in memory for the current sign-in attempt instead of local storage, so resend cooldowns do not carry across login/logout. Switching between password and email code reuses an unexpired code and preserves its countdown without sending duplicate emails. Track cooldowns separately for each email address, allow explicit resends after 60 seconds, and send a fresh code when the previous one has expired. Refreshing the email-code page starts a new countdown without automatically sending another email. Disable resend while a request is pending.
8
+
3
9
  ## 0.2.28
4
10
 
5
11
  ### Patch Changes
@@ -16,7 +16,7 @@ import { InputOTP, InputOTPGroup, InputOTPSeparator, InputOTPSlot, } from "@/com
16
16
  import { getLastUsedLoginMethod, notifyAuthChange, refreshAuthSession, } from "./auth-atoms.js";
17
17
  import { authClientApi, authHttpClient } from "./auth-client-api.js";
18
18
  import { PasswordField } from "./password-field.js";
19
- import { emailOtpSendsAtom, emailOtpSendState, EMAIL_OTP_RESEND_COOLDOWN_SECONDS, } from "./email-otp-state.js";
19
+ import { emailOtpResendSeconds as getEmailOtpResendSeconds, shouldSendEmailOtp, EMAIL_OTP_RESEND_COOLDOWN_SECONDS, } from "./email-otp-state.js";
20
20
  import { passwordResetSearch, passwordResetConfirmation, passwordResetConfirmationSearch, passwordResetCallbackUrl, requestPasswordResetEmail, resetPasswordAndSignOut, } from "./password-reset.js";
21
21
  import { PasswordResetActions, PasswordResetFeedback, usePasswordResetRequest, } from "./password-reset-flow.js";
22
22
  import { useKrakstackAuth } from "./auth-provider.js";
@@ -300,12 +300,19 @@ export function Signin(props) {
300
300
  const [emailSubmitted, setEmailSubmitted] = useState(initialMethodStep);
301
301
  const [authMethod, setAuthMethod] = useState(initialAuthMethod);
302
302
  const [otpSentTo, setOtpSentTo] = useState(initialMethodStep && initialAuthMethod === "emailOtp" ? initialEmail : "");
303
- const [emailOtpResendAvailableAt, setEmailOtpResendAvailableAt] = useState(0);
303
+ const [emailOtpResendAvailableAt, setEmailOtpResendAvailableAt] = useState(() => initialMethodStep && initialAuthMethod === "emailOtp"
304
+ ? Date.now() + EMAIL_OTP_RESEND_COOLDOWN_SECONDS * 1000
305
+ : 0);
304
306
  const [emailOtpResendSeconds, setEmailOtpResendSeconds] = useState(0);
305
- const otpSends = useAtomValue(emailOtpSendsAtom(baseUrl ?? ""));
306
- const persistOtpSends = useAtomSet(emailOtpSendsAtom(baseUrl ?? ""));
307
- const otpSendsRef = useRef(otpSends);
308
- otpSendsRef.current = otpSends;
307
+ const otpSendsRef = useRef(new Map(initialMethodStep && initialAuthMethod === "emailOtp"
308
+ ? [
309
+ [
310
+ initialEmail,
311
+ emailOtpResendAvailableAt -
312
+ EMAIL_OTP_RESEND_COOLDOWN_SECONDS * 1000,
313
+ ],
314
+ ]
315
+ : []));
309
316
  const [errorContext, setErrorContext] = useState("signIn");
310
317
  const selectedAuthMethod = authMethod === "password" && options.emailPassword
311
318
  ? "password"
@@ -320,7 +327,7 @@ export function Signin(props) {
320
327
  return;
321
328
  }
322
329
  const updateResendSeconds = () => {
323
- const seconds = Math.max(0, Math.ceil((emailOtpResendAvailableAt - Date.now()) / 1000));
330
+ const seconds = getEmailOtpResendSeconds(emailOtpResendAvailableAt, Date.now());
324
331
  setEmailOtpResendSeconds(seconds);
325
332
  if (seconds === 0)
326
333
  setEmailOtpResendAvailableAt(0);
@@ -348,23 +355,18 @@ export function Signin(props) {
348
355
  }));
349
356
  return;
350
357
  }
351
- const previousSend = otpSendsRef.current[email];
352
- const previousSendState = emailOtpSendState(previousSend, Date.now());
353
- const reuseCode = previousSendState.reusable &&
354
- (action.type !== "resendEmailOtp" ||
355
- previousSendState.resendSeconds > 0);
356
- const sendEmailOtp = (reuseCode
357
- ? Effect.void
358
- : authHttpClient(baseUrl, locale).pipe(Effect.flatMap((client) => client.auth.sendVerificationOtp({
359
- payload: { email, type: "sign-in" },
360
- })), Effect.asVoid, Effect.tap(() => Effect.sync(() => {
361
- const sends = {
362
- ...otpSendsRef.current,
363
- [email]: Date.now(),
364
- };
365
- otpSendsRef.current = sends;
366
- persistOtpSends(sends);
367
- })))).pipe(Effect.tap(() => Effect.sync(() => {
358
+ const sendEmailOtpRequest = authHttpClient(baseUrl, locale).pipe(Effect.flatMap((client) => client.auth.sendVerificationOtp({
359
+ payload: { email, type: "sign-in" },
360
+ })), Effect.asVoid, Effect.tap(() => Effect.sync(() => {
361
+ otpSendsRef.current.set(email, Date.now());
362
+ })));
363
+ const sendEmailOtp = (shouldSendEmailOtp({
364
+ sentAt: otpSendsRef.current.get(email),
365
+ now: Date.now(),
366
+ resend: action.type === "resendEmailOtp",
367
+ })
368
+ ? sendEmailOtpRequest
369
+ : Effect.void).pipe(Effect.tap(() => Effect.sync(() => {
368
370
  setAuthMethod("emailOtp");
369
371
  setEmailSubmitted(true);
370
372
  setOtpSentTo(email);
@@ -373,7 +375,7 @@ export function Signin(props) {
373
375
  search: authMethodSearch(searchString, "emailOtp", email),
374
376
  replace: true,
375
377
  });
376
- setEmailOtpResendAvailableAt((otpSendsRef.current[email] ?? 0) +
378
+ setEmailOtpResendAvailableAt((otpSendsRef.current.get(email) ?? 0) +
377
379
  EMAIL_OTP_RESEND_COOLDOWN_SECONDS * 1000);
378
380
  })));
379
381
  if (action.type === "sendEmailOtp" ||
@@ -459,10 +461,6 @@ export function Signin(props) {
459
461
  password: "",
460
462
  otp: "",
461
463
  }));
462
- const lastOtpSentAt = otpSends[formValues.email.trim()];
463
- useEffect(() => {
464
- setEmailOtpResendAvailableAt((lastOtpSentAt ?? 0) + EMAIL_OTP_RESEND_COOLDOWN_SECONDS * 1000);
465
- }, [lastOtpSentAt]);
466
464
  const resetForm = useAtomSet(form.reset);
467
465
  const setEmail = useAtomSet(form.getFieldAtoms(form.fields.email).setValue);
468
466
  const setPassword = useAtomSet(form.getFieldAtoms(form.fields.password).setValue);
@@ -532,7 +530,7 @@ export function Signin(props) {
532
530
  setErrorContext("resetPassword");
533
531
  submit({ type: "resetPassword" });
534
532
  },
535
- }, 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
533
+ }, 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: submitResult.waiting || emailOtpResendSeconds > 0, onClick: resendEmailOtp, children: emailOtpResendSeconds > 0
536
534
  ? text(m.sign_in_email_otp_resend_countdown, {
537
535
  seconds: String(emailOtpResendSeconds),
538
536
  })
@@ -1,11 +1,7 @@
1
- import { Atom } from "effect/reactivity";
2
1
  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
- };
2
+ export declare const emailOtpResendSeconds: (availableAt: number, now: number) => number;
3
+ export declare const shouldSendEmailOtp: ({ sentAt, now, resend, }: {
4
+ sentAt: number | undefined;
5
+ now: number;
6
+ resend: boolean;
7
+ }) => boolean;
@@ -1,25 +1,8 @@
1
- import { Schema } from "effect";
2
- import { KeyValueStore } from "effect/persistence";
3
- import { Atom } from "effect/reactivity";
4
1
  export const EMAIL_OTP_RESEND_COOLDOWN_SECONDS = 60;
5
2
  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
- });
3
+ export const emailOtpResendSeconds = (availableAt, now) => Math.max(0, Math.ceil((availableAt - now) / 1000));
4
+ export const shouldSendEmailOtp = ({ sentAt, now, resend, }) => sentAt === undefined ||
5
+ now < sentAt ||
6
+ now - sentAt >= EMAIL_OTP_LIFETIME_MS ||
7
+ (resend &&
8
+ emailOtpResendSeconds(sentAt + EMAIL_OTP_RESEND_COOLDOWN_SECONDS * 1000, now) === 0);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krak-stack/auth",
3
- "version": "0.2.28",
3
+ "version": "0.2.29",
4
4
  "description": "Effect HttpApi clients and schemas for KrakStack Auth.",
5
5
  "license": "MIT",
6
6
  "files": [