@donotdev/auth 0.3.3 → 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/dist/components/EmailLinkForm.d.ts.map +1 -1
- package/dist/components/EmailLinkForm.js +1 -1
- package/dist/components/EmailPasswordForm.d.ts +1 -1
- package/dist/components/EmailPasswordForm.d.ts.map +1 -1
- package/dist/components/EmailPasswordForm.js +1 -1
- package/dist/components/FeaturePlaceholder.d.ts +3 -3
- 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 +0 -6
- 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 +10 -3
- package/dist/emailAuth/fields.d.ts.map +1 -1
- package/dist/emailAuth/fields.js +1 -1
- package/dist/emailAuth/flows.d.ts +19 -10
- package/dist/emailAuth/flows.d.ts.map +1 -1
- package/dist/emailAuth/flows.js +1 -1
- package/dist/emailAuth/rules.d.ts +12 -4
- 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/index.d.ts +2 -0
- 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.js +1 -1
- package/guidelines/AUTH.md +53 -0
- package/package.json +5 -5
package/dist/useAuth.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useEffect as ce,useCallback 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
|
@@ -211,6 +211,38 @@ Firebase records no confirmation time: a verified Firebase address carries the a
|
|
|
211
211
|
| `'toast'` (default) | Toast "Check your email" with Resend; the link in the email confirms | Form error with "Resend verification email" | All |
|
|
212
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
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
|
+
|
|
214
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).
|
|
215
247
|
|
|
216
248
|
**Composed (sheet, own fields):**
|
|
@@ -248,6 +280,27 @@ return (
|
|
|
248
280
|
|
|
249
281
|
---
|
|
250
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
|
+
|
|
302
|
+
---
|
|
303
|
+
|
|
251
304
|
## User Roles
|
|
252
305
|
|
|
253
306
|
**Role hierarchy:** `guest (0) < user (1) < admin (2) < super (3)`
|
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",
|