@aiquants/auth-react-router 0.24.0 → 0.25.0
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 +23 -2
- package/dist/server.d.mts +1 -0
- package/dist/server.d.ts +1 -0
- package/dist/server.js +1 -1
- package/dist/server.mjs +1 -1
- package/package.json +7 -7
package/README.md
CHANGED
|
@@ -67,6 +67,24 @@ createAuthServer({
|
|
|
67
67
|
})
|
|
68
68
|
```
|
|
69
69
|
|
|
70
|
+
Scopes for one sign-in on top of `google.scopes` (a wider permission a reader is asked to grant on a dedicated sign-in path,
|
|
71
|
+
for example), read from the sign-in request when the authorization redirect is built:
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
createAuthServer({
|
|
75
|
+
google: {
|
|
76
|
+
...,
|
|
77
|
+
// Synchronous. Map the request to a fixed set of scopes; never copy a scope from the request itself
|
|
78
|
+
additionalScopes: (request) => (new URL(request.url).searchParams.get("grant") === "edit" ? ["https://www.googleapis.com/auth/drive"] : []),
|
|
79
|
+
},
|
|
80
|
+
...
|
|
81
|
+
})
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The scope sent is `google.scopes` followed by the additional ones, each once. A scope that is empty or holds white space
|
|
85
|
+
throws `RangeError` when the redirect is built. With `includeGrantedScopes` (the default), a scope granted once stays
|
|
86
|
+
with the later sign-ins too.
|
|
87
|
+
|
|
70
88
|
A sign-in written outside `googleCallbackLoader` (a test fixture that needs a signed-in cookie, say) goes through the
|
|
71
89
|
same write path, so it carries a valid stamp:
|
|
72
90
|
|
|
@@ -316,8 +334,10 @@ this package imports it **directly** — `src/admin/labels.ts` resolves the UI l
|
|
|
316
334
|
`resolveVirtualScrollLocale`, so `dist/admin.mjs` carries its specifier. The pickers use the `locale` / `labels` props
|
|
317
335
|
of `@aiquants/select-box` and its 0.11 render and typing contract (`RenderOptionContext.highlight`, and `value` /
|
|
318
336
|
`onChange` typed by the option type), plus the locale resolution of `@aiquants/virtualscroll` 3.7.0. The published manifest carries the versions the release
|
|
319
|
-
was built and tested with
|
|
320
|
-
|
|
337
|
+
was built and tested with (its `peerDependencies`), so a host installs at least those (a 0.x minor is outside the caret
|
|
338
|
+
range: a host on select-box 0.15 bumps it explicitly). The select-box version that range resolves to names its own
|
|
339
|
+
floors for fuzzy-search and virtualscroll, which can be higher than this package's: install the ranges the resolved
|
|
340
|
+
select-box's manifest names.
|
|
321
341
|
|
|
322
342
|
All three are **required** peers, not optional. `src/admin/views.tsx` imports `@aiquants/select-box` and
|
|
323
343
|
`src/admin/labels.ts` imports `@aiquants/virtualscroll` at the top level, and `./admin` re-exports both modules, so the
|
|
@@ -339,6 +359,7 @@ package's own `react: ">=18"`; a host that mounts `/admin` must satisfy the stri
|
|
|
339
359
|
- **One authentication per request**: the guard performs its work at most once per `Request` instance and shares a mode-neutral result, so a root loader (`null`) and a leaf loader (`"/auth/login"`) in the same React Router data pass share a single pass — one warmup, one token refresh, one `Set-Cookie`. The failure policy is applied per caller on top of the shared result, so it must never be part of the cache key.
|
|
340
360
|
- **Infrastructure failures are never laundered into logouts**: anything that is not an authentication failure (an unexpected error inside the auth step, a `getUserPhoto` port outage, a `saveSession` failure, a defect of the session generation store) propagates unchanged in **both** modes. The session is not destroyed and no redirect is produced.
|
|
341
361
|
- Photo lookups are cached with in-flight dedup per factory instance.
|
|
362
|
+
- **The test backdoor's tokens are the port's**: when `mockUser.enabled(request)` holds, `authenticate` (and so `authenticateInLoader`) returns the `accessToken`, `refreshToken` and `expirationDateMs` of the profile `mockUser.resolve(request)` builds, never a fixed value, so a host can sign the backdoor's user in with a token its API accepts. The backdoor's tokens are not refreshed.
|
|
342
363
|
- **Profiles handed to route code carry no refresh token**: `authenticateInLoader` returns `user: LoaderUser`
|
|
343
364
|
(`Omit<MyGoogleProfile, "refreshToken">`) and `getSessionUser` / `requireUser` / `requireAdminUser` return `SessionUser`
|
|
344
365
|
(`Omit<SessionProfile, "refreshToken">`); the key is absent at runtime as well, for the `mockUser` backdoor's user and for
|
package/dist/server.d.mts
CHANGED
|
@@ -14,6 +14,7 @@ type GoogleOAuthConfig = {
|
|
|
14
14
|
accessType?: "online" | "offline";
|
|
15
15
|
includeGrantedScopes?: boolean;
|
|
16
16
|
prompt?: "none" | "consent" | "select_account";
|
|
17
|
+
additionalScopes?: (request: Request) => readonly string[];
|
|
17
18
|
revocationTimeoutMs?: number;
|
|
18
19
|
};
|
|
19
20
|
type FetchPort = (url: string, init: RequestInit) => Promise<Response>;
|
package/dist/server.d.ts
CHANGED
|
@@ -14,6 +14,7 @@ type GoogleOAuthConfig = {
|
|
|
14
14
|
accessType?: "online" | "offline";
|
|
15
15
|
includeGrantedScopes?: boolean;
|
|
16
16
|
prompt?: "none" | "consent" | "select_account";
|
|
17
|
+
additionalScopes?: (request: Request) => readonly string[];
|
|
17
18
|
revocationTimeoutMs?: number;
|
|
18
19
|
};
|
|
19
20
|
type FetchPort = (url: string, init: RequestInit) => Promise<Response>;
|
package/dist/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var oe=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var Ae=Object.prototype.hasOwnProperty;var Ge=(e,t)=>{for(var n in t)oe(e,n,{get:t[n],enumerable:!0})},Te=(e,t,n,c)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ve(t))!Ae.call(e,i)&&i!==n&&oe(e,i,{get:()=>t[i],enumerable:!(c=ke(t,i))||c.enumerable});return e};var Pe=e=>Te(oe({},"__esModule",{value:!0}),e);var He={};Ge(He,{AuthRequiredError:()=>N,DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS:()=>ue,DEFAULT_SESSION_GENERATION_CACHE_TTL_MS:()=>re,DEFAULT_SESSION_GENERATION_TIMEOUT_MS:()=>se,GoogleInvalidGrantError:()=>F,SessionGenerationUnavailableError:()=>C,TokenRefreshError:()=>M,createAuthHandlers:()=>Q,createAuthServer:()=>ye,createAuthSessionStorage:()=>Z,createAuthenticate:()=>B,createAuthenticateInLoader:()=>X,createGoogleAuthenticator:()=>W,signOutRefusal:()=>J,signOutRefusalResponse:()=>z});module.exports=Pe(He);var ie=require("react-router");var Re="https://oauth2.googleapis.com/revoke",ue=5e3;var Ee="google",_e="invalid_token";var de=e=>{if(e===void 0)return 5e3;if(!Number.isInteger(e)||e<1||e>2147483647)throw new RangeError(`google.revocationTimeoutMs must be an integer from 1 to 2147483647 (milliseconds); got ${String(e)}`);return e},be=e=>{if(typeof e.refreshToken=="string"&&e.refreshToken!=="")return e.refreshToken;if(typeof e.accessToken=="string"&&e.accessToken!=="")return e.accessToken},Ie=async e=>{let t=await e.json().catch(()=>{});return typeof t=="object"&&t!==null&&"error"in t&&typeof t.error=="string"?t.error:void 0},Oe=e=>e instanceof Error?e.cause instanceof Error?`${e.message} (${e.cause.message})`:e.message:String(e),xe=async(e,t,n)=>{try{let c=await t(Re,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:e}).toString(),signal:n});if(c.ok)return await c.body?.cancel(),{outcome:"revoked"};let i=await Ie(c);return c.status===400&&i===_e?{outcome:"already-invalid"}:{outcome:"failed",reason:i===void 0?`Google answered ${c.status}`:`Google answered ${c.status} ${i}`}}catch(c){return{outcome:"failed",reason:Oe(c)}}},le=async(e,t)=>{if(e===void 0)return{outcome:"nothing-to-revoke"};let n=be(e);if(n===void 0)return{outcome:"nothing-to-revoke"};if(e.provider!==Ee)return{outcome:"failed",reason:`the session's provider "${String(e.provider)}" has no revocation endpoint`};let c=new AbortController;return await new Promise(i=>{let k=setTimeout(()=>{i({outcome:"failed",reason:`Google did not answer within ${t.timeoutMs} ms`}),c.abort()},t.timeoutMs);xe(n,t.fetch,c.signal).then(v=>{clearTimeout(k),i(v)})})};var x="generation",re=15e3,se=3e3,Ue=6e4,C=class extends Error{constructor(t,n){super(t,n),this.name="SessionGenerationUnavailableError"}},O=e=>typeof e=="string"?JSON.stringify(e):typeof e=="function"?"a function":typeof e=="object"&&e!==null?Array.isArray(e)?"an array":"an object":typeof e=="bigint"?`${e}n`:String(e),Le=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return O(e);let t="store"in e?e.store:void 0;if(typeof t!="object"||t===null)return`an object whose store is ${O(t)}`;let n="current"in t?t.current:void 0,c="advance"in t?t.advance:void 0;return`an object whose store.current is ${O(n)} and store.advance is ${O(c)}`},Ne=e=>typeof e=="object"&&e!==null&&"current"in e&&typeof e.current=="function"&&"advance"in e&&typeof e.advance=="function",fe=(e,t,n,c)=>{if(t===void 0)return c;if(typeof t!="number"||!Number.isInteger(t)||t<n||t>2147483647)throw new RangeError(`${e} must be an integer from ${n} to ${2147483647} (milliseconds); got ${O(t)}`);return t},Ce=e=>{if(e===!1)return!1;let t=e;if(typeof t!="object"||t===null||!("store"in t)||!Ne(t.store))throw new TypeError(`sessionGeneration must be { store, cacheTtlMs?, timeoutMs? } or false; got ${Le(t)}`);return{store:t.store,cacheTtlMs:fe("sessionGeneration.cacheTtlMs","cacheTtlMs"in t?t.cacheTtlMs:void 0,0,re),timeoutMs:fe("sessionGeneration.timeoutMs","timeoutMs"in t?t.timeoutMs:void 0,1,se)}},$=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,ne=e=>typeof e.provider=="string"&&e.provider!==""&&typeof e.id=="string"&&e.id!=="",pe=e=>new TypeError(`a session generation identity needs a non-empty provider and id; got provider ${O(e.provider)} and id ${O(e.id)}`),$e=e=>$(e)&&$(e+1),Fe=e=>new TypeError(`a session generation advance needs the signed-out session's stamp, an integer from 0 to ${Number.MAX_SAFE_INTEGER-1}; got ${O(e)}`),L=e=>({provider:e.provider,id:e.id}),ge=(e,t)=>{let n=Ce(e);if(n===!1)return null;let{store:c,cacheTtlMs:i,timeoutMs:k}=n,v=new Map,A=new Map,S=new Map,h=new Map,w=Number.NEGATIVE_INFINITY,f=a=>`${a.provider}\0${a.id}`,g=(a,o)=>{let d=v.get(a);if(d!==void 0){if(o-d.at<i)return d;v.delete(a)}},l=(a,o,d)=>{if(d!==void 0&&o.at<=d.answeredAt&&o.value<d.value)return;let y=g(a,performance.now());if(y===void 0){v.set(a,o);return}o.value<y.value||v.set(a,{value:o.value,at:Math.max(y.at,o.at)})},p=a=>{let o=h.get(a);if(o!==void 0)return o.count+=1,o;let d={count:1,floor:void 0};return h.set(a,d),d},m=(a,o)=>{o.count-=1,o.count===0&&h.delete(a)},R=(a,o)=>{a.floor={value:a.floor===void 0?o:Math.max(a.floor.value,o),answeredAt:performance.now()}},s=(a,o)=>{let d=S.get(a);return d===void 0?!1:o<d?!0:(S.delete(a),!1)},r=(a,o)=>{let d=performance.now();return S.set(a,d+i),d-w>=Ue&&(w=d,t.warn("Session generation store unavailable; skipping the sign-out generation check:",o)),"unavailable"},u=(a,o,d)=>new Promise((y,T)=>{let{operation:G}=a,I=a.operation==="advance"?a.from+1:0,we=performance.now(),V=p(d),U=!1,ce=setTimeout(()=>{U=!0,y({kind:"unavailable",error:new C(`sessionGeneration.store.${G} did not settle within ${k} ms`)})},k);new Promise(_=>_(a.operation==="advance"?c.advance(o,a.from):c.current(o))).then(_=>{if(clearTimeout(ce),!($(_)&&_>=I)){m(d,V),U||(U=!0,T(new TypeError(`sessionGeneration.store.${G} must resolve to an integer >= ${I}; got ${O(_)}`)));return}G==="advance"&&(R(V,_),A.delete(d)),l(d,{value:_,at:we},V.floor),m(d,V),!U&&(U=!0,S.delete(d),y({kind:"value",value:_}))},_=>{if(clearTimeout(ce),m(d,V),!U){if(U=!0,_ instanceof C){y({kind:"unavailable",error:_});return}T(_)}})}),P=(a,o,d)=>{let y=A.get(o);if(y!==void 0&&d-y.startedAt<i)return y.read;let T={read:u({operation:"current"},a,o),startedAt:d};A.set(o,T);let G=()=>{A.get(o)===T&&A.delete(o)};return T.read.then(G,G),T.read},E=async(a,o,d)=>{let y=await u({operation:"current"},a,o);return y.kind==="unavailable"?r(o,y.error):d===y.value?"current":"stale"};return{check:async(a,o)=>{if(!($(o)&&ne(a)))return"stale";let d=performance.now(),y=f(a),T=g(y,d);if(T!==void 0){if(o===T.value)return"current";if(o<T.value)return"stale"}if(s(y,d))return"unavailable";if(T!==void 0)return await E(a,y,o);let G=await P(a,y,d);return G.kind==="unavailable"?r(y,G.error):o===G.value?"current":o<G.value?"stale":await E(a,y,o)},stamp:async a=>{if(!ne(a))throw pe(a);let o=await u({operation:"current"},a,f(a));if(o.kind==="unavailable")throw o.error;return o.value},advance:async(a,o)=>{if(!ne(a))return{kind:"failed",error:pe(a)};if(!$e(o))return{kind:"failed",error:Fe(o)};try{let d=await u({operation:"advance",from:o},a,f(a));return d.kind==="value"?{kind:"advanced",generation:d.value}:{kind:"unavailable",error:d.error}}catch(d){return{kind:"failed",error:d}}}}};var M=class extends Error{constructor(t){super(t),this.name="TokenRefreshError"}},F=class extends M{constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},N=class extends Error{constructor(t){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=t}},qe=["access_token","expires_in"],B=(e,t,n)=>{let c=e.loginPath??"/auth/login",i=t.sessionKey,k=async S=>{let w=S.get(i)?.refreshToken;if(!w)throw new Error("Refresh token not found in session");try{let f="https://www.googleapis.com/oauth2/v4/token",g={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:w},p=await(e.fetch??globalThis.fetch)(f,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(g)});if(!p.ok){let u=await p.json().catch(()=>{});if(p.status===400&&typeof u=="object"&&!!u&&"error"in u&&u.error==="invalid_grant")throw new F;let E=typeof u=="object"&&u&&"error_description"in u?String(u.error_description):"Unknown error";throw new M(`Google token refresh failed: ${p.status} ${E}`)}let m=await p.json(),R=qe.filter(u=>!m?.[u]);if(R.length>0)throw n.error("Invalid token response from Google; missing or empty keys:",R.join(", ")),new Error("Invalid token response from Google");let{access_token:s,expires_in:r}=m;return{accessToken:s,refreshToken:w,expirationDateMs:Number(Date.now())+r*1e3}}catch(f){if(f instanceof M)throw f;let g=f instanceof Error?f.message:"Unknown error";throw new M(`Failed to refresh Google access token: ${g}`)}},v=async S=>{let w=S.get(i).provider;if(!w)throw new Error("Provider not found in session");if(w==="google")return await k(S);throw new Error("Provider not supported")};return{authenticate:async(S,h,w)=>{let{failureRedirect:f}=w||{},g=l=>{if(f===null)return new N(l);if(f==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let p=f??c;return l!==void 0?(0,ie.redirect)(p,{headers:{"Set-Cookie":l}}):(0,ie.redirect)(p)};try{if(e.mockUser?.enabled(S))return{accessToken:"mock-access-token",refreshToken:"mock-refresh-token",expirationDateMs:Date.now()+36e5};let l=h.get(i),p=t.sessionGenerationGate;if(l!==void 0&&p!==null&&await p.check(L(l),h.get(x))==="stale")throw g(await t.destroySession(h));if(!(l?.accessToken&&l.expirationDateMs))throw g();let{accessToken:m,refreshToken:R,expirationDateMs:s}=l;if(s<Date.now())throw R?new Error("Expired"):g();return{accessToken:m,refreshToken:R,expirationDateMs:s}}catch(l){if(l instanceof Error&&l.message==="Expired")try{let p=await v(h),m=h.get(i);return h.set(i,{...m,...p}),p}catch(p){if(p instanceof F)n.warn("Google refresh token invalid or revoked");else{let R=p instanceof Error?p.message:"Unknown error";n.error("Failed to refresh token:",R)}let m=await t.destroySession(h);throw g(m)}throw l}},refreshedAccessToken:v}};var ae=require("react-router");var K=({refreshToken:e,...t})=>t;var X=(e,t,n,c)=>{let i=new Map,k=new Map,v=async f=>{let g=i.get(f);if(g!==void 0)return g;let l=k.get(f);if(l!==void 0)return l;let p=(async()=>{try{let m=e.getUserPhoto?await e.getUserPhoto(f):"";return i.set(f,m),m}catch(m){throw i.delete(f),m}finally{k.delete(f)}})();return k.set(f,p),p},A=new WeakMap,S=async f=>{e.warmup&&await e.warmup();let g=await t.resolveSession(f);if(g.kind==="revoked")return{kind:"unauthenticated",cookie:await t.destroySession(g.session)};if(g.kind!=="signed-in")return{kind:"unauthenticated"};let{user:l,session:p}=g,m;try{m=await n.authenticate(f,p,{failureRedirect:null})}catch(b){if(b instanceof N)return b.setCookie!==void 0?{kind:"unauthenticated",cookie:b.setCookie}:{kind:"unauthenticated"};throw c.error("Error in authenticateInLoader:",b),b}let R={accessToken:m.accessToken,refreshToken:m.refreshToken,expirationDateMs:m.expirationDateMs,provider:l.provider},s={id:l.id,displayName:l.displayName,name:l.name,emails:l.emails,...R,role:l.role},r=await v(l.id),u=K({...l,...R,photo:r}),E=m.accessToken!==l.accessToken?await t.saveSession(f,s):void 0;return E!==void 0?{kind:"authenticated",user:u,cookie:E}:{kind:"authenticated",user:u}},h=f=>{let g=A.get(f);if(g!==void 0)return g;let l=S(f);return A.set(f,l),l};async function w(f,g){let{failureRedirect:l}=g;if(l==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let p=await h(f);if(p.kind==="authenticated")return p.cookie!==void 0?{user:p.user,cookie:p.cookie}:{user:p.user};if(l===null)return p.cookie!==void 0?{cookie:p.cookie}:{};throw p.cookie!==void 0?(0,ae.redirect)(l,{headers:{"Set-Cookie":p.cookie}}):(0,ae.redirect)(l)}return w};var me=require("@aiquants/auth-core"),Y=require("react-router"),Se=require("remix-auth");var he=require("remix-auth-oauth2"),De=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],je="google",Ve="https://www.googleapis.com/oauth2/v3/userinfo",H=class extends he.OAuth2Strategy{constructor({clientId:n,clientSecret:c,redirectURI:i,scopes:k,accessType:v,includeGrantedScopes:A,prompt:S,hd:h,loginHint:w},f){let g=k??De;super({clientId:n,clientSecret:c,redirectURI:i,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:g},f);this.name=je;this.scopes=g,this.accessType=v??"online",this.includeGrantedScopes=A??!1,this.prompt=S,this.hd=h,this.loginHint=w}authorizationParams(n,c){return n.set("access_type",this.accessType),n.set("include_granted_scopes",String(this.includeGrantedScopes)),this.scopes&&this.scopes.length>0&&n.set("scope",this.scopes.join(" ")),this.prompt&&n.set("prompt",this.prompt),this.hd&&n.set("hd",this.hd),this.loginHint&&n.set("login_hint",this.loginHint),n}static async userProfile(n){let c=await fetch(Ve,{headers:{Authorization:`Bearer ${n.accessToken()}`}});if(!c.ok)throw new Error(`Failed to fetch user profile: ${c.statusText}`);let i=await c.json();return{id:i.sub,displayName:i.name,name:{familyName:i.family_name,givenName:i.given_name},emails:[{value:i.email}],photos:[{value:i.picture}],_json:i}}};var q={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var W=e=>{let t=e.logger??q,n=(0,me.resolveAuthMessages)(e.messages),c=e.loginPath??"/auth/login",i=new H({clientId:e.google.clientId,clientSecret:e.google.clientSecret,redirectURI:e.google.redirectURI,scopes:e.google.scopes,accessType:e.google.accessType??"offline",includeGrantedScopes:e.google.includeGrantedScopes??!0,prompt:e.google.prompt??"consent"},async({request:v,tokens:A})=>{let{access_token:S,refresh_token:h,expires_in:w,scope:f,id_token:g}=A.data,{_json:{sub:l,email:p,picture:m,hd:R,email_verified:s},photos:r,...u}=await H.userProfile(A),{id:P,displayName:E,name:{familyName:b,givenName:ee},emails:te}=u,a="google";if(S===void 0||h===void 0||w===void 0||f===void 0||P===void 0||E===void 0||l===void 0||p===void 0||s===void 0){if(s===!1){let d=encodeURIComponent(n.emailNotVerified);throw(0,Y.redirect)(`${c}?error=${d}`)}let o=encodeURIComponent(n.googleFailed);throw(0,Y.redirect)(`${c}?error=${o}`)}t.info("Authenticated on Google: ",u.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(a,S)){t.error("Backend verification returned false for user:",u.displayName);let I=encodeURIComponent(n.backendFailed);throw(0,Y.redirect)(`${c}?error=${I}`)}t.info("Authenticated on Backend: ",u.displayName)}let o=u.emails[0]?.value;if(!await e.isEmailAllowed(o)){let G=new Error("You are not allowed to access this application");throw t.error(G),G}if(e.isUserActive&&!await e.isUserActive(u)){let G=new Error("You are not allowed to access this application");throw t.error("Deactivated account attempted to sign in:",o),G}e.backendAuth&&await e.backendAuth.signup(a,S,u),t.info("Authenticated complete: ",u.displayName);let d=Date.now()+w*1e3;return{...u,...{accessToken:S,refreshToken:h,expirationDateMs:d,provider:a},photo:m}}catch(o){let d=o;typeof o=="object"&&o!==null&&"cause"in o&&(d=o.cause||o),t.error("Error during backend authentication or subsequent processing:",d);let y=n.unexpected,T=!1;if(typeof o=="object"&&o!==null&&"cause"in o){let I=o.cause;I&&typeof I=="object"&&"message"in I&&typeof I.message=="string"&&I.message.includes("getaddrinfo ENOTFOUND")&&(y=n.backendUnreachable,T=!0)}if(!T&&o instanceof Error&&o.message.includes("You are not allowed to access this application")&&(y=n.notAllowed,T=!0),!T&&o instanceof Response&&o.headers.get("Location")?.startsWith(c))throw o;let G=encodeURIComponent(y);throw(0,Y.redirect)(`${c}?error=${G}`)}}),k=new Se.Authenticator;return k.use(i),k};var D=require("react-router");var Ke=new Map([["document",new Set(["none","same-origin","same-site"])],["empty",new Set(["same-origin"])]]),J=e=>{let t=e.headers.get("Sec-Fetch-Dest");if(t!==null){let c=Ke.get(t);if(c===void 0)return`its fetch destination is "${t}"`;let i=e.headers.get("Sec-Fetch-Site");if(i===null)return`its "${t}" request states no site`;if(!c.has(i))return`its "${t}" request comes from a "${i}" page`}let n=e.headers.get("Sec-Purpose");if(n!==null)return`it is speculative ("${n}")`},z=e=>new Response(`Signing out is refused because ${e}: only a navigation that does not come from another site, or a script's request from this origin, signs out.`,{status:403,headers:{"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"}});var Q=(e,t,n,c)=>{let i=e.loginPath??"/auth/login",k=e.postLoginRedirect??"/",v=e.postLogoutRedirect??"/",A=de(e.google.revocationTimeoutMs),S=async({request:s})=>{if(await t.getSessionUser(s))throw(0,D.redirect)(k);return{error:new URL(s.url).searchParams.get("error")}},h=async({request:s})=>{if((await s.clone().formData()).get("_action")!=="Sign In with Google")return null;throw await n.authenticate("google",s),(0,D.redirect)(i)},w=(s,r)=>{switch(s.outcome){case"failed":c.error(`Sign-out could not revoke the Google grant of user ${String(r)}; the session cookie is destroyed, but the grant stays valid until it expires or is revoked elsewhere:`,s.reason);return;case"already-invalid":c.info(`Sign-out found the Google grant of user ${String(r)} already unusable`);return;case"revoked":case"nothing-to-revoke":return}},f=(s,r)=>{s.kind!=="advanced"&&c.error(`Sign-out could not advance the session generation of ${r.provider} user ${r.id}; a session cookie refreshed before this sign-out stays valid until a later sign-out advances the generation or the cookie expires:`,s.error)},g=async(s,r)=>{let u=t.sessionGenerationGate;if(u!==null){if(!$(r)){c.info(`Sign-out found no usable session generation stamp in the session of ${s.provider} user ${s.id}; every guard already rejects that cookie, so the generation is not advanced`);return}f(await u.advance(s,r),s)}},l=async s=>{let r=await t.getSession(s),u=r.get(t.sessionKey),[P]=await Promise.all([le(u,{fetch:e.fetch??globalThis.fetch,timeoutMs:A}),u===void 0?void 0:g(L(u),r.get(x))]);return w(P,u?.id),await t.destroySession(r)},p=async s=>{let r=await l(s),u=new Headers;return u.append("Set-Cookie",r),(0,D.redirect)(v,{headers:u})};return{loginLoader:S,loginAction:h,logoutLoader:async({request:s})=>{let r=J(s);throw r!==void 0?z(r):await p(s)},logout:l,logoutAndRedirect:p,googleCallbackLoader:async({request:s})=>{try{let r=await n.authenticate("google",s),E=(await t.getSession(s)).get(t.sessionKey)?.refreshToken,b={accessToken:r.accessToken,refreshToken:r.refreshToken||E,expirationDateMs:r.expirationDateMs,provider:r.provider},ee={id:r.id,displayName:r.displayName,name:r.name,emails:r.emails,...b,role:r.role},te=await t.saveSignedInSession(s,ee);throw(0,D.redirect)(k,{headers:{"Set-Cookie":te}})}catch(r){throw r instanceof Response?r:(c.error("Authentication error:",r),(0,D.redirect)(i))}}}};var j=require("react-router");var Z=(e,t)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(s=>!s))throw new Error("REMIX_SESSION_SECRET must be set");let n=e.sessionKey??"user";if(n===x)throw new RangeError(`session.sessionKey must not be ${JSON.stringify(x)}, the key the session generation is stored under; got ${JSON.stringify(n)}`);let c=e.maxAge??3600*24*30,i=t.loginPath??"/auth/login",k=t.postLoginRedirect??"/",v=t.mockUser,A=t.isUserActive,S=ge(t.sessionGeneration,t.logger??q),h=(0,j.createCookieSessionStorage)({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:e.secure??process.env.NODE_ENV==="production",maxAge:c}}),w=async s=>await h.getSession(s.headers.get("Cookie")),f=async s=>{if(v?.enabled(s))return{kind:"signed-in",user:K(v.resolve(s)),session:await w(s)};let r=await w(s),u=r.get(n);if(u===void 0)return{kind:"signed-out"};let P=K(u),[E,b]=await Promise.all([A===void 0?!0:A(P),S===null?"current":S.check(L(u),r.get(x))]);return b==="stale"?{kind:"revoked",session:r}:E?{kind:"signed-in",user:P,session:r}:{kind:"inactive"}},g=async s=>{let r=await f(s);return r.kind==="signed-in"?r.user:void 0},l=async(s,r)=>{let u=await w(s);return u.set(n,r),await h.commitSession(u)},p=async(s,r)=>{let u=S===null?void 0:await S.stamp(L(r)),P=await w(s);return P.set(n,r),u!==void 0&&P.set(x,u),await h.commitSession(P)},m=async s=>{let r=await f(s);switch(r.kind){case"signed-in":return r.user;case"revoked":throw(0,j.redirect)(i,{headers:{"Set-Cookie":await h.destroySession(r.session)}});case"signed-out":case"inactive":throw(0,j.redirect)(i)}};return{sessionStorage:h,sessionKey:n,sessionGenerationGate:S,getSession:w,resolveSession:f,getSessionUser:g,saveSession:l,saveSignedInSession:p,requireUser:m,requireAdminUser:async s=>{let r=await m(s);if(r.role!=="admin")throw(0,j.redirect)(k);return r},commitSession:h.commitSession,destroySession:h.destroySession}};var ye=e=>{let t=e.logger??q,n=Z(e.session,{sessionGeneration:e.sessionGeneration,logger:t,mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive}),c=W(e),i=B(e,n,t),k=X(e,n,i,t),v=Q(e,n,c,t);return{authenticator:c,storage:n,authFns:i,sessionStorage:n.sessionStorage,getSession:n.getSession,getSessionUser:n.getSessionUser,saveSession:n.saveSession,requireUser:n.requireUser,requireAdminUser:n.requireAdminUser,commitSession:n.commitSession,destroySession:n.destroySession,authenticate:i.authenticate,refreshedAccessToken:i.refreshedAccessToken,authenticateInLoader:k,...v}};0&&(module.exports={AuthRequiredError,DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS,DEFAULT_SESSION_GENERATION_CACHE_TTL_MS,DEFAULT_SESSION_GENERATION_TIMEOUT_MS,GoogleInvalidGrantError,SessionGenerationUnavailableError,TokenRefreshError,createAuthHandlers,createAuthServer,createAuthSessionStorage,createAuthenticate,createAuthenticateInLoader,createGoogleAuthenticator,signOutRefusal,signOutRefusalResponse});
|
|
1
|
+
"use strict";var oe=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var Ae=Object.prototype.hasOwnProperty;var Ge=(e,t)=>{for(var n in t)oe(e,n,{get:t[n],enumerable:!0})},Te=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ve(t))!Ae.call(e,i)&&i!==n&&oe(e,i,{get:()=>t[i],enumerable:!(a=ke(t,i))||a.enumerable});return e};var Re=e=>Te(oe({},"__esModule",{value:!0}),e);var He={};Ge(He,{AuthRequiredError:()=>N,DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS:()=>ue,DEFAULT_SESSION_GENERATION_CACHE_TTL_MS:()=>re,DEFAULT_SESSION_GENERATION_TIMEOUT_MS:()=>se,GoogleInvalidGrantError:()=>F,SessionGenerationUnavailableError:()=>C,TokenRefreshError:()=>M,createAuthHandlers:()=>Q,createAuthServer:()=>ye,createAuthSessionStorage:()=>Z,createAuthenticate:()=>B,createAuthenticateInLoader:()=>X,createGoogleAuthenticator:()=>J,signOutRefusal:()=>W,signOutRefusalResponse:()=>z});module.exports=Re(He);var ie=require("react-router");var Pe="https://oauth2.googleapis.com/revoke",ue=5e3;var Ee="google",_e="invalid_token";var de=e=>{if(e===void 0)return 5e3;if(!Number.isInteger(e)||e<1||e>2147483647)throw new RangeError(`google.revocationTimeoutMs must be an integer from 1 to 2147483647 (milliseconds); got ${String(e)}`);return e},be=e=>{if(typeof e.refreshToken=="string"&&e.refreshToken!=="")return e.refreshToken;if(typeof e.accessToken=="string"&&e.accessToken!=="")return e.accessToken},Ie=async e=>{let t=await e.json().catch(()=>{});return typeof t=="object"&&t!==null&&"error"in t&&typeof t.error=="string"?t.error:void 0},Oe=e=>e instanceof Error?e.cause instanceof Error?`${e.message} (${e.cause.message})`:e.message:String(e),xe=async(e,t,n)=>{try{let a=await t(Pe,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:e}).toString(),signal:n});if(a.ok)return await a.body?.cancel(),{outcome:"revoked"};let i=await Ie(a);return a.status===400&&i===_e?{outcome:"already-invalid"}:{outcome:"failed",reason:i===void 0?`Google answered ${a.status}`:`Google answered ${a.status} ${i}`}}catch(a){return{outcome:"failed",reason:Oe(a)}}},le=async(e,t)=>{if(e===void 0)return{outcome:"nothing-to-revoke"};let n=be(e);if(n===void 0)return{outcome:"nothing-to-revoke"};if(e.provider!==Ee)return{outcome:"failed",reason:`the session's provider "${String(e.provider)}" has no revocation endpoint`};let a=new AbortController;return await new Promise(i=>{let w=setTimeout(()=>{i({outcome:"failed",reason:`Google did not answer within ${t.timeoutMs} ms`}),a.abort()},t.timeoutMs);xe(n,t.fetch,a.signal).then(v=>{clearTimeout(w),i(v)})})};var x="generation",re=15e3,se=3e3,Ue=6e4,C=class extends Error{constructor(t,n){super(t,n),this.name="SessionGenerationUnavailableError"}},O=e=>typeof e=="string"?JSON.stringify(e):typeof e=="function"?"a function":typeof e=="object"&&e!==null?Array.isArray(e)?"an array":"an object":typeof e=="bigint"?`${e}n`:String(e),Le=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return O(e);let t="store"in e?e.store:void 0;if(typeof t!="object"||t===null)return`an object whose store is ${O(t)}`;let n="current"in t?t.current:void 0,a="advance"in t?t.advance:void 0;return`an object whose store.current is ${O(n)} and store.advance is ${O(a)}`},Ne=e=>typeof e=="object"&&e!==null&&"current"in e&&typeof e.current=="function"&&"advance"in e&&typeof e.advance=="function",fe=(e,t,n,a)=>{if(t===void 0)return a;if(typeof t!="number"||!Number.isInteger(t)||t<n||t>2147483647)throw new RangeError(`${e} must be an integer from ${n} to ${2147483647} (milliseconds); got ${O(t)}`);return t},Ce=e=>{if(e===!1)return!1;let t=e;if(typeof t!="object"||t===null||!("store"in t)||!Ne(t.store))throw new TypeError(`sessionGeneration must be { store, cacheTtlMs?, timeoutMs? } or false; got ${Le(t)}`);return{store:t.store,cacheTtlMs:fe("sessionGeneration.cacheTtlMs","cacheTtlMs"in t?t.cacheTtlMs:void 0,0,re),timeoutMs:fe("sessionGeneration.timeoutMs","timeoutMs"in t?t.timeoutMs:void 0,1,se)}},$=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,ne=e=>typeof e.provider=="string"&&e.provider!==""&&typeof e.id=="string"&&e.id!=="",pe=e=>new TypeError(`a session generation identity needs a non-empty provider and id; got provider ${O(e.provider)} and id ${O(e.id)}`),$e=e=>$(e)&&$(e+1),Fe=e=>new TypeError(`a session generation advance needs the signed-out session's stamp, an integer from 0 to ${Number.MAX_SAFE_INTEGER-1}; got ${O(e)}`),L=e=>({provider:e.provider,id:e.id}),ge=(e,t)=>{let n=Ce(e);if(n===!1)return null;let{store:a,cacheTtlMs:i,timeoutMs:w}=n,v=new Map,A=new Map,m=new Map,h=new Map,k=Number.NEGATIVE_INFINITY,f=u=>`${u.provider}\0${u.id}`,g=(u,o)=>{let l=v.get(u);if(l!==void 0){if(o-l.at<i)return l;v.delete(u)}},d=(u,o,l)=>{if(l!==void 0&&o.at<=l.answeredAt&&o.value<l.value)return;let y=g(u,performance.now());if(y===void 0){v.set(u,o);return}o.value<y.value||v.set(u,{value:o.value,at:Math.max(y.at,o.at)})},p=u=>{let o=h.get(u);if(o!==void 0)return o.count+=1,o;let l={count:1,floor:void 0};return h.set(u,l),l},S=(u,o)=>{o.count-=1,o.count===0&&h.delete(u)},P=(u,o)=>{u.floor={value:u.floor===void 0?o:Math.max(u.floor.value,o),answeredAt:performance.now()}},s=(u,o)=>{let l=m.get(u);return l===void 0?!1:o<l?!0:(m.delete(u),!1)},r=(u,o)=>{let l=performance.now();return m.set(u,l+i),l-k>=Ue&&(k=l,t.warn("Session generation store unavailable; skipping the sign-out generation check:",o)),"unavailable"},c=(u,o,l)=>new Promise((y,R)=>{let{operation:G}=u,I=u.operation==="advance"?u.from+1:0,we=performance.now(),V=p(l),U=!1,ce=setTimeout(()=>{U=!0,y({kind:"unavailable",error:new C(`sessionGeneration.store.${G} did not settle within ${w} ms`)})},w);new Promise(_=>_(u.operation==="advance"?a.advance(o,u.from):a.current(o))).then(_=>{if(clearTimeout(ce),!($(_)&&_>=I)){S(l,V),U||(U=!0,R(new TypeError(`sessionGeneration.store.${G} must resolve to an integer >= ${I}; got ${O(_)}`)));return}G==="advance"&&(P(V,_),A.delete(l)),d(l,{value:_,at:we},V.floor),S(l,V),!U&&(U=!0,m.delete(l),y({kind:"value",value:_}))},_=>{if(clearTimeout(ce),S(l,V),!U){if(U=!0,_ instanceof C){y({kind:"unavailable",error:_});return}R(_)}})}),T=(u,o,l)=>{let y=A.get(o);if(y!==void 0&&l-y.startedAt<i)return y.read;let R={read:c({operation:"current"},u,o),startedAt:l};A.set(o,R);let G=()=>{A.get(o)===R&&A.delete(o)};return R.read.then(G,G),R.read},E=async(u,o,l)=>{let y=await c({operation:"current"},u,o);return y.kind==="unavailable"?r(o,y.error):l===y.value?"current":"stale"};return{check:async(u,o)=>{if(!($(o)&&ne(u)))return"stale";let l=performance.now(),y=f(u),R=g(y,l);if(R!==void 0){if(o===R.value)return"current";if(o<R.value)return"stale"}if(s(y,l))return"unavailable";if(R!==void 0)return await E(u,y,o);let G=await T(u,y,l);return G.kind==="unavailable"?r(y,G.error):o===G.value?"current":o<G.value?"stale":await E(u,y,o)},stamp:async u=>{if(!ne(u))throw pe(u);let o=await c({operation:"current"},u,f(u));if(o.kind==="unavailable")throw o.error;return o.value},advance:async(u,o)=>{if(!ne(u))return{kind:"failed",error:pe(u)};if(!$e(o))return{kind:"failed",error:Fe(o)};try{let l=await c({operation:"advance",from:o},u,f(u));return l.kind==="value"?{kind:"advanced",generation:l.value}:{kind:"unavailable",error:l.error}}catch(l){return{kind:"failed",error:l}}}}};var M=class extends Error{constructor(t){super(t),this.name="TokenRefreshError"}},F=class extends M{constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},N=class extends Error{constructor(t){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=t}},qe=["access_token","expires_in"],B=(e,t,n)=>{let a=e.loginPath??"/auth/login",i=t.sessionKey,w=async m=>{let k=m.get(i)?.refreshToken;if(!k)throw new Error("Refresh token not found in session");try{let f="https://www.googleapis.com/oauth2/v4/token",g={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:k},p=await(e.fetch??globalThis.fetch)(f,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(g)});if(!p.ok){let c=await p.json().catch(()=>{});if(p.status===400&&typeof c=="object"&&!!c&&"error"in c&&c.error==="invalid_grant")throw new F;let E=typeof c=="object"&&c&&"error_description"in c?String(c.error_description):"Unknown error";throw new M(`Google token refresh failed: ${p.status} ${E}`)}let S=await p.json(),P=qe.filter(c=>!S?.[c]);if(P.length>0)throw n.error("Invalid token response from Google; missing or empty keys:",P.join(", ")),new Error("Invalid token response from Google");let{access_token:s,expires_in:r}=S;return{accessToken:s,refreshToken:k,expirationDateMs:Number(Date.now())+r*1e3}}catch(f){if(f instanceof M)throw f;let g=f instanceof Error?f.message:"Unknown error";throw new M(`Failed to refresh Google access token: ${g}`)}},v=async m=>{let k=m.get(i).provider;if(!k)throw new Error("Provider not found in session");if(k==="google")return await w(m);throw new Error("Provider not supported")};return{authenticate:async(m,h,k)=>{let{failureRedirect:f}=k||{},g=d=>{if(f===null)return new N(d);if(f==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let p=f??a;return d!==void 0?(0,ie.redirect)(p,{headers:{"Set-Cookie":d}}):(0,ie.redirect)(p)};try{if(e.mockUser?.enabled(m)){let{accessToken:r,refreshToken:c,expirationDateMs:T}=e.mockUser.resolve(m);return{accessToken:r,refreshToken:c,expirationDateMs:T}}let d=h.get(i),p=t.sessionGenerationGate;if(d!==void 0&&p!==null&&await p.check(L(d),h.get(x))==="stale")throw g(await t.destroySession(h));if(!(d?.accessToken&&d.expirationDateMs))throw g();let{accessToken:S,refreshToken:P,expirationDateMs:s}=d;if(s<Date.now())throw P?new Error("Expired"):g();return{accessToken:S,refreshToken:P,expirationDateMs:s}}catch(d){if(d instanceof Error&&d.message==="Expired")try{let p=await v(h),S=h.get(i);return h.set(i,{...S,...p}),p}catch(p){if(p instanceof F)n.warn("Google refresh token invalid or revoked");else{let P=p instanceof Error?p.message:"Unknown error";n.error("Failed to refresh token:",P)}let S=await t.destroySession(h);throw g(S)}throw d}},refreshedAccessToken:v}};var ae=require("react-router");var K=({refreshToken:e,...t})=>t;var X=(e,t,n,a)=>{let i=new Map,w=new Map,v=async f=>{let g=i.get(f);if(g!==void 0)return g;let d=w.get(f);if(d!==void 0)return d;let p=(async()=>{try{let S=e.getUserPhoto?await e.getUserPhoto(f):"";return i.set(f,S),S}catch(S){throw i.delete(f),S}finally{w.delete(f)}})();return w.set(f,p),p},A=new WeakMap,m=async f=>{e.warmup&&await e.warmup();let g=await t.resolveSession(f);if(g.kind==="revoked")return{kind:"unauthenticated",cookie:await t.destroySession(g.session)};if(g.kind!=="signed-in")return{kind:"unauthenticated"};let{user:d,session:p}=g,S;try{S=await n.authenticate(f,p,{failureRedirect:null})}catch(b){if(b instanceof N)return b.setCookie!==void 0?{kind:"unauthenticated",cookie:b.setCookie}:{kind:"unauthenticated"};throw a.error("Error in authenticateInLoader:",b),b}let P={accessToken:S.accessToken,refreshToken:S.refreshToken,expirationDateMs:S.expirationDateMs,provider:d.provider},s={id:d.id,displayName:d.displayName,name:d.name,emails:d.emails,...P,role:d.role},r=await v(d.id),c=K({...d,...P,photo:r}),E=S.accessToken!==d.accessToken?await t.saveSession(f,s):void 0;return E!==void 0?{kind:"authenticated",user:c,cookie:E}:{kind:"authenticated",user:c}},h=f=>{let g=A.get(f);if(g!==void 0)return g;let d=m(f);return A.set(f,d),d};async function k(f,g){let{failureRedirect:d}=g;if(d==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let p=await h(f);if(p.kind==="authenticated")return p.cookie!==void 0?{user:p.user,cookie:p.cookie}:{user:p.user};if(d===null)return p.cookie!==void 0?{cookie:p.cookie}:{};throw p.cookie!==void 0?(0,ae.redirect)(d,{headers:{"Set-Cookie":p.cookie}}):(0,ae.redirect)(d)}return k};var me=require("@aiquants/auth-core"),Y=require("react-router"),Se=require("remix-auth");var he=require("remix-auth-oauth2"),De=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],je="google",Ve="https://www.googleapis.com/oauth2/v3/userinfo",H=class extends he.OAuth2Strategy{constructor({clientId:n,clientSecret:a,redirectURI:i,scopes:w,accessType:v,includeGrantedScopes:A,prompt:m,hd:h,loginHint:k,additionalScopes:f},g){let d=w??De;super({clientId:n,clientSecret:a,redirectURI:i,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:d},g);this.name=je;this.scopes=d,this.accessType=v??"online",this.includeGrantedScopes=A??!1,this.prompt=m,this.hd=h,this.loginHint=k,this.additionalScopes=f}authorizationParams(n,a){n.set("access_type",this.accessType),n.set("include_granted_scopes",String(this.includeGrantedScopes));let i=a===void 0||this.additionalScopes===void 0?[]:this.additionalScopes(a);for(let v of i)if(v===""||/\s/u.test(v))throw new RangeError(`[auth-react-router] an additional scope must be a non-empty string without white space; got ${JSON.stringify(v)}`);let w=[...new Set([...this.scopes,...i])];return w.length>0&&n.set("scope",w.join(" ")),this.prompt&&n.set("prompt",this.prompt),this.hd&&n.set("hd",this.hd),this.loginHint&&n.set("login_hint",this.loginHint),n}static async userProfile(n){let a=await fetch(Ve,{headers:{Authorization:`Bearer ${n.accessToken()}`}});if(!a.ok)throw new Error(`Failed to fetch user profile: ${a.statusText}`);let i=await a.json();return{id:i.sub,displayName:i.name,name:{familyName:i.family_name,givenName:i.given_name},emails:[{value:i.email}],photos:[{value:i.picture}],_json:i}}};var q={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var J=e=>{let t=e.logger??q,n=(0,me.resolveAuthMessages)(e.messages),a=e.loginPath??"/auth/login",i=new H({clientId:e.google.clientId,clientSecret:e.google.clientSecret,redirectURI:e.google.redirectURI,scopes:e.google.scopes,accessType:e.google.accessType??"offline",includeGrantedScopes:e.google.includeGrantedScopes??!0,prompt:e.google.prompt??"consent",additionalScopes:e.google.additionalScopes},async({request:v,tokens:A})=>{let{access_token:m,refresh_token:h,expires_in:k,scope:f,id_token:g}=A.data,{_json:{sub:d,email:p,picture:S,hd:P,email_verified:s},photos:r,...c}=await H.userProfile(A),{id:T,displayName:E,name:{familyName:b,givenName:ee},emails:te}=c,u="google";if(m===void 0||h===void 0||k===void 0||f===void 0||T===void 0||E===void 0||d===void 0||p===void 0||s===void 0){if(s===!1){let l=encodeURIComponent(n.emailNotVerified);throw(0,Y.redirect)(`${a}?error=${l}`)}let o=encodeURIComponent(n.googleFailed);throw(0,Y.redirect)(`${a}?error=${o}`)}t.info("Authenticated on Google: ",c.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(u,m)){t.error("Backend verification returned false for user:",c.displayName);let I=encodeURIComponent(n.backendFailed);throw(0,Y.redirect)(`${a}?error=${I}`)}t.info("Authenticated on Backend: ",c.displayName)}let o=c.emails[0]?.value;if(!await e.isEmailAllowed(o)){let G=new Error("You are not allowed to access this application");throw t.error(G),G}if(e.isUserActive&&!await e.isUserActive(c)){let G=new Error("You are not allowed to access this application");throw t.error("Deactivated account attempted to sign in:",o),G}e.backendAuth&&await e.backendAuth.signup(u,m,c),t.info("Authenticated complete: ",c.displayName);let l=Date.now()+k*1e3;return{...c,...{accessToken:m,refreshToken:h,expirationDateMs:l,provider:u},photo:S}}catch(o){let l=o;typeof o=="object"&&o!==null&&"cause"in o&&(l=o.cause||o),t.error("Error during backend authentication or subsequent processing:",l);let y=n.unexpected,R=!1;if(typeof o=="object"&&o!==null&&"cause"in o){let I=o.cause;I&&typeof I=="object"&&"message"in I&&typeof I.message=="string"&&I.message.includes("getaddrinfo ENOTFOUND")&&(y=n.backendUnreachable,R=!0)}if(!R&&o instanceof Error&&o.message.includes("You are not allowed to access this application")&&(y=n.notAllowed,R=!0),!R&&o instanceof Response&&o.headers.get("Location")?.startsWith(a))throw o;let G=encodeURIComponent(y);throw(0,Y.redirect)(`${a}?error=${G}`)}}),w=new Se.Authenticator;return w.use(i),w};var D=require("react-router");var Ke=new Map([["document",new Set(["none","same-origin","same-site"])],["empty",new Set(["same-origin"])]]),W=e=>{let t=e.headers.get("Sec-Fetch-Dest");if(t!==null){let a=Ke.get(t);if(a===void 0)return`its fetch destination is "${t}"`;let i=e.headers.get("Sec-Fetch-Site");if(i===null)return`its "${t}" request states no site`;if(!a.has(i))return`its "${t}" request comes from a "${i}" page`}let n=e.headers.get("Sec-Purpose");if(n!==null)return`it is speculative ("${n}")`},z=e=>new Response(`Signing out is refused because ${e}: only a navigation that does not come from another site, or a script's request from this origin, signs out.`,{status:403,headers:{"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"}});var Q=(e,t,n,a)=>{let i=e.loginPath??"/auth/login",w=e.postLoginRedirect??"/",v=e.postLogoutRedirect??"/",A=de(e.google.revocationTimeoutMs),m=async({request:s})=>{if(await t.getSessionUser(s))throw(0,D.redirect)(w);return{error:new URL(s.url).searchParams.get("error")}},h=async({request:s})=>{if((await s.clone().formData()).get("_action")!=="Sign In with Google")return null;throw await n.authenticate("google",s),(0,D.redirect)(i)},k=(s,r)=>{switch(s.outcome){case"failed":a.error(`Sign-out could not revoke the Google grant of user ${String(r)}; the session cookie is destroyed, but the grant stays valid until it expires or is revoked elsewhere:`,s.reason);return;case"already-invalid":a.info(`Sign-out found the Google grant of user ${String(r)} already unusable`);return;case"revoked":case"nothing-to-revoke":return}},f=(s,r)=>{s.kind!=="advanced"&&a.error(`Sign-out could not advance the session generation of ${r.provider} user ${r.id}; a session cookie refreshed before this sign-out stays valid until a later sign-out advances the generation or the cookie expires:`,s.error)},g=async(s,r)=>{let c=t.sessionGenerationGate;if(c!==null){if(!$(r)){a.info(`Sign-out found no usable session generation stamp in the session of ${s.provider} user ${s.id}; every guard already rejects that cookie, so the generation is not advanced`);return}f(await c.advance(s,r),s)}},d=async s=>{let r=await t.getSession(s),c=r.get(t.sessionKey),[T]=await Promise.all([le(c,{fetch:e.fetch??globalThis.fetch,timeoutMs:A}),c===void 0?void 0:g(L(c),r.get(x))]);return k(T,c?.id),await t.destroySession(r)},p=async s=>{let r=await d(s),c=new Headers;return c.append("Set-Cookie",r),(0,D.redirect)(v,{headers:c})};return{loginLoader:m,loginAction:h,logoutLoader:async({request:s})=>{let r=W(s);throw r!==void 0?z(r):await p(s)},logout:d,logoutAndRedirect:p,googleCallbackLoader:async({request:s})=>{try{let r=await n.authenticate("google",s),E=(await t.getSession(s)).get(t.sessionKey)?.refreshToken,b={accessToken:r.accessToken,refreshToken:r.refreshToken||E,expirationDateMs:r.expirationDateMs,provider:r.provider},ee={id:r.id,displayName:r.displayName,name:r.name,emails:r.emails,...b,role:r.role},te=await t.saveSignedInSession(s,ee);throw(0,D.redirect)(w,{headers:{"Set-Cookie":te}})}catch(r){throw r instanceof Response?r:(a.error("Authentication error:",r),(0,D.redirect)(i))}}}};var j=require("react-router");var Z=(e,t)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(s=>!s))throw new Error("REMIX_SESSION_SECRET must be set");let n=e.sessionKey??"user";if(n===x)throw new RangeError(`session.sessionKey must not be ${JSON.stringify(x)}, the key the session generation is stored under; got ${JSON.stringify(n)}`);let a=e.maxAge??3600*24*30,i=t.loginPath??"/auth/login",w=t.postLoginRedirect??"/",v=t.mockUser,A=t.isUserActive,m=ge(t.sessionGeneration,t.logger??q),h=(0,j.createCookieSessionStorage)({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:e.secure??process.env.NODE_ENV==="production",maxAge:a}}),k=async s=>await h.getSession(s.headers.get("Cookie")),f=async s=>{if(v?.enabled(s))return{kind:"signed-in",user:K(v.resolve(s)),session:await k(s)};let r=await k(s),c=r.get(n);if(c===void 0)return{kind:"signed-out"};let T=K(c),[E,b]=await Promise.all([A===void 0?!0:A(T),m===null?"current":m.check(L(c),r.get(x))]);return b==="stale"?{kind:"revoked",session:r}:E?{kind:"signed-in",user:T,session:r}:{kind:"inactive"}},g=async s=>{let r=await f(s);return r.kind==="signed-in"?r.user:void 0},d=async(s,r)=>{let c=await k(s);return c.set(n,r),await h.commitSession(c)},p=async(s,r)=>{let c=m===null?void 0:await m.stamp(L(r)),T=await k(s);return T.set(n,r),c!==void 0&&T.set(x,c),await h.commitSession(T)},S=async s=>{let r=await f(s);switch(r.kind){case"signed-in":return r.user;case"revoked":throw(0,j.redirect)(i,{headers:{"Set-Cookie":await h.destroySession(r.session)}});case"signed-out":case"inactive":throw(0,j.redirect)(i)}};return{sessionStorage:h,sessionKey:n,sessionGenerationGate:m,getSession:k,resolveSession:f,getSessionUser:g,saveSession:d,saveSignedInSession:p,requireUser:S,requireAdminUser:async s=>{let r=await S(s);if(r.role!=="admin")throw(0,j.redirect)(w);return r},commitSession:h.commitSession,destroySession:h.destroySession}};var ye=e=>{let t=e.logger??q,n=Z(e.session,{sessionGeneration:e.sessionGeneration,logger:t,mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive}),a=J(e),i=B(e,n,t),w=X(e,n,i,t),v=Q(e,n,a,t);return{authenticator:a,storage:n,authFns:i,sessionStorage:n.sessionStorage,getSession:n.getSession,getSessionUser:n.getSessionUser,saveSession:n.saveSession,requireUser:n.requireUser,requireAdminUser:n.requireAdminUser,commitSession:n.commitSession,destroySession:n.destroySession,authenticate:i.authenticate,refreshedAccessToken:i.refreshedAccessToken,authenticateInLoader:w,...v}};0&&(module.exports={AuthRequiredError,DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS,DEFAULT_SESSION_GENERATION_CACHE_TTL_MS,DEFAULT_SESSION_GENERATION_TIMEOUT_MS,GoogleInvalidGrantError,SessionGenerationUnavailableError,TokenRefreshError,createAuthHandlers,createAuthServer,createAuthSessionStorage,createAuthenticate,createAuthenticateInLoader,createGoogleAuthenticator,signOutRefusal,signOutRefusalResponse});
|
package/dist/server.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{redirect as le}from"react-router";var ge="https://oauth2.googleapis.com/revoke",he=5e3;var me="google",Se="invalid_token";var re=e=>{if(e===void 0)return 5e3;if(!Number.isInteger(e)||e<1||e>2147483647)throw new RangeError(`google.revocationTimeoutMs must be an integer from 1 to 2147483647 (milliseconds); got ${String(e)}`);return e},ye=e=>{if(typeof e.refreshToken=="string"&&e.refreshToken!=="")return e.refreshToken;if(typeof e.accessToken=="string"&&e.accessToken!=="")return e.accessToken},we=async e=>{let t=await e.json().catch(()=>{});return typeof t=="object"&&t!==null&&"error"in t&&typeof t.error=="string"?t.error:void 0},ke=e=>e instanceof Error?e.cause instanceof Error?`${e.message} (${e.cause.message})`:e.message:String(e),ve=async(e,t,n)=>{try{let c=await t(ge,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:e}).toString(),signal:n});if(c.ok)return await c.body?.cancel(),{outcome:"revoked"};let u=await we(c);return c.status===400&&u===Se?{outcome:"already-invalid"}:{outcome:"failed",reason:u===void 0?`Google answered ${c.status}`:`Google answered ${c.status} ${u}`}}catch(c){return{outcome:"failed",reason:ke(c)}}},se=async(e,t)=>{if(e===void 0)return{outcome:"nothing-to-revoke"};let n=ye(e);if(n===void 0)return{outcome:"nothing-to-revoke"};if(e.provider!==me)return{outcome:"failed",reason:`the session's provider "${String(e.provider)}" has no revocation endpoint`};let c=new AbortController;return await new Promise(u=>{let k=setTimeout(()=>{u({outcome:"failed",reason:`Google did not answer within ${t.timeoutMs} ms`}),c.abort()},t.timeoutMs);ve(n,t.fetch,c.signal).then(v=>{clearTimeout(k),u(v)})})};var x="generation",ce=15e3,ue=3e3,Ge=6e4,q=class extends Error{constructor(t,n){super(t,n),this.name="SessionGenerationUnavailableError"}},O=e=>typeof e=="string"?JSON.stringify(e):typeof e=="function"?"a function":typeof e=="object"&&e!==null?Array.isArray(e)?"an array":"an object":typeof e=="bigint"?`${e}n`:String(e),Te=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return O(e);let t="store"in e?e.store:void 0;if(typeof t!="object"||t===null)return`an object whose store is ${O(t)}`;let n="current"in t?t.current:void 0,c="advance"in t?t.advance:void 0;return`an object whose store.current is ${O(n)} and store.advance is ${O(c)}`},Pe=e=>typeof e=="object"&&e!==null&&"current"in e&&typeof e.current=="function"&&"advance"in e&&typeof e.advance=="function",ie=(e,t,n,c)=>{if(t===void 0)return c;if(typeof t!="number"||!Number.isInteger(t)||t<n||t>2147483647)throw new RangeError(`${e} must be an integer from ${n} to ${2147483647} (milliseconds); got ${O(t)}`);return t},Re=e=>{if(e===!1)return!1;let t=e;if(typeof t!="object"||t===null||!("store"in t)||!Pe(t.store))throw new TypeError(`sessionGeneration must be { store, cacheTtlMs?, timeoutMs? } or false; got ${Te(t)}`);return{store:t.store,cacheTtlMs:ie("sessionGeneration.cacheTtlMs","cacheTtlMs"in t?t.cacheTtlMs:void 0,0,ce),timeoutMs:ie("sessionGeneration.timeoutMs","timeoutMs"in t?t.timeoutMs:void 0,1,ue)}},N=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,X=e=>typeof e.provider=="string"&&e.provider!==""&&typeof e.id=="string"&&e.id!=="",ae=e=>new TypeError(`a session generation identity needs a non-empty provider and id; got provider ${O(e.provider)} and id ${O(e.id)}`),Ee=e=>N(e)&&N(e+1),_e=e=>new TypeError(`a session generation advance needs the signed-out session's stamp, an integer from 0 to ${Number.MAX_SAFE_INTEGER-1}; got ${O(e)}`),U=e=>({provider:e.provider,id:e.id}),de=(e,t)=>{let n=Re(e);if(n===!1)return null;let{store:c,cacheTtlMs:u,timeoutMs:k}=n,v=new Map,A=new Map,S=new Map,h=new Map,w=Number.NEGATIVE_INFINITY,f=i=>`${i.provider}\0${i.id}`,g=(i,o)=>{let d=v.get(i);if(d!==void 0){if(o-d.at<u)return d;v.delete(i)}},l=(i,o,d)=>{if(d!==void 0&&o.at<=d.answeredAt&&o.value<d.value)return;let y=g(i,performance.now());if(y===void 0){v.set(i,o);return}o.value<y.value||v.set(i,{value:o.value,at:Math.max(y.at,o.at)})},p=i=>{let o=h.get(i);if(o!==void 0)return o.count+=1,o;let d={count:1,floor:void 0};return h.set(i,d),d},m=(i,o)=>{o.count-=1,o.count===0&&h.delete(i)},R=(i,o)=>{i.floor={value:i.floor===void 0?o:Math.max(i.floor.value,o),answeredAt:performance.now()}},s=(i,o)=>{let d=S.get(i);return d===void 0?!1:o<d?!0:(S.delete(i),!1)},r=(i,o)=>{let d=performance.now();return S.set(i,d+u),d-w>=Ge&&(w=d,t.warn("Session generation store unavailable; skipping the sign-out generation check:",o)),"unavailable"},a=(i,o,d)=>new Promise((y,T)=>{let{operation:G}=i,I=i.operation==="advance"?i.from+1:0,pe=performance.now(),F=p(d),M=!1,ne=setTimeout(()=>{M=!0,y({kind:"unavailable",error:new q(`sessionGeneration.store.${G} did not settle within ${k} ms`)})},k);new Promise(_=>_(i.operation==="advance"?c.advance(o,i.from):c.current(o))).then(_=>{if(clearTimeout(ne),!(N(_)&&_>=I)){m(d,F),M||(M=!0,T(new TypeError(`sessionGeneration.store.${G} must resolve to an integer >= ${I}; got ${O(_)}`)));return}G==="advance"&&(R(F,_),A.delete(d)),l(d,{value:_,at:pe},F.floor),m(d,F),!M&&(M=!0,S.delete(d),y({kind:"value",value:_}))},_=>{if(clearTimeout(ne),m(d,F),!M){if(M=!0,_ instanceof q){y({kind:"unavailable",error:_});return}T(_)}})}),P=(i,o,d)=>{let y=A.get(o);if(y!==void 0&&d-y.startedAt<u)return y.read;let T={read:a({operation:"current"},i,o),startedAt:d};A.set(o,T);let G=()=>{A.get(o)===T&&A.delete(o)};return T.read.then(G,G),T.read},E=async(i,o,d)=>{let y=await a({operation:"current"},i,o);return y.kind==="unavailable"?r(o,y.error):d===y.value?"current":"stale"};return{check:async(i,o)=>{if(!(N(o)&&X(i)))return"stale";let d=performance.now(),y=f(i),T=g(y,d);if(T!==void 0){if(o===T.value)return"current";if(o<T.value)return"stale"}if(s(y,d))return"unavailable";if(T!==void 0)return await E(i,y,o);let G=await P(i,y,d);return G.kind==="unavailable"?r(y,G.error):o===G.value?"current":o<G.value?"stale":await E(i,y,o)},stamp:async i=>{if(!X(i))throw ae(i);let o=await a({operation:"current"},i,f(i));if(o.kind==="unavailable")throw o.error;return o.value},advance:async(i,o)=>{if(!X(i))return{kind:"failed",error:ae(i)};if(!Ee(o))return{kind:"failed",error:_e(o)};try{let d=await a({operation:"advance",from:o},i,f(i));return d.kind==="value"?{kind:"advanced",generation:d.value}:{kind:"unavailable",error:d.error}}catch(d){return{kind:"failed",error:d}}}}};var L=class extends Error{constructor(t){super(t),this.name="TokenRefreshError"}},D=class extends L{constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},C=class extends Error{constructor(t){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=t}},be=["access_token","expires_in"],W=(e,t,n)=>{let c=e.loginPath??"/auth/login",u=t.sessionKey,k=async S=>{let w=S.get(u)?.refreshToken;if(!w)throw new Error("Refresh token not found in session");try{let f="https://www.googleapis.com/oauth2/v4/token",g={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:w},p=await(e.fetch??globalThis.fetch)(f,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(g)});if(!p.ok){let a=await p.json().catch(()=>{});if(p.status===400&&typeof a=="object"&&!!a&&"error"in a&&a.error==="invalid_grant")throw new D;let E=typeof a=="object"&&a&&"error_description"in a?String(a.error_description):"Unknown error";throw new L(`Google token refresh failed: ${p.status} ${E}`)}let m=await p.json(),R=be.filter(a=>!m?.[a]);if(R.length>0)throw n.error("Invalid token response from Google; missing or empty keys:",R.join(", ")),new Error("Invalid token response from Google");let{access_token:s,expires_in:r}=m;return{accessToken:s,refreshToken:w,expirationDateMs:Number(Date.now())+r*1e3}}catch(f){if(f instanceof L)throw f;let g=f instanceof Error?f.message:"Unknown error";throw new L(`Failed to refresh Google access token: ${g}`)}},v=async S=>{let w=S.get(u).provider;if(!w)throw new Error("Provider not found in session");if(w==="google")return await k(S);throw new Error("Provider not supported")};return{authenticate:async(S,h,w)=>{let{failureRedirect:f}=w||{},g=l=>{if(f===null)return new C(l);if(f==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let p=f??c;return l!==void 0?le(p,{headers:{"Set-Cookie":l}}):le(p)};try{if(e.mockUser?.enabled(S))return{accessToken:"mock-access-token",refreshToken:"mock-refresh-token",expirationDateMs:Date.now()+36e5};let l=h.get(u),p=t.sessionGenerationGate;if(l!==void 0&&p!==null&&await p.check(U(l),h.get(x))==="stale")throw g(await t.destroySession(h));if(!(l?.accessToken&&l.expirationDateMs))throw g();let{accessToken:m,refreshToken:R,expirationDateMs:s}=l;if(s<Date.now())throw R?new Error("Expired"):g();return{accessToken:m,refreshToken:R,expirationDateMs:s}}catch(l){if(l instanceof Error&&l.message==="Expired")try{let p=await v(h),m=h.get(u);return h.set(u,{...m,...p}),p}catch(p){if(p instanceof D)n.warn("Google refresh token invalid or revoked");else{let R=p instanceof Error?p.message:"Unknown error";n.error("Failed to refresh token:",R)}let m=await t.destroySession(h);throw g(m)}throw l}},refreshedAccessToken:v}};import{redirect as fe}from"react-router";var j=({refreshToken:e,...t})=>t;var J=(e,t,n,c)=>{let u=new Map,k=new Map,v=async f=>{let g=u.get(f);if(g!==void 0)return g;let l=k.get(f);if(l!==void 0)return l;let p=(async()=>{try{let m=e.getUserPhoto?await e.getUserPhoto(f):"";return u.set(f,m),m}catch(m){throw u.delete(f),m}finally{k.delete(f)}})();return k.set(f,p),p},A=new WeakMap,S=async f=>{e.warmup&&await e.warmup();let g=await t.resolveSession(f);if(g.kind==="revoked")return{kind:"unauthenticated",cookie:await t.destroySession(g.session)};if(g.kind!=="signed-in")return{kind:"unauthenticated"};let{user:l,session:p}=g,m;try{m=await n.authenticate(f,p,{failureRedirect:null})}catch(b){if(b instanceof C)return b.setCookie!==void 0?{kind:"unauthenticated",cookie:b.setCookie}:{kind:"unauthenticated"};throw c.error("Error in authenticateInLoader:",b),b}let R={accessToken:m.accessToken,refreshToken:m.refreshToken,expirationDateMs:m.expirationDateMs,provider:l.provider},s={id:l.id,displayName:l.displayName,name:l.name,emails:l.emails,...R,role:l.role},r=await v(l.id),a=j({...l,...R,photo:r}),E=m.accessToken!==l.accessToken?await t.saveSession(f,s):void 0;return E!==void 0?{kind:"authenticated",user:a,cookie:E}:{kind:"authenticated",user:a}},h=f=>{let g=A.get(f);if(g!==void 0)return g;let l=S(f);return A.set(f,l),l};async function w(f,g){let{failureRedirect:l}=g;if(l==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let p=await h(f);if(p.kind==="authenticated")return p.cookie!==void 0?{user:p.user,cookie:p.cookie}:{user:p.user};if(l===null)return p.cookie!==void 0?{cookie:p.cookie}:{};throw p.cookie!==void 0?fe(l,{headers:{"Set-Cookie":p.cookie}}):fe(l)}return w};import{resolveAuthMessages as Ue}from"@aiquants/auth-core";import{redirect as H}from"react-router";import{Authenticator as Le}from"remix-auth";import{OAuth2Strategy as Ie}from"remix-auth-oauth2";var Oe=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],xe="google",Me="https://www.googleapis.com/oauth2/v3/userinfo",V=class extends Ie{constructor({clientId:n,clientSecret:c,redirectURI:u,scopes:k,accessType:v,includeGrantedScopes:A,prompt:S,hd:h,loginHint:w},f){let g=k??Oe;super({clientId:n,clientSecret:c,redirectURI:u,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:g},f);this.name=xe;this.scopes=g,this.accessType=v??"online",this.includeGrantedScopes=A??!1,this.prompt=S,this.hd=h,this.loginHint=w}authorizationParams(n,c){return n.set("access_type",this.accessType),n.set("include_granted_scopes",String(this.includeGrantedScopes)),this.scopes&&this.scopes.length>0&&n.set("scope",this.scopes.join(" ")),this.prompt&&n.set("prompt",this.prompt),this.hd&&n.set("hd",this.hd),this.loginHint&&n.set("login_hint",this.loginHint),n}static async userProfile(n){let c=await fetch(Me,{headers:{Authorization:`Bearer ${n.accessToken()}`}});if(!c.ok)throw new Error(`Failed to fetch user profile: ${c.statusText}`);let u=await c.json();return{id:u.sub,displayName:u.name,name:{familyName:u.family_name,givenName:u.given_name},emails:[{value:u.email}],photos:[{value:u.picture}],_json:u}}};var $={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var z=e=>{let t=e.logger??$,n=Ue(e.messages),c=e.loginPath??"/auth/login",u=new V({clientId:e.google.clientId,clientSecret:e.google.clientSecret,redirectURI:e.google.redirectURI,scopes:e.google.scopes,accessType:e.google.accessType??"offline",includeGrantedScopes:e.google.includeGrantedScopes??!0,prompt:e.google.prompt??"consent"},async({request:v,tokens:A})=>{let{access_token:S,refresh_token:h,expires_in:w,scope:f,id_token:g}=A.data,{_json:{sub:l,email:p,picture:m,hd:R,email_verified:s},photos:r,...a}=await V.userProfile(A),{id:P,displayName:E,name:{familyName:b,givenName:Y},emails:B}=a,i="google";if(S===void 0||h===void 0||w===void 0||f===void 0||P===void 0||E===void 0||l===void 0||p===void 0||s===void 0){if(s===!1){let d=encodeURIComponent(n.emailNotVerified);throw H(`${c}?error=${d}`)}let o=encodeURIComponent(n.googleFailed);throw H(`${c}?error=${o}`)}t.info("Authenticated on Google: ",a.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(i,S)){t.error("Backend verification returned false for user:",a.displayName);let I=encodeURIComponent(n.backendFailed);throw H(`${c}?error=${I}`)}t.info("Authenticated on Backend: ",a.displayName)}let o=a.emails[0]?.value;if(!await e.isEmailAllowed(o)){let G=new Error("You are not allowed to access this application");throw t.error(G),G}if(e.isUserActive&&!await e.isUserActive(a)){let G=new Error("You are not allowed to access this application");throw t.error("Deactivated account attempted to sign in:",o),G}e.backendAuth&&await e.backendAuth.signup(i,S,a),t.info("Authenticated complete: ",a.displayName);let d=Date.now()+w*1e3;return{...a,...{accessToken:S,refreshToken:h,expirationDateMs:d,provider:i},photo:m}}catch(o){let d=o;typeof o=="object"&&o!==null&&"cause"in o&&(d=o.cause||o),t.error("Error during backend authentication or subsequent processing:",d);let y=n.unexpected,T=!1;if(typeof o=="object"&&o!==null&&"cause"in o){let I=o.cause;I&&typeof I=="object"&&"message"in I&&typeof I.message=="string"&&I.message.includes("getaddrinfo ENOTFOUND")&&(y=n.backendUnreachable,T=!0)}if(!T&&o instanceof Error&&o.message.includes("You are not allowed to access this application")&&(y=n.notAllowed,T=!0),!T&&o instanceof Response&&o.headers.get("Location")?.startsWith(c))throw o;let G=encodeURIComponent(y);throw H(`${c}?error=${G}`)}}),k=new Le;return k.use(u),k};import{redirect as K}from"react-router";var Ne=new Map([["document",new Set(["none","same-origin","same-site"])],["empty",new Set(["same-origin"])]]),Q=e=>{let t=e.headers.get("Sec-Fetch-Dest");if(t!==null){let c=Ne.get(t);if(c===void 0)return`its fetch destination is "${t}"`;let u=e.headers.get("Sec-Fetch-Site");if(u===null)return`its "${t}" request states no site`;if(!c.has(u))return`its "${t}" request comes from a "${u}" page`}let n=e.headers.get("Sec-Purpose");if(n!==null)return`it is speculative ("${n}")`},Z=e=>new Response(`Signing out is refused because ${e}: only a navigation that does not come from another site, or a script's request from this origin, signs out.`,{status:403,headers:{"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"}});var ee=(e,t,n,c)=>{let u=e.loginPath??"/auth/login",k=e.postLoginRedirect??"/",v=e.postLogoutRedirect??"/",A=re(e.google.revocationTimeoutMs),S=async({request:s})=>{if(await t.getSessionUser(s))throw K(k);return{error:new URL(s.url).searchParams.get("error")}},h=async({request:s})=>{if((await s.clone().formData()).get("_action")!=="Sign In with Google")return null;throw await n.authenticate("google",s),K(u)},w=(s,r)=>{switch(s.outcome){case"failed":c.error(`Sign-out could not revoke the Google grant of user ${String(r)}; the session cookie is destroyed, but the grant stays valid until it expires or is revoked elsewhere:`,s.reason);return;case"already-invalid":c.info(`Sign-out found the Google grant of user ${String(r)} already unusable`);return;case"revoked":case"nothing-to-revoke":return}},f=(s,r)=>{s.kind!=="advanced"&&c.error(`Sign-out could not advance the session generation of ${r.provider} user ${r.id}; a session cookie refreshed before this sign-out stays valid until a later sign-out advances the generation or the cookie expires:`,s.error)},g=async(s,r)=>{let a=t.sessionGenerationGate;if(a!==null){if(!N(r)){c.info(`Sign-out found no usable session generation stamp in the session of ${s.provider} user ${s.id}; every guard already rejects that cookie, so the generation is not advanced`);return}f(await a.advance(s,r),s)}},l=async s=>{let r=await t.getSession(s),a=r.get(t.sessionKey),[P]=await Promise.all([se(a,{fetch:e.fetch??globalThis.fetch,timeoutMs:A}),a===void 0?void 0:g(U(a),r.get(x))]);return w(P,a?.id),await t.destroySession(r)},p=async s=>{let r=await l(s),a=new Headers;return a.append("Set-Cookie",r),K(v,{headers:a})};return{loginLoader:S,loginAction:h,logoutLoader:async({request:s})=>{let r=Q(s);throw r!==void 0?Z(r):await p(s)},logout:l,logoutAndRedirect:p,googleCallbackLoader:async({request:s})=>{try{let r=await n.authenticate("google",s),E=(await t.getSession(s)).get(t.sessionKey)?.refreshToken,b={accessToken:r.accessToken,refreshToken:r.refreshToken||E,expirationDateMs:r.expirationDateMs,provider:r.provider},Y={id:r.id,displayName:r.displayName,name:r.name,emails:r.emails,...b,role:r.role},B=await t.saveSignedInSession(s,Y);throw K(k,{headers:{"Set-Cookie":B}})}catch(r){throw r instanceof Response?r:(c.error("Authentication error:",r),K(u))}}}};import{createCookieSessionStorage as Ce,redirect as te}from"react-router";var oe=(e,t)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(s=>!s))throw new Error("REMIX_SESSION_SECRET must be set");let n=e.sessionKey??"user";if(n===x)throw new RangeError(`session.sessionKey must not be ${JSON.stringify(x)}, the key the session generation is stored under; got ${JSON.stringify(n)}`);let c=e.maxAge??3600*24*30,u=t.loginPath??"/auth/login",k=t.postLoginRedirect??"/",v=t.mockUser,A=t.isUserActive,S=de(t.sessionGeneration,t.logger??$),h=Ce({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:e.secure??process.env.NODE_ENV==="production",maxAge:c}}),w=async s=>await h.getSession(s.headers.get("Cookie")),f=async s=>{if(v?.enabled(s))return{kind:"signed-in",user:j(v.resolve(s)),session:await w(s)};let r=await w(s),a=r.get(n);if(a===void 0)return{kind:"signed-out"};let P=j(a),[E,b]=await Promise.all([A===void 0?!0:A(P),S===null?"current":S.check(U(a),r.get(x))]);return b==="stale"?{kind:"revoked",session:r}:E?{kind:"signed-in",user:P,session:r}:{kind:"inactive"}},g=async s=>{let r=await f(s);return r.kind==="signed-in"?r.user:void 0},l=async(s,r)=>{let a=await w(s);return a.set(n,r),await h.commitSession(a)},p=async(s,r)=>{let a=S===null?void 0:await S.stamp(U(r)),P=await w(s);return P.set(n,r),a!==void 0&&P.set(x,a),await h.commitSession(P)},m=async s=>{let r=await f(s);switch(r.kind){case"signed-in":return r.user;case"revoked":throw te(u,{headers:{"Set-Cookie":await h.destroySession(r.session)}});case"signed-out":case"inactive":throw te(u)}};return{sessionStorage:h,sessionKey:n,sessionGenerationGate:S,getSession:w,resolveSession:f,getSessionUser:g,saveSession:l,saveSignedInSession:p,requireUser:m,requireAdminUser:async s=>{let r=await m(s);if(r.role!=="admin")throw te(k);return r},commitSession:h.commitSession,destroySession:h.destroySession}};var $e=e=>{let t=e.logger??$,n=oe(e.session,{sessionGeneration:e.sessionGeneration,logger:t,mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive}),c=z(e),u=W(e,n,t),k=J(e,n,u,t),v=ee(e,n,c,t);return{authenticator:c,storage:n,authFns:u,sessionStorage:n.sessionStorage,getSession:n.getSession,getSessionUser:n.getSessionUser,saveSession:n.saveSession,requireUser:n.requireUser,requireAdminUser:n.requireAdminUser,commitSession:n.commitSession,destroySession:n.destroySession,authenticate:u.authenticate,refreshedAccessToken:u.refreshedAccessToken,authenticateInLoader:k,...v}};export{C as AuthRequiredError,he as DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS,ce as DEFAULT_SESSION_GENERATION_CACHE_TTL_MS,ue as DEFAULT_SESSION_GENERATION_TIMEOUT_MS,D as GoogleInvalidGrantError,q as SessionGenerationUnavailableError,L as TokenRefreshError,ee as createAuthHandlers,$e as createAuthServer,oe as createAuthSessionStorage,W as createAuthenticate,J as createAuthenticateInLoader,z as createGoogleAuthenticator,Q as signOutRefusal,Z as signOutRefusalResponse};
|
|
1
|
+
import{redirect as le}from"react-router";var ge="https://oauth2.googleapis.com/revoke",he=5e3;var me="google",Se="invalid_token";var re=e=>{if(e===void 0)return 5e3;if(!Number.isInteger(e)||e<1||e>2147483647)throw new RangeError(`google.revocationTimeoutMs must be an integer from 1 to 2147483647 (milliseconds); got ${String(e)}`);return e},ye=e=>{if(typeof e.refreshToken=="string"&&e.refreshToken!=="")return e.refreshToken;if(typeof e.accessToken=="string"&&e.accessToken!=="")return e.accessToken},we=async e=>{let t=await e.json().catch(()=>{});return typeof t=="object"&&t!==null&&"error"in t&&typeof t.error=="string"?t.error:void 0},ke=e=>e instanceof Error?e.cause instanceof Error?`${e.message} (${e.cause.message})`:e.message:String(e),ve=async(e,t,n)=>{try{let c=await t(ge,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:e}).toString(),signal:n});if(c.ok)return await c.body?.cancel(),{outcome:"revoked"};let u=await we(c);return c.status===400&&u===Se?{outcome:"already-invalid"}:{outcome:"failed",reason:u===void 0?`Google answered ${c.status}`:`Google answered ${c.status} ${u}`}}catch(c){return{outcome:"failed",reason:ke(c)}}},se=async(e,t)=>{if(e===void 0)return{outcome:"nothing-to-revoke"};let n=ye(e);if(n===void 0)return{outcome:"nothing-to-revoke"};if(e.provider!==me)return{outcome:"failed",reason:`the session's provider "${String(e.provider)}" has no revocation endpoint`};let c=new AbortController;return await new Promise(u=>{let w=setTimeout(()=>{u({outcome:"failed",reason:`Google did not answer within ${t.timeoutMs} ms`}),c.abort()},t.timeoutMs);ve(n,t.fetch,c.signal).then(v=>{clearTimeout(w),u(v)})})};var x="generation",ce=15e3,ue=3e3,Ge=6e4,q=class extends Error{constructor(t,n){super(t,n),this.name="SessionGenerationUnavailableError"}},O=e=>typeof e=="string"?JSON.stringify(e):typeof e=="function"?"a function":typeof e=="object"&&e!==null?Array.isArray(e)?"an array":"an object":typeof e=="bigint"?`${e}n`:String(e),Te=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return O(e);let t="store"in e?e.store:void 0;if(typeof t!="object"||t===null)return`an object whose store is ${O(t)}`;let n="current"in t?t.current:void 0,c="advance"in t?t.advance:void 0;return`an object whose store.current is ${O(n)} and store.advance is ${O(c)}`},Re=e=>typeof e=="object"&&e!==null&&"current"in e&&typeof e.current=="function"&&"advance"in e&&typeof e.advance=="function",ie=(e,t,n,c)=>{if(t===void 0)return c;if(typeof t!="number"||!Number.isInteger(t)||t<n||t>2147483647)throw new RangeError(`${e} must be an integer from ${n} to ${2147483647} (milliseconds); got ${O(t)}`);return t},Pe=e=>{if(e===!1)return!1;let t=e;if(typeof t!="object"||t===null||!("store"in t)||!Re(t.store))throw new TypeError(`sessionGeneration must be { store, cacheTtlMs?, timeoutMs? } or false; got ${Te(t)}`);return{store:t.store,cacheTtlMs:ie("sessionGeneration.cacheTtlMs","cacheTtlMs"in t?t.cacheTtlMs:void 0,0,ce),timeoutMs:ie("sessionGeneration.timeoutMs","timeoutMs"in t?t.timeoutMs:void 0,1,ue)}},N=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,X=e=>typeof e.provider=="string"&&e.provider!==""&&typeof e.id=="string"&&e.id!=="",ae=e=>new TypeError(`a session generation identity needs a non-empty provider and id; got provider ${O(e.provider)} and id ${O(e.id)}`),Ee=e=>N(e)&&N(e+1),_e=e=>new TypeError(`a session generation advance needs the signed-out session's stamp, an integer from 0 to ${Number.MAX_SAFE_INTEGER-1}; got ${O(e)}`),U=e=>({provider:e.provider,id:e.id}),de=(e,t)=>{let n=Pe(e);if(n===!1)return null;let{store:c,cacheTtlMs:u,timeoutMs:w}=n,v=new Map,A=new Map,m=new Map,h=new Map,k=Number.NEGATIVE_INFINITY,f=a=>`${a.provider}\0${a.id}`,g=(a,o)=>{let l=v.get(a);if(l!==void 0){if(o-l.at<u)return l;v.delete(a)}},d=(a,o,l)=>{if(l!==void 0&&o.at<=l.answeredAt&&o.value<l.value)return;let y=g(a,performance.now());if(y===void 0){v.set(a,o);return}o.value<y.value||v.set(a,{value:o.value,at:Math.max(y.at,o.at)})},p=a=>{let o=h.get(a);if(o!==void 0)return o.count+=1,o;let l={count:1,floor:void 0};return h.set(a,l),l},S=(a,o)=>{o.count-=1,o.count===0&&h.delete(a)},P=(a,o)=>{a.floor={value:a.floor===void 0?o:Math.max(a.floor.value,o),answeredAt:performance.now()}},s=(a,o)=>{let l=m.get(a);return l===void 0?!1:o<l?!0:(m.delete(a),!1)},r=(a,o)=>{let l=performance.now();return m.set(a,l+u),l-k>=Ge&&(k=l,t.warn("Session generation store unavailable; skipping the sign-out generation check:",o)),"unavailable"},i=(a,o,l)=>new Promise((y,R)=>{let{operation:G}=a,I=a.operation==="advance"?a.from+1:0,pe=performance.now(),F=p(l),M=!1,ne=setTimeout(()=>{M=!0,y({kind:"unavailable",error:new q(`sessionGeneration.store.${G} did not settle within ${w} ms`)})},w);new Promise(_=>_(a.operation==="advance"?c.advance(o,a.from):c.current(o))).then(_=>{if(clearTimeout(ne),!(N(_)&&_>=I)){S(l,F),M||(M=!0,R(new TypeError(`sessionGeneration.store.${G} must resolve to an integer >= ${I}; got ${O(_)}`)));return}G==="advance"&&(P(F,_),A.delete(l)),d(l,{value:_,at:pe},F.floor),S(l,F),!M&&(M=!0,m.delete(l),y({kind:"value",value:_}))},_=>{if(clearTimeout(ne),S(l,F),!M){if(M=!0,_ instanceof q){y({kind:"unavailable",error:_});return}R(_)}})}),T=(a,o,l)=>{let y=A.get(o);if(y!==void 0&&l-y.startedAt<u)return y.read;let R={read:i({operation:"current"},a,o),startedAt:l};A.set(o,R);let G=()=>{A.get(o)===R&&A.delete(o)};return R.read.then(G,G),R.read},E=async(a,o,l)=>{let y=await i({operation:"current"},a,o);return y.kind==="unavailable"?r(o,y.error):l===y.value?"current":"stale"};return{check:async(a,o)=>{if(!(N(o)&&X(a)))return"stale";let l=performance.now(),y=f(a),R=g(y,l);if(R!==void 0){if(o===R.value)return"current";if(o<R.value)return"stale"}if(s(y,l))return"unavailable";if(R!==void 0)return await E(a,y,o);let G=await T(a,y,l);return G.kind==="unavailable"?r(y,G.error):o===G.value?"current":o<G.value?"stale":await E(a,y,o)},stamp:async a=>{if(!X(a))throw ae(a);let o=await i({operation:"current"},a,f(a));if(o.kind==="unavailable")throw o.error;return o.value},advance:async(a,o)=>{if(!X(a))return{kind:"failed",error:ae(a)};if(!Ee(o))return{kind:"failed",error:_e(o)};try{let l=await i({operation:"advance",from:o},a,f(a));return l.kind==="value"?{kind:"advanced",generation:l.value}:{kind:"unavailable",error:l.error}}catch(l){return{kind:"failed",error:l}}}}};var L=class extends Error{constructor(t){super(t),this.name="TokenRefreshError"}},D=class extends L{constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},C=class extends Error{constructor(t){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=t}},be=["access_token","expires_in"],J=(e,t,n)=>{let c=e.loginPath??"/auth/login",u=t.sessionKey,w=async m=>{let k=m.get(u)?.refreshToken;if(!k)throw new Error("Refresh token not found in session");try{let f="https://www.googleapis.com/oauth2/v4/token",g={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:k},p=await(e.fetch??globalThis.fetch)(f,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(g)});if(!p.ok){let i=await p.json().catch(()=>{});if(p.status===400&&typeof i=="object"&&!!i&&"error"in i&&i.error==="invalid_grant")throw new D;let E=typeof i=="object"&&i&&"error_description"in i?String(i.error_description):"Unknown error";throw new L(`Google token refresh failed: ${p.status} ${E}`)}let S=await p.json(),P=be.filter(i=>!S?.[i]);if(P.length>0)throw n.error("Invalid token response from Google; missing or empty keys:",P.join(", ")),new Error("Invalid token response from Google");let{access_token:s,expires_in:r}=S;return{accessToken:s,refreshToken:k,expirationDateMs:Number(Date.now())+r*1e3}}catch(f){if(f instanceof L)throw f;let g=f instanceof Error?f.message:"Unknown error";throw new L(`Failed to refresh Google access token: ${g}`)}},v=async m=>{let k=m.get(u).provider;if(!k)throw new Error("Provider not found in session");if(k==="google")return await w(m);throw new Error("Provider not supported")};return{authenticate:async(m,h,k)=>{let{failureRedirect:f}=k||{},g=d=>{if(f===null)return new C(d);if(f==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let p=f??c;return d!==void 0?le(p,{headers:{"Set-Cookie":d}}):le(p)};try{if(e.mockUser?.enabled(m)){let{accessToken:r,refreshToken:i,expirationDateMs:T}=e.mockUser.resolve(m);return{accessToken:r,refreshToken:i,expirationDateMs:T}}let d=h.get(u),p=t.sessionGenerationGate;if(d!==void 0&&p!==null&&await p.check(U(d),h.get(x))==="stale")throw g(await t.destroySession(h));if(!(d?.accessToken&&d.expirationDateMs))throw g();let{accessToken:S,refreshToken:P,expirationDateMs:s}=d;if(s<Date.now())throw P?new Error("Expired"):g();return{accessToken:S,refreshToken:P,expirationDateMs:s}}catch(d){if(d instanceof Error&&d.message==="Expired")try{let p=await v(h),S=h.get(u);return h.set(u,{...S,...p}),p}catch(p){if(p instanceof D)n.warn("Google refresh token invalid or revoked");else{let P=p instanceof Error?p.message:"Unknown error";n.error("Failed to refresh token:",P)}let S=await t.destroySession(h);throw g(S)}throw d}},refreshedAccessToken:v}};import{redirect as fe}from"react-router";var j=({refreshToken:e,...t})=>t;var W=(e,t,n,c)=>{let u=new Map,w=new Map,v=async f=>{let g=u.get(f);if(g!==void 0)return g;let d=w.get(f);if(d!==void 0)return d;let p=(async()=>{try{let S=e.getUserPhoto?await e.getUserPhoto(f):"";return u.set(f,S),S}catch(S){throw u.delete(f),S}finally{w.delete(f)}})();return w.set(f,p),p},A=new WeakMap,m=async f=>{e.warmup&&await e.warmup();let g=await t.resolveSession(f);if(g.kind==="revoked")return{kind:"unauthenticated",cookie:await t.destroySession(g.session)};if(g.kind!=="signed-in")return{kind:"unauthenticated"};let{user:d,session:p}=g,S;try{S=await n.authenticate(f,p,{failureRedirect:null})}catch(b){if(b instanceof C)return b.setCookie!==void 0?{kind:"unauthenticated",cookie:b.setCookie}:{kind:"unauthenticated"};throw c.error("Error in authenticateInLoader:",b),b}let P={accessToken:S.accessToken,refreshToken:S.refreshToken,expirationDateMs:S.expirationDateMs,provider:d.provider},s={id:d.id,displayName:d.displayName,name:d.name,emails:d.emails,...P,role:d.role},r=await v(d.id),i=j({...d,...P,photo:r}),E=S.accessToken!==d.accessToken?await t.saveSession(f,s):void 0;return E!==void 0?{kind:"authenticated",user:i,cookie:E}:{kind:"authenticated",user:i}},h=f=>{let g=A.get(f);if(g!==void 0)return g;let d=m(f);return A.set(f,d),d};async function k(f,g){let{failureRedirect:d}=g;if(d==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let p=await h(f);if(p.kind==="authenticated")return p.cookie!==void 0?{user:p.user,cookie:p.cookie}:{user:p.user};if(d===null)return p.cookie!==void 0?{cookie:p.cookie}:{};throw p.cookie!==void 0?fe(d,{headers:{"Set-Cookie":p.cookie}}):fe(d)}return k};import{resolveAuthMessages as Ue}from"@aiquants/auth-core";import{redirect as H}from"react-router";import{Authenticator as Le}from"remix-auth";import{OAuth2Strategy as Ie}from"remix-auth-oauth2";var Oe=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],xe="google",Me="https://www.googleapis.com/oauth2/v3/userinfo",V=class extends Ie{constructor({clientId:n,clientSecret:c,redirectURI:u,scopes:w,accessType:v,includeGrantedScopes:A,prompt:m,hd:h,loginHint:k,additionalScopes:f},g){let d=w??Oe;super({clientId:n,clientSecret:c,redirectURI:u,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:d},g);this.name=xe;this.scopes=d,this.accessType=v??"online",this.includeGrantedScopes=A??!1,this.prompt=m,this.hd=h,this.loginHint=k,this.additionalScopes=f}authorizationParams(n,c){n.set("access_type",this.accessType),n.set("include_granted_scopes",String(this.includeGrantedScopes));let u=c===void 0||this.additionalScopes===void 0?[]:this.additionalScopes(c);for(let v of u)if(v===""||/\s/u.test(v))throw new RangeError(`[auth-react-router] an additional scope must be a non-empty string without white space; got ${JSON.stringify(v)}`);let w=[...new Set([...this.scopes,...u])];return w.length>0&&n.set("scope",w.join(" ")),this.prompt&&n.set("prompt",this.prompt),this.hd&&n.set("hd",this.hd),this.loginHint&&n.set("login_hint",this.loginHint),n}static async userProfile(n){let c=await fetch(Me,{headers:{Authorization:`Bearer ${n.accessToken()}`}});if(!c.ok)throw new Error(`Failed to fetch user profile: ${c.statusText}`);let u=await c.json();return{id:u.sub,displayName:u.name,name:{familyName:u.family_name,givenName:u.given_name},emails:[{value:u.email}],photos:[{value:u.picture}],_json:u}}};var $={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var z=e=>{let t=e.logger??$,n=Ue(e.messages),c=e.loginPath??"/auth/login",u=new V({clientId:e.google.clientId,clientSecret:e.google.clientSecret,redirectURI:e.google.redirectURI,scopes:e.google.scopes,accessType:e.google.accessType??"offline",includeGrantedScopes:e.google.includeGrantedScopes??!0,prompt:e.google.prompt??"consent",additionalScopes:e.google.additionalScopes},async({request:v,tokens:A})=>{let{access_token:m,refresh_token:h,expires_in:k,scope:f,id_token:g}=A.data,{_json:{sub:d,email:p,picture:S,hd:P,email_verified:s},photos:r,...i}=await V.userProfile(A),{id:T,displayName:E,name:{familyName:b,givenName:Y},emails:B}=i,a="google";if(m===void 0||h===void 0||k===void 0||f===void 0||T===void 0||E===void 0||d===void 0||p===void 0||s===void 0){if(s===!1){let l=encodeURIComponent(n.emailNotVerified);throw H(`${c}?error=${l}`)}let o=encodeURIComponent(n.googleFailed);throw H(`${c}?error=${o}`)}t.info("Authenticated on Google: ",i.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(a,m)){t.error("Backend verification returned false for user:",i.displayName);let I=encodeURIComponent(n.backendFailed);throw H(`${c}?error=${I}`)}t.info("Authenticated on Backend: ",i.displayName)}let o=i.emails[0]?.value;if(!await e.isEmailAllowed(o)){let G=new Error("You are not allowed to access this application");throw t.error(G),G}if(e.isUserActive&&!await e.isUserActive(i)){let G=new Error("You are not allowed to access this application");throw t.error("Deactivated account attempted to sign in:",o),G}e.backendAuth&&await e.backendAuth.signup(a,m,i),t.info("Authenticated complete: ",i.displayName);let l=Date.now()+k*1e3;return{...i,...{accessToken:m,refreshToken:h,expirationDateMs:l,provider:a},photo:S}}catch(o){let l=o;typeof o=="object"&&o!==null&&"cause"in o&&(l=o.cause||o),t.error("Error during backend authentication or subsequent processing:",l);let y=n.unexpected,R=!1;if(typeof o=="object"&&o!==null&&"cause"in o){let I=o.cause;I&&typeof I=="object"&&"message"in I&&typeof I.message=="string"&&I.message.includes("getaddrinfo ENOTFOUND")&&(y=n.backendUnreachable,R=!0)}if(!R&&o instanceof Error&&o.message.includes("You are not allowed to access this application")&&(y=n.notAllowed,R=!0),!R&&o instanceof Response&&o.headers.get("Location")?.startsWith(c))throw o;let G=encodeURIComponent(y);throw H(`${c}?error=${G}`)}}),w=new Le;return w.use(u),w};import{redirect as K}from"react-router";var Ne=new Map([["document",new Set(["none","same-origin","same-site"])],["empty",new Set(["same-origin"])]]),Q=e=>{let t=e.headers.get("Sec-Fetch-Dest");if(t!==null){let c=Ne.get(t);if(c===void 0)return`its fetch destination is "${t}"`;let u=e.headers.get("Sec-Fetch-Site");if(u===null)return`its "${t}" request states no site`;if(!c.has(u))return`its "${t}" request comes from a "${u}" page`}let n=e.headers.get("Sec-Purpose");if(n!==null)return`it is speculative ("${n}")`},Z=e=>new Response(`Signing out is refused because ${e}: only a navigation that does not come from another site, or a script's request from this origin, signs out.`,{status:403,headers:{"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"}});var ee=(e,t,n,c)=>{let u=e.loginPath??"/auth/login",w=e.postLoginRedirect??"/",v=e.postLogoutRedirect??"/",A=re(e.google.revocationTimeoutMs),m=async({request:s})=>{if(await t.getSessionUser(s))throw K(w);return{error:new URL(s.url).searchParams.get("error")}},h=async({request:s})=>{if((await s.clone().formData()).get("_action")!=="Sign In with Google")return null;throw await n.authenticate("google",s),K(u)},k=(s,r)=>{switch(s.outcome){case"failed":c.error(`Sign-out could not revoke the Google grant of user ${String(r)}; the session cookie is destroyed, but the grant stays valid until it expires or is revoked elsewhere:`,s.reason);return;case"already-invalid":c.info(`Sign-out found the Google grant of user ${String(r)} already unusable`);return;case"revoked":case"nothing-to-revoke":return}},f=(s,r)=>{s.kind!=="advanced"&&c.error(`Sign-out could not advance the session generation of ${r.provider} user ${r.id}; a session cookie refreshed before this sign-out stays valid until a later sign-out advances the generation or the cookie expires:`,s.error)},g=async(s,r)=>{let i=t.sessionGenerationGate;if(i!==null){if(!N(r)){c.info(`Sign-out found no usable session generation stamp in the session of ${s.provider} user ${s.id}; every guard already rejects that cookie, so the generation is not advanced`);return}f(await i.advance(s,r),s)}},d=async s=>{let r=await t.getSession(s),i=r.get(t.sessionKey),[T]=await Promise.all([se(i,{fetch:e.fetch??globalThis.fetch,timeoutMs:A}),i===void 0?void 0:g(U(i),r.get(x))]);return k(T,i?.id),await t.destroySession(r)},p=async s=>{let r=await d(s),i=new Headers;return i.append("Set-Cookie",r),K(v,{headers:i})};return{loginLoader:m,loginAction:h,logoutLoader:async({request:s})=>{let r=Q(s);throw r!==void 0?Z(r):await p(s)},logout:d,logoutAndRedirect:p,googleCallbackLoader:async({request:s})=>{try{let r=await n.authenticate("google",s),E=(await t.getSession(s)).get(t.sessionKey)?.refreshToken,b={accessToken:r.accessToken,refreshToken:r.refreshToken||E,expirationDateMs:r.expirationDateMs,provider:r.provider},Y={id:r.id,displayName:r.displayName,name:r.name,emails:r.emails,...b,role:r.role},B=await t.saveSignedInSession(s,Y);throw K(w,{headers:{"Set-Cookie":B}})}catch(r){throw r instanceof Response?r:(c.error("Authentication error:",r),K(u))}}}};import{createCookieSessionStorage as Ce,redirect as te}from"react-router";var oe=(e,t)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(s=>!s))throw new Error("REMIX_SESSION_SECRET must be set");let n=e.sessionKey??"user";if(n===x)throw new RangeError(`session.sessionKey must not be ${JSON.stringify(x)}, the key the session generation is stored under; got ${JSON.stringify(n)}`);let c=e.maxAge??3600*24*30,u=t.loginPath??"/auth/login",w=t.postLoginRedirect??"/",v=t.mockUser,A=t.isUserActive,m=de(t.sessionGeneration,t.logger??$),h=Ce({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:e.secure??process.env.NODE_ENV==="production",maxAge:c}}),k=async s=>await h.getSession(s.headers.get("Cookie")),f=async s=>{if(v?.enabled(s))return{kind:"signed-in",user:j(v.resolve(s)),session:await k(s)};let r=await k(s),i=r.get(n);if(i===void 0)return{kind:"signed-out"};let T=j(i),[E,b]=await Promise.all([A===void 0?!0:A(T),m===null?"current":m.check(U(i),r.get(x))]);return b==="stale"?{kind:"revoked",session:r}:E?{kind:"signed-in",user:T,session:r}:{kind:"inactive"}},g=async s=>{let r=await f(s);return r.kind==="signed-in"?r.user:void 0},d=async(s,r)=>{let i=await k(s);return i.set(n,r),await h.commitSession(i)},p=async(s,r)=>{let i=m===null?void 0:await m.stamp(U(r)),T=await k(s);return T.set(n,r),i!==void 0&&T.set(x,i),await h.commitSession(T)},S=async s=>{let r=await f(s);switch(r.kind){case"signed-in":return r.user;case"revoked":throw te(u,{headers:{"Set-Cookie":await h.destroySession(r.session)}});case"signed-out":case"inactive":throw te(u)}};return{sessionStorage:h,sessionKey:n,sessionGenerationGate:m,getSession:k,resolveSession:f,getSessionUser:g,saveSession:d,saveSignedInSession:p,requireUser:S,requireAdminUser:async s=>{let r=await S(s);if(r.role!=="admin")throw te(w);return r},commitSession:h.commitSession,destroySession:h.destroySession}};var $e=e=>{let t=e.logger??$,n=oe(e.session,{sessionGeneration:e.sessionGeneration,logger:t,mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive}),c=z(e),u=J(e,n,t),w=W(e,n,u,t),v=ee(e,n,c,t);return{authenticator:c,storage:n,authFns:u,sessionStorage:n.sessionStorage,getSession:n.getSession,getSessionUser:n.getSessionUser,saveSession:n.saveSession,requireUser:n.requireUser,requireAdminUser:n.requireAdminUser,commitSession:n.commitSession,destroySession:n.destroySession,authenticate:u.authenticate,refreshedAccessToken:u.refreshedAccessToken,authenticateInLoader:w,...v}};export{C as AuthRequiredError,he as DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS,ce as DEFAULT_SESSION_GENERATION_CACHE_TTL_MS,ue as DEFAULT_SESSION_GENERATION_TIMEOUT_MS,D as GoogleInvalidGrantError,q as SessionGenerationUnavailableError,L as TokenRefreshError,ee as createAuthHandlers,$e as createAuthServer,oe as createAuthSessionStorage,J as createAuthenticate,W as createAuthenticateInLoader,z as createGoogleAuthenticator,Q as signOutRefusal,Z as signOutRefusalResponse};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aiquants/auth-react-router",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.25.0",
|
|
4
4
|
"description": "React Router v7 / v8 auth adapter for @aiquants/auth-core: Google OAuth strategy factory (remix-auth), cookie session storage with DI test backdoor, a loader guard that authenticates at most once per request (token refresh + photo cache), auth route handlers, and a <GoogleForm> login button.",
|
|
5
5
|
"sideEffects": [
|
|
6
6
|
"**/*.css"
|
|
@@ -50,9 +50,9 @@
|
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
52
|
"@aiquants/auth-core": "0.6.1",
|
|
53
|
-
"@aiquants/fuzzy-search": "3.
|
|
54
|
-
"@aiquants/select-box": "0.16.
|
|
55
|
-
"@aiquants/virtualscroll": "3.
|
|
53
|
+
"@aiquants/fuzzy-search": "3.2.0",
|
|
54
|
+
"@aiquants/select-box": "0.16.3",
|
|
55
|
+
"@aiquants/virtualscroll": "3.17.0",
|
|
56
56
|
"@tailwindcss/cli": "^4.1.18",
|
|
57
57
|
"@testing-library/react": "^16.3.2",
|
|
58
58
|
"@types/node": "^25.9.1",
|
|
@@ -72,9 +72,9 @@
|
|
|
72
72
|
},
|
|
73
73
|
"peerDependencies": {
|
|
74
74
|
"@aiquants/auth-core": "^0.6.1",
|
|
75
|
-
"@aiquants/fuzzy-search": "^3.
|
|
76
|
-
"@aiquants/select-box": "^0.16.
|
|
77
|
-
"@aiquants/virtualscroll": "^3.
|
|
75
|
+
"@aiquants/fuzzy-search": "^3.2.0",
|
|
76
|
+
"@aiquants/select-box": "^0.16.3",
|
|
77
|
+
"@aiquants/virtualscroll": "^3.17.0",
|
|
78
78
|
"react": ">=18",
|
|
79
79
|
"react-dom": ">=18",
|
|
80
80
|
"react-icons": ">=5",
|