@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
package/dist/useAuth.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAuth.d.ts","sourceRoot":"","sources":["../src/useAuth.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAKV,OAAO,EAER,MAAM,gBAAgB,CAAC;AA+KxB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6DG;AACH,wBAAgB,OAAO,CAAC,CAAC,SAAS,MAAM,OAAO,EAAE,GAAG,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,
|
|
1
|
+
{"version":3,"file":"useAuth.d.ts","sourceRoot":"","sources":["../src/useAuth.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAKV,OAAO,EAER,MAAM,gBAAgB,CAAC;AA+KxB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6DG;AACH,wBAAgB,OAAO,CAAC,CAAC,SAAS,MAAM,OAAO,EAAE,GAAG,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAwdnE"}
|
package/dist/useAuth.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useEffect as
|
|
1
|
+
"use client";import{useEffect as ce,useCallback as t,useMemo as I}from"react";import{DoNotDevError as E,ERROR_CODES as g,DEGRADED_AUTH_API as U,FEATURE_STATUS as h,handleError as oe,hasProvider as le,getProvider as fe,isClient as s,USER_ROLES as A,SUBSCRIPTION_TIERS as w,hasRoleAccess as v,hasTierAccess as he,getGlobalSingleton as de,useAuthSessionSnapshot as me}from"@donotdev/core";import{useAuthStore as c}from"./AuthStore";import{getAuthMethod as M}from"./constants";const e=de("auth-provider",()=>({instance:null,initializing:!1,errorNotified:!1,unsubscribe:null}));function W(i){const l=r=>{const u=i();if(v(u.user?.role,A.ADMIN))return!0;const f=u.userProfile?.permissions;return f?f.includes(r):!1};return{navigate:r=>{const u=i();return r===!1?!0:r===!0?!!u.user:!(r.required&&!u.user||r.role&&!v(u.user?.role,r.role)||r.tier&&!he(u.userSubscription?.tier??w.FREE,r.tier)||r.validate&&(!u.userSubscription||!u.user?.role||!r.validate(u.user.role,u.userSubscription.tier)))},view:r=>l(`${r}:view`),edit:r=>l(`${r}:edit`),delete:r=>l(`${r}:delete`),create:r=>l(`${r}:create`),has:r=>l(r),perform:(r,u)=>{const f=i();if(v(f.user?.role,A.ADMIN))return!0;if(!l(r))return!1;if(u){const S=f.userProfile?.capabilities;if(S?.[r]){const p=S[r];for(const[y,R]of Object.entries(u))if(typeof p[y]=="number"&&typeof R=="number"&&R>p[y])return!1}}return!0}}}const L=new Set(["user","loading","error","status","userProfile","userSubscription","emailVerification","passwordResetPending","partnerError","getPartnerState","setPartnerState"]);function Ee(i){return L.has(i)}function ge(i){ce(()=>{if(!s())return;const{status:n}=c.getState();return n===h.READY||e.initializing?void 0:(e.initializing=!0,(async()=>{try{if(le("auth"))e.instance=fe("auth");else{const{getFirebaseAuth:a}=await import("@donotdev/firebase");e.instance=a()}if(!e.instance)return;"setStore"in e.instance&&e.instance.setStore(c.getState()),c.getState().setAuthService(e.instance),await e.instance.initialize(),e.unsubscribe||(e.unsubscribe=e.instance.onAuthStateChanged(()=>{})),e.errorNotified=!1}catch(a){c.getState().setStatus(h.DEGRADED),e.errorNotified||(oe(a,{userMessage:"Authentication initialization failed",context:{operation:"useAuth.initialize"},severity:"warning",showNotification:!1}),e.errorNotified=!0)}finally{e.initializing=!1}})(),()=>{e.initializing=!1})},[]);const l=t(async(n,a)=>!s()||!e.instance?null:e.instance.signInWithEmail(n,a),[]),r=t(async(n,a,m)=>!s()||!e.instance?null:e.instance.createUserWithEmail(n,a,m),[]),u=t(async(n,a)=>{if(!s()||!e.instance)return null;const m=M(a);return e.instance.signInWithPartner(n,m)},[]),f=t(async(n,a)=>{if(!s()||!e.instance)return null;const m=M(a);return e.instance.linkWithPartner(n,m)},[]),S=t(async n=>!s()||!e.instance?null:e.instance.signInWithGoogleCredential(n),[]),p=t(async()=>{if(!(!s()||!e.instance))return e.instance.signOut()},[]),y=t(async n=>{if(!(!s()||!e.instance))return e.instance.sendPasswordResetEmail(n)},[]),R=t(async n=>{if(!(!s()||!e.instance))return e.instance.updatePassword(n)},[]),G=t(async n=>!s()||!e.instance?.verifyPasswordResetCode?null:e.instance.verifyPasswordResetCode(n),[]),k=t(async(n,a)=>{if(!(!s()||!e.instance?.confirmPasswordReset))return e.instance.confirmPasswordReset(n,a)},[]),V=t(async n=>{if(!(!s()||!e.instance))return e.instance.sendEmailVerification(n)},[]),z=t(async(n,a)=>{if(!s()||!e.instance)throw new E("Authentication is not ready",g.UNAVAILABLE,{source:"auth"});if(!e.instance.verifyEmailCode)throw new E("Email confirmation by code is not supported by this auth provider",g.UNIMPLEMENTED,{source:"auth"});return e.instance.verifyEmailCode(n,a)},[]),O=t(async(n,a)=>{if(!(!s()||!e.instance))return e.instance.sendSignInLinkToEmail(n,a)},[]),F=t(async(n,a)=>!s()||!e.instance?null:e.instance.signInWithEmailLink(n,a),[]),_=t(n=>!s()||!e.instance?!1:e.instance.isSignInWithEmailLink(n),[]),$=t(async()=>!s()||!e.instance?null:e.instance.getCurrentUser(),[]),B=t(async()=>!s()||!e.instance?{status:"pending"}:e.instance.getEmailVerificationStatus(),[]),x=t(async()=>!s()||!e.instance?!1:e.instance.isEmailVerificationEnabled(),[]),Y=t(async n=>!s()||!e.instance?!1:e.instance.hasRole(n),[]),Z=t(async n=>!s()||!e.instance?!1:e.instance.hasTier(n),[]),j=t(async n=>!s()||!e.instance?!1:e.instance.hasFeature(n),[]),q=t(()=>s()?c.getState().getCustomClaims():{},[]),H=t(n=>s()?c.getState().getCustomClaim(n):null,[]),J=t(async n=>{if(!(!s()||!e.instance))return e.instance.reauthenticateWithPassword(n)},[]),K=t(async(n,a)=>{if(!(!s()||!e.instance))return e.instance.reauthenticateWithProvider(n,a)},[]),Q=t(async n=>{if(!(!s()||!e.instance))return e.instance.deleteAccount(n)},[]),X=t(async()=>{if(!s()||!e.instance)throw new E("Authentication is not ready",g.UNAVAILABLE,{source:"auth"});if(!e.instance.listUsers)throw new E("Listing users is not supported by this auth provider",g.UNIMPLEMENTED,{source:"auth"});return e.instance.listUsers()},[]),P=t(()=>{const n=e.instance;return!s()||!n?.setRememberMe?!1:n.supportsRememberMe?n.supportsRememberMe():!0},[]),ee=t(async n=>{if(!P()||!e.instance?.setRememberMe)throw new E("Remember me is not supported by this auth provider",g.UNIMPLEMENTED,{source:"auth"});return e.instance.setRememberMe(n)},[P]),C={signInWithEmail:l,createUserWithEmail:r,signInWithPartner:u,linkWithPartner:f,signInWithGoogleCredential:S,signOut:p,sendPasswordResetEmail:y,updatePassword:R,verifyPasswordResetCode:G,confirmPasswordReset:k,sendEmailVerification:V,verifyEmailCode:z,getEmailVerificationStatus:B,isEmailVerificationEnabled:x,sendSignInLinkToEmail:O,signInWithEmailLink:F,isSignInWithEmailLink:_,getCurrentUser:$,reauthenticateWithPassword:J,reauthenticateWithProvider:K,deleteAccount:Q,listUsers:X,setRememberMe:ee,canRememberMe:P,hasRole:Y,hasTier:Z,hasFeature:j,getCustomClaims:q,getCustomClaim:H},N=new Set(["isAuthenticated","userRole","userTier","can"]),ne=c(n=>Ee(i)?n[i]:null),ie=c(n=>N.has(i)?i==="isAuthenticated"?!!n.user:i==="userRole"?n.user?.role||A.GUEST:i==="userTier"?n.userSubscription?.tier||w.FREE:null:null),T=c(n=>n.status),o=me(),D=T===h.INITIALIZING&&o!==null,b=D?h.READY:T,te=c(n=>i==="can"?n.user:null),se=c(n=>i==="can"?n.userProfile:null),re=c(n=>i==="can"?n.userSubscription:null),ae=I(()=>W(c.getState),[te,se,re]),d=I(()=>o===null?null:{user:o.user,userProfile:o.user?{userId:o.user.id,role:o.user.role}:null,userSubscription:o.user?o.userSubscription??null:null},[o]),ue=I(()=>d===null?null:W(()=>d),[d]);if(i==="status")return b;if(D){if(i==="userSubscription")return d?.userSubscription;if(i==="userProfile")return d?.userProfile;if(i==="userTier")return d?.userSubscription?.tier??w.FREE;if(i==="can")return ue;if(i==="user")return o.user;if(i==="isAuthenticated")return!!o.user;if(i==="userRole")return o.user?.role||A.GUEST}return b===h.INITIALIZING||b===h.DEGRADED||b===h.ERROR?U[i]:i==="isAvailable"?!0:L.has(i)?ne:i in C?C[i]:i==="can"?ae:N.has(i)?ie:U[i]}export{ge as useAuth};
|
package/guidelines/AUTH.md
CHANGED
|
@@ -180,6 +180,125 @@ const signOut = useAuth('signOut');
|
|
|
180
180
|
|
|
181
181
|
**Pre-configured:** `AuthHeader` in layout (null if auth disabled), OAuth callbacks, session management, account linking.
|
|
182
182
|
|
|
183
|
+
### Admin: list users
|
|
184
|
+
|
|
185
|
+
`useAuthUsers()` lists every auth account for admin pages (emails, confirmation, sign-in dates), read from the auth backend itself: no user table, no copy.
|
|
186
|
+
|
|
187
|
+
```tsx
|
|
188
|
+
import { useAuthUsers } from '@donotdev/auth';
|
|
189
|
+
|
|
190
|
+
const { users, loading, error, reload } = useAuthUsers();
|
|
191
|
+
// users: AuthUserSummary[] = { id, email, emailConfirmedAt, createdAt, lastSignInAt, displayName }
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
Loads once auth is ready, through `useAuth('listUsers')` (throws `UNIMPLEMENTED` on a provider without it). Deploy the admin-only server function; non-admin callers are refused, surfaced as `error`:
|
|
195
|
+
|
|
196
|
+
| Backend | Deploy |
|
|
197
|
+
|---------|--------|
|
|
198
|
+
| Supabase | `supabase/functions/list-auth-users/index.ts`: `import { createListAuthUsers } from '@donotdev/functions/supabase'; Deno.serve(createListAuthUsers());` |
|
|
199
|
+
| Firebase | `functions/src/index.ts`: `import { listAuthUsers as frameworkListAuthUsers } from '@donotdev/functions/firebase'; export const listAuthUsers = frameworkListAuthUsers();` |
|
|
200
|
+
|
|
201
|
+
Firebase records no confirmation time: a verified Firebase address carries the account creation time as `emailConfirmedAt`.
|
|
202
|
+
|
|
203
|
+
---
|
|
204
|
+
|
|
205
|
+
## Email Sign-Up Confirmation
|
|
206
|
+
|
|
207
|
+
`useEmailSignUp` (the flow behind `EmailPasswordForm` and the `Auth*Field` pieces) ends a sign-up that needs confirmation in one of two ways (`confirmation` option). `useEmailSignIn` takes the same option for an address that was never confirmed:
|
|
208
|
+
|
|
209
|
+
| `confirmation` | Sign-up | Sign-in of an unconfirmed address | Provider |
|
|
210
|
+
|---|---|---|---|
|
|
211
|
+
| `'toast'` (default) | Toast "Check your email" with Resend; the link in the email confirms | Form error with "Resend verification email" | All |
|
|
212
|
+
| `'code'` | No toast. `onSuccess({ awaitingConfirmation: true, email })`: show the code step | A fresh code is sent (`sendEmailVerification`), then `onCodeSent(email)`: show the code step. A rate-limited resend (a code went out moments ago) still calls `onCodeSent`: that code stays valid; other resend errors are the form error | Implements `verifyEmailCode` (Supabase) |
|
|
213
|
+
|
|
214
|
+
**Sign-up, whole flow, app fields and steps included: `EmailSignUpFlow`.** Account (email, password, the app's `fields`) → 6-digit emailed code → the app's `steps` → `onDone(user)`. The flow renders each step's title, description and "Step n of N" (i18n `auth:signUpFlow.*`, `auth:codeConfirmation.intro`); the host (sheet, page) renders nothing per step. No toast: every error and "new code sent" is inline.
|
|
215
|
+
|
|
216
|
+
```tsx
|
|
217
|
+
import { AuthNameField, EmailSignUpFlow } from '@donotdev/auth';
|
|
218
|
+
|
|
219
|
+
<EmailSignUpFlow
|
|
220
|
+
fields={<AuthNameField info={t('nameHelp')} />} // inside the form, after the password
|
|
221
|
+
metadata={{ locale: i18n.language }} // user_metadata (name / consent added for you)
|
|
222
|
+
steps={[{ id: 'company', title: t('company.title'), description: t('company.lead'),
|
|
223
|
+
render: ({ user, next, back }) => <CompanyStep user={user} onSaved={next} /> }]}
|
|
224
|
+
onStepChange={(step) => setShowLoginLink(step === 'account')} // optional
|
|
225
|
+
onDone={close}
|
|
226
|
+
/>
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
| Prop | Why |
|
|
230
|
+
|---|---|
|
|
231
|
+
| `fields` | App fields in the account form, read at submit like the framework ones (`AuthNameField`, `AuthConsentField`, a privacy link) |
|
|
232
|
+
| `metadata` | App sign-up metadata (e.g. `locale` = the confirmation email's language) |
|
|
233
|
+
| `steps` | App steps after the code: `{ id, title, description?, render({ user, next, back? }) }`; `back` is absent on the first (the account exists by then); ids must be unique, not `account` / `code` |
|
|
234
|
+
| `onStepChange` | The host reacts to the step (`'account'`, `'code'`, an app step id), the first one included |
|
|
235
|
+
| `onDone` | Signed in and the last step done: close the host |
|
|
236
|
+
|
|
237
|
+
Fixed behaviour (no props):
|
|
238
|
+
- **Password:** minimum length (8) + breached-password check, no composition rules (NIST SP 800-63B-4 §3.1.1.2: composition rules SHALL NOT be imposed; blocklist check SHALL). Code length 6 (Supabase default `mailer_otp_length`), resend countdown 60 s, anti-enumeration as below.
|
|
239
|
+
- **"Change address"** goes back to the account form with every input as typed (the form stays mounted, hidden, until signed in).
|
|
240
|
+
- **Host closes / reload:** the step and the address awaiting its code (never the password) are kept in `sessionStorage` (`dndev.auth.signUp`, via `safeSessionStorage`): reopening resumes the code step (the resend countdown restarts at 60 s). A stored app step resumes only when signed in. Cleared on "Change address", sign-out, `onDone`.
|
|
241
|
+
- **Signed in at mount** (e.g. a sign-up left after the code): the stored app step, else the first; no app steps: `onDone` at once.
|
|
242
|
+
- **Transition:** the entering step fades in, sliding from the end side (forward) or the start side (back), RTL mirrored (`dndev-animate-step-*`, `--dur-normal`, `--ease-in-out`); no slide under reduced motion.
|
|
243
|
+
- **Focus:** each change scrolls the step to the top and focuses its title; the code step focuses the code input. Touch devices: the submit tap focuses a hidden input (inside the tap, so iOS opens the keyboard), the code input takes the focus over when the code step shows: no extra tap. A submit that stays on the account step gives the focus to the invalid field, else back where it was. (Device verification on iOS Safari: pending.)
|
|
244
|
+
- **Needs:** a provider with `verifyEmailCode` (Supabase) and a confirmation template with the code (`{{ .Token }}`). Other password rules: compose the pieces below. CAPTCHA: built in, see [CAPTCHA (Turnstile)](#captcha-turnstile).
|
|
245
|
+
|
|
246
|
+
**Whole flow, no app code:** `<EmailPasswordForm confirmation="code" onSuccess={close} />` (sign-up or unconfirmed sign-in → code step → signed in → `onSuccess`; "Change address" goes back to the form).
|
|
247
|
+
|
|
248
|
+
**Composed (sheet, own fields):**
|
|
249
|
+
|
|
250
|
+
```tsx
|
|
251
|
+
import { AuthCodeStep, AuthEmailField, AuthForm, AuthFormAlerts, AuthNameField,
|
|
252
|
+
AuthPasswordField, AuthSubmitButton, useEmailSignUp } from '@donotdev/auth';
|
|
253
|
+
|
|
254
|
+
const [email, setEmail] = useState<string | null>(null);
|
|
255
|
+
const flow = useEmailSignUp({
|
|
256
|
+
confirmation: 'code',
|
|
257
|
+
passwordComposition: false, // optional: length only (default true)
|
|
258
|
+
onSuccess: (outcome) => (outcome.awaitingConfirmation ? setEmail(outcome.email) : next()),
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
if (email) return <AuthCodeStep email={email} onSuccess={next} onChangeEmail={() => setEmail(null)} />;
|
|
262
|
+
return (
|
|
263
|
+
<AuthForm flow={flow}>
|
|
264
|
+
<AuthNameField info={t('nameHelp')} />
|
|
265
|
+
<AuthEmailField />
|
|
266
|
+
<AuthPasswordField />
|
|
267
|
+
<AuthFormAlerts />
|
|
268
|
+
<AuthSubmitButton />
|
|
269
|
+
</AuthForm>
|
|
270
|
+
);
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
- **`AuthNameField`** (`name="displayName"`, `label`, `info`, `placeholder`, `defaultValue`): the name the user wants in emails. Never required, never validated. Filled: sign-up stores it trimmed as metadata `full_name` (the provider's `displayName`); empty: nothing.
|
|
274
|
+
- **`AuthCodeStep`** (`email`, `length?`, `onSuccess?`, `onChangeEmail?`): "Enter the code sent to {email}", `AuthCodeField`, Resend with countdown, "A new code has been sent." inline after a resend (the code input has focus again), and "Change address" when `onChangeEmail` is given. No toast. Lower level: `useEmailCodeConfirmation(...)` + `<AuthCodeField confirmation={...} />` (`confirmation.resent`, `confirmation.error`).
|
|
275
|
+
- **Anti-enumeration:** a new address, an unconfirmed one and an already confirmed one end on the same screen (`awaitingConfirmation: true`). Supabase sends no email to an already confirmed address, so in code mode the flow sends that address a password-reset email instead (`sendPasswordResetEmail`, fire-and-forget; word the recovery template to also cover "you already have an account"). Its failure is logged, never shown.
|
|
276
|
+
- **Code step:** `length` (default 6) must match the provider (Supabase `mailer_otp_length`); the confirmation email template must contain the code (`{{ .Token }}`). `resendCooldownSeconds` (default 60) counts down from mount; Resend uses `sendEmailVerification(email)`; its outcome is inline (`resent` / `error`), never a toast. Wrong / expired codes and rate limits get translated messages (`errors.invalid_code`, `errors.code_expired`, `errors.rate_limit`). Success signs the user in.
|
|
277
|
+
- **`passwordComposition: false`:** only the minimum length applies (no uppercase / lowercase / digit / special rules, no requirements checklist); the breached-password check stays.
|
|
278
|
+
- **Password reset without toast:** `usePasswordResetRequest({ toast: false })` shows no toast; render the "check your inbox" message from `flow.sent` (true after a request, until the next submit). Default `toast: true` is unchanged.
|
|
279
|
+
- **Same validation in app forms:** `validateEmail(t, email)`, `isEmail`, `newPasswordError(password, minLength, t, composition)`, `DEFAULT_PASSWORD_MIN_LENGTH` and the `AuthT` type are exported: an app form validates exactly like the flows.
|
|
280
|
+
|
|
281
|
+
---
|
|
282
|
+
|
|
283
|
+
## CAPTCHA (Turnstile)
|
|
284
|
+
|
|
285
|
+
Supabase Auth only (Cloudflare Turnstile). Framework-owned: no prop, no app code. The switch is the public env var `TURNSTILE_SITE_KEY`; without it there is no script, no widget and no token.
|
|
286
|
+
|
|
287
|
+
**What the framework does** (source: `@donotdev/core` `captcha.ts`, `@donotdev/auth` `emailAuth/captcha.tsx`, `@donotdev/supabase` `client/auth.ts`):
|
|
288
|
+
- **Widget:** `AuthSubmitButton` renders it just above the button, so every `AuthForm` has it (`EmailPasswordForm`, `EmailSignUpFlow`, app compositions); `AuthCodeField` above Resend; `EmailLinkForm` above its submit. Theme `auto`, the app language, full width, `interaction-only`: hidden unless Cloudflare asks the visitor to interact (Managed widget: a checkbox for suspicious visitors; Invisible widget: never shown). It renders when the form mounts, so a token is usually ready at submit; Cloudflare refreshes an expired one.
|
|
289
|
+
- **Tokens:** each gated call takes one fresh single-use token from the most recently mounted widget, which then resets for the next call (sign-up then the existing-account reset email = two tokens). No token yet: the call waits (submit button busy) up to 60 s. A gated call with no widget mounted (toast Resend, direct `useAuth` call) gets a one-off widget at the bottom of the page.
|
|
290
|
+
- **Gated calls** (send `captchaToken`): sign-up, password sign-in and re-authentication, magic link / OTP, resend of the confirmation code or email, password-reset request. Not gated: code confirmation (`verifyOtp`), OAuth, password update, token refresh.
|
|
291
|
+
- **Errors:** inline form error `errors.captcha_failed` (script blocked, widget error, timeout, or the server refused the token: GoTrue code `captcha_failed`); the password-reset request shows it too (other reset errors stay hidden, anti-enumeration).
|
|
292
|
+
- **CSP:** the header policy allows `https://challenges.cloudflare.com` in `script-src` and `frame-src` for every `@donotdev/supabase` app.
|
|
293
|
+
- **Firebase:** unaffected (App Check with reCAPTCHA, `RECAPTCHA_SITE_KEY`). **Expo:** no Turnstile; do not enable CAPTCHA on a Supabase project an Expo app signs in to.
|
|
294
|
+
|
|
295
|
+
**Enable (in this order):**
|
|
296
|
+
1. Cloudflare dashboard > Turnstile > Add widget: mode **Managed** (or Invisible), hostnames = every domain that serves the auth forms (production, `localhost` for dev, preview domains: a hostname not listed fails every gated call). Note the site key and the secret key.
|
|
297
|
+
2. Set the site key in every app on the project (Supabase CAPTCHA is project-wide: the shop and the admin alike): `VITE_TURNSTILE_SITE_KEY` (Vite) / `NEXT_PUBLIC_TURNSTILE_SITE_KEY` (Next), in `.env` and in the host's env; deploy. The widget runs, tokens are sent; the server ignores them until step 3.
|
|
298
|
+
3. Last: turn it on in Supabase. Dashboard: Authentication > Bot and Abuse Protection > Enable CAPTCHA protection, provider Turnstile, the secret key. Or the Management API: `PATCH https://api.supabase.com/v1/projects/<ref>/config/auth` with `{ "security_captcha_enabled": true, "security_captcha_provider": "turnstile", "security_captcha_secret": "<secret>" }`. Enabling it before step 2 is live breaks every sign-up, sign-in and reset. Scripts that call Supabase Auth directly with the public key (e2e fixtures, workers) need a token too, or the service-role key.
|
|
299
|
+
|
|
300
|
+
**Test keys** (Cloudflare, any hostname): site `1x00000000000000000000AA` visible, always passes; `3x00000000000000000000FF` visible, forces the interactive challenge; `2x00000000000000000000AB` visible, always fails; `1x00000000000000000000BB` invisible, passes. Secret `1x0000000000000000000000000000000AA` always passes.
|
|
301
|
+
|
|
183
302
|
---
|
|
184
303
|
|
|
185
304
|
## User Roles
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@donotdev/auth",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.4",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -43,10 +43,10 @@
|
|
|
43
43
|
"type-check": "bunx tsc --noEmit"
|
|
44
44
|
},
|
|
45
45
|
"peerDependencies": {
|
|
46
|
-
"@donotdev/components": "^0.3.
|
|
47
|
-
"@donotdev/core": "^0.3.
|
|
48
|
-
"@donotdev/firebase": "^0.3.
|
|
49
|
-
"@donotdev/supabase": "^0.3.
|
|
46
|
+
"@donotdev/components": "^0.3.5",
|
|
47
|
+
"@donotdev/core": "^0.3.4",
|
|
48
|
+
"@donotdev/firebase": "^0.3.4",
|
|
49
|
+
"@donotdev/supabase": "^0.3.4",
|
|
50
50
|
"lucide-react": "*",
|
|
51
51
|
"react": "^19.3.1",
|
|
52
52
|
"react-dom": "^19.3.1",
|