@donotdev/auth 0.3.2 → 0.3.4
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/README.md +6 -1
- package/dist/AuthStore.js +1 -1
- package/dist/authHelpers.js +1 -1
- package/dist/components/AccountLinking.js +1 -1
- package/dist/components/AuthFallback.js +1 -1
- package/dist/components/AuthPartnerButton.js +1 -1
- package/dist/components/DeleteAccountDialogs.js +1 -1
- package/dist/components/EmailLinkForm.d.ts.map +1 -1
- package/dist/components/EmailLinkForm.js +1 -1
- package/dist/components/EmailPasswordForm.d.ts +4 -2
- package/dist/components/EmailPasswordForm.d.ts.map +1 -1
- package/dist/components/EmailPasswordForm.js +1 -1
- package/dist/components/EmailVerification.js +1 -1
- package/dist/components/Feature.js +1 -1
- package/dist/components/FeatureGuard.js +1 -1
- package/dist/components/LoginModal.js +1 -1
- package/dist/components/MultipleAuthProviders.js +1 -1
- package/dist/components/PasswordStrengthIndicator.d.ts +8 -2
- package/dist/components/PasswordStrengthIndicator.d.ts.map +1 -1
- package/dist/components/PasswordStrengthIndicator.js +1 -1
- package/dist/constants.d.ts +7 -4
- package/dist/constants.d.ts.map +1 -1
- package/dist/emailAuth/captcha.d.ts +9 -0
- package/dist/emailAuth/captcha.d.ts.map +1 -0
- package/dist/emailAuth/captcha.js +1 -0
- package/dist/emailAuth/fields.d.ts +74 -4
- package/dist/emailAuth/fields.d.ts.map +1 -1
- package/dist/emailAuth/fields.js +1 -1
- package/dist/emailAuth/flows.d.ts +195 -19
- package/dist/emailAuth/flows.d.ts.map +1 -1
- package/dist/emailAuth/flows.js +1 -1
- package/dist/emailAuth/rules.d.ts +42 -5
- package/dist/emailAuth/rules.d.ts.map +1 -1
- package/dist/emailAuth/rules.js +2 -2
- package/dist/emailAuth/signUpFlow.d.ts +78 -0
- package/dist/emailAuth/signUpFlow.d.ts.map +1 -0
- package/dist/emailAuth/signUpFlow.js +1 -0
- package/dist/hooks/useAuthMethodToggle.js +1 -1
- package/dist/hooks/useAuthPartner.js +1 -1
- package/dist/hooks/useAuthUsers.d.ts +34 -0
- package/dist/hooks/useAuthUsers.d.ts.map +1 -0
- package/dist/hooks/useAuthUsers.js +1 -0
- package/dist/hooks/useDeleteAccount.js +1 -1
- package/dist/hooks/useEmailLinkForm.js +1 -1
- package/dist/hooks/useGoogleOneTap.js +1 -1
- package/dist/index.d.ts +11 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/symbol-index.json +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/useAuth.d.ts.map +1 -1
- package/dist/useAuth.js +1 -1
- package/guidelines/AUTH.md +119 -0
- package/package.json +5 -5
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { FormEvent } from 'react';
|
|
2
|
-
import type { SignUpMetadata } from '@donotdev/core';
|
|
2
|
+
import type { AuthUser, SignUpMetadata } from '@donotdev/core';
|
|
3
|
+
import type { AuthT } from './rules';
|
|
3
4
|
/** Field names the flows read from the submitted form. */
|
|
4
5
|
export declare const AUTH_FIELD: {
|
|
5
6
|
readonly EMAIL: "email";
|
|
@@ -7,7 +8,13 @@ export declare const AUTH_FIELD: {
|
|
|
7
8
|
readonly CONFIRM_PASSWORD: "confirmPassword";
|
|
8
9
|
readonly REMEMBER_ME: "rememberMe";
|
|
9
10
|
readonly CONSENT: "consent";
|
|
11
|
+
readonly DISPLAY_NAME: "displayName";
|
|
10
12
|
};
|
|
13
|
+
/**
|
|
14
|
+
* Sign-up: quiet time (ms) after the last keystroke before the breached-password
|
|
15
|
+
* pre-check starts, so it never fires per keystroke.
|
|
16
|
+
*/
|
|
17
|
+
export declare const BREACH_PRECHECK_DEBOUNCE_MS = 600;
|
|
11
18
|
/** Which flow a form runs. */
|
|
12
19
|
export type EmailAuthMode = 'signin' | 'signup' | 'reset';
|
|
13
20
|
/** Per-field validation messages, keyed by field name. */
|
|
@@ -23,20 +30,41 @@ export interface EmailAuthFlowOptions {
|
|
|
23
30
|
onSuccess?: () => void;
|
|
24
31
|
/** Called with the provider error after a failed attempt */
|
|
25
32
|
onError?: (error: Error) => void;
|
|
33
|
+
}
|
|
34
|
+
/** Options of {@link useEmailSignIn}. */
|
|
35
|
+
export interface EmailSignInOptions extends EmailAuthFlowOptions {
|
|
26
36
|
/**
|
|
27
|
-
*
|
|
28
|
-
*
|
|
37
|
+
* How a sign-in of an unconfirmed address ends (default `'toast'`).
|
|
38
|
+
* - `'toast'`: the form error, with a "Resend verification email" action.
|
|
39
|
+
* - `'code'`: the flow sends a fresh code (`sendEmailVerification`) and calls
|
|
40
|
+
* `onCodeSent`; the app shows the code step (`AuthCodeStep`). A rate-limited
|
|
41
|
+
* resend still calls `onCodeSent` (the code already sent stays valid); other
|
|
42
|
+
* resend errors are the form error.
|
|
29
43
|
*/
|
|
30
|
-
|
|
44
|
+
confirmation?: EmailSignUpConfirmation;
|
|
45
|
+
/** Code mode: a fresh code was sent to this unconfirmed address; show the code step */
|
|
46
|
+
onCodeSent?: (email: string) => void;
|
|
31
47
|
}
|
|
32
48
|
/** Outcome of a successful sign-up. */
|
|
33
49
|
export interface EmailSignUpOutcome {
|
|
34
50
|
/**
|
|
35
|
-
* The address must be confirmed before the user can sign in (no session yet).
|
|
36
|
-
* flow already showed the "check your email" toast with Resend.
|
|
51
|
+
* The address must be confirmed before the user can sign in (no session yet).
|
|
52
|
+
* Toast mode: the flow already showed the "check your email" toast with Resend.
|
|
53
|
+
* Code mode: show the code step for `email`.
|
|
37
54
|
*/
|
|
38
55
|
awaitingConfirmation: boolean;
|
|
56
|
+
/** The address that signed up (trimmed), e.g. for the code step */
|
|
57
|
+
email: string;
|
|
39
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* How a sign-up that needs confirmation ends.
|
|
61
|
+
* - `'toast'`: a toast that stays until dismissed says to open the confirmation
|
|
62
|
+
* email, with Resend (the link in the email confirms).
|
|
63
|
+
* - `'code'`: no toast; the app shows the code step (`useEmailCodeConfirmation`).
|
|
64
|
+
* Needs a provider that implements `verifyEmailCode` (Supabase) and an email
|
|
65
|
+
* template that sends the code.
|
|
66
|
+
*/
|
|
67
|
+
export type EmailSignUpConfirmation = 'toast' | 'code';
|
|
40
68
|
/** Options of {@link useEmailSignUp}. */
|
|
41
69
|
export interface EmailSignUpOptions extends Omit<EmailAuthFlowOptions, 'onSuccess'> {
|
|
42
70
|
/** Called once sign-up succeeded: close the dialog / sheet here */
|
|
@@ -50,6 +78,20 @@ export interface EmailSignUpOptions extends Omit<EmailAuthFlowOptions, 'onSucces
|
|
|
50
78
|
title: string;
|
|
51
79
|
description?: string;
|
|
52
80
|
};
|
|
81
|
+
/**
|
|
82
|
+
* How a sign-up that needs confirmation ends (default `'toast'`, see
|
|
83
|
+
* {@link EmailSignUpConfirmation}). Code mode, existing address: the provider sends
|
|
84
|
+
* no confirmation code, so the flow sends a password-reset email instead
|
|
85
|
+
* (fire-and-forget; the app words that template to cover "you already have an
|
|
86
|
+
* account"). Its failure is logged, never shown, never changes the outcome.
|
|
87
|
+
*/
|
|
88
|
+
confirmation?: EmailSignUpConfirmation;
|
|
89
|
+
/**
|
|
90
|
+
* Apply the character-class rules to the new password (uppercase, lowercase, digit,
|
|
91
|
+
* special; default `true`). `false`: only the minimum length applies; the
|
|
92
|
+
* breached-password check stays.
|
|
93
|
+
*/
|
|
94
|
+
passwordComposition?: boolean;
|
|
53
95
|
}
|
|
54
96
|
/** What a form needs from a flow: pass it to `AuthForm`. */
|
|
55
97
|
export interface EmailAuthFlow {
|
|
@@ -63,7 +105,7 @@ export interface EmailAuthFlow {
|
|
|
63
105
|
ready: boolean;
|
|
64
106
|
/** The provider failed to start: show an "unavailable" notice instead of the form */
|
|
65
107
|
unavailable: boolean;
|
|
66
|
-
/** Submit is blocked (
|
|
108
|
+
/** Submit is blocked (client-side throttle cooldown) */
|
|
67
109
|
blocked: boolean;
|
|
68
110
|
/** Form-level error (provider error, throttle) */
|
|
69
111
|
error: string | null;
|
|
@@ -75,12 +117,35 @@ export interface EmailAuthFlow {
|
|
|
75
117
|
resendVerification: (email: string) => Promise<void>;
|
|
76
118
|
/** Minimum new-password length (sign-up) */
|
|
77
119
|
passwordMinLength: number;
|
|
120
|
+
/**
|
|
121
|
+
* The character-class rules apply to the new password (sign-up). Absent = `true`.
|
|
122
|
+
* `AuthPasswordField` shows the requirements checklist only then.
|
|
123
|
+
*/
|
|
124
|
+
passwordComposition?: boolean;
|
|
125
|
+
/**
|
|
126
|
+
* Sign-up only: tell the flow the new password changed. Once typing has stopped
|
|
127
|
+
* ({@link BREACH_PRECHECK_DEBOUNCE_MS}) and the password meets the strength rules,
|
|
128
|
+
* the flow runs the breached-password check in the background and shows the
|
|
129
|
+
* breached error on the password field at once; submit reuses that result.
|
|
130
|
+
* Absent in the other flows.
|
|
131
|
+
*/
|
|
132
|
+
watchPassword?: (password: string) => void;
|
|
78
133
|
}
|
|
134
|
+
/**
|
|
135
|
+
* The email check of every flow: the translated "required" / "invalid" message, or
|
|
136
|
+
* `undefined` when `email` (already trimmed) is valid.
|
|
137
|
+
*
|
|
138
|
+
* @param t - Translate function of the `auth` namespace
|
|
139
|
+
* @param email - The trimmed address
|
|
140
|
+
* @returns The error message, or `undefined`
|
|
141
|
+
*/
|
|
142
|
+
export declare const validateEmail: (t: AuthT, email: string) => string | undefined;
|
|
79
143
|
/**
|
|
80
144
|
* Email + password sign-in. Remember me is applied when the form renders
|
|
81
|
-
* `AuthRememberMeField
|
|
145
|
+
* `AuthRememberMeField`. An unconfirmed address offers a resend, or with
|
|
146
|
+
* `confirmation: 'code'` gets a fresh code and `onCodeSent(email)` (show `AuthCodeStep`).
|
|
82
147
|
*
|
|
83
|
-
* @param options - Callbacks
|
|
148
|
+
* @param options - Callbacks, confirmation mode
|
|
84
149
|
* @returns The flow, for `AuthForm`
|
|
85
150
|
*
|
|
86
151
|
* @example
|
|
@@ -95,26 +160,137 @@ export interface EmailAuthFlow {
|
|
|
95
160
|
* </AuthForm>
|
|
96
161
|
* ```
|
|
97
162
|
*/
|
|
98
|
-
export declare function useEmailSignIn(options?:
|
|
163
|
+
export declare function useEmailSignIn(options?: EmailSignInOptions): EmailAuthFlow;
|
|
99
164
|
/**
|
|
100
|
-
* Email + password sign-up. Password policy
|
|
101
|
-
*
|
|
165
|
+
* Email + password sign-up. Password policy (`passwordComposition: false` = length
|
|
166
|
+
* only) and breached-password check apply; the confirmation field and consent are
|
|
167
|
+
* required when the form renders them. `AuthNameField`, when rendered and filled, is
|
|
168
|
+
* stored trimmed as the user's display name (metadata `full_name`); never required.
|
|
102
169
|
*
|
|
103
170
|
* Anti-enumeration: an address that already has an account ends exactly like a new
|
|
104
|
-
* one (
|
|
105
|
-
*
|
|
171
|
+
* one (`awaitingConfirmation: true`). When the provider asks for confirmation,
|
|
172
|
+
* `onSuccess` runs and then:
|
|
173
|
+
* - `confirmation: 'toast'` (default): a toast that stays until dismissed tells the
|
|
174
|
+
* user to confirm, with Resend;
|
|
175
|
+
* - `confirmation: 'code'`: nothing more; the app shows the code step for
|
|
176
|
+
* `outcome.email`. For an existing address the flow sends a password-reset
|
|
177
|
+
* email (`sendPasswordResetEmail`), fire-and-forget: a failure goes to
|
|
178
|
+
* `console.error`, never to the screen.
|
|
179
|
+
* A project that does not require confirmation signs the user in at once:
|
|
180
|
+
* `awaitingConfirmation: false`.
|
|
106
181
|
*
|
|
107
|
-
* @param options - Callbacks,
|
|
182
|
+
* @param options - Callbacks, password policy, extra metadata,
|
|
183
|
+
* confirmation mode
|
|
108
184
|
* @returns The flow, for `AuthForm`
|
|
185
|
+
*
|
|
186
|
+
* @example
|
|
187
|
+
* ```tsx
|
|
188
|
+
* const [email, setEmail] = useState<string | null>(null);
|
|
189
|
+
* const flow = useEmailSignUp({
|
|
190
|
+
* confirmation: 'code',
|
|
191
|
+
* onSuccess: (outcome) => {
|
|
192
|
+
* if (outcome.awaitingConfirmation) setEmail(outcome.email);
|
|
193
|
+
* else close();
|
|
194
|
+
* },
|
|
195
|
+
* });
|
|
196
|
+
* ```
|
|
109
197
|
*/
|
|
110
198
|
export declare function useEmailSignUp(options?: EmailSignUpOptions): EmailAuthFlow;
|
|
199
|
+
/** Options of {@link usePasswordResetRequest}. */
|
|
200
|
+
export interface PasswordResetRequestOptions extends EmailAuthFlowOptions {
|
|
201
|
+
/**
|
|
202
|
+
* Confirm with a toast that stays until dismissed (default `true`). `false`: no
|
|
203
|
+
* toast; render the "check your inbox" message inline from `flow.sent`.
|
|
204
|
+
* @default true
|
|
205
|
+
*/
|
|
206
|
+
toast?: boolean;
|
|
207
|
+
}
|
|
208
|
+
/** The password-reset request flow: an {@link EmailAuthFlow} plus `sent`. */
|
|
209
|
+
export interface PasswordResetRequestFlow extends EmailAuthFlow {
|
|
210
|
+
/** The request went through (any address): `true` until the next submit */
|
|
211
|
+
sent: boolean;
|
|
212
|
+
}
|
|
111
213
|
/**
|
|
112
214
|
* Password-reset request. Anti-enumeration: the same outcome whether or not the address
|
|
113
|
-
* has an account; `onSuccess` runs and a toast that stays until
|
|
114
|
-
* the inbox
|
|
215
|
+
* has an account; `sent` turns `true`, `onSuccess` runs and a toast that stays until
|
|
216
|
+
* dismissed says to check the inbox (`toast: false`: no toast, the app shows the
|
|
217
|
+
* message inline from `sent`). Throttling and a CAPTCHA failure are the form error
|
|
218
|
+
* (the request did not go out); any other provider error is hidden.
|
|
115
219
|
*
|
|
116
|
-
* @param options - Callbacks
|
|
220
|
+
* @param options - Callbacks, toast opt-out
|
|
117
221
|
* @returns The flow, for `AuthForm`
|
|
118
222
|
*/
|
|
119
|
-
export declare function usePasswordResetRequest(options?:
|
|
223
|
+
export declare function usePasswordResetRequest(options?: PasswordResetRequestOptions): PasswordResetRequestFlow;
|
|
224
|
+
/** Options of {@link useEmailCodeConfirmation}. */
|
|
225
|
+
export interface EmailCodeConfirmationOptions {
|
|
226
|
+
/** The address that signed up (`EmailSignUpOutcome.email`) */
|
|
227
|
+
email: string;
|
|
228
|
+
/**
|
|
229
|
+
* Characters of the emailed code: match the provider (Supabase:
|
|
230
|
+
* `mailer_otp_length`).
|
|
231
|
+
* @default 6
|
|
232
|
+
*/
|
|
233
|
+
length?: number;
|
|
234
|
+
/**
|
|
235
|
+
* Seconds before the code can be sent again. The countdown starts at mount: the
|
|
236
|
+
* sign-up just sent a code.
|
|
237
|
+
* @default 60
|
|
238
|
+
*/
|
|
239
|
+
resendCooldownSeconds?: number;
|
|
240
|
+
/** Called with the signed-in user once the code is confirmed: close the sheet here */
|
|
241
|
+
onSuccess?: (user: AuthUser) => void;
|
|
242
|
+
/** Called with the provider error after a failed confirmation or resend */
|
|
243
|
+
onError?: (error: Error) => void;
|
|
244
|
+
}
|
|
245
|
+
/** What the code step needs from {@link useEmailCodeConfirmation}: pass it to `AuthCodeField`. */
|
|
246
|
+
export interface EmailCodeConfirmation {
|
|
247
|
+
/** The address the code was sent to */
|
|
248
|
+
email: string;
|
|
249
|
+
/** Characters of the code */
|
|
250
|
+
length: number;
|
|
251
|
+
/** The code typed so far */
|
|
252
|
+
code: string;
|
|
253
|
+
/** Update the typed code */
|
|
254
|
+
setCode: (code: string) => void;
|
|
255
|
+
/**
|
|
256
|
+
* Confirm the code (`code` by default; pass the value when it is not in state yet,
|
|
257
|
+
* e.g. from `onComplete`). A wrong or expired code clears the typed code.
|
|
258
|
+
*/
|
|
259
|
+
submit: (code?: string) => Promise<void>;
|
|
260
|
+
/** A confirmation is in progress */
|
|
261
|
+
busy: boolean;
|
|
262
|
+
/** Translated message of the last failure (wrong / expired code, throttle, failed resend...), or `null` */
|
|
263
|
+
error: string | null;
|
|
264
|
+
/**
|
|
265
|
+
* Send a new code (no-op while `resendIn > 0`) and restart the countdown. No toast:
|
|
266
|
+
* success sets `resent`, a failure sets `error`.
|
|
267
|
+
*/
|
|
268
|
+
resend: () => Promise<void>;
|
|
269
|
+
/** A new code was sent: `true` after a successful resend until the next submit or resend */
|
|
270
|
+
resent: boolean;
|
|
271
|
+
/** A resend is in progress */
|
|
272
|
+
resending: boolean;
|
|
273
|
+
/** Seconds left before `resend` is allowed (0 = allowed) */
|
|
274
|
+
resendIn: number;
|
|
275
|
+
/** The provider is ready (confirm and resend wait for it) */
|
|
276
|
+
ready: boolean;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* The code step of a sign-up made with `useEmailSignUp({ confirmation: 'code' })`:
|
|
280
|
+
* the user types the emailed code, `useAuth('verifyEmailCode')` confirms it and signs
|
|
281
|
+
* the user in. Same client throttle as the email flows; wrong / expired code and rate
|
|
282
|
+
* limits get translated messages. Resend sends a new code with
|
|
283
|
+
* `useAuth('sendEmailVerification')` once the countdown is over. No toast: the
|
|
284
|
+
* outcome is state (`error`, `resent`) that `AuthCodeField` renders inline.
|
|
285
|
+
*
|
|
286
|
+
* @param options - Address, code length, resend cooldown, callbacks
|
|
287
|
+
* @returns The code step state, for `AuthCodeField`
|
|
288
|
+
*
|
|
289
|
+
* @example
|
|
290
|
+
* ```tsx
|
|
291
|
+
* const confirmation = useEmailCodeConfirmation({ email, length: 8, onSuccess: close });
|
|
292
|
+
* <AuthCodeField confirmation={confirmation} />
|
|
293
|
+
* ```
|
|
294
|
+
*/
|
|
295
|
+
export declare function useEmailCodeConfirmation(options: EmailCodeConfirmationOptions): EmailCodeConfirmation;
|
|
120
296
|
//# sourceMappingURL=flows.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flows.d.ts","sourceRoot":"","sources":["../../src/emailAuth/flows.tsx"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"flows.d.ts","sourceRoot":"","sources":["../../src/emailAuth/flows.tsx"],"names":[],"mappings":"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"}
|
package/dist/emailAuth/flows.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{jsx as
|
|
1
|
+
"use client";import{jsx as x}from"react/jsx-runtime";import{useEffect as v,useRef as b,useState as R}from"react";import{Button as z,ToastAction as J,toast as L}from"@donotdev/components";import{useTranslation as Q}from"@donotdev/core";import{useAuth as h}from"../useAuth";import{DEFAULT_CONFIRMATION_CODE_LENGTH as X,DEFAULT_PASSWORD_MIN_LENGTH as k,DEFAULT_RESEND_COOLDOWN_SECONDS as Z,authErrorMessage as q,codeErrorMessage as B,isAlreadyRegisteredError as ee,isBreachedPassword as te,isCaptchaError as re,isEmail as se,isRateLimitError as H,isUnconfirmedError as j,newPasswordError as $}from"./rules";const l={EMAIL:"email",PASSWORD:"password",CONFIRM_PASSWORD:"confirmPassword",REMEMBER_ME:"rememberMe",CONSENT:"consent",DISPLAY_NAME:"displayName"},ne="full_name",G=600,ae=6e4,ie=5,oe=3e4;function Y(){const e=b([]),[t,r]=R(null);return v(()=>{if(t===null)return;const a=setTimeout(()=>r(null),Math.max(0,t-Date.now()));return()=>clearTimeout(a)},[t]),{attempt:()=>{const a=Date.now();return t!==null&&a<t?Math.ceil((t-a)/1e3):(e.current=e.current.filter(S=>a-S<ae),e.current.push(a),e.current.length>=ie&&(e.current=[],r(a+oe)),0)},throttled:t!==null}}const F=e=>e instanceof Error?e:new Error(String(e)),p=(e,t)=>{const r=e.get(t);return typeof r=="string"?r:""},W=(e,t)=>{const r=e.elements.namedItem(t);return r instanceof HTMLInputElement?r:void 0};function K(){const{t:e}=Q("auth");return(t,r,a)=>e(t,{defaultValue:r,...a})}function V(e,t){const r=K(),a=h("isAvailable"),S=h("status"),g=h("sendEmailVerification"),d=Y(),[y,C]=R(!1),[u,o]=R(null),[M,f]=R({}),[E,I]=R(null),_=async w=>{try{await g(w),L("success",r("verificationSent","Verification email sent."))}catch(s){L("error",q(s,r))}};return{t:r,submit:async(w,s,i)=>{if(w.preventDefault(),y||!a)return;const n=w.currentTarget,c=new FormData(n),O=s(n,c);if(f(O),I(null),Object.keys(O).length>0){o(null);return}const P=d.attempt();if(P>0){o(r("errors.rate_limit_cooldown",`Too many attempts. Please wait ${P} seconds.`,{seconds:P}));return}o(null),C(!0);try{await i(n,c)}catch(m){e==="signin"&&j(m)&&I(p(c,l.EMAIL).trim()),o(q(m,r)),t.onError?.(F(m))}finally{C(!1)}},flow:(w,s,i,n)=>({mode:e,onSubmit:w,busy:y,ready:a,unavailable:S==="degraded"||S==="error",blocked:d.throttled,error:u,fieldErrors:M,unconfirmedEmail:E,resendVerification:_,passwordMinLength:s,...i===void 0?{}:{passwordComposition:i},...n?{watchPassword:n}:{}}),resendVerification:_,setFieldErrors:f}}const N=(e,t)=>{if(t==="")return e("emailRequired","Email is required");if(!se(t))return e("emailInvalid","Invalid email address")},U=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0));function ce(e={}){const t=V("signin",e),{t:r}=t,a=h("signInWithEmail"),S=h("sendEmailVerification"),g=h("setRememberMe"),d=h("canRememberMe"),y=C=>{t.submit(C,(u,o)=>U({email:N(r,p(o,l.EMAIL).trim()),password:p(o,l.PASSWORD)===""?r("passwordRequired","Password is required"):void 0}),async(u,o)=>{const M=W(u,l.REMEMBER_ME);M&&d()&&await g(M.checked);const f=p(o,l.EMAIL).trim();try{const E=await a(f,p(o,l.PASSWORD));if(!E?.success)throw new Error(E?.error??"Sign in failed")}catch(E){if(e.confirmation!=="code"||!j(E))throw E;try{await S(f)}catch(I){if(!H(I))throw I}e.onCodeSent?.(f);return}e.onSuccess?.()})};return t.flow(y,k)}function le(e={}){const t=V("signup",e),{t:r}=t,a=h("createUserWithEmail"),S=h("sendPasswordResetEmail"),g=e.passwordMinLength??k,d=e.confirmation??"toast",y=e.passwordComposition??!0,C=s=>{(async()=>{try{await S(s)}catch{}})()},u=b(null),o=b(""),M=b(void 0);v(()=>()=>clearTimeout(M.current),[]);const f=r("errors.breached_password","This password has appeared in a data breach. Please choose a different password."),E=s=>{if(u.current?.password===s)return u.current.breached;const i=te(s);return u.current={password:s,breached:i},i},I=s=>{o.current=s,clearTimeout(M.current),t.setFieldErrors(i=>{if(i.password!==f)return i;const{password:n,...c}=i;return c}),$(s,g,r,y)===null&&(M.current=setTimeout(()=>{E(s).then(i=>{!i||o.current!==s||t.setFieldErrors(n=>({...n,password:f}))})},G))},_=s=>{L({title:e.checkEmailMessage?.title??r("signup.success_title","Check your email"),description:e.checkEmailMessage?.description??r("signup.check_email","If an account was created, you will receive a confirmation email. Check your inbox and spam folder."),toastType:"success",duration:0,action:x(J,{asChild:!0,altText:r("resendEmail","Resend email"),children:x(z,{onClick:()=>{t.resendVerification(s)},children:r("resendEmail","Resend email")})})})},w=s=>{t.submit(s,(i,n)=>{const c=p(n,l.PASSWORD),O=i.elements.namedItem(l.CONFIRM_PASSWORD),P=W(i,l.CONSENT);return U({email:N(r,p(n,l.EMAIL).trim()),password:$(c,g,r,y)??void 0,confirmPassword:O&&p(n,l.CONFIRM_PASSWORD)!==c?r("confirmPasswordMismatch","Passwords do not match"):void 0,consent:P&&!P.checked?r("terms.required","Please accept the terms to continue"):void 0})},async(i,n)=>{const c=p(n,l.EMAIL).trim(),O=p(n,l.PASSWORD);if(clearTimeout(M.current),await E(O)){t.setFieldErrors({password:f});return}const P=W(i,l.CONSENT),m=p(n,l.DISPLAY_NAME).trim(),D=P?.checked||m?{...e.metadata,...P?.checked?{gdpr_consent_at:new Date().toISOString()}:{},...m?{[ne]:m}:{}}:e.metadata;try{const A=await a(c,O,D);if(!A?.success)throw new Error(A?.error??"Sign up failed");const T=!A.user?.emailVerified;e.onSuccess?.({awaitingConfirmation:T,email:c}),T&&d==="toast"&&_(c)}catch(A){if(!ee(A))throw A;e.onSuccess?.({awaitingConfirmation:!0,email:c}),d==="toast"?_(c):C(c)}})};return t.flow(w,g,e.passwordComposition,I)}function ue(e={}){const t=V("reset",e),{t:r}=t,a=h("sendPasswordResetEmail"),[S,g]=R(!1),d=y=>{g(!1),t.submit(y,(C,u)=>U({email:N(r,p(u,l.EMAIL).trim())}),async(C,u)=>{try{await a(p(u,l.EMAIL).trim())}catch(o){if(H(o)||re(o))throw o}g(!0),e.onSuccess?.(),e.toast!==!1&&L({title:r("forgotPassword.sent","Password reset email sent"),description:r("forgotPassword.check_email_safe","If an account exists with this email, you will receive password reset instructions."),toastType:"success",duration:0})})};return{...t.flow(d,k),sent:S}}function de(e){const t=K(),r=h("isAvailable"),a=h("verifyEmailCode"),S=h("sendEmailVerification"),g=Y(),d=e.length??X,y=e.resendCooldownSeconds??Z,[C,u]=R(""),[o,M]=R(!1),[f,E]=R(!1),[I,_]=R(null),[w,s]=R(y),[i,n]=R(!1),c=b(!1);v(()=>{if(w<=0)return;const m=setTimeout(()=>s(D=>Math.max(0,D-1)),1e3);return()=>clearTimeout(m)},[w]);const O=async m=>{const D=(m??C).trim();if(c.current||!r)return;if(n(!1),D.length!==d){_(t("codeConfirmation.incomplete",`Enter the ${d}-digit code.`,{length:d}));return}const A=g.attempt();if(A>0){_(t("errors.rate_limit_cooldown",`Too many attempts. Please wait ${A} seconds.`,{seconds:A}));return}c.current=!0,_(null),M(!0);try{const T=await a(e.email,D);e.onSuccess?.(T)}catch(T){_(B(T,t)),u(""),e.onError?.(F(T))}finally{c.current=!1,M(!1)}},P=async()=>{if(!(w>0||f||!r)){E(!0),n(!1),_(null);try{await S(e.email),s(y),n(!0)}catch(m){_(B(m,t)),e.onError?.(F(m))}finally{E(!1)}}};return{email:e.email,length:d,code:C,setCode:u,submit:O,busy:o,error:I,resend:P,resending:f,resent:i,resendIn:w,ready:r}}export{l as AUTH_FIELD,G as BREACH_PRECHECK_DEBOUNCE_MS,de as useEmailCodeConfirmation,ce as useEmailSignIn,le as useEmailSignUp,ue as usePasswordResetRequest,N as validateEmail};
|
|
@@ -2,7 +2,12 @@
|
|
|
2
2
|
* @fileoverview Email auth rules
|
|
3
3
|
* @description The rules every email/password flow shares, framework form or app form:
|
|
4
4
|
* provider error -> user message, email format, new-password policy, breached-password
|
|
5
|
-
* check (HaveIBeenPwned k-anonymity, NIST 800-63B)
|
|
5
|
+
* check (HaveIBeenPwned k-anonymity, NIST 800-63B), confirmation-code errors, CAPTCHA
|
|
6
|
+
* failures.
|
|
7
|
+
*
|
|
8
|
+
* Provider errors are recognised by their structured code first (the error's `code`,
|
|
9
|
+
* or the provider code `wrapAuthError` keeps in `details.originalCode`), then by
|
|
10
|
+
* their message.
|
|
6
11
|
*
|
|
7
12
|
* @version 0.1.0
|
|
8
13
|
* @since 0.2.3
|
|
@@ -18,15 +23,47 @@ export declare function isEmail(email: string): boolean;
|
|
|
18
23
|
export declare function isRateLimitError(error: unknown): boolean;
|
|
19
24
|
/** Provider error: the address exists but was never confirmed. */
|
|
20
25
|
export declare function isUnconfirmedError(error: unknown): boolean;
|
|
21
|
-
/**
|
|
26
|
+
/**
|
|
27
|
+
* Provider error: sign-up with an address that already has an account. Structured
|
|
28
|
+
* code first, message as the fallback (Supabase with confirmations on reports it as
|
|
29
|
+
* a fake user, which the provider turns into an "already exists" message).
|
|
30
|
+
*/
|
|
22
31
|
export declare function isAlreadyRegisteredError(error: unknown): boolean;
|
|
23
|
-
/**
|
|
32
|
+
/**
|
|
33
|
+
* CAPTCHA failure: the auth server refused the token, or no token could be obtained
|
|
34
|
+
* (Turnstile script blocked, widget error, no answer in time). Structured code only:
|
|
35
|
+
* the wrapped message carries the email address, which may contain "captcha".
|
|
36
|
+
*/
|
|
37
|
+
export declare function isCaptchaError(error: unknown): boolean;
|
|
38
|
+
/** User-facing message for a provider error (CAPTCHA, rate limit, credentials, network...). */
|
|
24
39
|
export declare function authErrorMessage(error: unknown, t: AuthT): string;
|
|
40
|
+
/** Default number of characters of an emailed confirmation code. */
|
|
41
|
+
export declare const DEFAULT_CONFIRMATION_CODE_LENGTH = 6;
|
|
42
|
+
/** Default seconds before a confirmation code can be sent again. */
|
|
43
|
+
export declare const DEFAULT_RESEND_COOLDOWN_SECONDS = 60;
|
|
44
|
+
/** Provider error: the confirmation code is known to have expired. */
|
|
45
|
+
export declare function isCodeExpiredError(error: unknown): boolean;
|
|
46
|
+
/** Provider error: the confirmation code is wrong (or wrong or expired, see `otp_expired`). */
|
|
47
|
+
export declare function isInvalidCodeError(error: unknown): boolean;
|
|
48
|
+
/**
|
|
49
|
+
* User-facing message for a failed code confirmation or code resend: CAPTCHA failure
|
|
50
|
+
* (resend), expired code, wrong code, rate limit (structured codes included), else
|
|
51
|
+
* `authErrorMessage`.
|
|
52
|
+
*/
|
|
53
|
+
export declare function codeErrorMessage(error: unknown, t: AuthT): string;
|
|
25
54
|
/**
|
|
26
55
|
* First rule a new password breaks, or `null`. Policy: minimum length (8 by default),
|
|
27
|
-
* one uppercase letter, one lowercase letter,
|
|
56
|
+
* then, unless `composition` is `false`, one uppercase letter, one lowercase letter,
|
|
57
|
+
* one digit, one special character.
|
|
58
|
+
*
|
|
59
|
+
* @param password - The new password
|
|
60
|
+
* @param minLength - Minimum length
|
|
61
|
+
* @param t - Translate function of the `auth` namespace
|
|
62
|
+
* @param composition - Apply the character-class rules (default `true`); `false` keeps
|
|
63
|
+
* only the empty check and the minimum length (NIST 800-63B: length over composition)
|
|
64
|
+
* @returns The message of the first broken rule, or `null`
|
|
28
65
|
*/
|
|
29
|
-
export declare function newPasswordError(password: string, minLength: number, t: AuthT): string | null;
|
|
66
|
+
export declare function newPasswordError(password: string, minLength: number, t: AuthT, composition?: boolean): string | null;
|
|
30
67
|
/**
|
|
31
68
|
* Whether the password appears in a known breach (HaveIBeenPwned range API: only the
|
|
32
69
|
* first 5 hex chars of the SHA-1 leave the browser). Fails open: an unreachable API
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../../src/emailAuth/rules.ts"],"names":[],"mappings":"AAEA
|
|
1
|
+
{"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../../src/emailAuth/rules.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;GAcG;AAEH,iFAAiF;AACjF,MAAM,MAAM,KAAK,GAAG,CAClB,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,MAAM,EAChB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAC7B,MAAM,CAAC;AAEZ,gDAAgD;AAChD,eAAO,MAAM,2BAA2B,IAAI,CAAC;AAI7C,+EAA+E;AAC/E,wBAAgB,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAE9C;AAwBD,oEAAoE;AACpE,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAOxD;AAED,kEAAkE;AAClE,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAO1D;AASD;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAShE;AAOD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAEtD;AA8CD,+FAA+F;AAC/F,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK,GAAG,MAAM,CAYjE;AAMD,oEAAoE;AACpE,eAAO,MAAM,gCAAgC,IAAI,CAAC;AAElD,oEAAoE;AACpE,eAAO,MAAM,+BAA+B,KAAK,CAAC;AAqBlD,sEAAsE;AACtE,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAK1D;AAED,+FAA+F;AAC/F,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAQ1D;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK,GAAG,MAAM,CAkBjE;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB,CAC9B,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EACjB,CAAC,EAAE,KAAK,EACR,WAAW,UAAO,GACjB,MAAM,GAAG,IAAI,CAmCf;AAED;;;;GAIG;AACH,wBAAsB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAsB3E"}
|
package/dist/emailAuth/rules.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const
|
|
2
|
-
`).some(n=>n.split(":")[0]?.trim()===
|
|
1
|
+
const w=8,h=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function _(e){return h.test(e)}const a=e=>(e instanceof Error?e.message:String(e)).toLowerCase();function y(e){if(typeof e!="object"||e===null)return[];const r=[];if("code"in e&&typeof e.code=="string"&&r.push(e.code),"details"in e&&typeof e.details=="object"&&e.details){const t=e.details.originalCode;typeof t=="string"&&r.push(t)}return r}const i=(e,r)=>y(e).some(t=>r.has(t));function l(e){const r=a(e);return r.includes("429")||r.includes("rate")||r.includes("too_many_requests")}function k(e){const r=a(e);return r.includes("email_not_confirmed")||r.includes("email not confirmed")||r.includes("auth/unverified-email")}const g=new Set(["user_already_exists","email_exists","auth/email-already-in-use","already-exists"]);function E(e){if(i(e,g))return!0;const r=a(e);return r.includes("already")||r.includes("exists")||r.includes("user_already_exists")||r.includes("auth/email-already-in-use")}const v=new Set(["captcha_failed","auth/captcha-check-failed"]);function o(e){return i(e,v)}const P=[{test:l,key:"errors.rate_limit",fallback:"Too many attempts. Please wait a moment and try again."},{test:e=>e.includes("email_not_confirmed")||e.includes("email not confirmed")||e.includes("auth/unverified-email"),key:"errors.email_not_confirmed",fallback:"Please verify your email before signing in."},{test:e=>e.includes("invalid_credentials")||e.includes("invalid login credentials")||e.includes("invalid-credential")||e.includes("auth/wrong-password")||e.includes("auth/user-not-found")||e.includes("invalid")&&e.includes("credential"),key:"errors.invalid_credentials",fallback:"Invalid email or password."},{test:e=>e.includes("weak_password")||e.includes("weak password")||e.includes("auth/weak-password"),key:"errors.weak_password",fallback:"Password is too weak. Please choose a stronger password."},{test:e=>e.includes("network")||e.includes("fetch"),key:"networkError",fallback:"Network error. Please check your connection and try again."}];function c(e,r){if(o(e))return r("errors.captcha_failed","The security check failed. Please try again.");const t=a(e);for(const s of P)if(s.test(t))return r(s.key,s.fallback);return r("errorGeneric","Authentication failed. Please try again.")}const x=6,S=60,b=new Set(["auth/expired-action-code"]),u=new Set(["otp_expired","auth/invalid-action-code","auth/invalid-verification-code"]),A=new Set(["over_request_rate_limit","over_email_send_rate_limit","auth/too-many-requests","rate-limit-exceeded"]);function m(e){if(i(e,b))return!0;if(i(e,u))return!1;const r=a(e);return r.includes("expired")&&!r.includes("invalid")}function f(e){if(i(e,u))return!0;const r=a(e);return r.includes("expired or is invalid")||r.includes("invalid")&&(r.includes("code")||r.includes("token")||r.includes("otp"))}function T(e,r){return o(e)?c(e,r):m(e)?r("errors.code_expired","This code has expired. Request a new code."):f(e)?r("errors.invalid_code","This code is incorrect or has expired. Check the email or request a new code."):i(e,A)?r("errors.rate_limit","Too many attempts. Please wait a moment and try again."):c(e,r)}function C(e,r,t,s=!0){return e===""?t("passwordRequired","Password is required"):e.length<r?t("passwordMinLength",`Password must be at least ${r} characters`,{count:r}):s?/[A-Z]/.test(e)?/[a-z]/.test(e)?/[0-9]/.test(e)?/[^a-zA-Z0-9]/.test(e)?null:t("passwordRequirement.special","Password must contain at least one special character"):t("passwordRequirement.number","Password must contain at least one number"):t("passwordRequirement.lowercase","Password must contain at least one lowercase letter"):t("passwordRequirement.uppercase","Password must contain at least one uppercase letter"):null}async function R(e){try{const r=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(e)),t=Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("").toUpperCase(),s=t.slice(0,5),p=t.slice(5),d=await fetch(`https://api.pwnedpasswords.com/range/${s}`,{headers:{"Add-Padding":"true"},credentials:"omit"});return d.ok?(await d.text()).split(`
|
|
2
|
+
`).some(n=>n.split(":")[0]?.trim()===p):!1}catch{return!1}}export{x as DEFAULT_CONFIRMATION_CODE_LENGTH,w as DEFAULT_PASSWORD_MIN_LENGTH,S as DEFAULT_RESEND_COOLDOWN_SECONDS,c as authErrorMessage,T as codeErrorMessage,E as isAlreadyRegisteredError,R as isBreachedPassword,o as isCaptchaError,m as isCodeExpiredError,_ as isEmail,f as isInvalidCodeError,l as isRateLimitError,k as isUnconfirmedError,C as newPasswordError};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
import type { AuthUser, SignUpMetadata } from '@donotdev/core';
|
|
3
|
+
/** Step of the flow: `'account'`, `'code'`, or the `id` of an app step. */
|
|
4
|
+
export type EmailSignUpStepId = 'account' | 'code' | (string & {});
|
|
5
|
+
/** What an app step receives. */
|
|
6
|
+
export interface EmailSignUpStepContext {
|
|
7
|
+
/** The signed-in user (the code confirmed the address) */
|
|
8
|
+
user: AuthUser;
|
|
9
|
+
/** To the following app step; after the last one, `onDone` */
|
|
10
|
+
next: () => void;
|
|
11
|
+
/** To the previous app step; absent on the first one (the account exists by then) */
|
|
12
|
+
back?: () => void;
|
|
13
|
+
}
|
|
14
|
+
/** An app step, shown once the user is signed in (e.g. company details). */
|
|
15
|
+
export interface EmailSignUpStep {
|
|
16
|
+
/** Step id, reported by `onStepChange` and kept across the host closing */
|
|
17
|
+
id: string;
|
|
18
|
+
/** Title the flow renders above the step (translated by the app) */
|
|
19
|
+
title: string;
|
|
20
|
+
/** Text under the title */
|
|
21
|
+
description?: ReactNode;
|
|
22
|
+
/** The step's content */
|
|
23
|
+
render: (context: EmailSignUpStepContext) => ReactNode;
|
|
24
|
+
}
|
|
25
|
+
/** Props of {@link EmailSignUpFlow}. */
|
|
26
|
+
export interface EmailSignUpFlowProps {
|
|
27
|
+
/**
|
|
28
|
+
* App fields, rendered inside the account form after the password (read at submit
|
|
29
|
+
* like the framework fields): e.g. `<AuthNameField />`, `<AuthConsentField />`, a
|
|
30
|
+
* privacy link.
|
|
31
|
+
*/
|
|
32
|
+
fields?: ReactNode;
|
|
33
|
+
/** Extra sign-up metadata stored with the user (e.g. `{ locale }`) */
|
|
34
|
+
metadata?: SignUpMetadata;
|
|
35
|
+
/** App steps after the code, in order */
|
|
36
|
+
steps?: EmailSignUpStep[];
|
|
37
|
+
/** Called with each step shown, the first one included (e.g. a link only on `'account'`) */
|
|
38
|
+
onStepChange?: (step: EmailSignUpStepId) => void;
|
|
39
|
+
/** Called with the signed-in user once the last step is done: close the host here */
|
|
40
|
+
onDone?: (user: AuthUser) => void;
|
|
41
|
+
}
|
|
42
|
+
/** Session storage key of the pending step (never the password). */
|
|
43
|
+
export declare const SIGN_UP_FLOW_STORAGE_KEY = "dndev.auth.signUp";
|
|
44
|
+
/**
|
|
45
|
+
* The whole email sign-up: account (email, password, `fields`) -> 6-digit emailed
|
|
46
|
+
* code -> `steps` -> `onDone(user)`. Inline only, no toast. The flow renders each
|
|
47
|
+
* step's title, description and "Step n of N"; the host renders nothing per step.
|
|
48
|
+
*
|
|
49
|
+
* - Password: minimum length + breached-password check, no composition rules.
|
|
50
|
+
* - "Change address" goes back to the account form with every input as typed.
|
|
51
|
+
* - The step (and the address awaiting its code, never the password) is kept in
|
|
52
|
+
* session storage: closing and reopening the host resumes it; a reload too.
|
|
53
|
+
* - Signed in when it mounts (e.g. a sign-up left after the code): the first app step
|
|
54
|
+
* (or the stored one), or `onDone` at once when there are none.
|
|
55
|
+
* - Forward slides in from the end side, back from the start side (RTL mirrored); no
|
|
56
|
+
* slide under reduced motion. Each change scrolls the step to the top and focuses
|
|
57
|
+
* its title; the code step focuses the code input.
|
|
58
|
+
* - Touch devices: the submit tap focuses a hidden input, so the keyboard is already
|
|
59
|
+
* open when the code input takes the focus (iOS opens it only from a tap).
|
|
60
|
+
*
|
|
61
|
+
* Needs a provider with `verifyEmailCode` (Supabase) and a confirmation email that
|
|
62
|
+
* sends the 6-digit code.
|
|
63
|
+
*
|
|
64
|
+
* @param props - EmailSignUpFlowProps
|
|
65
|
+
* @returns The flow
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* ```tsx
|
|
69
|
+
* <EmailSignUpFlow
|
|
70
|
+
* fields={<AuthNameField />}
|
|
71
|
+
* metadata={{ locale: i18n.language }}
|
|
72
|
+
* steps={[{ id: 'company', title: t('company.title'), render: ({ next }) => <Company onSaved={next} /> }]}
|
|
73
|
+
* onDone={close}
|
|
74
|
+
* />
|
|
75
|
+
* ```
|
|
76
|
+
*/
|
|
77
|
+
export declare function EmailSignUpFlow({ fields, metadata, steps, onStepChange, onDone, }: EmailSignUpFlowProps): import("react").JSX.Element;
|
|
78
|
+
//# sourceMappingURL=signUpFlow.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"signUpFlow.d.ts","sourceRoot":"","sources":["../../src/emailAuth/signUpFlow.tsx"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EAAa,SAAS,EAAO,MAAM,OAAO,CAAC;AAIvD,OAAO,KAAK,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAc/D,2EAA2E;AAC3E,MAAM,MAAM,iBAAiB,GAAG,SAAS,GAAG,MAAM,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC;AAEnE,iCAAiC;AACjC,MAAM,WAAW,sBAAsB;IACrC,0DAA0D;IAC1D,IAAI,EAAE,QAAQ,CAAC;IACf,8DAA8D;IAC9D,IAAI,EAAE,MAAM,IAAI,CAAC;IACjB,qFAAqF;IACrF,IAAI,CAAC,EAAE,MAAM,IAAI,CAAC;CACnB;AAED,4EAA4E;AAC5E,MAAM,WAAW,eAAe;IAC9B,2EAA2E;IAC3E,EAAE,EAAE,MAAM,CAAC;IACX,oEAAoE;IACpE,KAAK,EAAE,MAAM,CAAC;IACd,2BAA2B;IAC3B,WAAW,CAAC,EAAE,SAAS,CAAC;IACxB,yBAAyB;IACzB,MAAM,EAAE,CAAC,OAAO,EAAE,sBAAsB,KAAK,SAAS,CAAC;CACxD;AAED,wCAAwC;AACxC,MAAM,WAAW,oBAAoB;IACnC;;;;OAIG;IACH,MAAM,CAAC,EAAE,SAAS,CAAC;IACnB,sEAAsE;IACtE,QAAQ,CAAC,EAAE,cAAc,CAAC;IAC1B,yCAAyC;IACzC,KAAK,CAAC,EAAE,eAAe,EAAE,CAAC;IAC1B,4FAA4F;IAC5F,YAAY,CAAC,EAAE,CAAC,IAAI,EAAE,iBAAiB,KAAK,IAAI,CAAC;IACjD,qFAAqF;IACrF,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,QAAQ,KAAK,IAAI,CAAC;CACnC;AAED,oEAAoE;AACpE,eAAO,MAAM,wBAAwB,sBAAsB,CAAC;AAqI5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,wBAAgB,eAAe,CAAC,EAC9B,MAAM,EACN,QAAQ,EACR,KAAU,EACV,YAAY,EACZ,MAAM,GACP,EAAE,oBAAoB,+BA2StB"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use client";import{jsx as o,jsxs as f}from"react/jsx-runtime";import{useEffect as ee,useId as de,useLayoutEffect as te,useRef as u,useState as d}from"react";import{Button as me,BUTTON_VARIANT as fe,Stack as S,Text as q}from"@donotdev/components";import{safeSessionStorage as U,useTranslation as z}from"@donotdev/core";import{useAuth as ne}from"../useAuth";import{AuthCodeField as pe,AuthEmailField as he,AuthForm as we,AuthFormAlerts as ve,AuthPasswordField as ye,AuthSubmitButton as ge}from"./fields";import{useEmailCodeConfirmation as Se,useEmailSignUp as be}from"./flows";import{isEmail as Ee}from"./rules";const k="dndev.auth.signUp";function Ce(){const r=U.getItem(k);if(r===null)return null;try{const c=JSON.parse(r);if(typeof c!="object"||c===null)return null;const{step:t,email:i}=c;return typeof t!="string"||t==="account"||i!==void 0&&(typeof i!="string"||!Ee(i))||t==="code"&&i===void 0?null:i===void 0?{step:t}:{step:t,email:i}}catch{return null}}const x=r=>{r===null?U.removeItem(k):U.setItem(k,JSON.stringify(r))};function Ie(){if(U.removeItem("dndev.auth.returnTo"),typeof window>"u")return;const r=new URL(window.location.href);r.searchParams.has("returnTo")&&(r.searchParams.delete("returnTo"),window.history.replaceState(window.history.state,"",r))}const Ae=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&!window.matchMedia("(prefers-reduced-motion: reduce)").matches,Fe=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches,Ne={fontSize:"var(--font-size-input)"};function B({titleId:r,titleRef:c,title:t,description:i,position:p,total:h}){const{t:l}=z("auth");return f(S,{gap:"tight",children:[o(q,{as:"p",level:"caption",variant:"muted",children:l("signUpFlow.progress",{defaultValue:`Step ${p} of ${h}`,current:p,total:h})}),o(q,{as:"h2",level:"h3",id:r,ref:c,tabIndex:-1,children:t}),i!==void 0&&o(q,{variant:"muted",children:i})]})}function Te({email:r,onConfirmed:c,onChangeEmail:t}){const{t:i}=z("auth"),p=Se({email:r,onSuccess:c});return f(S,{children:[o(pe,{confirmation:p}),o(me,{type:"button",variant:fe.LINK,onClick:t,children:i("codeConfirmation.change_email",{defaultValue:"Change address"})})]})}function Ue({fields:r,metadata:c,steps:t=[],onStepChange:i,onDone:p}){const{t:h}=z("auth"),l=ne("user"),$=ne("status"),[s,G]=d("account"),[b,J]=d(null),[oe,re]=d(),[K,ie]=d(null),[ae,D]=d(null),[H,le]=d(0),[ce,ue]=d(0),[R,V]=d(!1),_=u(!1),I=u(!1),W=u(!1),Y=u(l),A=u(null),M=u(null),Q=u(null),F=u(null),N=u(null),w=de(),T=new Set(t.map(e=>e.id));if(T.has("account")||T.has("code")||T.size!==t.length)throw new Error('EmailSignUpFlow: step ids must be unique and not "account" or "code"');const m=t.findIndex(e=>e.id===s),L=l??ae,O=e=>{_.current||(_.current=!0,x(null),p?.(e))},v=(e,n,a=b)=>{G(e),ie(Ae()?n:null),le(C=>C+1),x(e==="account"?null:e==="code"&&a!==null?{step:e,email:a}:{step:e}),i?.(e)},X=e=>{if(I.current)return;I.current=!0;const n=t[0];n?v(n.id,"forward"):O(e)};te(()=>{const e=Ce(),n=e&&T.has(e.step)?e.step:null;let a="account";if(l){I.current=!0;const C=t[0];if(n)a=n;else if(C)a=C.id,x({step:C.id});else{O(l);return}}else e?.step==="code"&&e.email?(J(e.email),re(e.email),a="code"):n?(a=n,V(!0)):e&&x(null);a!=="account"&&G(a),i?.(a)},[]),ee(()=>{const e=Y.current;if(Y.current=l,!W.current){W.current=!0;return}if(l){R&&V(!1),(s==="account"||s==="code")&&X(l);return}(e!=null||R&&$==="ready")&&m>=0&&(V(!1),D(null),I.current=!1,_.current=!1,v("account","back"))},[l,$,R]),te(()=>{if(H===0)return;const e=F.current;e&&(e.scrollIntoView?.({block:"start"}),(s==="code"?e.querySelector("input"):N.current)?.focus({preventScroll:!0}))},[H]);const y=be({confirmation:"code",passwordComposition:!1,metadata:c,onSuccess:({awaitingConfirmation:e,email:n})=>{J(n),Ie(),e&&v("code","forward",n)}}),se=e=>{Fe()&&A.current&&(M.current=document.activeElement instanceof HTMLElement?document.activeElement:null,A.current.focus({preventScroll:!0}),ue(n=>n+1)),y.onSubmit(e)};ee(()=>{const e=A.current;if(!e||document.activeElement!==e||y.busy||s!=="account")return;const n=Q.current?.querySelector('[aria-invalid="true"]'),a=M.current;M.current=null,n?n.focus():a?.isConnected&&a!==e?a.focus():e.blur()},[ce,y.busy,y.fieldErrors,y.error,s]);const P=2+t.length,j=K===null?void 0:K==="forward"?"dndev-animate-step-forward":"dndev-animate-step-back",E=s==="account",g=m>=0?t[m]:void 0,Z=m>0?t[m-1]:void 0;return f(S,{children:[!g&&o("div",{ref:e=>{Q.current=e,E&&(F.current=e)},hidden:!E,role:"group","aria-labelledby":E?w:void 0,className:E?j:void 0,children:f(S,{children:[E&&o(B,{titleId:w,titleRef:N,title:h("signUpFlow.account_title",{defaultValue:"Create your account"}),position:1,total:P}),f(we,{flow:{...y,onSubmit:se},children:[o(he,{defaultValue:oe}),o(ye,{}),r,o(ve,{}),o(ge,{})]})]})}),s==="code"&&b!==null&&o("div",{ref:F,role:"group","aria-labelledby":w,className:j,children:f(S,{children:[o(B,{titleId:w,titleRef:N,title:h("signUpFlow.code_title",{defaultValue:"Check your email"}),description:h("codeConfirmation.intro",{defaultValue:`Enter the code sent to ${b}`,email:b}),position:2,total:P}),o(Te,{email:b,onConfirmed:e=>{D(e),X(e)},onChangeEmail:()=>v("account","back")})]})}),g&&o("div",{ref:F,role:"group","aria-labelledby":w,className:j,children:f(S,{children:[o(B,{titleId:w,titleRef:N,title:g.title,description:g.description,position:3+m,total:P}),L&&g.render({user:L,next:()=>{const e=t[m+1];e?v(e.id,"forward"):O(L)},...Z?{back:()=>v(Z.id,"back")}:{}})]})},g.id),o("input",{ref:A,type:"text",inputMode:"numeric",tabIndex:-1,"aria-hidden":"true",autoComplete:"off",className:"dndev-sr-only",style:Ne})]})}export{Ue as EmailSignUpFlow,k as SIGN_UP_FLOW_STORAGE_KEY};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useState as l,useCallback as t}from"react";function g({defaultValue:
|
|
1
|
+
"use client";import{useState as l,useCallback as t}from"react";function g({defaultValue:r="popup"}={}){const[o,e]=l(r),d=o==="redirect",u=o==="popup",i=t(()=>{e(p=>p==="redirect"?"popup":"redirect")},[]),s=t(()=>{e("redirect")},[]),a=t(()=>{e("popup")},[]),c=t(p=>{e(p?"redirect":"popup")},[]);return{isRedirectMode:d,isPopupMode:u,authMethod:o,toggleMode:i,setRedirectMode:s,setPopupMode:a,handleToggleChange:c}}export{g as useAuthMethodToggle};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useCallback as
|
|
1
|
+
"use client";import{useCallback as t}from"react";import{useAuth as o}from"../useAuth";function w(r,g={}){const p=o("getPartnerState"),e=o("setPartnerState"),d=o("signInWithPartner"),i=o("partnerError"),{onSuccess:s,onError:l}=g,c=p(r),E=c==="authenticated",S=c==="loading",n=i?.partnerId===r,f=n&&i?.error?new Error(i.error):null,u=t(()=>{n&&e(r,"idle")},[n,r,e]),m=t(()=>{e(r,"loading")},[r,e]),A=t(()=>{e(r,"idle")},[r,e]),P=t(async I=>{n&&u();try{e(r,"loading");const a=await d(r,I);if(a===null){e(r,"idle");return}a&&s&&s(a)}catch(a){const h=a;e(r,"error",h),l&&l(h)}},[r,n,u,e,d,s,l]);return{partnerState:c,isAuthenticated:E,isAuthenticating:S,hasError:n,error:f,handleSignIn:P,clearError:u,setLoading:m,setIdle:A}}export{w as useAuthPartner};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { AuthUserSummary } from '@donotdev/core';
|
|
2
|
+
/**
|
|
3
|
+
* Auth user list state
|
|
4
|
+
*
|
|
5
|
+
* @version 0.1.0
|
|
6
|
+
* @since 0.3.3
|
|
7
|
+
*/
|
|
8
|
+
export interface AuthUsersState {
|
|
9
|
+
/** Every auth account; empty until loaded */
|
|
10
|
+
users: AuthUserSummary[];
|
|
11
|
+
/** True while auth initialises or the list loads */
|
|
12
|
+
loading: boolean;
|
|
13
|
+
/** Load failure (not an admin, server function not deployed, network) */
|
|
14
|
+
error: Error | null;
|
|
15
|
+
/** Load the list again */
|
|
16
|
+
reload: () => Promise<void>;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Lists every auth account for admin pages. Loads once when auth is ready; the
|
|
20
|
+
* provider calls its admin-only `listAuthUsers` server function, which the app deploys
|
|
21
|
+
* (`createListAuthUsers` for Supabase, `listAuthUsers` for Firebase, from
|
|
22
|
+
* `@donotdev/functions`). A non-admin gets `error`, never a partial list.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```tsx
|
|
26
|
+
* const { users, loading, error, reload } = useAuthUsers();
|
|
27
|
+
* ```
|
|
28
|
+
*
|
|
29
|
+
* @returns `{ users, loading, error, reload }`
|
|
30
|
+
* @version 0.1.0
|
|
31
|
+
* @since 0.3.3
|
|
32
|
+
*/
|
|
33
|
+
export declare function useAuthUsers(): AuthUsersState;
|
|
34
|
+
//# sourceMappingURL=useAuthUsers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useAuthUsers.d.ts","sourceRoot":"","sources":["../../src/hooks/useAuthUsers.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAMtD;;;;;GAKG;AACH,MAAM,WAAW,cAAc;IAC7B,6CAA6C;IAC7C,KAAK,EAAE,eAAe,EAAE,CAAC;IACzB,oDAAoD;IACpD,OAAO,EAAE,OAAO,CAAC;IACjB,yEAAyE;IACzE,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IACpB,0BAA0B;IAC1B,MAAM,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7B;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,YAAY,IAAI,cAAc,CAqC7C"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use client";import{useCallback as A,useEffect as p,useRef as E,useState as n}from"react";import{FEATURE_STATUS as I}from"@donotdev/core";import{useAuthStore as S}from"../AuthStore";import{useAuth as h}from"../useAuth";function U(){const a=h("listUsers"),e=S(t=>t.status===I.INITIALIZING),[i,l]=n([]),[f,o]=n(!1),[m,c]=n(null),r=E(0),u=A(async()=>{const t=++r.current;o(!0),c(null);try{const s=await a();t===r.current&&l(s)}catch(s){t===r.current&&c(s instanceof Error?s:new Error(String(s)))}finally{t===r.current&&o(!1)}},[a]);return p(()=>{if(!e)return u(),()=>{r.current++}},[e,u]),{users:i,loading:e||f,error:m,reload:u}}export{U as useAuthUsers};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useState as l}from"react";import{useTranslation as
|
|
1
|
+
"use client";import{useState as l}from"react";import{useTranslation as g}from"@donotdev/core";import{useAuth as h}from"../useAuth";const f="deleteAccount.errors.",E=/^[A-Za-z0-9_-]+$/;function w(e){const s=typeof e=="object"&&e!==null&&"details"in e?e.details:void 0;return[s?.serverCode,s?.serverMessage,e instanceof Error?e.message:void 0].filter(o=>typeof o=="string"&&E.test(o))}function y(){const e=h("deleteAccount"),{t:s}=g("auth"),[o,t]=l(!1),[d,n]=l(!1),[m,c]=l(!1),[A,r]=l(null);return{showConfirmDialog:o,showPasswordDialog:d,isDeleting:m,error:A,startDeleteFlow:()=>{r(null),t(!0)},confirmDelete:async D=>{c(!0),r(null);try{await e(D),t(!1),n(!1)}catch(u){const a=u.message;if(a==="REQUIRES_PASSWORD")t(!1),n(!0);else if(a==="REAUTH_CANCELLED")t(!1),n(!1);else{const p=w(u).map(i=>s(`${f}${i}`)).find(i=>!i.startsWith(f));r(p??(a||"Failed to delete account"))}}finally{c(!1)}},cancel:()=>{t(!1),n(!1),r(null)}}}export{y as useDeleteAccount};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useState as r,useCallback as l}from"react";import{handleError as I}from"@donotdev/core";import{useAuth as f}from"../useAuth";function
|
|
1
|
+
"use client";import{useState as r,useCallback as l}from"react";import{handleError as I}from"@donotdev/core";import{useAuth as f}from"../useAuth";function v(S={}){const t=f("sendSignInLinkToEmail"),g=f("isAvailable"),{onSuccess:s,onError:o,actionCodeSettings:m}=S,[e,E]=r(""),[u,c]=r(!1),[h,d]=r(!1),[p,n]=r(null),i=e.trim().length>0&&e.includes("@"),k=i&&!u&&g,y=l(()=>{n(null)},[]),L=l(async w=>{if(w.preventDefault(),!i){n("Please enter a valid email address");return}c(!0),n(null);try{typeof window<"u"&&localStorage.setItem("emailForSignIn",e.trim()),await t(e.trim(),m),d(!0),s?.()}catch(a){const F=a instanceof Error?a.message:"Failed to send sign-in link";n(F),o?.(a),I(a)}finally{c(!1)}},[e,i,t,m,s,o]),b=l(()=>{d(!1),n(null)},[]);return{email:e,setEmail:E,isLoading:u,isSent:h,error:p,handleSendLink:L,handleResend:b,clearError:y,isValid:i,canSubmit:k}}export{v as useEmailLinkForm};
|