@donotdev/auth 0.3.0 → 0.3.1
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/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.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.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.js +1 -1
- package/dist/emailAuth/fields.js +1 -1
- package/dist/emailAuth/flows.js +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/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.js +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/useAuth.js +1 -1
- package/guidelines/AUTH.md +4 -4
- package/package.json +5 -5
package/dist/useAuth.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useEffect as
|
|
1
|
+
"use client";import{useEffect as ie,useCallback as i,useMemo as A}from"react";import{DoNotDevError as se,ERROR_CODES as ae,DEGRADED_AUTH_API as M,FEATURE_STATUS as h,handleError as ue,hasProvider as ce,getProvider as oe,isClient as s,USER_ROLES as b,SUBSCRIPTION_TIERS as I,hasRoleAccess as w,hasTierAccess as le,getGlobalSingleton as fe,useAuthSessionSnapshot as me}from"@donotdev/core";import{useAuthStore as c}from"./AuthStore";import{getAuthMethod as C}from"./constants";const e=fe("auth-provider",()=>({instance:null,initializing:!1,errorNotified:!1,unsubscribe:null}));function N(n){const f=r=>{const a=n();if(w(a.user?.role,b.ADMIN))return!0;const m=a.userProfile?.permissions;return m?m.includes(r):!1};return{navigate:r=>{const a=n();return r===!1?!0:r===!0?!!a.user:!(r.required&&!a.user||r.role&&!w(a.user?.role,r.role)||r.tier&&!le(a.userSubscription?.tier??I.FREE,r.tier)||r.validate&&(!a.userSubscription||!a.user?.role||!r.validate(a.user.role,a.userSubscription.tier)))},view:r=>f(`${r}:view`),edit:r=>f(`${r}:edit`),delete:r=>f(`${r}:delete`),create:r=>f(`${r}:create`),has:r=>f(r),perform:(r,a)=>{const m=n();if(w(m.user?.role,b.ADMIN))return!0;if(!f(r))return!1;if(a){const E=m.userProfile?.capabilities;if(E?.[r]){const S=E[r];for(const[p,R]of Object.entries(a))if(typeof S[p]=="number"&&typeof R=="number"&&R>S[p])return!1}}return!0}}}const U=new Set(["user","loading","error","status","userProfile","userSubscription","emailVerification","passwordResetPending","partnerError","getPartnerState","setPartnerState"]);function he(n){return U.has(n)}function Re(n){ie(()=>{if(!s())return;const{status:t}=c.getState();return t===h.READY||e.initializing?void 0:(e.initializing=!0,(async()=>{try{if(ce("auth"))e.instance=oe("auth");else{const{getFirebaseAuth:l}=await import("@donotdev/firebase");e.instance=l()}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(l){c.getState().setStatus(h.DEGRADED),e.errorNotified||(ue(l,{userMessage:"Authentication initialization failed",context:{operation:"useAuth.initialize"},severity:"warning",showNotification:!1}),e.errorNotified=!0)}finally{e.initializing=!1}})(),()=>{e.initializing=!1})},[]);const f=i(async(t,u)=>!s()||!e.instance?null:e.instance.signInWithEmail(t,u),[]),r=i(async(t,u,l)=>!s()||!e.instance?null:e.instance.createUserWithEmail(t,u,l),[]),a=i(async(t,u)=>{if(!s()||!e.instance)return null;const l=C(u);return e.instance.signInWithPartner(t,l)},[]),m=i(async(t,u)=>{if(!s()||!e.instance)return null;const l=C(u);return e.instance.linkWithPartner(t,l)},[]),E=i(async t=>!s()||!e.instance?null:e.instance.signInWithGoogleCredential(t),[]),S=i(async()=>{if(!(!s()||!e.instance))return e.instance.signOut()},[]),p=i(async t=>{if(!(!s()||!e.instance))return e.instance.sendPasswordResetEmail(t)},[]),R=i(async t=>{if(!(!s()||!e.instance))return e.instance.updatePassword(t)},[]),y=i(async t=>!s()||!e.instance?.verifyPasswordResetCode?null:e.instance.verifyPasswordResetCode(t),[]),G=i(async(t,u)=>{if(!(!s()||!e.instance?.confirmPasswordReset))return e.instance.confirmPasswordReset(t,u)},[]),L=i(async t=>{if(!(!s()||!e.instance))return e.instance.sendEmailVerification(t)},[]),O=i(async(t,u)=>{if(!(!s()||!e.instance))return e.instance.sendSignInLinkToEmail(t,u)},[]),V=i(async(t,u)=>!s()||!e.instance?null:e.instance.signInWithEmailLink(t,u),[]),z=i(t=>!s()||!e.instance?!1:e.instance.isSignInWithEmailLink(t),[]),_=i(async()=>!s()||!e.instance?null:e.instance.getCurrentUser(),[]),F=i(async()=>!s()||!e.instance?{status:"pending"}:e.instance.getEmailVerificationStatus(),[]),$=i(async()=>!s()||!e.instance?!1:e.instance.isEmailVerificationEnabled(),[]),K=i(async t=>!s()||!e.instance?!1:e.instance.hasRole(t),[]),Y=i(async t=>!s()||!e.instance?!1:e.instance.hasTier(t),[]),B=i(async t=>!s()||!e.instance?!1:e.instance.hasFeature(t),[]),Z=i(()=>s()?c.getState().getCustomClaims():{},[]),j=i(t=>s()?c.getState().getCustomClaim(t):null,[]),q=i(async t=>{if(!(!s()||!e.instance))return e.instance.reauthenticateWithPassword(t)},[]),x=i(async(t,u)=>{if(!(!s()||!e.instance))return e.instance.reauthenticateWithProvider(t,u)},[]),H=i(async t=>{if(!(!s()||!e.instance))return e.instance.deleteAccount(t)},[]),P=i(()=>{const t=e.instance;return!s()||!t?.setRememberMe?!1:t.supportsRememberMe?t.supportsRememberMe():!0},[]),J=i(async t=>{if(!P()||!e.instance?.setRememberMe)throw new se("Remember me is not supported by this auth provider",ae.UNIMPLEMENTED,{source:"auth"});return e.instance.setRememberMe(t)},[P]),v={signInWithEmail:f,createUserWithEmail:r,signInWithPartner:a,linkWithPartner:m,signInWithGoogleCredential:E,signOut:S,sendPasswordResetEmail:p,updatePassword:R,verifyPasswordResetCode:y,confirmPasswordReset:G,sendEmailVerification:L,getEmailVerificationStatus:F,isEmailVerificationEnabled:$,sendSignInLinkToEmail:O,signInWithEmailLink:V,isSignInWithEmailLink:z,getCurrentUser:_,reauthenticateWithPassword:q,reauthenticateWithProvider:x,deleteAccount:H,setRememberMe:J,canRememberMe:P,hasRole:K,hasTier:Y,hasFeature:B,getCustomClaims:Z,getCustomClaim:j},T=new Set(["isAuthenticated","userRole","userTier","can"]),Q=c(t=>he(n)?t[n]:null),X=c(t=>T.has(n)?n==="isAuthenticated"?!!t.user:n==="userRole"?t.user?.role||b.GUEST:n==="userTier"?t.userSubscription?.tier||I.FREE:null:null),W=c(t=>t.status),o=me(),D=W===h.INITIALIZING&&o!==null,g=D?h.READY:W,k=c(t=>n==="can"?t.user:null),ee=c(t=>n==="can"?t.userProfile:null),te=c(t=>n==="can"?t.userSubscription:null),ne=A(()=>N(c.getState),[k,ee,te]),d=A(()=>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]),re=A(()=>d===null?null:N(()=>d),[d]);if(n==="status")return g;if(D){if(n==="userSubscription")return d?.userSubscription;if(n==="userProfile")return d?.userProfile;if(n==="userTier")return d?.userSubscription?.tier??I.FREE;if(n==="can")return re;if(n==="user")return o.user;if(n==="isAuthenticated")return!!o.user;if(n==="userRole")return o.user?.role||b.GUEST}return g===h.INITIALIZING||g===h.DEGRADED||g===h.ERROR?M[n]:n==="isAvailable"?!0:U.has(n)?Q:n in v?v[n]:n==="can"?ne:T.has(n)?X:M[n]}export{Re as useAuth};
|
package/guidelines/AUTH.md
CHANGED
|
@@ -102,11 +102,11 @@ export const meta: PageMeta = {
|
|
|
102
102
|
With `createBrowserClient` (session in cookies), `dndev` generates `src/proxy.next.ts`. On every page request (not `api`, `_next`, files):
|
|
103
103
|
|
|
104
104
|
- **No auth cookie** (`sb-<ref>-auth-token`, `hasSupabaseSessionCookie`): signed out, nothing verified or written; `auth` pages redirect to `authRoute` (no `authRoute`: rendered per request, the page's `AuthGuard` decides), every other page is served from the cache (see "Cached pages" below).
|
|
105
|
-
- **Auth cookie:** `refreshSupabaseSession` (`@donotdev/supabase/server`)
|
|
105
|
+
- **Auth cookie:** `refreshSupabaseSession` (`@donotdev/supabase/server`) verifies each authenticated page request and refreshes an expired token as needed: `getUser()` against Auth for documents (network latency), local `getClaims()` (JWKS, asymmetric signing keys) for RSC soft navigations and prefetches. Redirects use the verified result only: `auth` pages send a signed-out visitor to `authRoute` (`?returnTo=`), `signedInRedirect` pages send a signed-in one to their target. Auth rejection / refresh failure = signed out. Supabase unreachable = unknown, no redirect.
|
|
106
106
|
- Signed in or unknown: the page renders per request (internal rewrite to `src/app/dndev-session/…`, `src/app/[lang]/dndev-session/…` with 2+ languages; a direct request to that path is a 404).
|
|
107
107
|
- **`auth` pages have no cached copy:** they are generated only in the per-request tree, and every visitor who is not redirected gets them per request. They read the request on the server, query string included (`useSearchParams`), with no `<Suspense>`. Forwarded render cookies bind identity and subscription to the verified user, not the incoming cookie's user object. On outage, unverified auth cookies are removed from the render request, not the browser. Refreshed browser cookies are applied to responses; personal auth must never be globally cached.
|
|
108
108
|
|
|
109
|
-
**Cached pages.** The generated `src/app/(site)` layout renders `ClientLayout` without request data: every page is static, served from the cache and re-rendered at most hourly (`revalidate = 3600`, ISR; `appConfig.revalidate` sets another lifetime in seconds, or `false` to keep pages until the next deploy), one entry per URL (page and language). Guests, crawlers and LLMs get it; so does every visitor of an app whose session the server cannot read (Firebase, localStorage session: no per-request tree, no proxy needed for it). The layout puts no Suspense boundary around the page, and the framework never adds one at layout level: it would show every static page only after the first paint (Lighthouse). A cached page that reads the query string (`useSearchParams`, `useLocation().search`) wraps that read in its own `<Suspense>`, which renders that part in the browser, and `next build` fails without one; use `useRoutePath()` when only the path is needed. `auth` pages of a cookie-session app are per request (see above) and need none. The framework generates the root layout (`src/app/layout.next.tsx`, `src/app/[lang]/layout.next.tsx` with 2+ languages) and the 404 pages; it renders the app's HTML shell `src/app/AppDocument.tsx` (cli `app-next` template) with the page's `<html lang>`. Both trees sit under it, so sign-in and sign-out stay client-side navigations. An `AppDocument` that renders `ClientLayout`, imports `next/headers` or exports `dynamic`, or an app-owned root layout / root `not-found`, fails the build.
|
|
109
|
+
**Cached pages.** The generated `src/app/(site)` layout renders `ClientLayout` without request data: every page is static, served from the cache and re-rendered at most hourly (`revalidate = 3600`, ISR; `appConfig.revalidate` sets another lifetime in seconds, or `false` to keep pages until the next deploy), one entry per URL (page and language). Dynamic pages: an entity page (`/produits/:slug`, entity from its `src/pages/<entity>/` folder, in the sitemap) is prerendered at build once per published record, the sitemap's records read with the public (anonymous) reader, so a first visit is a cache hit; a record published later, and any other dynamic page, renders on its first request, then is cached (`appConfig.prerenderRecords: false`: every URL on its first request). The build then reads the database: missing `NEXT_PUBLIC_SUPABASE_*` or a failed read fails it. Guests, crawlers and LLMs get it; so does every visitor of an app whose session the server cannot read (Firebase, localStorage session: no per-request tree, no proxy needed for it). The layout puts no Suspense boundary around the page, and the framework never adds one at layout level: it would show every static page only after the first paint (Lighthouse). A cached page that reads the query string (`useSearchParams`, `useLocation().search`) wraps that read in its own `<Suspense>`, which renders that part in the browser, and `next build` fails without one; use `useRoutePath()` when only the path is needed. `auth` pages of a cookie-session app are per request (see above) and need none. The framework generates the root layout (`src/app/layout.next.tsx`, `src/app/[lang]/layout.next.tsx` with 2+ languages) and the 404 pages; it renders the app's HTML shell `src/app/AppDocument.tsx` (cli `app-next` template) with the page's `<html lang>`. Both trees sit under it, so sign-in and sign-out stay client-side navigations. An `AppDocument` that renders `ClientLayout`, imports `next/headers` or exports `dynamic`, or an app-owned root layout / root `not-found`, fails the build.
|
|
110
110
|
|
|
111
111
|
Needs `NEXT_PUBLIC_SUPABASE_URL` and `NEXT_PUBLIC_SUPABASE_PUBLIC_KEY` (the proxy throws without them). Without a proxy, a cookie whose access token expired reads as "unknown": the first paint waits for the provider instead of showing a user the browser may no longer have.
|
|
112
112
|
|
|
@@ -265,7 +265,7 @@ const token = await getProvider('auth').refreshToken();
|
|
|
265
265
|
if (token === null) throw new Error('Auth refresh failed');
|
|
266
266
|
```
|
|
267
267
|
|
|
268
|
-
`refreshToken()` is an existing provider method, not a `useAuth` selector. On success it applies canonical user/subscription state before resolving; `useAuth('userSubscription')`, `useAuth('userTier')`, guards and capabilities then observe it. Other users' browsers require their own refresh; the server setter does not push session updates.
|
|
268
|
+
`refreshToken()` throws on provider error (e.g. Supabase `refresh_token_not_found`, wrapped with the original reason) and returns `null` only when the auth state changed during the refresh (sign-out, account switch) or no session exists. `refreshToken()` is an existing provider method, not a `useAuth` selector. On success it applies canonical user/subscription state before resolving; `useAuth('userSubscription')`, `useAuth('userTier')`, guards and capabilities then observe it. Other users' browsers require their own refresh; the server setter does not push session updates.
|
|
269
269
|
|
|
270
270
|
### Access semantics and trust
|
|
271
271
|
|
|
@@ -274,7 +274,7 @@ if (token === null) throw new Error('Auth refresh failed');
|
|
|
274
274
|
- Existing status strings, including legacy/custom statuses, remain accepted. This introduces no trial, grace or expiry policy.
|
|
275
275
|
- Supabase authorization claims/roles come only from `app_metadata`; `user_metadata` is editable profile data (name/avatar), never authorization. A signed-in user with no explicit application role has baseline role `user`.
|
|
276
276
|
- SSR `AuthSessionSnapshot.userSubscription` is display-only request context (optional for older providers). During initialization, `useAuth` reads request-local identity, subscription and capabilities; never write a request identity into the singleton auth store. Protected server actions must reauthorize using fresh trusted auth.
|
|
277
|
-
- Proxy `getUser()` supplies current trusted metadata for
|
|
277
|
+
- Proxy `getUser()` supplies current trusted metadata for document renders; RSC soft navigations and prefetches (GET/HEAD) get a user built from the access token's claims only (`getClaims()`: metadata as of the token's issue, no `email_confirmed_at`, a revoked session valid until the token expires). Staleness bound: a profile change shows up on soft navigations within one access-token lifetime (default 3600 s), or on the next document load. Neither promises JWT/session revocation everywhere. Direct RLS using `auth.jwt()` may still see old claims until token refresh/expiry. Immediate revocation requires authoritative server/database policy at the protected operation, not a guard or client refresh alone.
|
|
278
278
|
- Claim updates are not a transactional grant/revoke API. Firebase merges a read snapshot before replacing claims; Supabase accepts key patches but provides no compare-and-set contract. Coordinate concurrent authorization writers per user when ordering matters. A browser refresh cannot repair a server-side lost update.
|
|
279
279
|
|
|
280
280
|
### Redirect URLs (Supabase only)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@donotdev/auth",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.1",
|
|
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.2",
|
|
47
|
+
"@donotdev/core": "^0.3.1",
|
|
48
|
+
"@donotdev/firebase": "^0.3.1",
|
|
49
|
+
"@donotdev/supabase": "^0.3.1",
|
|
50
50
|
"lucide-react": "*",
|
|
51
51
|
"react": "^19.3.1",
|
|
52
52
|
"react-dom": "^19.3.1",
|