@donotdev/auth 0.3.1 → 0.3.3
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 +2 -2
- package/dist/components/DeleteAccountDialogs.js +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/FeaturePlaceholder.d.ts +3 -3
- package/dist/components/FeaturePlaceholder.js +1 -1
- package/dist/components/GoogleOneTap.js +1 -1
- package/dist/components/LoginModal.js +1 -1
- package/dist/components/MultipleAuthProviders.js +1 -1
- package/dist/components/NetworkStatusIndicator.js +1 -1
- package/dist/components/PasswordResetCallback.js +1 -1
- package/dist/components/PasswordStrengthIndicator.js +1 -1
- package/dist/components/PasswordUpdateDialog.js +1 -1
- package/dist/components/RateLimitAlert.js +1 -1
- package/dist/components/index.js +1 -1
- package/dist/constants.d.ts +9 -0
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +1 -1
- package/dist/emailAuth/fields.d.ts +65 -2
- package/dist/emailAuth/fields.d.ts.map +1 -1
- package/dist/emailAuth/fields.js +1 -1
- package/dist/emailAuth/flows.d.ts +182 -15
- package/dist/emailAuth/flows.d.ts.map +1 -1
- package/dist/emailAuth/flows.js +1 -1
- package/dist/emailAuth/rules.d.ts +33 -4
- package/dist/emailAuth/rules.d.ts.map +1 -1
- package/dist/emailAuth/rules.js +2 -2
- package/dist/hooks/useAccountLinking.js +1 -1
- 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/useEmailLinkAuth.js +1 -1
- package/dist/hooks/useEmailLinkForm.js +1 -1
- package/dist/hooks/useFedCM.js +1 -1
- package/dist/hooks/useGoogleOneTap.js +1 -1
- package/dist/hooks/useNetworkStatus.js +1 -1
- package/dist/index.d.ts +9 -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 +68 -2
- package/package.json +5 -5
package/dist/emailAuth/fields.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{jsx as
|
|
1
|
+
"use client";import{jsx as a,jsxs as f,Fragment as I}from"react/jsx-runtime";import{createContext as k,use as M,useId as p,useRef as D,useState as R}from"react";import{Alert as N,ALERT_VARIANT as E,Button as v,BUTTON_VARIANT as w,Checkbox as P,Dialog as O,Input as L,Label as K,PasswordInput as x,PinInput as j,Stack as m,Text as C,cn as B}from"@donotdev/components";import{useAppConfig as W,useTranslation as c}from"@donotdev/core";import{useAuth as $}from"../useAuth";import{PasswordStrengthIndicator as H}from"../components/PasswordStrengthIndicator";import{AUTH_FIELD as b,useEmailCodeConfirmation as U}from"./flows";const _=k(null);function h(){const e=M(_);if(!e)throw new Error("Auth fields must be rendered inside <AuthForm>");return e}function te({flow:e,children:n,className:t}){const{t:r}=c("auth");return e.unavailable?a(N,{variant:E.WARNING,title:r("unavailable.title","Authentication Unavailable"),description:r("unavailable.description","Sign-in is temporarily unavailable. Please try again later.")}):a(_,{value:e,children:a("form",{noValidate:!0,onSubmit:e.onSubmit,className:B("dndev-auth-form",t),children:a(m,{children:n})})})}function y({id:e,message:n}){return n?a(C,{as:"span",level:"caption",variant:"destructive",id:e,role:"alert",children:n}):null}function ne({label:e,placeholder:n,defaultValue:t}){const{t:r}=c("auth"),o=h(),i=p(),d=p(),s=o.fieldErrors.email;return f(m,{gap:"tight",children:[a(L,{id:i,name:b.EMAIL,type:"email",autoComplete:"username",label:e??r("email","Email"),placeholder:n??r("emailPlaceholder","Enter your email"),defaultValue:t,disabled:o.busy,"aria-invalid":!!s,"aria-describedby":s?d:void 0,"data-variant":s?"destructive":void 0,className:"dndev-w-full"}),a(y,{id:d,message:s})]})}function re({label:e,placeholder:n,defaultValue:t,info:r}){const{t:o}=c("auth"),i=h();return a(L,{name:b.DISPLAY_NAME,type:"text",autoComplete:"name",label:e??o("name","Name"),placeholder:n,defaultValue:t,info:r,disabled:i.busy,className:"dndev-w-full"})}function F(){const{t:e}=c("auth");return{show:e("passwordToggle.show",{defaultValue:"Show password"}),hide:e("passwordToggle.hide",{defaultValue:"Hide password"})}}function ae({label:e,placeholder:n}){const{t}=c("auth"),r=h(),o=p(),i=p(),[d,s]=R(""),l=r.mode==="signup",u=r.fieldErrors.password,g=F();return f(m,{gap:"tight",children:[a(x,{id:o,name:b.PASSWORD,autoComplete:l?"new-password":"current-password",revealAriaLabel:g,label:e??t("password","Password"),placeholder:n??t("passwordPlaceholder","Enter your password"),onInput:l?A=>s(A.target.value):void 0,disabled:r.busy,"aria-invalid":!!u,"aria-describedby":u?i:void 0,"data-variant":u?"destructive":void 0,className:"dndev-w-full"}),a(y,{id:i,message:u}),l&&d!==""&&a(H,{password:d,minLength:r.passwordMinLength,showRequirements:r.passwordComposition!==!1})]})}function oe({label:e,placeholder:n}){const{t}=c("auth"),r=h(),o=p(),i=p(),d=r.fieldErrors.confirmPassword,s=F();return f(m,{gap:"tight",children:[a(x,{id:o,name:b.CONFIRM_PASSWORD,autoComplete:"new-password",revealAriaLabel:s,label:e??t("confirmPassword","Confirm Password"),placeholder:n??t("confirmPasswordPlaceholder","Re-enter your password"),disabled:r.busy,"aria-invalid":!!d,"aria-describedby":d?i:void 0,"data-variant":d?"destructive":void 0,className:"dndev-w-full"}),a(y,{id:i,message:d})]})}function ie({label:e,defaultChecked:n=!0}){const{t}=c("auth"),r=h(),o=$("canRememberMe");return!r.ready||!o()?null:a(P,{name:b.REMEMBER_ME,defaultChecked:n,disabled:r.busy,label:e??t("rememberMe","Remember me")})}const Y={minHeight:"auto",padding:0,display:"inline"};function S({label:e,document:n}){const[t,r]=R(!1),o=typeof n=="string";return f(I,{children:[a(v,{type:"button",variant:w.LINK,onClick:()=>o?window.open(n,"_blank","noopener,noreferrer"):r(!0),className:"dndev-p-0 dndev-h-auto",style:Y,children:e}),!o&&a(O,{open:t,onOpenChange:r,title:e,showClose:!0,children:n})]})}function se({tos:e,privacy:n}){const{t}=c("auth"),r=h(),o=W("app"),i=p(),d=p(),s=(A,V)=>o?.footer?.legalLinks?.find(T=>T.path.includes(A))?.path??V,l=e===void 0?s("terms","/legal/terms"):e,u=n===void 0?s("privacy","/legal/privacy"):n;if(l===!1&&u===!1)return null;const g=r.fieldErrors.consent;return f(m,{gap:"tight",children:[f(m,{direction:"row",gap:"tight",align:"start",children:[a(P,{id:i,name:b.CONSENT,disabled:r.busy,"aria-invalid":!!g,"aria-describedby":g?d:void 0}),a(K,{htmlFor:i,children:f(C,{as:"span",level:"caption",children:[t("terms.accept_prefix","I accept the")," ",l!==!1&&a(S,{label:t("terms.tos","Terms of Service"),document:l}),l!==!1&&u!==!1&&f(I,{children:[" ",t("terms.and","and")," "]}),u!==!1&&a(S,{label:t("terms.privacy","Privacy Policy"),document:u})]})})]}),a(y,{id:d,message:g})]})}function de(){const{t:e}=c("auth"),n=h();if(!n.error)return null;const t=n.unconfirmedEmail;return f(m,{gap:"tight",children:[a(N,{variant:E.ERROR,description:n.error}),t&&a(v,{type:"button",variant:w.LINK,onClick:()=>{n.resendVerification(t)},children:e("signup.resend_verification","Resend verification email")})]})}function le({children:e}){const{t:n}=c("auth"),t=h(),r=t.mode==="signup"?n("actions.sign_up_submit","Create account"):t.mode==="reset"?n("forgotPassword.submit","Send reset link"):n("actions.sign_in_submit","Sign In");return a(v,{type:"submit",variant:w.PRIMARY,fullWidth:!0,loading:t.busy,disabled:!t.ready||t.blocked,children:e??r})}function q({confirmation:e,label:n}){const{t}=c("auth"),r=p(),o=D(null),{error:i,resent:d,resendIn:s}=e;return f(m,{gap:"tight",children:[a(j,{ref:o,value:e.code,onChange:e.setCode,onComplete:l=>{e.submit(l)},length:e.length,mask:!1,autoFocus:!0,label:n??t("codeConfirmation.label",{defaultValue:"Confirmation code"}),disabled:e.busy||!e.ready,digitAriaLabel:(l,u)=>t("codeConfirmation.digit",{defaultValue:`Digit ${l} of ${u}`,index:l,length:u}),"aria-invalid":!!i,"aria-describedby":i?r:void 0}),a(y,{id:r,message:i??void 0}),d&&a(C,{as:"span",level:"caption",variant:"success",role:"status",children:t("codeConfirmation.sent",{defaultValue:"A new code has been sent."})}),a(v,{type:"button",variant:w.LINK,loading:e.resending,disabled:s>0||!e.ready,onClick:()=>{e.resend().then(()=>o.current?.focus())},children:s>0?t("codeConfirmation.resend_in",{defaultValue:`Resend code in ${s} s`,seconds:s}):t("codeConfirmation.resend",{defaultValue:"Resend code"})})]})}function ue({email:e,length:n,onSuccess:t,onChangeEmail:r}){const{t:o}=c("auth"),i=U({email:e,length:n,onSuccess:t});return f(m,{children:[a(C,{variant:"muted",children:o("codeConfirmation.intro",{defaultValue:`Enter the code sent to ${e}`,email:e})}),a(q,{confirmation:i}),r&&a(v,{type:"button",variant:w.LINK,onClick:r,children:o("codeConfirmation.change_email",{defaultValue:"Change address"})})]})}export{q as AuthCodeField,ue as AuthCodeStep,oe as AuthConfirmPasswordField,se as AuthConsentField,ne as AuthEmailField,te as AuthForm,de as AuthFormAlerts,re as AuthNameField,ae as AuthPasswordField,ie as AuthRememberMeField,le as AuthSubmitButton};
|
|
@@ -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,6 +8,7 @@ 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
|
};
|
|
11
13
|
/** Which flow a form runs. */
|
|
12
14
|
export type EmailAuthMode = 'signin' | 'signup' | 'reset';
|
|
@@ -29,14 +31,40 @@ export interface EmailAuthFlowOptions {
|
|
|
29
31
|
*/
|
|
30
32
|
captchaToken?: string | null;
|
|
31
33
|
}
|
|
34
|
+
/** Options of {@link useEmailSignIn}. */
|
|
35
|
+
export interface EmailSignInOptions extends EmailAuthFlowOptions {
|
|
36
|
+
/**
|
|
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.
|
|
43
|
+
*/
|
|
44
|
+
confirmation?: EmailSignUpConfirmation;
|
|
45
|
+
/** Code mode: a fresh code was sent to this unconfirmed address; show the code step */
|
|
46
|
+
onCodeSent?: (email: string) => void;
|
|
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 {
|
|
@@ -75,12 +117,27 @@ 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;
|
|
78
125
|
}
|
|
126
|
+
/**
|
|
127
|
+
* The email check of every flow: the translated "required" / "invalid" message, or
|
|
128
|
+
* `undefined` when `email` (already trimmed) is valid.
|
|
129
|
+
*
|
|
130
|
+
* @param t - Translate function of the `auth` namespace
|
|
131
|
+
* @param email - The trimmed address
|
|
132
|
+
* @returns The error message, or `undefined`
|
|
133
|
+
*/
|
|
134
|
+
export declare const validateEmail: (t: AuthT, email: string) => string | undefined;
|
|
79
135
|
/**
|
|
80
136
|
* Email + password sign-in. Remember me is applied when the form renders
|
|
81
|
-
* `AuthRememberMeField
|
|
137
|
+
* `AuthRememberMeField`. An unconfirmed address offers a resend, or with
|
|
138
|
+
* `confirmation: 'code'` gets a fresh code and `onCodeSent(email)` (show `AuthCodeStep`).
|
|
82
139
|
*
|
|
83
|
-
* @param options - Callbacks
|
|
140
|
+
* @param options - Callbacks, CAPTCHA token, confirmation mode
|
|
84
141
|
* @returns The flow, for `AuthForm`
|
|
85
142
|
*
|
|
86
143
|
* @example
|
|
@@ -95,26 +152,136 @@ export interface EmailAuthFlow {
|
|
|
95
152
|
* </AuthForm>
|
|
96
153
|
* ```
|
|
97
154
|
*/
|
|
98
|
-
export declare function useEmailSignIn(options?:
|
|
155
|
+
export declare function useEmailSignIn(options?: EmailSignInOptions): EmailAuthFlow;
|
|
99
156
|
/**
|
|
100
|
-
* Email + password sign-up. Password policy
|
|
101
|
-
*
|
|
157
|
+
* Email + password sign-up. Password policy (`passwordComposition: false` = length
|
|
158
|
+
* only) and breached-password check apply; the confirmation field and consent are
|
|
159
|
+
* required when the form renders them. `AuthNameField`, when rendered and filled, is
|
|
160
|
+
* stored trimmed as the user's display name (metadata `full_name`); never required.
|
|
102
161
|
*
|
|
103
162
|
* Anti-enumeration: an address that already has an account ends exactly like a new
|
|
104
|
-
* one (
|
|
105
|
-
*
|
|
163
|
+
* one (`awaitingConfirmation: true`). When the provider asks for confirmation,
|
|
164
|
+
* `onSuccess` runs and then:
|
|
165
|
+
* - `confirmation: 'toast'` (default): a toast that stays until dismissed tells the
|
|
166
|
+
* user to confirm, with Resend;
|
|
167
|
+
* - `confirmation: 'code'`: nothing more; the app shows the code step for
|
|
168
|
+
* `outcome.email`. For an existing address the flow sends a password-reset
|
|
169
|
+
* email (`sendPasswordResetEmail`), fire-and-forget: a failure goes to
|
|
170
|
+
* `console.error`, never to the screen.
|
|
171
|
+
* A project that does not require confirmation signs the user in at once:
|
|
172
|
+
* `awaitingConfirmation: false`.
|
|
106
173
|
*
|
|
107
|
-
* @param options - Callbacks, CAPTCHA token, password
|
|
174
|
+
* @param options - Callbacks, CAPTCHA token, password policy, extra metadata,
|
|
175
|
+
* confirmation mode
|
|
108
176
|
* @returns The flow, for `AuthForm`
|
|
177
|
+
*
|
|
178
|
+
* @example
|
|
179
|
+
* ```tsx
|
|
180
|
+
* const [email, setEmail] = useState<string | null>(null);
|
|
181
|
+
* const flow = useEmailSignUp({
|
|
182
|
+
* confirmation: 'code',
|
|
183
|
+
* onSuccess: (outcome) => {
|
|
184
|
+
* if (outcome.awaitingConfirmation) setEmail(outcome.email);
|
|
185
|
+
* else close();
|
|
186
|
+
* },
|
|
187
|
+
* });
|
|
188
|
+
* ```
|
|
109
189
|
*/
|
|
110
190
|
export declare function useEmailSignUp(options?: EmailSignUpOptions): EmailAuthFlow;
|
|
191
|
+
/** Options of {@link usePasswordResetRequest}. */
|
|
192
|
+
export interface PasswordResetRequestOptions extends EmailAuthFlowOptions {
|
|
193
|
+
/**
|
|
194
|
+
* Confirm with a toast that stays until dismissed (default `true`). `false`: no
|
|
195
|
+
* toast; render the "check your inbox" message inline from `flow.sent`.
|
|
196
|
+
* @default true
|
|
197
|
+
*/
|
|
198
|
+
toast?: boolean;
|
|
199
|
+
}
|
|
200
|
+
/** The password-reset request flow: an {@link EmailAuthFlow} plus `sent`. */
|
|
201
|
+
export interface PasswordResetRequestFlow extends EmailAuthFlow {
|
|
202
|
+
/** The request went through (any address): `true` until the next submit */
|
|
203
|
+
sent: boolean;
|
|
204
|
+
}
|
|
111
205
|
/**
|
|
112
206
|
* 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
|
|
207
|
+
* has an account; `sent` turns `true`, `onSuccess` runs and a toast that stays until
|
|
208
|
+
* dismissed says to check the inbox (`toast: false`: no toast, the app shows the
|
|
209
|
+
* message inline from `sent`).
|
|
115
210
|
*
|
|
116
|
-
* @param options - Callbacks
|
|
211
|
+
* @param options - Callbacks, CAPTCHA token, toast opt-out
|
|
117
212
|
* @returns The flow, for `AuthForm`
|
|
118
213
|
*/
|
|
119
|
-
export declare function usePasswordResetRequest(options?:
|
|
214
|
+
export declare function usePasswordResetRequest(options?: PasswordResetRequestOptions): PasswordResetRequestFlow;
|
|
215
|
+
/** Options of {@link useEmailCodeConfirmation}. */
|
|
216
|
+
export interface EmailCodeConfirmationOptions {
|
|
217
|
+
/** The address that signed up (`EmailSignUpOutcome.email`) */
|
|
218
|
+
email: string;
|
|
219
|
+
/**
|
|
220
|
+
* Characters of the emailed code: match the provider (Supabase:
|
|
221
|
+
* `mailer_otp_length`).
|
|
222
|
+
* @default 6
|
|
223
|
+
*/
|
|
224
|
+
length?: number;
|
|
225
|
+
/**
|
|
226
|
+
* Seconds before the code can be sent again. The countdown starts at mount: the
|
|
227
|
+
* sign-up just sent a code.
|
|
228
|
+
* @default 60
|
|
229
|
+
*/
|
|
230
|
+
resendCooldownSeconds?: number;
|
|
231
|
+
/** Called with the signed-in user once the code is confirmed: close the sheet here */
|
|
232
|
+
onSuccess?: (user: AuthUser) => void;
|
|
233
|
+
/** Called with the provider error after a failed confirmation or resend */
|
|
234
|
+
onError?: (error: Error) => void;
|
|
235
|
+
}
|
|
236
|
+
/** What the code step needs from {@link useEmailCodeConfirmation}: pass it to `AuthCodeField`. */
|
|
237
|
+
export interface EmailCodeConfirmation {
|
|
238
|
+
/** The address the code was sent to */
|
|
239
|
+
email: string;
|
|
240
|
+
/** Characters of the code */
|
|
241
|
+
length: number;
|
|
242
|
+
/** The code typed so far */
|
|
243
|
+
code: string;
|
|
244
|
+
/** Update the typed code */
|
|
245
|
+
setCode: (code: string) => void;
|
|
246
|
+
/**
|
|
247
|
+
* Confirm the code (`code` by default; pass the value when it is not in state yet,
|
|
248
|
+
* e.g. from `onComplete`). A wrong or expired code clears the typed code.
|
|
249
|
+
*/
|
|
250
|
+
submit: (code?: string) => Promise<void>;
|
|
251
|
+
/** A confirmation is in progress */
|
|
252
|
+
busy: boolean;
|
|
253
|
+
/** Translated message of the last failure (wrong / expired code, throttle, failed resend...), or `null` */
|
|
254
|
+
error: string | null;
|
|
255
|
+
/**
|
|
256
|
+
* Send a new code (no-op while `resendIn > 0`) and restart the countdown. No toast:
|
|
257
|
+
* success sets `resent`, a failure sets `error`.
|
|
258
|
+
*/
|
|
259
|
+
resend: () => Promise<void>;
|
|
260
|
+
/** A new code was sent: `true` after a successful resend until the next submit or resend */
|
|
261
|
+
resent: boolean;
|
|
262
|
+
/** A resend is in progress */
|
|
263
|
+
resending: boolean;
|
|
264
|
+
/** Seconds left before `resend` is allowed (0 = allowed) */
|
|
265
|
+
resendIn: number;
|
|
266
|
+
/** The provider is ready (confirm and resend wait for it) */
|
|
267
|
+
ready: boolean;
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* The code step of a sign-up made with `useEmailSignUp({ confirmation: 'code' })`:
|
|
271
|
+
* the user types the emailed code, `useAuth('verifyEmailCode')` confirms it and signs
|
|
272
|
+
* the user in. Same client throttle as the email flows; wrong / expired code and rate
|
|
273
|
+
* limits get translated messages. Resend sends a new code with
|
|
274
|
+
* `useAuth('sendEmailVerification')` once the countdown is over. No toast: the
|
|
275
|
+
* outcome is state (`error`, `resent`) that `AuthCodeField` renders inline.
|
|
276
|
+
*
|
|
277
|
+
* @param options - Address, code length, resend cooldown, callbacks
|
|
278
|
+
* @returns The code step state, for `AuthCodeField`
|
|
279
|
+
*
|
|
280
|
+
* @example
|
|
281
|
+
* ```tsx
|
|
282
|
+
* const confirmation = useEmailCodeConfirmation({ email, length: 8, onSuccess: close });
|
|
283
|
+
* <AuthCodeField confirmation={confirmation} />
|
|
284
|
+
* ```
|
|
285
|
+
*/
|
|
286
|
+
export declare function useEmailCodeConfirmation(options: EmailCodeConfirmationOptions): EmailCodeConfirmation;
|
|
120
287
|
//# 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 F}from"react/jsx-runtime";import{useEffect as U,useRef as V,useState as A}from"react";import{Button as G,ToastAction as K,toast as C}from"@donotdev/components";import{useTranslation as X}from"@donotdev/core";import{useAuth as S}from"../useAuth";import{DEFAULT_CONFIRMATION_CODE_LENGTH as z,DEFAULT_PASSWORD_MIN_LENGTH as L,DEFAULT_RESEND_COOLDOWN_SECONDS as J,authErrorMessage as q,codeErrorMessage as B,isAlreadyRegisteredError as Q,isBreachedPassword as Z,isEmail as ee,isRateLimitError as j,isUnconfirmedError as H,newPasswordError as te}from"./rules";const c={EMAIL:"email",PASSWORD:"password",CONFIRM_PASSWORD:"confirmPassword",REMEMBER_ME:"rememberMe",CONSENT:"consent",DISPLAY_NAME:"displayName"},re="full_name",ne=6e4,se=5,ie=3e4;function Y(){const e=V([]),[t,r]=A(null);return U(()=>{if(t===null)return;const n=setTimeout(()=>r(null),Math.max(0,t-Date.now()));return()=>clearTimeout(n)},[t]),{attempt:()=>{const n=Date.now();return t!==null&&n<t?Math.ceil((t-n)/1e3):(e.current=e.current.filter(E=>n-E<ne),e.current.push(n),e.current.length>=se&&(e.current=[],r(n+ie)),0)},throttled:t!==null}}const N=e=>e instanceof Error?e:new Error(String(e)),_=(e,t)=>{const r=e.get(t);return typeof r=="string"?r:""},v=(e,t)=>{const r=e.elements.namedItem(t);return r instanceof HTMLInputElement?r:void 0};function $(){const{t:e}=X("auth");return(t,r,f)=>e(t,{defaultValue:r,...f})}function W(e,t){const r=$(),f=S("isAvailable"),n=S("status"),E=S("sendEmailVerification"),u=Y(),[g,y]=A(!1),[m,i]=A(null),[w,l]=A({}),[s,o]=A(null),d=t.captchaToken!==void 0&&!t.captchaToken,h=async a=>{try{await E(a),C("success",r("verificationSent","Verification email sent."))}catch(M){C("error",q(M,r))}};return{t:r,submit:async(a,M,P)=>{if(a.preventDefault(),g||d||!f)return;const b=a.currentTarget,R=new FormData(b),p=M(b,R);if(l(p),o(null),Object.keys(p).length>0){i(null);return}const O=u.attempt();if(O>0){i(r("errors.rate_limit_cooldown",`Too many attempts. Please wait ${O} seconds.`,{seconds:O}));return}i(null),y(!0);try{await P(b,R)}catch(T){e==="signin"&&H(T)&&o(_(R,c.EMAIL).trim()),i(q(T,r)),t.onError?.(N(T))}finally{y(!1)}},flow:(a,M,P)=>({mode:e,onSubmit:a,busy:g,ready:f,unavailable:n==="degraded"||n==="error",blocked:d||u.throttled,error:m,fieldErrors:w,unconfirmedEmail:s,resendVerification:h,passwordMinLength:M,...P===void 0?{}:{passwordComposition:P}}),resendVerification:h,setFieldErrors:l}}const x=(e,t)=>{if(t==="")return e("emailRequired","Email is required");if(!ee(t))return e("emailInvalid","Invalid email address")},k=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0));function de(e={}){const t=W("signin",e),{t:r}=t,f=S("signInWithEmail"),n=S("sendEmailVerification"),E=S("setRememberMe"),u=S("canRememberMe"),g=y=>{t.submit(y,(m,i)=>k({email:x(r,_(i,c.EMAIL).trim()),password:_(i,c.PASSWORD)===""?r("passwordRequired","Password is required"):void 0}),async(m,i)=>{const w=v(m,c.REMEMBER_ME);w&&u()&&await E(w.checked);const l=_(i,c.EMAIL).trim();try{const s=await f(l,_(i,c.PASSWORD));if(!s?.success)throw new Error(s?.error??"Sign in failed")}catch(s){if(e.confirmation!=="code"||!H(s))throw s;try{await n(l)}catch(o){if(!j(o))throw o}e.onCodeSent?.(l);return}e.onSuccess?.()})};return t.flow(g,L)}function fe(e={}){const t=W("signup",e),{t:r}=t,f=S("createUserWithEmail"),n=S("sendPasswordResetEmail"),E=e.passwordMinLength??L,u=e.confirmation??"toast",g=e.passwordComposition??!0,y=w=>{(async()=>{try{await n(w)}catch{}})()},m=w=>{C({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:F(K,{asChild:!0,altText:r("resendEmail","Resend email"),children:F(G,{onClick:()=>{t.resendVerification(w)},children:r("resendEmail","Resend email")})})})},i=w=>{t.submit(w,(l,s)=>{const o=_(s,c.PASSWORD),d=l.elements.namedItem(c.CONFIRM_PASSWORD),h=v(l,c.CONSENT);return k({email:x(r,_(s,c.EMAIL).trim()),password:te(o,E,r,g)??void 0,confirmPassword:d&&_(s,c.CONFIRM_PASSWORD)!==o?r("confirmPasswordMismatch","Passwords do not match"):void 0,consent:h&&!h.checked?r("terms.required","Please accept the terms to continue"):void 0})},async(l,s)=>{const o=_(s,c.EMAIL).trim(),d=_(s,c.PASSWORD);if(await Z(d)){t.setFieldErrors({password:r("errors.breached_password","This password has appeared in a data breach. Please choose a different password.")});return}const h=v(l,c.CONSENT),I=_(s,c.DISPLAY_NAME).trim(),D=h?.checked||I?{...e.metadata,...h?.checked?{gdpr_consent_at:new Date().toISOString()}:{},...I?{[re]:I}:{}}:e.metadata;try{const a=await f(o,d,D);if(!a?.success)throw new Error(a?.error??"Sign up failed");const M=!a.user?.emailVerified;e.onSuccess?.({awaitingConfirmation:M,email:o}),M&&u==="toast"&&m(o)}catch(a){if(!Q(a))throw a;e.onSuccess?.({awaitingConfirmation:!0,email:o}),u==="toast"?m(o):y(o)}})};return t.flow(i,E,e.passwordComposition)}function Ee(e={}){const t=W("reset",e),{t:r}=t,f=S("sendPasswordResetEmail"),[n,E]=A(!1),u=g=>{E(!1),t.submit(g,(y,m)=>k({email:x(r,_(m,c.EMAIL).trim())}),async(y,m)=>{try{await f(_(m,c.EMAIL).trim())}catch(i){if(j(i))throw i}E(!0),e.onSuccess?.(),e.toast!==!1&&C({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(u,L),sent:n}}function we(e){const t=$(),r=S("isAvailable"),f=S("verifyEmailCode"),n=S("sendEmailVerification"),E=Y(),u=e.length??z,g=e.resendCooldownSeconds??J,[y,m]=A(""),[i,w]=A(!1),[l,s]=A(!1),[o,d]=A(null),[h,I]=A(g),[D,a]=A(!1),M=V(!1);U(()=>{if(h<=0)return;const R=setTimeout(()=>I(p=>Math.max(0,p-1)),1e3);return()=>clearTimeout(R)},[h]);const P=async R=>{const p=(R??y).trim();if(M.current||!r)return;if(a(!1),p.length!==u){d(t("codeConfirmation.incomplete",`Enter the ${u}-digit code.`,{length:u}));return}const O=E.attempt();if(O>0){d(t("errors.rate_limit_cooldown",`Too many attempts. Please wait ${O} seconds.`,{seconds:O}));return}M.current=!0,d(null),w(!0);try{const T=await f(e.email,p);e.onSuccess?.(T)}catch(T){d(B(T,t)),m(""),e.onError?.(N(T))}finally{M.current=!1,w(!1)}},b=async()=>{if(!(h>0||l||!r)){s(!0),a(!1),d(null);try{await n(e.email),I(g),a(!0)}catch(R){d(B(R,t)),e.onError?.(N(R))}finally{s(!1)}}};return{email:e.email,length:u,code:y,setCode:m,submit:P,busy:i,error:o,resend:b,resending:l,resent:D,resendIn:h,ready:r}}export{c as AUTH_FIELD,we as useEmailCodeConfirmation,de as useEmailSignIn,fe as useEmailSignUp,Ee as usePasswordResetRequest,x as validateEmail};
|
|
@@ -2,7 +2,11 @@
|
|
|
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.
|
|
6
|
+
*
|
|
7
|
+
* Provider errors are recognised by their structured code first (the error's `code`,
|
|
8
|
+
* or the provider code `wrapAuthError` keeps in `details.originalCode`), then by
|
|
9
|
+
* their message.
|
|
6
10
|
*
|
|
7
11
|
* @version 0.1.0
|
|
8
12
|
* @since 0.2.3
|
|
@@ -18,15 +22,40 @@ export declare function isEmail(email: string): boolean;
|
|
|
18
22
|
export declare function isRateLimitError(error: unknown): boolean;
|
|
19
23
|
/** Provider error: the address exists but was never confirmed. */
|
|
20
24
|
export declare function isUnconfirmedError(error: unknown): boolean;
|
|
21
|
-
/**
|
|
25
|
+
/**
|
|
26
|
+
* Provider error: sign-up with an address that already has an account. Structured
|
|
27
|
+
* code first, message as the fallback (Supabase with confirmations on reports it as
|
|
28
|
+
* a fake user, which the provider turns into an "already exists" message).
|
|
29
|
+
*/
|
|
22
30
|
export declare function isAlreadyRegisteredError(error: unknown): boolean;
|
|
23
31
|
/** User-facing message for a provider error (rate limit, credentials, network...). */
|
|
24
32
|
export declare function authErrorMessage(error: unknown, t: AuthT): string;
|
|
33
|
+
/** Default number of characters of an emailed confirmation code. */
|
|
34
|
+
export declare const DEFAULT_CONFIRMATION_CODE_LENGTH = 6;
|
|
35
|
+
/** Default seconds before a confirmation code can be sent again. */
|
|
36
|
+
export declare const DEFAULT_RESEND_COOLDOWN_SECONDS = 60;
|
|
37
|
+
/** Provider error: the confirmation code is known to have expired. */
|
|
38
|
+
export declare function isCodeExpiredError(error: unknown): boolean;
|
|
39
|
+
/** Provider error: the confirmation code is wrong (or wrong or expired, see `otp_expired`). */
|
|
40
|
+
export declare function isInvalidCodeError(error: unknown): boolean;
|
|
41
|
+
/**
|
|
42
|
+
* User-facing message for a failed code confirmation or code resend: expired code,
|
|
43
|
+
* wrong code, rate limit (structured codes included), else `authErrorMessage`.
|
|
44
|
+
*/
|
|
45
|
+
export declare function codeErrorMessage(error: unknown, t: AuthT): string;
|
|
25
46
|
/**
|
|
26
47
|
* First rule a new password breaks, or `null`. Policy: minimum length (8 by default),
|
|
27
|
-
* one uppercase letter, one lowercase letter,
|
|
48
|
+
* then, unless `composition` is `false`, one uppercase letter, one lowercase letter,
|
|
49
|
+
* one digit, one special character.
|
|
50
|
+
*
|
|
51
|
+
* @param password - The new password
|
|
52
|
+
* @param minLength - Minimum length
|
|
53
|
+
* @param t - Translate function of the `auth` namespace
|
|
54
|
+
* @param composition - Apply the character-class rules (default `true`); `false` keeps
|
|
55
|
+
* only the empty check and the minimum length (NIST 800-63B: length over composition)
|
|
56
|
+
* @returns The message of the first broken rule, or `null`
|
|
28
57
|
*/
|
|
29
|
-
export declare function newPasswordError(password: string, minLength: number, t: AuthT): string | null;
|
|
58
|
+
export declare function newPasswordError(password: string, minLength: number, t: AuthT, composition?: boolean): string | null;
|
|
30
59
|
/**
|
|
31
60
|
* Whether the password appears in a known breach (HaveIBeenPwned range API: only the
|
|
32
61
|
* 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;;;;;;;;;;;;;GAaG;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;AA8CD,sFAAsF;AACtF,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK,GAAG,MAAM,CAMjE;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;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK,GAAG,MAAM,CAiBjE;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(
|
|
1
|
+
const p=8,f=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function _(e){return f.test(e)}const a=e=>(e instanceof Error?e.message:String(e)).toLowerCase();function h(e){if(typeof e!="object"||e===null)return[];const s=[];if("code"in e&&typeof e.code=="string"&&s.push(e.code),"details"in e&&typeof e.details=="object"&&e.details){const t=e.details.originalCode;typeof t=="string"&&s.push(t)}return s}const i=(e,s)=>h(e).some(t=>s.has(t));function d(e){const s=a(e);return s.includes("429")||s.includes("rate")||s.includes("too_many_requests")}function y(e){const s=a(e);return s.includes("email_not_confirmed")||s.includes("email not confirmed")||s.includes("auth/unverified-email")}const k=new Set(["user_already_exists","email_exists","auth/email-already-in-use","already-exists"]);function g(e){if(i(e,k))return!0;const s=a(e);return s.includes("already")||s.includes("exists")||s.includes("user_already_exists")||s.includes("auth/email-already-in-use")}const E=[{test:d,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,s){const t=a(e);for(const r of E)if(r.test(t))return s(r.key,r.fallback);return s("errorGeneric","Authentication failed. Please try again.")}const v=6,x=60,P=new Set(["auth/expired-action-code"]),l=new Set(["otp_expired","auth/invalid-action-code","auth/invalid-verification-code"]),b=new Set(["over_request_rate_limit","over_email_send_rate_limit","auth/too-many-requests","rate-limit-exceeded"]);function u(e){if(i(e,P))return!0;if(i(e,l))return!1;const s=a(e);return s.includes("expired")&&!s.includes("invalid")}function m(e){if(i(e,l))return!0;const s=a(e);return s.includes("expired or is invalid")||s.includes("invalid")&&(s.includes("code")||s.includes("token")||s.includes("otp"))}function A(e,s){return u(e)?s("errors.code_expired","This code has expired. Request a new code."):m(e)?s("errors.invalid_code","This code is incorrect or has expired. Check the email or request a new code."):i(e,b)?s("errors.rate_limit","Too many attempts. Please wait a moment and try again."):c(e,s)}function S(e,s,t,r=!0){return e===""?t("passwordRequired","Password is required"):e.length<s?t("passwordMinLength",`Password must be at least ${s} characters`,{count:s}):r?/[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 s=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(e)),t=Array.from(new Uint8Array(s)).map(n=>n.toString(16).padStart(2,"0")).join("").toUpperCase(),r=t.slice(0,5),w=t.slice(5),o=await fetch(`https://api.pwnedpasswords.com/range/${r}`,{headers:{"Add-Padding":"true"},credentials:"omit"});return o.ok?(await o.text()).split(`
|
|
2
|
+
`).some(n=>n.split(":")[0]?.trim()===w):!1}catch{return!1}}export{v as DEFAULT_CONFIRMATION_CODE_LENGTH,p as DEFAULT_PASSWORD_MIN_LENGTH,x as DEFAULT_RESEND_COOLDOWN_SECONDS,c as authErrorMessage,A as codeErrorMessage,g as isAlreadyRegisteredError,R as isBreachedPassword,u as isCodeExpiredError,_ as isEmail,m as isInvalidCodeError,d as isRateLimitError,y as isUnconfirmedError,S as newPasswordError};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useState as
|
|
1
|
+
"use client";import{useState as k,useEffect as v,useCallback as a}from"react";import{safeSessionStorage as e,handleError as p,isClient as t,isDev as r}from"@donotdev/core";import{getAuthMethod as L}from"../constants";import{useAuth as c}from"../useAuth";function P(){const s=c("signInWithPartner"),u=c("user"),[i,o]=k(null);v(()=>{if(t()){try{const n=e.getItem("accountLinkingInfo");if(n){const I=JSON.parse(n);o(I)}}catch{r()}return()=>{if(!t())return;const n=e.getItem("accountLinkingInfo");if(n)try{JSON.parse(n).isRequired||e.removeItem("accountLinkingInfo")}catch{}}}},[u]);const l=a(async()=>{if(!(!i||!i.isRequired))try{const{existingProvider:n}=i;if(n==="password"||n==="emailLink"){r();return}r(),await s(n,L())}catch(n){p(n)}},[i,s]),f=a(()=>{t()&&(e.removeItem("accountLinkingInfo"),o(null))},[]),g=i?.isRequired||!1,m=i?.email||null,d=i?.existingProvider||null,h=i?.newProvider||null;return{accountLinking:i,isRequired:g,email:m,existingProvider:d,newProvider:h,handleSignInWithExistingProvider:l,clearAccountLinking:f}}export{P as useAccountLinking};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useState as
|
|
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{useEffect as g,useState as
|
|
1
|
+
"use client";import{useEffect as g,useState as t,useCallback as E}from"react";import{handleError as k,isDev as s}from"@donotdev/core";import{useAuth as l}from"../useAuth";function p(){const o=l("isSignInWithEmailLink"),n=l("signInWithEmailLink"),[r,e]=t(!1),[m,a]=t(null),c=o();g(()=>{if(typeof window<"u"){const i=localStorage.getItem("emailForSignIn");i&&a(i)}},[]);const u=E(async i=>{if(!i){s();return}e(!0);try{s(),(await n(i))?.success&&(localStorage.removeItem("emailForSignIn"),a(null))}catch(f){k(f)}finally{e(!1)}},[n]);return{isEmailLink:c,isProcessing:r,email:m,completeEmailLinkSignIn:u}}export{p as useEmailLinkAuth};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useState as
|
|
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};
|
package/dist/hooks/useFedCM.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useState as
|
|
1
|
+
"use client";import{useState as s,useEffect as h,useMemo as C,useRef as E}from"react";import{handleError as S,isClient as u}from"@donotdev/core";function y({checkGoogleServices:a=!0,onError:i}={}){const[n,l]=s(!1),[m,d]=s(!1),[p,f]=s(null),c=E(i);c.current=i,h(()=>{u()&&(async()=>{try{const e="IdentityCredential"in window;let o=!0;if(a){const t=new Promise(r=>setTimeout(r,2e3));await Promise.race([new Promise(r=>{const w=setInterval(()=>{window.google?.accounts?.id&&(clearInterval(w),r(!0))},100)}),t]),o=!!window.google?.accounts?.id}l(e&&o),d(!0)}catch(e){const o=S(e,{userMessage:"Failed to detect FedCM support",context:{operation:"fedcm_detection"},severity:"warning"});f(o),d(!0),c.current?.(o)}})()},[a]);const g=C(()=>{if(!u())return{name:"Unknown",isSupported:!1,recommendation:"Loading..."};const e=navigator.userAgent;let o="Unknown",t="Please update your browser";if(e.includes("Chrome/")){const r=parseInt(e.match(/Chrome\/(\d+)/)?.[1]||"0");o=`Chrome ${r}`,t=r>=116?"Supported":"Please update to Chrome 116 or later"}else if(e.includes("Edg/")){const r=parseInt(e.match(/Edg\/(\d+)/)?.[1]||"0");o=`Edge ${r}`,t=r>=116?"Supported":"Please update to Edge 116 or later"}else e.includes("Safari/")&&!e.includes("Chrome")?(o="Safari",t="Not supported yet. Please use Chrome or Edge"):e.includes("Firefox/")&&(o="Firefox",t="Not supported yet. Please use Chrome or Edge");return{name:o,isSupported:n,recommendation:t}},[n]);return{isSupported:n,isReady:m,error:p,browserInfo:g}}export{y as useFedCM};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useState as
|
|
1
|
+
"use client";import{useState as G,useEffect as L,useRef as f,useCallback as j,startTransition as _,useMemo as B}from"react";import{useIsDark as oe}from"@donotdev/components";import{handleError as g,getOAuthClientId as te,getEnabledAuthPartners as re,isClient as ne,useTranslation as ae,useScriptLoader as ie}from"@donotdev/core";import{useAuth as J}from"../useAuth";import{useFedCM as se}from"./useFedCM";function ce({clientId:Q,autoSelect:x=!0,cancelOnTapOutside:v=!0,promptParentId:y,disabled:l=!1,onSuccess:C,onError:i,allowedParentOrigins:N,cspNonce:S,clientOnly:R=!1}={}){const{t:n}=ae("auth"),T=J("user"),A=J("signInWithGoogleCredential"),I=oe(),s=Q||te("google"),E=re().includes("google"),{isSupported:r,isReady:d,error:F,browserInfo:U}=se({checkGoogleServices:!0,onError:o=>{const t=g(o,{userMessage:n("auth.fedcmNotSupported","Your browser does not support Google One Tap"),context:{operation:"fedcm_detection"},severity:"warning"});i?.(t)}}),{isLoading:V,isLoaded:O,error:P,isReady:q,load:X,loadTriggered:Z}=ie("https://accounts.google.com/gsi/client",{enabled:E&&!!s&&!l&&d&&r,nonce:S,checkExisting:!0,isLoaded:()=>!!window.google?.accounts?.id,onError:o=>{const t=g(o,{userMessage:n("auth.googleScriptLoadError","Failed to load Google Identity Services"),context:{operation:"google_script_load"},severity:"error"});i?.(t)}}),[b,$]=G(!1),[z,Y]=G(null),K=f(null),a=f(!1),c=f(null),D=f(0),[H,p]=G(!1),m="gsi_hide_until",w=600*1e3,M=B(()=>E&&!!s&&!l&&!T&&r&&(R?b:!0)&&!H,[E,s,l,T,r,R,b,H]),ee=B(()=>!r&&d?new Error(n("auth.fedcmRequired","Google One Tap requires a modern browser (Chrome 116+ or Edge 116+)")):P||F||z,[P,F,z,r,d,n]),h=j(async o=>{try{if(!o||typeof o!="string")throw new Error("Invalid credential format");await A(o),_(()=>{C?.(o)})}catch(t){const e=g(t,{userMessage:n("auth.googleOneTapError","Google One Tap authentication failed"),context:{operation:"google_one_tap_signin",credentialLength:o?.length||0},severity:"error"});throw _(()=>{Y(e)}),i?.(e),e}},[A,C,i,n]),k=j(()=>{if(!ne()||!q||!s||!window.google?.accounts?.id||!r||a.current)return;const o=Date.now();if(!(o-D.current<w&&D.current>0))try{a.current=!0,D.current=o;const t={client_id:s,callback:async e=>{try{await h(e.credential)}catch(W){g(W,{userMessage:"Google One Tap credential handling failed",context:{operation:"google_one_tap_callback"},severity:"error"})}},auto_select:x,cancel_on_tap_outside:v,context:"signin",ux_mode:"popup",itp_support:!0,state:I?"dark":"light",use_fedcm_for_prompt:!0,allowed_parent_origins:N,csp_nonce:S,moment_callback:e=>{const W=e.getMomentType();if(e.isDisplayMoment?.()){if(!e.isDisplayed?.()&&e.getNotDisplayedReason){a.current=!1;try{const u=Date.now()+w;localStorage.setItem(m,String(u)),p(!0)}catch{}}}else if(e.isSkippedMoment?.()){a.current=!1;try{const u=Date.now()+w;localStorage.setItem(m,String(u)),p(!0)}catch{}}else if(e.isDismissedMoment?.()){a.current=!1;try{const u=Date.now()+w;localStorage.setItem(m,String(u)),p(!0)}catch{}}}};y&&(t.prompt_parent_id=y),window.google.accounts.id.initialize(t),c.current&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{window.google?.accounts?.id?.prompt(e=>{e?.credential&&h(e.credential)}),c.current=null},100)}catch(t){const e=g(t,{userMessage:n("auth.googleOneTapInitError","Failed to initialize Google One Tap"),context:{operation:"google_one_tap_initialize",fedcmSupported:r},severity:"error"});_(()=>{Y(e)}),i?.(e),a.current=!1}},[q,s,r,x,v,y,I,h,i,N,S,n]);return L(()=>{if(typeof window<"u"){_(()=>{$(!0)});try{const o=Number(localStorage.getItem(m)||0);p(o>Date.now())}catch{}}},[]),L(()=>{O&&!l&&M&&d&&k()},[O,l,M,d,k]),L(()=>()=>{c.current&&window.clearTimeout(c.current),a.current=!1},[]),{isLoaded:O,isLoading:V,error:ee,user:T,isDark:I,fedcmSupported:r,isHydrated:b,containerRef:K,initialize:k,handleCredential:h,shouldShow:M,browserInfo:U,triggerLoad:X,loadTriggered:Z}}export{ce as useGoogleOneTap};
|