@donotdev/auth 0.3.2 → 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 +1 -1
- 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/LoginModal.js +1 -1
- package/dist/components/MultipleAuthProviders.js +1 -1
- package/dist/constants.d.ts +9 -0
- package/dist/constants.d.ts.map +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/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 +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 +66 -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 s,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 i,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(t){const l=r=>{const u=t();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=t();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=t();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(t){return L.has(t)}function ge(t){ce(()=>{if(!i())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=s(async(n,a)=>!i()||!e.instance?null:e.instance.signInWithEmail(n,a),[]),r=s(async(n,a,m)=>!i()||!e.instance?null:e.instance.createUserWithEmail(n,a,m),[]),u=s(async(n,a)=>{if(!i()||!e.instance)return null;const m=M(a);return e.instance.signInWithPartner(n,m)},[]),f=s(async(n,a)=>{if(!i()||!e.instance)return null;const m=M(a);return e.instance.linkWithPartner(n,m)},[]),S=s(async n=>!i()||!e.instance?null:e.instance.signInWithGoogleCredential(n),[]),p=s(async()=>{if(!(!i()||!e.instance))return e.instance.signOut()},[]),y=s(async n=>{if(!(!i()||!e.instance))return e.instance.sendPasswordResetEmail(n)},[]),R=s(async n=>{if(!(!i()||!e.instance))return e.instance.updatePassword(n)},[]),G=s(async n=>!i()||!e.instance?.verifyPasswordResetCode?null:e.instance.verifyPasswordResetCode(n),[]),k=s(async(n,a)=>{if(!(!i()||!e.instance?.confirmPasswordReset))return e.instance.confirmPasswordReset(n,a)},[]),V=s(async n=>{if(!(!i()||!e.instance))return e.instance.sendEmailVerification(n)},[]),z=s(async(n,a)=>{if(!i()||!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=s(async(n,a)=>{if(!(!i()||!e.instance))return e.instance.sendSignInLinkToEmail(n,a)},[]),F=s(async(n,a)=>!i()||!e.instance?null:e.instance.signInWithEmailLink(n,a),[]),_=s(n=>!i()||!e.instance?!1:e.instance.isSignInWithEmailLink(n),[]),$=s(async()=>!i()||!e.instance?null:e.instance.getCurrentUser(),[]),B=s(async()=>!i()||!e.instance?{status:"pending"}:e.instance.getEmailVerificationStatus(),[]),x=s(async()=>!i()||!e.instance?!1:e.instance.isEmailVerificationEnabled(),[]),Y=s(async n=>!i()||!e.instance?!1:e.instance.hasRole(n),[]),Z=s(async n=>!i()||!e.instance?!1:e.instance.hasTier(n),[]),j=s(async n=>!i()||!e.instance?!1:e.instance.hasFeature(n),[]),q=s(()=>i()?c.getState().getCustomClaims():{},[]),H=s(n=>i()?c.getState().getCustomClaim(n):null,[]),J=s(async n=>{if(!(!i()||!e.instance))return e.instance.reauthenticateWithPassword(n)},[]),K=s(async(n,a)=>{if(!(!i()||!e.instance))return e.instance.reauthenticateWithProvider(n,a)},[]),Q=s(async n=>{if(!(!i()||!e.instance))return e.instance.deleteAccount(n)},[]),X=s(async()=>{if(!i()||!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=s(()=>{const n=e.instance;return!i()||!n?.setRememberMe?!1:n.supportsRememberMe?n.supportsRememberMe():!0},[]),ee=s(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(t)?n[t]:null),te=c(n=>N.has(t)?t==="isAuthenticated"?!!n.user:t==="userRole"?n.user?.role||A.GUEST:t==="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,se=c(n=>t==="can"?n.user:null),ie=c(n=>t==="can"?n.userProfile:null),re=c(n=>t==="can"?n.userSubscription:null),ae=I(()=>W(c.getState),[se,ie,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(t==="status")return b;if(D){if(t==="userSubscription")return d?.userSubscription;if(t==="userProfile")return d?.userProfile;if(t==="userTier")return d?.userSubscription?.tier??w.FREE;if(t==="can")return ue;if(t==="user")return o.user;if(t==="isAuthenticated")return!!o.user;if(t==="userRole")return o.user?.role||A.GUEST}return b===h.INITIALIZING||b===h.DEGRADED||b===h.ERROR?U[t]:t==="isAvailable"?!0:L.has(t)?ne:t in C?C[t]:t==="can"?ae:N.has(t)?te:U[t]}export{ge as useAuth};
|
package/guidelines/AUTH.md
CHANGED
|
@@ -180,6 +180,72 @@ 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
|
+
**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
|
+
|
|
216
|
+
**Composed (sheet, own fields):**
|
|
217
|
+
|
|
218
|
+
```tsx
|
|
219
|
+
import { AuthCodeStep, AuthEmailField, AuthForm, AuthFormAlerts, AuthNameField,
|
|
220
|
+
AuthPasswordField, AuthSubmitButton, useEmailSignUp } from '@donotdev/auth';
|
|
221
|
+
|
|
222
|
+
const [email, setEmail] = useState<string | null>(null);
|
|
223
|
+
const flow = useEmailSignUp({
|
|
224
|
+
confirmation: 'code',
|
|
225
|
+
passwordComposition: false, // optional: length only (default true)
|
|
226
|
+
onSuccess: (outcome) => (outcome.awaitingConfirmation ? setEmail(outcome.email) : next()),
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
if (email) return <AuthCodeStep email={email} onSuccess={next} onChangeEmail={() => setEmail(null)} />;
|
|
230
|
+
return (
|
|
231
|
+
<AuthForm flow={flow}>
|
|
232
|
+
<AuthNameField info={t('nameHelp')} />
|
|
233
|
+
<AuthEmailField />
|
|
234
|
+
<AuthPasswordField />
|
|
235
|
+
<AuthFormAlerts />
|
|
236
|
+
<AuthSubmitButton />
|
|
237
|
+
</AuthForm>
|
|
238
|
+
);
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
- **`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.
|
|
242
|
+
- **`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`).
|
|
243
|
+
- **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.
|
|
244
|
+
- **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.
|
|
245
|
+
- **`passwordComposition: false`:** only the minimum length applies (no uppercase / lowercase / digit / special rules, no requirements checklist); the breached-password check stays.
|
|
246
|
+
- **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.
|
|
247
|
+
- **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.
|
|
248
|
+
|
|
183
249
|
---
|
|
184
250
|
|
|
185
251
|
## 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.3",
|
|
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.4",
|
|
47
|
+
"@donotdev/core": "^0.3.3",
|
|
48
|
+
"@donotdev/firebase": "^0.3.3",
|
|
49
|
+
"@donotdev/supabase": "^0.3.3",
|
|
50
50
|
"lucide-react": "*",
|
|
51
51
|
"react": "^19.3.1",
|
|
52
52
|
"react-dom": "^19.3.1",
|