@aiquants/auth-react-router 0.44.0 → 0.45.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/dist/server.d.ts CHANGED
@@ -1,11 +1,9 @@
1
1
  import * as _aiquants_auth_core from "@aiquants/auth-core";
2
- import { SessionProfile, MyGoogleProfile, IdentityProfile, GoogleProfileBase, AuthMessages } from "@aiquants/auth-core";
2
+ import { IdentityProfile, GoogleProfileBase, SessionProfile, AuthMessages, MyGoogleProfile } from "@aiquants/auth-core";
3
3
  import * as react_router from "react-router";
4
4
  import { Session } from "react-router";
5
5
  import * as remix_auth from "remix-auth";
6
6
  import { Authenticator } from "remix-auth";
7
- type SessionUser = Omit<SessionProfile, "refreshToken">;
8
- type LoaderUser = Omit<MyGoogleProfile, "refreshToken">;
9
7
  type GoogleOAuthConfig = {
10
8
  clientId: string;
11
9
  clientSecret: string;
@@ -67,6 +65,7 @@ type AuthServerConfig = {
67
65
  isEmailAllowed: (email: string | null | undefined) => boolean | Promise<boolean>;
68
66
  isUserActive?: (profile: IdentityProfile) => boolean | Promise<boolean>;
69
67
  sessionGeneration: SessionGenerationConfig | false;
68
+ readerCheck: boolean;
70
69
  backendAuth?: BackendAuthPort;
71
70
  getUserPhoto?: UserPhotoPort;
72
71
  warmup?: WarmupPort;
@@ -79,6 +78,8 @@ type AuthServerConfig = {
79
78
  logger?: LoggerPort;
80
79
  fetch?: FetchPort;
81
80
  };
81
+ type SessionUser = Omit<SessionProfile, "refreshToken">;
82
+ type LoaderUser = Omit<MyGoogleProfile, "refreshToken">;
82
83
  type ReturnToFlow = {
83
84
  readonly path: string | undefined;
84
85
  readonly deletion: string | undefined;
@@ -119,6 +120,7 @@ declare const DEFAULT_SESSION_MAX_AGE_SECONDS: number;
119
120
  type AuthSessionStorage = ReturnType<typeof createAuthSessionStorage>;
120
121
  type AuthSessionStorageOptions = {
121
122
  readonly sessionGeneration: SessionGenerationConfig | false;
123
+ readonly readerCheck: boolean;
122
124
  readonly logger?: LoggerPort;
123
125
  readonly mockUser?: MockUserPort;
124
126
  readonly loginPath?: string;
@@ -137,6 +139,8 @@ type SessionResolution = {
137
139
  } | {
138
140
  readonly kind: "revoked";
139
141
  readonly session: Session;
142
+ } | {
143
+ readonly kind: "other-reader";
140
144
  };
141
145
  declare const createAuthSessionStorage: (config: SessionConfig, options: AuthSessionStorageOptions) => {
142
146
  sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
@@ -151,6 +155,7 @@ declare const createAuthSessionStorage: (config: SessionConfig, options: AuthSes
151
155
  saveSignedInSession: (request: Request, profile: SessionProfile) => Promise<string>;
152
156
  requireUser: (request: Request, returnTo: string) => Promise<SessionUser>;
153
157
  requireAdminUser: (request: Request, returnTo: string) => Promise<SessionUser>;
158
+ readerStampOf: (reader: SessionGenerationIdentity | undefined) => Promise<string>;
154
159
  commitSession: (session: Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
155
160
  destroySession: (session: Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
156
161
  };
@@ -188,6 +193,7 @@ declare const createAuthServer: (config: AuthServerConfig) => {
188
193
  saveSignedInSession: (request: Request, profile: _aiquants_auth_core.SessionProfile) => Promise<string>;
189
194
  requireUser: (request: Request, returnTo: string) => Promise<SessionUser>;
190
195
  requireAdminUser: (request: Request, returnTo: string) => Promise<SessionUser>;
196
+ readerStampOf: (reader: SessionGenerationIdentity | undefined) => Promise<string>;
191
197
  commitSession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
192
198
  destroySession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
193
199
  };
@@ -211,6 +217,7 @@ declare const createAuthServer: (config: AuthServerConfig) => {
211
217
  sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
212
218
  getSession: (request: Request) => Promise<react_router.Session<react_router.SessionData, react_router.SessionData>>;
213
219
  getSessionUser: (request: Request) => Promise<SessionUser | undefined>;
220
+ readerStampOf: (reader: SessionGenerationIdentity | undefined) => Promise<string>;
214
221
  saveSession: (request: Request, user: _aiquants_auth_core.SessionProfile) => Promise<string>;
215
222
  requireUser: (request: Request, returnTo: string) => Promise<SessionUser>;
216
223
  requireAdminUser: (request: Request, returnTo: string) => Promise<SessionUser>;
package/dist/server.js CHANGED
@@ -1 +1 @@
1
- "use strict";var ce=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Fe=Object.prototype.hasOwnProperty;var $e=(e,t)=>{for(var n in t)ce(e,n,{get:t[n],enumerable:!0})},qe=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Me(t))!Fe.call(e,s)&&s!==n&&ce(e,s,{get:()=>t[s],enumerable:!(o=Ce(t,s))||o.enumerable});return e};var De=e=>qe(ce({},"__esModule",{value:!0}),e);var mt={};$e(mt,{AuthRequiredError:()=>q,DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS:()=>ue,DEFAULT_SESSION_GENERATION_CACHE_TTL_MS:()=>le,DEFAULT_SESSION_GENERATION_TIMEOUT_MS:()=>fe,DEFAULT_SESSION_MAX_AGE_SECONDS:()=>me,GoogleInvalidGrantError:()=>j,SessionGenerationUnavailableError:()=>U,TokenRefreshError:()=>C,createAuthHandlers:()=>re,createAuthServer:()=>Le,createAuthSessionStorage:()=>ae,createAuthenticate:()=>B,createAuthenticateInLoader:()=>X,createGoogleAuthenticator:()=>Z,signOutRefusal:()=>ee,signOutRefusalResponse:()=>te});module.exports=De(mt);var Pe=require("@aiquants/auth-core");var we=require("@aiquants/auth-core"),Ke="https://oauth2.googleapis.com/revoke",ue=5e3,J=2147483647,je="invalid_token",He=400,Re=e=>{if(e===void 0)return ue;if(!Number.isInteger(e)||e<1||e>J)throw new RangeError(`google.revocationTimeoutMs must be an integer from 1 to ${J} (milliseconds); got ${String(e)}`);return e},Ve=e=>{if(typeof e.refreshToken=="string"&&e.refreshToken!=="")return e.refreshToken;if(typeof e.accessToken=="string"&&e.accessToken!=="")return e.accessToken},Je=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},We=e=>e instanceof Error?e.cause instanceof Error?`${e.message} (${e.cause.message})`:e.message:String(e),ze=async(e,t,n)=>{try{let o=await t(Ke,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:e}).toString(),signal:n});if(o.ok)return await o.body?.cancel(),{outcome:"revoked"};let s=await Je(o);return o.status===He&&s===je?{outcome:"already-invalid"}:{outcome:"failed",reason:s===void 0?`Google answered ${o.status}`:`Google answered ${o.status} ${s}`}}catch(o){return{outcome:"failed",reason:We(o)}}},ke=async(e,t)=>{if(e===void 0)return{outcome:"nothing-to-revoke"};let n=Ve(e);if(n===void 0)return{outcome:"nothing-to-revoke"};if(e.provider!==we.GOOGLE_PROVIDER)return{outcome:"failed",reason:`the session's provider "${String(e.provider)}" has no revocation endpoint`};let o=new AbortController;return await new Promise(s=>{let y=setTimeout(()=>{s({outcome:"failed",reason:`Google did not answer within ${t.timeoutMs} ms`}),o.abort()},t.timeoutMs);ze(n,t.fetch,o.signal).then(A=>{clearTimeout(y),s(A)})})};var N="generation",le=15e3,fe=3e3,Ye=6e4,U=class extends Error{constructor(t,n){super(t,n),this.name="SessionGenerationUnavailableError"}},I=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),Be=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return I(e);let t="store"in e?e.store:void 0;if(typeof t!="object"||t===null)return`an object whose store is ${I(t)}`;let n="current"in t?t.current:void 0,o="advance"in t?t.advance:void 0;return`an object whose store.current is ${I(n)} and store.advance is ${I(o)}`},Xe=e=>typeof e=="object"&&e!==null&&"current"in e&&typeof e.current=="function"&&"advance"in e&&typeof e.advance=="function",Te=(e,t,n,o)=>{if(t===void 0)return o;if(typeof t!="number"||!Number.isInteger(t)||t<n||t>J)throw new RangeError(`${e} must be an integer from ${n} to ${J} (milliseconds); got ${I(t)}`);return t},Qe=e=>{if(e===!1)return!1;let t=e;if(typeof t!="object"||t===null||!("store"in t)||!Xe(t.store))throw new TypeError(`sessionGeneration must be { store, cacheTtlMs?, timeoutMs? } or false; got ${Be(t)}`);return{store:t.store,cacheTtlMs:Te("sessionGeneration.cacheTtlMs","cacheTtlMs"in t?t.cacheTtlMs:void 0,0,le),timeoutMs:Te("sessionGeneration.timeoutMs","timeoutMs"in t?t.timeoutMs:void 0,1,fe)}},K=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,de=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 ${I(e.provider)} and id ${I(e.id)}`),Ze=e=>K(e)&&K(e+1),et=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 ${I(e)}`),$=e=>({provider:e.provider,id:e.id}),ve=(e,t)=>{let n=Qe(e);if(n===!1)return null;let{store:o,cacheTtlMs:s,timeoutMs:y}=n,A=new Map,k=new Map,T=new Map,S=new Map,P=Number.NEGATIVE_INFINITY,l=r=>`${r.provider}\0${r.id}`,p=(r,i)=>{let g=A.get(r);if(g!==void 0){if(i-g.at<s)return g;A.delete(r)}},f=(r,i,g)=>{if(g!==void 0&&i.at<=g.answeredAt&&i.value<g.value)return;let v=p(r,performance.now());if(v===void 0){A.set(r,i);return}i.value<v.value||A.set(r,{value:i.value,at:Math.max(v.at,i.at)})},x=r=>{let i=S.get(r);if(i!==void 0)return i.count+=1,i;let g={count:1,floor:void 0};return S.set(r,g),g},u=(r,i)=>{i.count-=1,i.count===0&&S.delete(r)},d=(r,i)=>{r.floor={value:r.floor===void 0?i:Math.max(r.floor.value,i),answeredAt:performance.now()}},R=(r,i)=>{let g=T.get(r);return g===void 0?!1:i<g?!0:(T.delete(r),!1)},m=(r,i)=>{let g=performance.now();return T.set(r,g+s),g-P>=Ye&&(P=g,t.warn("Session generation store unavailable; skipping the sign-out generation check:",i)),"unavailable"},h=(r,i,g)=>new Promise((v,G)=>{let{operation:O}=r,ye=r.operation==="advance"?r.from+1:0,Ue=performance.now(),V=x(g),F=!1,Se=setTimeout(()=>{F=!0,v({kind:"unavailable",error:new U(`sessionGeneration.store.${O} did not settle within ${y} ms`)})},y);new Promise(_=>_(r.operation==="advance"?o.advance(i,r.from):o.current(i))).then(_=>{if(clearTimeout(Se),!(K(_)&&_>=ye)){u(g,V),F||(F=!0,G(new TypeError(`sessionGeneration.store.${O} must resolve to an integer >= ${ye}; got ${I(_)}`)));return}O==="advance"&&(d(V,_),k.delete(g)),f(g,{value:_,at:Ue},V.floor),u(g,V),!F&&(F=!0,T.delete(g),v({kind:"value",value:_}))},_=>{if(clearTimeout(Se),u(g,V),!F){if(F=!0,_ instanceof U){v({kind:"unavailable",error:_});return}G(_)}})}),w=(r,i,g)=>{let v=k.get(i);if(v!==void 0&&g-v.startedAt<s)return v.read;let G={read:h({operation:"current"},r,i),startedAt:g};k.set(i,G);let O=()=>{k.get(i)===G&&k.delete(i)};return G.read.then(O,O),G.read},a=async(r,i,g)=>{let v=await h({operation:"current"},r,i);return v.kind==="unavailable"?m(i,v.error):g===v.value?"current":"stale"};return{check:async(r,i)=>{if(!(K(i)&&de(r)))return"stale";let g=performance.now(),v=l(r),G=p(v,g);if(G!==void 0){if(i===G.value)return"current";if(i<G.value)return"stale"}if(R(v,g))return"unavailable";if(G!==void 0)return await a(r,v,i);let O=await w(r,v,g);return O.kind==="unavailable"?m(v,O.error):i===O.value?"current":i<O.value?"stale":await a(r,v,i)},stamp:async r=>{if(!de(r))throw Ae(r);let i=await h({operation:"current"},r,l(r));if(i.kind==="unavailable")throw i.error;return i.value},advance:async(r,i)=>{if(!de(r))return{kind:"failed",error:Ae(r)};if(!Ze(i))return{kind:"failed",error:et(i)};try{let g=await h({operation:"advance",from:i},r,l(r));return g.kind==="value"?{kind:"advanced",generation:g.value}:{kind:"unavailable",error:g.error}}catch(g){return{kind:"failed",error:g}}}}};var C=class extends Error{constructor(t){super(t),this.name="TokenRefreshError"}},j=class extends C{constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},q=class extends Error{constructor(t){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=t}},tt=["access_token","expires_in"],B=(e,t,n)=>{let o=t.sessionKey,s=async k=>{let S=k.get(o)?.refreshToken;if(!S)throw new Error("Refresh token not found in session");try{let P="https://www.googleapis.com/oauth2/v4/token",l={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:S},f=await(e.fetch??globalThis.fetch)(P,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(l)});if(!f.ok){let m=await f.json().catch(()=>{});if(f.status===400&&typeof m=="object"&&!!m&&"error"in m&&m.error==="invalid_grant")throw new j;let w=typeof m=="object"&&m&&"error_description"in m?String(m.error_description):"Unknown error";throw new C(`Google token refresh failed: ${f.status} ${w}`)}let x=await f.json(),u=tt.filter(m=>!x?.[m]);if(u.length>0)throw n.error("Invalid token response from Google; missing or empty keys:",u.join(", ")),new Error("Invalid token response from Google");let{access_token:d,expires_in:R}=x;return{accessToken:d,refreshToken:S,expirationDateMs:Number(Date.now())+R*1e3}}catch(P){if(P instanceof C)throw P;let l=P instanceof Error?P.message:"Unknown error";throw new C(`Failed to refresh Google access token: ${l}`)}},y=async k=>{let S=k.get(o).provider;if(!S)throw new Error("Provider not found in session");if(S===Pe.GOOGLE_PROVIDER)return await s(k);throw new Error("Provider not supported")};return{authenticate:async(k,T,S)=>{S.failureRedirect!==null&&t.returnToPolicy.checkRedirectMode(k,S);let P=l=>S.failureRedirect===null?new q(l):t.returnToPolicy.signInRedirect(S.returnTo,l!==void 0?{headers:{"Set-Cookie":l}}:void 0);try{if(e.mockUser?.enabled(k)){let{accessToken:d,refreshToken:R,expirationDateMs:m}=e.mockUser.resolve(k);return{accessToken:d,refreshToken:R,expirationDateMs:m}}let l=T.get(o),p=t.sessionGenerationGate;if(l!==void 0&&p!==null&&await p.check($(l),T.get(N))==="stale")throw P(await t.destroySession(T));if(!(l?.accessToken&&l.expirationDateMs))throw P();let{accessToken:f,refreshToken:x,expirationDateMs:u}=l;if(u<Date.now())throw x?new Error("Expired"):P();return{accessToken:f,refreshToken:x,expirationDateMs:u}}catch(l){if(l instanceof Error&&l.message==="Expired")try{let p=await y(T),f=T.get(o);return T.set(o,{...f,...p}),p}catch(p){if(p instanceof j)n.warn("Google refresh token invalid or revoked");else{let x=p instanceof Error?p.message:"Unknown error";n.error("Failed to refresh token:",x)}let f=await t.destroySession(T);throw P(f)}throw l}},refreshedAccessToken:y}};var W=({refreshToken:e,...t})=>t;var X=(e,t,n,o)=>{let s=new Map,y=new Map,A=async l=>{let p=JSON.stringify([l.provider,l.id]),f=s.get(p);if(f!==void 0)return f;let x=y.get(p);if(x!==void 0)return x;let u=(async()=>{try{let d=e.getUserPhoto?await e.getUserPhoto(l):"";return s.set(p,d),d}catch(d){throw s.delete(p),d}finally{y.delete(p)}})();return y.set(p,u),u},k=new WeakMap,T=async l=>{e.warmup&&await e.warmup();let p=await t.resolveSession(l);if(p.kind==="revoked")return{kind:"unauthenticated",cookie:await t.destroySession(p.session)};if(p.kind!=="signed-in")return{kind:"unauthenticated"};let{user:f,session:x}=p,u;try{u=await n.authenticate(l,x,{failureRedirect:null})}catch(c){if(c instanceof q)return c.setCookie!==void 0?{kind:"unauthenticated",cookie:c.setCookie}:{kind:"unauthenticated"};throw o.error("Error in authenticateInLoader:",c),c}let d={accessToken:u.accessToken,refreshToken:u.refreshToken,expirationDateMs:u.expirationDateMs,provider:f.provider},R={id:f.id,displayName:f.displayName,name:f.name,emails:f.emails,...d,role:f.role},m=await A(f),h=W({...f,...d,photo:m}),a=u.accessToken!==f.accessToken?await t.saveSession(l,R):void 0;return a!==void 0?{kind:"authenticated",user:h,cookie:a}:{kind:"authenticated",user:h}},S=l=>{let p=k.get(l);if(p!==void 0)return p;let f=T(l);return k.set(l,f),f};async function P(l,p){p.failureRedirect!==null&&t.returnToPolicy.checkRedirectMode(l,p);let f=await S(l);if(f.kind==="authenticated")return f.cookie!==void 0?{user:f.user,cookie:f.cookie}:{user:f.user};if(p.failureRedirect===null)return f.cookie!==void 0?{cookie:f.cookie}:{};throw t.returnToPolicy.signInRedirect(p.returnTo,f.cookie!==void 0?{headers:{"Set-Cookie":f.cookie}}:void 0)}return P};var Ge=require("@aiquants/auth-core"),Q=require("react-router"),xe=require("remix-auth");var Ee=require("remix-auth-oauth2"),nt=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],rt="google",ot="https://www.googleapis.com/oauth2/v3/userinfo",z=class extends Ee.OAuth2Strategy{constructor({clientId:n,clientSecret:o,redirectURI:s,scopes:y,accessType:A,includeGrantedScopes:k,prompt:T,hd:S,loginHint:P,additionalScopes:l},p){let f=y??nt;super({clientId:n,clientSecret:o,redirectURI:s,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:f},p);this.name=rt;this.scopes=f,this.accessType=A??"online",this.includeGrantedScopes=k??!1,this.prompt=T,this.hd=S,this.loginHint=P,this.additionalScopes=l}authorizationParams(n,o){n.set("access_type",this.accessType),n.set("include_granted_scopes",String(this.includeGrantedScopes));let s=o===void 0||this.additionalScopes===void 0?[]:this.additionalScopes(o);for(let A of s)if(A===""||/\s/u.test(A))throw new RangeError(`[auth-react-router] an additional scope must be a non-empty string without white space; got ${JSON.stringify(A)}`);let y=[...new Set([...this.scopes,...s])];return y.length>0&&n.set("scope",y.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 o=await fetch(ot,{headers:{Authorization:`Bearer ${n.accessToken()}`}});if(!o.ok)throw new Error(`Failed to fetch user profile: ${o.statusText}`);let s=await o.json();return{id:s.sub,displayName:s.name,name:{familyName:s.family_name,givenName:s.given_name},emails:[{value:s.email}],photos:[{value:s.picture}],_json:s}}};var H={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var he="error",L=(e,t)=>`${e}?${new URLSearchParams({[he]:t}).toString()}`;var be=e=>e instanceof Error&&e.code==="access_denied"?"consentDenied":"googleFailed",Z=e=>{let t=e.logger??H,n=e.loginPath??"/auth/login",o=new z({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:y,tokens:A})=>{let{access_token:k,refresh_token:T,expires_in:S,scope:P,id_token:l}=A.data,{_json:{sub:p,email:f,picture:x,hd:u,email_verified:d},photos:R,...m}=await z.userProfile(A),{id:h,displayName:w,name:{familyName:a,givenName:c},emails:E}=m,b=Ge.GOOGLE_PROVIDER;if(k===void 0||T===void 0||S===void 0||P===void 0||h===void 0||w===void 0||p===void 0||f===void 0||d===void 0)throw(0,Q.redirect)(L(n,d===!1?"emailNotVerified":"googleFailed"));t.info("Authenticated on Google: ",m.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(b,k))throw t.error("Backend verification returned false for user:",m.displayName),(0,Q.redirect)(L(n,"backendFailed"));t.info("Authenticated on Backend: ",m.displayName)}let r=m.emails[0]?.value;if(!await e.isEmailAllowed(r)){let G=new Error("You are not allowed to access this application");throw t.error(G),G}if(e.isUserActive&&!await e.isUserActive({...m,provider:b})){let G=new Error("You are not allowed to access this application");throw t.error("Deactivated account attempted to sign in:",r),G}e.backendAuth&&await e.backendAuth.signup(b,k,m),t.info("Authenticated complete: ",m.displayName);let i=Date.now()+S*1e3;return{...m,...{accessToken:k,refreshToken:T,expirationDateMs:i,provider:b},photo:x}}catch(r){let i=r;typeof r=="object"&&r!==null&&"cause"in r&&(i=r.cause||r),t.error("Error during backend authentication or subsequent processing:",i);let g="unexpected",v=!1;if(typeof r=="object"&&r!==null&&"cause"in r){let G=r.cause;G&&typeof G=="object"&&"message"in G&&typeof G.message=="string"&&G.message.includes("getaddrinfo ENOTFOUND")&&(g="backendUnreachable",v=!0)}throw!v&&r instanceof Error&&r.message.includes("You are not allowed to access this application")&&(g="notAllowed",v=!0),!v&&r instanceof Response&&r.headers.get("Location")?.startsWith(n)?r:(0,Q.redirect)(L(n,g))}}),s=new xe.Authenticator;return s.use(o),s};var ne=require("@aiquants/auth-core"),D=require("react-router");var ge="returnTo",Y=(e,t)=>{let n=e.indexOf("?"),o=n===-1?e:e.slice(0,n),s=new URLSearchParams(n===-1?"":e.slice(n+1));return s.set(ge,t),`${o}?${s.toString()}`};var st=new Map([["document",new Set(["none","same-origin","same-site"])],["empty",new Set(["same-origin"])]]),ee=e=>{let t=e.headers.get("Sec-Fetch-Dest");if(t!==null){let o=st.get(t);if(o===void 0)return`its fetch destination is "${t}"`;let s=e.headers.get("Sec-Fetch-Site");if(s===null)return`its "${t}" request states no site`;if(!o.has(s))return`its "${t}" request comes from a "${s}" page`}let n=e.headers.get("Sec-Purpose");if(n!==null)return`it is speculative ("${n}")`},te=e=>new Response(e.signOutRefused,{status:403,headers:{"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"}});var re=(e,t,n,o)=>{let s=e.loginPath??"/auth/login",y=e.postLoginRedirect??"/",A=e.postLogoutRedirect??"/",k=Re(e.google.revocationTimeoutMs),T=(0,ne.resolveAuthMessages)(e.messages),S=t.returnToPolicy,P=async({request:a})=>{let c=S.requested(a),E=new URL(a.url).searchParams.get(he),b=(0,ne.isSignInFailureKey)(E)?E:null;if(b===null&&await t.getSessionUser(a))throw(0,D.redirect)(c??y);return{error:b===null?null:T[b]}},l=async a=>{let c=S.requested(a);try{await n.authenticate("google",a)}catch(E){throw c===void 0||!(E instanceof Response)?E:await S.bindToFlow(E,c,a)}throw(0,D.redirect)(c===void 0?s:Y(s,c))},p=async({request:a})=>(await a.clone().formData()).get("_action")!=="Sign In with Google"?null:await l(a),f=(a,c)=>{switch(a.outcome){case"failed":o.error(`Sign-out could not revoke the Google grant of user ${String(c)}; the session cookie is destroyed, but the grant stays valid until it expires or is revoked elsewhere:`,a.reason);return;case"already-invalid":o.info(`Sign-out found the Google grant of user ${String(c)} already unusable`);return;case"revoked":case"nothing-to-revoke":return}},x=(a,c)=>{a.kind!=="advanced"&&o.error(`Sign-out could not advance the session generation of ${c.provider} user ${c.id}; a session cookie refreshed before this sign-out stays valid until a later sign-out advances the generation or the cookie expires:`,a.error)},u=async(a,c)=>{let E=t.sessionGenerationGate;if(E!==null){if(!K(c)){o.info(`Sign-out found no usable session generation stamp in the session of ${a.provider} user ${a.id}; every guard already rejects that cookie, so the generation is not advanced`);return}x(await E.advance(a,c),a)}},d=async a=>{let c=await t.getSession(a),E=c.get(t.sessionKey),[b]=await Promise.all([ke(E,{fetch:e.fetch??globalThis.fetch,timeoutMs:k}),E===void 0?void 0:u($(E),c.get(N))]);return f(b,E?.id),await t.destroySession(c)},R=async a=>{let c=await d(a),E=new Headers;return E.append("Set-Cookie",c),(0,D.redirect)(A,{headers:E})},m=async({request:a})=>{let c=ee(a);throw c!==void 0?(o.warn(`Signing out is refused because ${c}`),te(T)):await R(a)},h=async(a,c)=>{let r=(await t.getSession(a)).get(t.sessionKey)?.refreshToken,i={accessToken:c.accessToken,refreshToken:c.refreshToken||r,expirationDateMs:c.expirationDateMs,provider:c.provider},g={id:c.id,displayName:c.displayName,name:c.name,emails:c.emails,...i,role:c.role};return await t.saveSignedInSession(a,g)};return{loginLoader:P,loginAction:p,startGoogleSignIn:l,logoutLoader:m,logout:d,logoutAndRedirect:R,googleCallbackLoader:async({request:a})=>{let c=await S.flowOf(a),E;try{E=await n.authenticate("google",a)}catch(i){throw i instanceof Response?S.endFailedFlow(i,c,a):(o.error("Authentication error:",i),S.endFailedFlow((0,D.redirect)(L(s,be(i))),c,a))}let b;try{b=await h(a,E)}catch(i){throw o.error("Saving the signed-in session failed:",i),S.endFailedFlow((0,D.redirect)(L(s,i instanceof U?"backendUnreachable":"unexpected")),c,a)}let r=new Headers;throw r.append("Set-Cookie",b),c.deletion!==void 0&&r.append("Set-Cookie",c.deletion),(0,D.redirect)(c.path??y,{headers:r})},messages:T}};var ie=require("react-router");var M=require("react-router");var it="__return_to.",at=300,_e=/^[A-Za-z0-9_-]{1,128}$/,ct=/%(?![0-9A-Fa-f]{2})/,oe="https://return-to.invalid",Oe=Object.freeze({path:void 0,deletion:void 0}),ut=e=>{if(e.includes("%"))return!1;let t=new URL(e,oe);return t.origin===oe&&t.pathname===e},dt=e=>{for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=31||n>=127&&n<=159||e[t]==="\\"||e[t]==="#")return!0}return!1},lt=e=>{if(e[0]!=="/"||e[1]==="/"||e[1]==="\\")return{malformed:'it does not start with a single "/"'};if(dt(e))return{malformed:'it holds a control character, a backslash or a "#"'};if(ct.test(e))return{malformed:'it holds a "%" that two hexadecimal digits do not follow'};let t=new URL(e,oe);if(t.origin!==oe||`${t.pathname}${t.search}`!==e)return{malformed:"the URL parser normalizes it"};let n;try{n=decodeURIComponent(t.pathname)}catch{return{malformed:"its path does not decode as UTF-8"}}return n.startsWith("//")||n.startsWith("/\\")?{malformed:'its decoded path starts with "//" or "/\\"'}:{decodedPath:n}},ft=e=>{if(e===null)return null;let t="returnTo.pages must be null or { excludedPathPrefixes: string[], maxLength: number }";if(typeof e!="object"||Array.isArray(e))throw new TypeError(`${t}; got ${JSON.stringify(e)}`);let{excludedPathPrefixes:n,maxLength:o}=e;if(!Array.isArray(n))throw new TypeError(`${t}; got excludedPathPrefixes ${JSON.stringify(n)}`);for(let y of n){if(typeof y!="string")throw new TypeError(`returnTo.pages.excludedPathPrefixes must hold strings; got ${JSON.stringify(y)}`);if(!y.startsWith("/"))throw new RangeError(`returnTo.pages.excludedPathPrefixes must hold path prefixes starting with "/"; got ${JSON.stringify(y)}`)}if(typeof o!="number")throw new TypeError(`${t}; got maxLength ${JSON.stringify(o)}`);if(!Number.isSafeInteger(o)||o<1)throw new RangeError(`returnTo.pages.maxLength must be a safe integer >= 1; got ${String(o)}`);let s=Object.freeze([...n]);return Object.freeze({excludedPathPrefixes:s,maxLength:o,lowerCasePrefixes:Object.freeze(s.map(y=>y.toLowerCase()))})},ht=e=>{if(e===void 0)return{allowedPaths:new Set,pages:null};let t=e;if(typeof t!="object"||t===null||!Array.isArray(t.allowedPaths))throw new TypeError(`returnTo must be { allowedPaths: string[], pages: { excludedPathPrefixes: string[], maxLength: number } | null }; got ${JSON.stringify(t)}`);let n=t.allowedPaths;for(let s of n){if(typeof s!="string")throw new TypeError(`returnTo.allowedPaths must hold strings; got ${JSON.stringify(s)}`);if(!ut(s))throw new RangeError(`returnTo.allowedPaths must hold canonical same-origin paths (one leading "/", no query, fragment, percent-encoding, backslash, white space, control or non-ASCII character, or dot segment); got ${JSON.stringify(s)}`)}let o=ft(t.pages);if(n.length===0&&o===null)throw new RangeError("returnTo allows no return-to (allowedPaths is empty and pages is null); omit returnTo to allow none");return{allowedPaths:new Set(n),pages:o}},se=e=>{if(typeof e!="string")throw new TypeError(`[auth-react-router] returnTo must be the page's path and query to return to after the sign-in; got ${JSON.stringify(e)}`);return e},gt=(e,t)=>e===null?!1:e.split(";").some(n=>n.trim().startsWith(`${t}=`)),pe=(e,t)=>new Response(e.body,{status:e.status,statusText:e.statusText,headers:t}),Ie=(e,t,n,o)=>{let{allowedPaths:s,pages:y}=ht(e),A=u=>{if(s.has(u))return{kind:"accepted"};if(y===null)return{kind:"closed"};let d=lt(u);if("malformed"in d)return{kind:"malformed",reason:d.malformed};let R=d.decodedPath.toLowerCase(),m=y.lowerCasePrefixes.findIndex(h=>R.startsWith(h));return m!==-1?{kind:"excluded",prefix:y.excludedPathPrefixes[m]}:u.length>y.maxLength?{kind:"tooLong",length:u.length}:{kind:"accepted"}},k=u=>(0,M.createCookie)(`${it}${u}`,{secrets:[...t.secrets],httpOnly:!0,sameSite:"lax",path:"/",secure:t.secure,maxAge:at}),T=(u,d,R)=>{let m=u.headers.get("Location");if(m===null)return u;let h=new URL(m,R.url);if(h.origin!==new URL(R.url).origin||h.pathname!==n)return u;let w=new Headers(u.headers);return w.set("Location",`${Y(`${h.pathname}${h.search}`,d)}${h.hash}`),pe(u,w)};return{requested:u=>{let d=new URL(u.url).searchParams.getAll(ge);if(d.length!==0){if(d.length===1&&A(d[0]).kind==="accepted")return d[0];throw(0,M.redirect)(L(n,"returnToRefused"))}},bindToFlow:async(u,d,R)=>{let m=u.headers.get("Location"),h=m===null?null:new URL(m,R.url).searchParams.get("state");if(h===null)return T(u,d,R);if(!_e.test(h))throw new Error(`The authorization redirect's state cannot name the return-to cookie; got ${JSON.stringify(h)}`);let w=new Headers(u.headers);return w.append("Set-Cookie",await k(h).serialize(d)),pe(u,w)},flowOf:async u=>{let d=new URL(u.url).searchParams.get("state");if(d===null||!_e.test(d))return Oe;let R=k(d),m=u.headers.get("Cookie");if(!gt(m,R.name))return Oe;let h=await R.serialize("",{maxAge:0}),w=await R.parse(m);return typeof w=="string"&&A(w).kind==="accepted"?{path:w,deletion:h}:(o.warn(`The sign-in's return-to cookie ${R.name} names no accepted return-to; the sign-in returns to the post-login path instead`),{path:void 0,deletion:h})},endFailedFlow:(u,d,R)=>{if(d.deletion===void 0)return u;let m=d.path===void 0?u:T(u,d.path,R),h=new Headers(m.headers);return h.append("Set-Cookie",d.deletion),pe(m,h)},signInRedirect:(u,d)=>{let R=A(se(u));switch(R.kind){case"accepted":return(0,M.redirect)(Y(n,u),d);case"closed":return(0,M.redirect)(n,d);case"malformed":return o.warn(`The sign-in redirect leaves its return-to out because ${R.reason}; the sign-in returns to the post-login path instead`),(0,M.redirect)(n,d);case"tooLong":return o.warn(`The sign-in redirect leaves its return-to out because its ${R.length} characters exceed returnTo.pages.maxLength; the sign-in returns to the post-login path instead`),(0,M.redirect)(n,d);case"excluded":throw new TypeError(`[auth-react-router] a page under the excluded prefix ${JSON.stringify(R.prefix)} redirected to the sign-in page; a route there answers 401 instead (pass failureRedirect: null)`)}},checkRedirectMode:(u,d)=>{if(d.failureRedirect!==n)throw new TypeError(`[auth-react-router] failureRedirect must be the sign-in page ${JSON.stringify(n)}, where the redirect mode sends an unauthenticated request; got ${JSON.stringify(d.failureRedirect)} (pass null to skip redirecting)`);if(se(d.returnTo),u.method!=="GET"&&u.method!=="HEAD")throw new TypeError("[auth-react-router] the redirect mode serves only GET and HEAD loaders; an action answers 401 data")}}};var me=3600*24*30,pt=e=>{if(e===void 0)return me;if(!Number.isSafeInteger(e)||e<1)throw new RangeError(`session.maxAge must be a safe integer of seconds >= 1; got ${String(e)}`);return e},Ne=e=>e.secure??process.env.NODE_ENV==="production",ae=(e,t)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(h=>!h))throw new Error("REMIX_SESSION_SECRET must be set");let n=e.sessionKey??"user";if(n===N)throw new RangeError(`session.sessionKey must not be ${JSON.stringify(N)}, the key the session generation is stored under; got ${JSON.stringify(n)}`);let o=pt(e.maxAge),s=t.loginPath??"/auth/login",y=t.postLoginRedirect??"/",A=t.mockUser,k=t.isUserActive,T=t.logger??H,S=ve(t.sessionGeneration,T),P=Ie(t.returnTo,{secrets:e.secrets,secure:Ne(e)},s,T),l=(0,ie.createCookieSessionStorage)({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:Ne(e),maxAge:o}}),p=async h=>await l.getSession(h.headers.get("Cookie")),f=async h=>{if(A?.enabled(h))return{kind:"signed-in",user:W(A.resolve(h)),session:await p(h)};let w=await p(h),a=w.get(n);if(a===void 0)return{kind:"signed-out"};let c=W(a),[E,b]=await Promise.all([k===void 0?!0:k(c),S===null?"current":S.check($(a),w.get(N))]);return b==="stale"?{kind:"revoked",session:w}:E?{kind:"signed-in",user:c,session:w}:{kind:"inactive"}},x=async h=>{let w=await f(h);return w.kind==="signed-in"?w.user:void 0},u=async(h,w)=>{let a=await p(h);return a.set(n,w),await l.commitSession(a)},d=async(h,w)=>{let a=S===null?void 0:await S.stamp($(w)),c=await p(h);return c.set(n,w),a!==void 0&&c.set(N,a),await l.commitSession(c)},R=async(h,w)=>{se(w);let a=await f(h);switch(a.kind){case"signed-in":return a.user;case"revoked":throw P.signInRedirect(w,{headers:{"Set-Cookie":await l.destroySession(a.session)}});case"signed-out":case"inactive":throw P.signInRedirect(w)}};return{sessionStorage:l,sessionKey:n,sessionMaxAgeSeconds:o,sessionGenerationGate:S,returnToPolicy:P,getSession:p,resolveSession:f,getSessionUser:x,saveSession:u,saveSignedInSession:d,requireUser:R,requireAdminUser:async(h,w)=>{let a=await R(h,w);if(a.role!=="admin")throw(0,ie.redirect)(y);return a},commitSession:l.commitSession,destroySession:l.destroySession}};var Le=e=>{let t=e.logger??H,n=ae(e.session,{sessionGeneration:e.sessionGeneration,logger:t,mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive,returnTo:e.returnTo}),o=Z(e),s=B(e,n,t),y=X(e,n,s,t),A=re(e,n,o,t);return{authenticator:o,storage:n,authFns:s,sessionStorage:n.sessionStorage,getSession:n.getSession,getSessionUser:n.getSessionUser,saveSession:n.saveSession,requireUser:n.requireUser,requireAdminUser:n.requireAdminUser,signInRedirect:n.returnToPolicy.signInRedirect,commitSession:n.commitSession,destroySession:n.destroySession,sessionMaxAgeSeconds:n.sessionMaxAgeSeconds,authenticate:s.authenticate,refreshedAccessToken:s.refreshedAccessToken,authenticateInLoader:y,...A}};0&&(module.exports={AuthRequiredError,DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS,DEFAULT_SESSION_GENERATION_CACHE_TTL_MS,DEFAULT_SESSION_GENERATION_TIMEOUT_MS,DEFAULT_SESSION_MAX_AGE_SECONDS,GoogleInvalidGrantError,SessionGenerationUnavailableError,TokenRefreshError,createAuthHandlers,createAuthServer,createAuthSessionStorage,createAuthenticate,createAuthenticateInLoader,createGoogleAuthenticator,signOutRefusal,signOutRefusalResponse});
1
+ "use strict";var ue=Object.defineProperty;var He=Object.getOwnPropertyDescriptor;var je=Object.getOwnPropertyNames;var Ve=Object.prototype.hasOwnProperty;var Je=(e,t)=>{for(var n in t)ue(e,n,{get:t[n],enumerable:!0})},We=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of je(t))!Ve.call(e,i)&&i!==n&&ue(e,i,{get:()=>t[i],enumerable:!(o=He(t,i))||o.enumerable});return e};var ze=e=>We(ue({},"__esModule",{value:!0}),e);var Pt={};Je(Pt,{AuthRequiredError:()=>q,DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS:()=>le,DEFAULT_SESSION_GENERATION_CACHE_TTL_MS:()=>he,DEFAULT_SESSION_GENERATION_TIMEOUT_MS:()=>pe,DEFAULT_SESSION_MAX_AGE_SECONDS:()=>we,GoogleInvalidGrantError:()=>H,SessionGenerationUnavailableError:()=>U,TokenRefreshError:()=>M,createAuthHandlers:()=>se,createAuthServer:()=>De,createAuthSessionStorage:()=>de,createAuthenticate:()=>Q,createAuthenticateInLoader:()=>Z,createGoogleAuthenticator:()=>te,signOutRefusal:()=>ne,signOutRefusalResponse:()=>re});module.exports=ze(Pt);var be=require("@aiquants/auth-core");var Te=require("@aiquants/auth-core"),Ye="https://oauth2.googleapis.com/revoke",le=5e3,W=2147483647,Be="invalid_token",Xe=400,Ae=e=>{if(e===void 0)return le;if(!Number.isInteger(e)||e<1||e>W)throw new RangeError(`google.revocationTimeoutMs must be an integer from 1 to ${W} (milliseconds); got ${String(e)}`);return e},Qe=e=>{if(typeof e.refreshToken=="string"&&e.refreshToken!=="")return e.refreshToken;if(typeof e.accessToken=="string"&&e.accessToken!=="")return e.accessToken},Ze=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},et=e=>e instanceof Error?e.cause instanceof Error?`${e.message} (${e.cause.message})`:e.message:String(e),tt=async(e,t,n)=>{try{let o=await t(Ye,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:e}).toString(),signal:n});if(o.ok)return await o.body?.cancel(),{outcome:"revoked"};let i=await Ze(o);return o.status===Xe&&i===Be?{outcome:"already-invalid"}:{outcome:"failed",reason:i===void 0?`Google answered ${o.status}`:`Google answered ${o.status} ${i}`}}catch(o){return{outcome:"failed",reason:et(o)}}},ve=async(e,t)=>{if(e===void 0)return{outcome:"nothing-to-revoke"};let n=Qe(e);if(n===void 0)return{outcome:"nothing-to-revoke"};if(e.provider!==Te.GOOGLE_PROVIDER)return{outcome:"failed",reason:`the session's provider "${String(e.provider)}" has no revocation endpoint`};let o=new AbortController;return await new Promise(i=>{let y=setTimeout(()=>{i({outcome:"failed",reason:`Google did not answer within ${t.timeoutMs} ms`}),o.abort()},t.timeoutMs);tt(n,t.fetch,o.signal).then(v=>{clearTimeout(y),i(v)})})};var N="generation",he=15e3,pe=3e3,nt=6e4,U=class extends Error{constructor(t,n){super(t,n),this.name="SessionGenerationUnavailableError"}},I=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),rt=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return I(e);let t="store"in e?e.store:void 0;if(typeof t!="object"||t===null)return`an object whose store is ${I(t)}`;let n="current"in t?t.current:void 0,o="advance"in t?t.advance:void 0;return`an object whose store.current is ${I(n)} and store.advance is ${I(o)}`},ot=e=>typeof e=="object"&&e!==null&&"current"in e&&typeof e.current=="function"&&"advance"in e&&typeof e.advance=="function",Pe=(e,t,n,o)=>{if(t===void 0)return o;if(typeof t!="number"||!Number.isInteger(t)||t<n||t>W)throw new RangeError(`${e} must be an integer from ${n} to ${W} (milliseconds); got ${I(t)}`);return t},st=e=>{if(e===!1)return!1;let t=e;if(typeof t!="object"||t===null||!("store"in t)||!ot(t.store))throw new TypeError(`sessionGeneration must be { store, cacheTtlMs?, timeoutMs? } or false; got ${rt(t)}`);return{store:t.store,cacheTtlMs:Pe("sessionGeneration.cacheTtlMs","cacheTtlMs"in t?t.cacheTtlMs:void 0,0,he),timeoutMs:Pe("sessionGeneration.timeoutMs","timeoutMs"in t?t.timeoutMs:void 0,1,pe)}},K=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,fe=e=>typeof e.provider=="string"&&e.provider!==""&&typeof e.id=="string"&&e.id!=="",Ee=e=>new TypeError(`a session generation identity needs a non-empty provider and id; got provider ${I(e.provider)} and id ${I(e.id)}`),it=e=>K(e)&&K(e+1),at=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 ${I(e)}`),C=e=>({provider:e.provider,id:e.id}),Ge=(e,t)=>{let n=st(e);if(n===!1)return null;let{store:o,cacheTtlMs:i,timeoutMs:y}=n,v=new Map,R=new Map,A=new Map,S=new Map,E=Number.NEGATIVE_INFINITY,h=r=>`${r.provider}\0${r.id}`,m=(r,s)=>{let u=v.get(r);if(u!==void 0){if(s-u.at<i)return u;v.delete(r)}},c=(r,s,u)=>{if(u!==void 0&&s.at<=u.answeredAt&&s.value<u.value)return;let P=m(r,performance.now());if(P===void 0){v.set(r,s);return}s.value<P.value||v.set(r,{value:s.value,at:Math.max(P.at,s.at)})},G=r=>{let s=S.get(r);if(s!==void 0)return s.count+=1,s;let u={count:1,floor:void 0};return S.set(r,u),u},a=(r,s)=>{s.count-=1,s.count===0&&S.delete(r)},d=(r,s)=>{r.floor={value:r.floor===void 0?s:Math.max(r.floor.value,s),answeredAt:performance.now()}},k=(r,s)=>{let u=A.get(r);return u===void 0?!1:s<u?!0:(A.delete(r),!1)},p=(r,s)=>{let u=performance.now();return A.set(r,u+i),u-E>=nt&&(E=u,t.warn("Session generation store unavailable; skipping the sign-out generation check:",s)),"unavailable"},T=(r,s,u)=>new Promise((P,b)=>{let{operation:_}=r,Re=r.operation==="advance"?r.from+1:0,Ke=performance.now(),J=G(u),F=!1,ke=setTimeout(()=>{F=!0,P({kind:"unavailable",error:new U(`sessionGeneration.store.${_} did not settle within ${y} ms`)})},y);new Promise(x=>x(r.operation==="advance"?o.advance(s,r.from):o.current(s))).then(x=>{if(clearTimeout(ke),!(K(x)&&x>=Re)){a(u,J),F||(F=!0,b(new TypeError(`sessionGeneration.store.${_} must resolve to an integer >= ${Re}; got ${I(x)}`)));return}_==="advance"&&(d(J,x),R.delete(u)),c(u,{value:x,at:Ke},J.floor),a(u,J),!F&&(F=!0,A.delete(u),P({kind:"value",value:x}))},x=>{if(clearTimeout(ke),a(u,J),!F){if(F=!0,x instanceof U){P({kind:"unavailable",error:x});return}b(x)}})}),O=(r,s,u)=>{let P=R.get(s);if(P!==void 0&&u-P.startedAt<i)return P.read;let b={read:T({operation:"current"},r,s),startedAt:u};R.set(s,b);let _=()=>{R.get(s)===b&&R.delete(s)};return b.read.then(_,_),b.read},g=async(r,s,u)=>{let P=await T({operation:"current"},r,s);return P.kind==="unavailable"?p(s,P.error):u===P.value?"current":"stale"};return{check:async(r,s)=>{if(!(K(s)&&fe(r)))return"stale";let u=performance.now(),P=h(r),b=m(P,u);if(b!==void 0){if(s===b.value)return"current";if(s<b.value)return"stale"}if(k(P,u))return"unavailable";if(b!==void 0)return await g(r,P,s);let _=await O(r,P,u);return _.kind==="unavailable"?p(P,_.error):s===_.value?"current":s<_.value?"stale":await g(r,P,s)},stamp:async r=>{if(!fe(r))throw Ee(r);let s=await T({operation:"current"},r,h(r));if(s.kind==="unavailable")throw s.error;return s.value},advance:async(r,s)=>{if(!fe(r))return{kind:"failed",error:Ee(r)};if(!it(s))return{kind:"failed",error:at(s)};try{let u=await T({operation:"advance",from:s},r,h(r));return u.kind==="value"?{kind:"advanced",generation:u.value}:{kind:"unavailable",error:u.error}}catch(u){return{kind:"failed",error:u}}}}};var M=class extends Error{constructor(t){super(t),this.name="TokenRefreshError"}},H=class extends M{constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},q=class extends Error{constructor(t){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=t}},ct=["access_token","expires_in"],Q=(e,t,n)=>{let o=t.sessionKey,i=async R=>{let S=R.get(o)?.refreshToken;if(!S)throw new Error("Refresh token not found in session");try{let E="https://www.googleapis.com/oauth2/v4/token",h={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:S},c=await(e.fetch??globalThis.fetch)(E,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(h)});if(!c.ok){let p=await c.json().catch(()=>{});if(c.status===400&&typeof p=="object"&&!!p&&"error"in p&&p.error==="invalid_grant")throw new H;let O=typeof p=="object"&&p&&"error_description"in p?String(p.error_description):"Unknown error";throw new M(`Google token refresh failed: ${c.status} ${O}`)}let G=await c.json(),a=ct.filter(p=>!G?.[p]);if(a.length>0)throw n.error("Invalid token response from Google; missing or empty keys:",a.join(", ")),new Error("Invalid token response from Google");let{access_token:d,expires_in:k}=G;return{accessToken:d,refreshToken:S,expirationDateMs:Number(Date.now())+k*1e3}}catch(E){if(E instanceof M)throw E;let h=E instanceof Error?E.message:"Unknown error";throw new M(`Failed to refresh Google access token: ${h}`)}},y=async R=>{let S=R.get(o).provider;if(!S)throw new Error("Provider not found in session");if(S===be.GOOGLE_PROVIDER)return await i(R);throw new Error("Provider not supported")};return{authenticate:async(R,A,S)=>{S.failureRedirect!==null&&t.returnToPolicy.checkRedirectMode(R,S);let E=h=>S.failureRedirect===null?new q(h):t.returnToPolicy.signInRedirect(S.returnTo,h!==void 0?{headers:{"Set-Cookie":h}}:void 0);try{if(e.mockUser?.enabled(R)){let{accessToken:d,refreshToken:k,expirationDateMs:p}=e.mockUser.resolve(R);return{accessToken:d,refreshToken:k,expirationDateMs:p}}let h=A.get(o),m=t.sessionGenerationGate;if(h!==void 0&&m!==null&&await m.check(C(h),A.get(N))==="stale")throw E(await t.destroySession(A));if(!(h?.accessToken&&h.expirationDateMs))throw E();let{accessToken:c,refreshToken:G,expirationDateMs:a}=h;if(a<Date.now())throw G?new Error("Expired"):E();return{accessToken:c,refreshToken:G,expirationDateMs:a}}catch(h){if(h instanceof Error&&h.message==="Expired")try{let m=await y(A),c=A.get(o);return A.set(o,{...c,...m}),m}catch(m){if(m instanceof H)n.warn("Google refresh token invalid or revoked");else{let G=m instanceof Error?m.message:"Unknown error";n.error("Failed to refresh token:",G)}let c=await t.destroySession(A);throw E(c)}throw h}},refreshedAccessToken:y}};var z=({refreshToken:e,...t})=>t;var Z=(e,t,n,o)=>{let i=new Map,y=new Map,v=async h=>{let m=JSON.stringify([h.provider,h.id]),c=i.get(m);if(c!==void 0)return c;let G=y.get(m);if(G!==void 0)return G;let a=(async()=>{try{let d=e.getUserPhoto?await e.getUserPhoto(h):"";return i.set(m,d),d}catch(d){throw i.delete(m),d}finally{y.delete(m)}})();return y.set(m,a),a},R=new WeakMap,A=async h=>{e.warmup&&await e.warmup();let m=await t.resolveSession(h);switch(m.kind){case"revoked":return{kind:"unauthenticated",cookie:await t.destroySession(m.session)};case"signed-out":case"inactive":case"other-reader":return{kind:"unauthenticated"};case"signed-in":break}let{user:c,session:G}=m,a;try{a=await n.authenticate(h,G,{failureRedirect:null})}catch(l){if(l instanceof q)return l.setCookie!==void 0?{kind:"unauthenticated",cookie:l.setCookie}:{kind:"unauthenticated"};throw o.error("Error in authenticateInLoader:",l),l}let d={accessToken:a.accessToken,refreshToken:a.refreshToken,expirationDateMs:a.expirationDateMs,provider:c.provider},k={id:c.id,displayName:c.displayName,name:c.name,emails:c.emails,...d,role:c.role},p=await v(c),T=z({...c,...d,photo:p}),g=a.accessToken!==c.accessToken?await t.saveSession(h,k):void 0;return g!==void 0?{kind:"authenticated",user:T,cookie:g}:{kind:"authenticated",user:T}},S=h=>{let m=R.get(h);if(m!==void 0)return m;let c=A(h);return R.set(h,c),c};async function E(h,m){m.failureRedirect!==null&&t.returnToPolicy.checkRedirectMode(h,m);let c=await S(h);if(c.kind==="authenticated")return c.cookie!==void 0?{user:c.user,cookie:c.cookie}:{user:c.user};if(m.failureRedirect===null)return c.cookie!==void 0?{cookie:c.cookie}:{};throw t.returnToPolicy.signInRedirect(m.returnTo,c.cookie!==void 0?{headers:{"Set-Cookie":c.cookie}}:void 0)}return E};var xe=require("@aiquants/auth-core"),ee=require("react-router"),_e=require("remix-auth");var Oe=require("remix-auth-oauth2"),dt=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],ut="google",lt="https://www.googleapis.com/oauth2/v3/userinfo",Y=class extends Oe.OAuth2Strategy{constructor({clientId:n,clientSecret:o,redirectURI:i,scopes:y,accessType:v,includeGrantedScopes:R,prompt:A,hd:S,loginHint:E,additionalScopes:h},m){let c=y??dt;super({clientId:n,clientSecret:o,redirectURI:i,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:c},m);this.name=ut;this.scopes=c,this.accessType=v??"online",this.includeGrantedScopes=R??!1,this.prompt=A,this.hd=S,this.loginHint=E,this.additionalScopes=h}authorizationParams(n,o){n.set("access_type",this.accessType),n.set("include_granted_scopes",String(this.includeGrantedScopes));let i=o===void 0||this.additionalScopes===void 0?[]:this.additionalScopes(o);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 y=[...new Set([...this.scopes,...i])];return y.length>0&&n.set("scope",y.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 o=await fetch(lt,{headers:{Authorization:`Bearer ${n.accessToken()}`}});if(!o.ok)throw new Error(`Failed to fetch user profile: ${o.statusText}`);let i=await o.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 j={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var ge="error",L=(e,t)=>`${e}?${new URLSearchParams({[ge]:t}).toString()}`;var Ie=e=>e instanceof Error&&e.code==="access_denied"?"consentDenied":"googleFailed",te=e=>{let t=e.logger??j,n=e.loginPath??"/auth/login",o=new Y({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:y,tokens:v})=>{let{access_token:R,refresh_token:A,expires_in:S,scope:E,id_token:h}=v.data,{_json:{sub:m,email:c,picture:G,hd:a,email_verified:d},photos:k,...p}=await Y.userProfile(v),{id:T,displayName:O,name:{familyName:g,givenName:l},emails:f}=p,w=xe.GOOGLE_PROVIDER;if(R===void 0||A===void 0||S===void 0||E===void 0||T===void 0||O===void 0||m===void 0||c===void 0||d===void 0)throw(0,ee.redirect)(L(n,d===!1?"emailNotVerified":"googleFailed"));t.info("Authenticated on Google: ",p.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(w,R))throw t.error("Backend verification returned false for user:",p.displayName),(0,ee.redirect)(L(n,"backendFailed"));t.info("Authenticated on Backend: ",p.displayName)}let r=p.emails[0]?.value;if(!await e.isEmailAllowed(r)){let b=new Error("You are not allowed to access this application");throw t.error(b),b}if(e.isUserActive&&!await e.isUserActive({...p,provider:w})){let b=new Error("You are not allowed to access this application");throw t.error("Deactivated account attempted to sign in:",r),b}e.backendAuth&&await e.backendAuth.signup(w,R,p),t.info("Authenticated complete: ",p.displayName);let s=Date.now()+S*1e3;return{...p,...{accessToken:R,refreshToken:A,expirationDateMs:s,provider:w},photo:G}}catch(r){let s=r;typeof r=="object"&&r!==null&&"cause"in r&&(s=r.cause||r),t.error("Error during backend authentication or subsequent processing:",s);let u="unexpected",P=!1;if(typeof r=="object"&&r!==null&&"cause"in r){let b=r.cause;b&&typeof b=="object"&&"message"in b&&typeof b.message=="string"&&b.message.includes("getaddrinfo ENOTFOUND")&&(u="backendUnreachable",P=!0)}throw!P&&r instanceof Error&&r.message.includes("You are not allowed to access this application")&&(u="notAllowed",P=!0),!P&&r instanceof Response&&r.headers.get("Location")?.startsWith(n)?r:(0,ee.redirect)(L(n,u))}}),i=new _e.Authenticator;return i.use(o),i};var oe=require("@aiquants/auth-core"),D=require("react-router");var me="returnTo",B=(e,t)=>{let n=e.indexOf("?"),o=n===-1?e:e.slice(0,n),i=new URLSearchParams(n===-1?"":e.slice(n+1));return i.set(me,t),`${o}?${i.toString()}`};var ft=new Map([["document",new Set(["none","same-origin","same-site"])],["empty",new Set(["same-origin"])]]),ne=e=>{let t=e.headers.get("Sec-Fetch-Dest");if(t!==null){let o=ft.get(t);if(o===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(!o.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}")`},re=e=>new Response(e.signOutRefused,{status:403,headers:{"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"}});var se=(e,t,n,o)=>{let i=e.loginPath??"/auth/login",y=e.postLoginRedirect??"/",v=e.postLogoutRedirect??"/",R=Ae(e.google.revocationTimeoutMs),A=(0,oe.resolveAuthMessages)(e.messages),S=t.returnToPolicy,E=async({request:g})=>{let l=S.requested(g),f=new URL(g.url).searchParams.get(ge),w=(0,oe.isSignInFailureKey)(f)?f:null;if(w===null&&await t.getSessionUser(g))throw(0,D.redirect)(l??y);return{error:w===null?null:A[w]}},h=async g=>{let l=S.requested(g);try{await n.authenticate("google",g)}catch(f){throw l===void 0||!(f instanceof Response)?f:await S.bindToFlow(f,l,g)}throw(0,D.redirect)(l===void 0?i:B(i,l))},m=async({request:g})=>(await g.clone().formData()).get("_action")!=="Sign In with Google"?null:await h(g),c=(g,l)=>{switch(g.outcome){case"failed":o.error(`Sign-out could not revoke the Google grant of user ${String(l)}; the session cookie is destroyed, but the grant stays valid until it expires or is revoked elsewhere:`,g.reason);return;case"already-invalid":o.info(`Sign-out found the Google grant of user ${String(l)} already unusable`);return;case"revoked":case"nothing-to-revoke":return}},G=(g,l)=>{g.kind!=="advanced"&&o.error(`Sign-out could not advance the session generation of ${l.provider} user ${l.id}; a session cookie refreshed before this sign-out stays valid until a later sign-out advances the generation or the cookie expires:`,g.error)},a=async(g,l)=>{let f=t.sessionGenerationGate;if(f!==null){if(!K(l)){o.info(`Sign-out found no usable session generation stamp in the session of ${g.provider} user ${g.id}; every guard already rejects that cookie, so the generation is not advanced`);return}G(await f.advance(g,l),g)}},d=async g=>{let l=await t.getSession(g),f=l.get(t.sessionKey),[w]=await Promise.all([ve(f,{fetch:e.fetch??globalThis.fetch,timeoutMs:R}),f===void 0?void 0:a(C(f),l.get(N))]);return c(w,f?.id),await t.destroySession(l)},k=async g=>{let l=await d(g),f=new Headers;return f.append("Set-Cookie",l),(0,D.redirect)(v,{headers:f})},p=async({request:g})=>{let l=ne(g);throw l!==void 0?(o.warn(`Signing out is refused because ${l}`),re(A)):await k(g)},T=async(g,l)=>{let r=(await t.getSession(g)).get(t.sessionKey)?.refreshToken,s={accessToken:l.accessToken,refreshToken:l.refreshToken||r,expirationDateMs:l.expirationDateMs,provider:l.provider},u={id:l.id,displayName:l.displayName,name:l.name,emails:l.emails,...s,role:l.role};return await t.saveSignedInSession(g,u)};return{loginLoader:E,loginAction:m,startGoogleSignIn:h,logoutLoader:p,logout:d,logoutAndRedirect:k,googleCallbackLoader:async({request:g})=>{let l=await S.flowOf(g),f;try{f=await n.authenticate("google",g)}catch(s){throw s instanceof Response?S.endFailedFlow(s,l,g):(o.error("Authentication error:",s),S.endFailedFlow((0,D.redirect)(L(i,Ie(s))),l,g))}let w;try{w=await T(g,f)}catch(s){throw o.error("Saving the signed-in session failed:",s),S.endFailedFlow((0,D.redirect)(L(i,s instanceof U?"backendUnreachable":"unexpected")),l,g)}let r=new Headers;throw r.append("Set-Cookie",w),l.deletion!==void 0&&r.append("Set-Cookie",l.deletion),(0,D.redirect)(l.path??y,{headers:r})},messages:A}};var V=require("@aiquants/auth-core"),ce=require("react-router");var X=require("@aiquants/auth-core"),ht="aiquants-reader-stamp",ye={name:"HMAC",hash:"SHA-256"},Le=new TextEncoder,Ne=({provider:e,id:t})=>Le.encode(`${ht}\0${JSON.stringify([e,t])}`),Ce=e=>btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,""),pt=e=>Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),t=>t.charCodeAt(0)),Ue=e=>{if(e.length===0)throw new RangeError("the reader stamps need at least one session secret");let t,n=()=>(t??(t=Promise.all(e.map(o=>crypto.subtle.importKey("raw",Le.encode(o),ye,!1,["sign","verify"])))),t);return{stampOf:async o=>{if(o===null)return X.ANONYMOUS_READER_STAMP;let[i]=await n();return Ce(new Uint8Array(await crypto.subtle.sign(ye.name,i,Ne(o))))},matches:async(o,i)=>{if(o===X.ANONYMOUS_READER_STAMP||!(0,X.isReaderStamp)(o))return!1;let y=pt(o);if(Ce(y)!==o)return!1;let v=Ne(i);for(let R of await n())if(await crypto.subtle.verify(ye.name,R,y,v))return!0;return!1}}};var $=require("react-router");var gt="__return_to.",mt=300,Me=/^[A-Za-z0-9_-]{1,128}$/,yt=/%(?![0-9A-Fa-f]{2})/,ie="https://return-to.invalid",$e=Object.freeze({path:void 0,deletion:void 0}),St=e=>{if(e.includes("%"))return!1;let t=new URL(e,ie);return t.origin===ie&&t.pathname===e},wt=e=>{for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=31||n>=127&&n<=159||e[t]==="\\"||e[t]==="#")return!0}return!1},Rt=e=>{if(e[0]!=="/"||e[1]==="/"||e[1]==="\\")return{malformed:'it does not start with a single "/"'};if(wt(e))return{malformed:'it holds a control character, a backslash or a "#"'};if(yt.test(e))return{malformed:'it holds a "%" that two hexadecimal digits do not follow'};let t=new URL(e,ie);if(t.origin!==ie||`${t.pathname}${t.search}`!==e)return{malformed:"the URL parser normalizes it"};let n;try{n=decodeURIComponent(t.pathname)}catch{return{malformed:"its path does not decode as UTF-8"}}return n.startsWith("//")||n.startsWith("/\\")?{malformed:'its decoded path starts with "//" or "/\\"'}:{decodedPath:n}},kt=e=>{if(e===null)return null;let t="returnTo.pages must be null or { excludedPathPrefixes: string[], maxLength: number }";if(typeof e!="object"||Array.isArray(e))throw new TypeError(`${t}; got ${JSON.stringify(e)}`);let{excludedPathPrefixes:n,maxLength:o}=e;if(!Array.isArray(n))throw new TypeError(`${t}; got excludedPathPrefixes ${JSON.stringify(n)}`);for(let y of n){if(typeof y!="string")throw new TypeError(`returnTo.pages.excludedPathPrefixes must hold strings; got ${JSON.stringify(y)}`);if(!y.startsWith("/"))throw new RangeError(`returnTo.pages.excludedPathPrefixes must hold path prefixes starting with "/"; got ${JSON.stringify(y)}`)}if(typeof o!="number")throw new TypeError(`${t}; got maxLength ${JSON.stringify(o)}`);if(!Number.isSafeInteger(o)||o<1)throw new RangeError(`returnTo.pages.maxLength must be a safe integer >= 1; got ${String(o)}`);let i=Object.freeze([...n]);return Object.freeze({excludedPathPrefixes:i,maxLength:o,lowerCasePrefixes:Object.freeze(i.map(y=>y.toLowerCase()))})},Tt=e=>{if(e===void 0)return{allowedPaths:new Set,pages:null};let t=e;if(typeof t!="object"||t===null||!Array.isArray(t.allowedPaths))throw new TypeError(`returnTo must be { allowedPaths: string[], pages: { excludedPathPrefixes: string[], maxLength: number } | null }; got ${JSON.stringify(t)}`);let n=t.allowedPaths;for(let i of n){if(typeof i!="string")throw new TypeError(`returnTo.allowedPaths must hold strings; got ${JSON.stringify(i)}`);if(!St(i))throw new RangeError(`returnTo.allowedPaths must hold canonical same-origin paths (one leading "/", no query, fragment, percent-encoding, backslash, white space, control or non-ASCII character, or dot segment); got ${JSON.stringify(i)}`)}let o=kt(t.pages);if(n.length===0&&o===null)throw new RangeError("returnTo allows no return-to (allowedPaths is empty and pages is null); omit returnTo to allow none");return{allowedPaths:new Set(n),pages:o}},ae=e=>{if(typeof e!="string")throw new TypeError(`[auth-react-router] returnTo must be the page's path and query to return to after the sign-in; got ${JSON.stringify(e)}`);return e},At=(e,t)=>e===null?!1:e.split(";").some(n=>n.trim().startsWith(`${t}=`)),Se=(e,t)=>new Response(e.body,{status:e.status,statusText:e.statusText,headers:t}),Fe=(e,t,n,o)=>{let{allowedPaths:i,pages:y}=Tt(e),v=a=>{if(i.has(a))return{kind:"accepted"};if(y===null)return{kind:"closed"};let d=Rt(a);if("malformed"in d)return{kind:"malformed",reason:d.malformed};let k=d.decodedPath.toLowerCase(),p=y.lowerCasePrefixes.findIndex(T=>k.startsWith(T));return p!==-1?{kind:"excluded",prefix:y.excludedPathPrefixes[p]}:a.length>y.maxLength?{kind:"tooLong",length:a.length}:{kind:"accepted"}},R=a=>(0,$.createCookie)(`${gt}${a}`,{secrets:[...t.secrets],httpOnly:!0,sameSite:"lax",path:"/",secure:t.secure,maxAge:mt}),A=(a,d,k)=>{let p=a.headers.get("Location");if(p===null)return a;let T=new URL(p,k.url);if(T.origin!==new URL(k.url).origin||T.pathname!==n)return a;let O=new Headers(a.headers);return O.set("Location",`${B(`${T.pathname}${T.search}`,d)}${T.hash}`),Se(a,O)};return{requested:a=>{let d=new URL(a.url).searchParams.getAll(me);if(d.length!==0){if(d.length===1&&v(d[0]).kind==="accepted")return d[0];throw(0,$.redirect)(L(n,"returnToRefused"))}},bindToFlow:async(a,d,k)=>{let p=a.headers.get("Location"),T=p===null?null:new URL(p,k.url).searchParams.get("state");if(T===null)return A(a,d,k);if(!Me.test(T))throw new Error(`The authorization redirect's state cannot name the return-to cookie; got ${JSON.stringify(T)}`);let O=new Headers(a.headers);return O.append("Set-Cookie",await R(T).serialize(d)),Se(a,O)},flowOf:async a=>{let d=new URL(a.url).searchParams.get("state");if(d===null||!Me.test(d))return $e;let k=R(d),p=a.headers.get("Cookie");if(!At(p,k.name))return $e;let T=await k.serialize("",{maxAge:0}),O=await k.parse(p);return typeof O=="string"&&v(O).kind==="accepted"?{path:O,deletion:T}:(o.warn(`The sign-in's return-to cookie ${k.name} names no accepted return-to; the sign-in returns to the post-login path instead`),{path:void 0,deletion:T})},endFailedFlow:(a,d,k)=>{if(d.deletion===void 0)return a;let p=d.path===void 0?a:A(a,d.path,k),T=new Headers(p.headers);return T.append("Set-Cookie",d.deletion),Se(p,T)},signInRedirect:(a,d)=>{let k=v(ae(a));switch(k.kind){case"accepted":return(0,$.redirect)(B(n,a),d);case"closed":return(0,$.redirect)(n,d);case"malformed":return o.warn(`The sign-in redirect leaves its return-to out because ${k.reason}; the sign-in returns to the post-login path instead`),(0,$.redirect)(n,d);case"tooLong":return o.warn(`The sign-in redirect leaves its return-to out because its ${k.length} characters exceed returnTo.pages.maxLength; the sign-in returns to the post-login path instead`),(0,$.redirect)(n,d);case"excluded":throw new TypeError(`[auth-react-router] a page under the excluded prefix ${JSON.stringify(k.prefix)} redirected to the sign-in page; a route there answers 401 instead (pass failureRedirect: null)`)}},checkRedirectMode:(a,d)=>{if(d.failureRedirect!==n)throw new TypeError(`[auth-react-router] failureRedirect must be the sign-in page ${JSON.stringify(n)}, where the redirect mode sends an unauthenticated request; got ${JSON.stringify(d.failureRedirect)} (pass null to skip redirecting)`);if(ae(d.returnTo),a.method!=="GET"&&a.method!=="HEAD")throw new TypeError("[auth-react-router] the redirect mode serves only GET and HEAD loaders; an action answers 401 data")}}};var we=3600*24*30,vt=e=>{if(e===void 0)return we;if(!Number.isSafeInteger(e)||e<1)throw new RangeError(`session.maxAge must be a safe integer of seconds >= 1; got ${String(e)}`);return e},qe=e=>e.secure??process.env.NODE_ENV==="production",de=(e,t)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(f=>!f))throw new Error("REMIX_SESSION_SECRET must be set");let n=e.sessionKey??"user";if(n===N)throw new RangeError(`session.sessionKey must not be ${JSON.stringify(N)}, the key the session generation is stored under; got ${JSON.stringify(n)}`);let o=vt(e.maxAge),i=t.loginPath??"/auth/login",y=t.postLoginRedirect??"/",v=t.mockUser,R=t.isUserActive,A=t.logger??j,S=Ge(t.sessionGeneration,A),E=Fe(t.returnTo,{secrets:e.secrets,secure:qe(e)},i,A),h=t.readerCheck;if(typeof h!="boolean")throw new TypeError(`readerCheck must be true or false; got ${I(h)}`);let m=Ue(e.secrets),c=(0,ce.createCookieSessionStorage)({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:qe(e),maxAge:o}}),G=async f=>await c.getSession(f.headers.get("Cookie")),a=async f=>{if(v?.enabled(f))return{kind:"signed-in",user:z(v.resolve(f)),session:await G(f)};let w=await G(f),r=w.get(n);if(r===void 0)return{kind:"signed-out"};let s=z(r),[u,P]=await Promise.all([R===void 0?!0:R(s),S===null?"current":S.check(C(r),w.get(N))]);return P==="stale"?{kind:"revoked",session:w}:u?{kind:"signed-in",user:s,session:w}:{kind:"inactive"}},d=async f=>{if(!(h&&(0,V.isWriteMethod)(f.method)))return await a(f);let w=new URL(f.url),r=(0,V.readReaderStamp)(w.searchParams);if(r.kind!=="stamped")throw(0,V.readerStampRefusalResponse)(r.kind);let s=await a(f);if(s.kind!=="signed-in")return s;let u=C(s.user);return await m.matches(r.stamp,u)?s:(A.warn(`Refused a ${f.method} to ${w.pathname} that a page of another reader sent under the session of ${u.provider} user ${u.id}`),{kind:"other-reader"})},k=async f=>{let w=await d(f);return w.kind==="signed-in"?w.user:void 0},p=async(f,w)=>{let r=await G(f);return r.set(n,w),await c.commitSession(r)},T=async(f,w)=>{let r=S===null?void 0:await S.stamp(C(w)),s=await G(f);return s.set(n,w),r!==void 0&&s.set(N,r),await c.commitSession(s)},O=async(f,w)=>{ae(w);let r=await d(f);switch(r.kind){case"signed-in":return r.user;case"revoked":throw E.signInRedirect(w,{headers:{"Set-Cookie":await c.destroySession(r.session)}});case"signed-out":case"inactive":case"other-reader":throw E.signInRedirect(w)}};return{sessionStorage:c,sessionKey:n,sessionMaxAgeSeconds:o,sessionGenerationGate:S,returnToPolicy:E,getSession:G,resolveSession:d,getSessionUser:k,saveSession:p,saveSignedInSession:T,requireUser:O,requireAdminUser:async(f,w)=>{let r=await O(f,w);if(r.role!=="admin")throw(0,ce.redirect)(y);return r},readerStampOf:async f=>await m.stampOf(f===void 0?null:C(f)),commitSession:c.commitSession,destroySession:c.destroySession}};var De=e=>{let t=e.logger??j,n=de(e.session,{sessionGeneration:e.sessionGeneration,readerCheck:e.readerCheck,logger:t,mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive,returnTo:e.returnTo}),o=te(e),i=Q(e,n,t),y=Z(e,n,i,t),v=se(e,n,o,t);return{authenticator:o,storage:n,authFns:i,sessionStorage:n.sessionStorage,getSession:n.getSession,getSessionUser:n.getSessionUser,readerStampOf:n.readerStampOf,saveSession:n.saveSession,requireUser:n.requireUser,requireAdminUser:n.requireAdminUser,signInRedirect:n.returnToPolicy.signInRedirect,commitSession:n.commitSession,destroySession:n.destroySession,sessionMaxAgeSeconds:n.sessionMaxAgeSeconds,authenticate:i.authenticate,refreshedAccessToken:i.refreshedAccessToken,authenticateInLoader:y,...v}};0&&(module.exports={AuthRequiredError,DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS,DEFAULT_SESSION_GENERATION_CACHE_TTL_MS,DEFAULT_SESSION_GENERATION_TIMEOUT_MS,DEFAULT_SESSION_MAX_AGE_SECONDS,GoogleInvalidGrantError,SessionGenerationUnavailableError,TokenRefreshError,createAuthHandlers,createAuthServer,createAuthSessionStorage,createAuthenticate,createAuthenticateInLoader,createGoogleAuthenticator,signOutRefusal,signOutRefusalResponse});
package/dist/server.mjs CHANGED
@@ -1 +1 @@
1
- import{GOOGLE_PROVIDER as De}from"@aiquants/auth-core";import{GOOGLE_PROVIDER as Ge}from"@aiquants/auth-core";var xe="https://oauth2.googleapis.com/revoke",fe=5e3,H=2147483647,be="invalid_token",_e=400,he=e=>{if(e===void 0)return fe;if(!Number.isInteger(e)||e<1||e>H)throw new RangeError(`google.revocationTimeoutMs must be an integer from 1 to ${H} (milliseconds); got ${String(e)}`);return e},Oe=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},Ne=e=>e instanceof Error?e.cause instanceof Error?`${e.message} (${e.cause.message})`:e.message:String(e),Le=async(e,t,n)=>{try{let o=await t(xe,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:e}).toString(),signal:n});if(o.ok)return await o.body?.cancel(),{outcome:"revoked"};let a=await Ie(o);return o.status===_e&&a===be?{outcome:"already-invalid"}:{outcome:"failed",reason:a===void 0?`Google answered ${o.status}`:`Google answered ${o.status} ${a}`}}catch(o){return{outcome:"failed",reason:Ne(o)}}},ge=async(e,t)=>{if(e===void 0)return{outcome:"nothing-to-revoke"};let n=Oe(e);if(n===void 0)return{outcome:"nothing-to-revoke"};if(e.provider!==Ge)return{outcome:"failed",reason:`the session's provider "${String(e.provider)}" has no revocation endpoint`};let o=new AbortController;return await new Promise(a=>{let y=setTimeout(()=>{a({outcome:"failed",reason:`Google did not answer within ${t.timeoutMs} ms`}),o.abort()},t.timeoutMs);Le(n,t.fetch,o.signal).then(A=>{clearTimeout(y),a(A)})})};var N="generation",ye=15e3,Se=3e3,Ue=6e4,C=class extends Error{constructor(t,n){super(t,n),this.name="SessionGenerationUnavailableError"}},I=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),Ce=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return I(e);let t="store"in e?e.store:void 0;if(typeof t!="object"||t===null)return`an object whose store is ${I(t)}`;let n="current"in t?t.current:void 0,o="advance"in t?t.advance:void 0;return`an object whose store.current is ${I(n)} and store.advance is ${I(o)}`},Me=e=>typeof e=="object"&&e!==null&&"current"in e&&typeof e.current=="function"&&"advance"in e&&typeof e.advance=="function",pe=(e,t,n,o)=>{if(t===void 0)return o;if(typeof t!="number"||!Number.isInteger(t)||t<n||t>H)throw new RangeError(`${e} must be an integer from ${n} to ${H} (milliseconds); got ${I(t)}`);return t},Fe=e=>{if(e===!1)return!1;let t=e;if(typeof t!="object"||t===null||!("store"in t)||!Me(t.store))throw new TypeError(`sessionGeneration must be { store, cacheTtlMs?, timeoutMs? } or false; got ${Ce(t)}`);return{store:t.store,cacheTtlMs:pe("sessionGeneration.cacheTtlMs","cacheTtlMs"in t?t.cacheTtlMs:void 0,0,ye),timeoutMs:pe("sessionGeneration.timeoutMs","timeoutMs"in t?t.timeoutMs:void 0,1,Se)}},$=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,Q=e=>typeof e.provider=="string"&&e.provider!==""&&typeof e.id=="string"&&e.id!=="",me=e=>new TypeError(`a session generation identity needs a non-empty provider and id; got provider ${I(e.provider)} and id ${I(e.id)}`),$e=e=>$(e)&&$(e+1),qe=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 ${I(e)}`),M=e=>({provider:e.provider,id:e.id}),we=(e,t)=>{let n=Fe(e);if(n===!1)return null;let{store:o,cacheTtlMs:a,timeoutMs:y}=n,A=new Map,k=new Map,T=new Map,S=new Map,P=Number.NEGATIVE_INFINITY,l=r=>`${r.provider}\0${r.id}`,p=(r,s)=>{let g=A.get(r);if(g!==void 0){if(s-g.at<a)return g;A.delete(r)}},f=(r,s,g)=>{if(g!==void 0&&s.at<=g.answeredAt&&s.value<g.value)return;let v=p(r,performance.now());if(v===void 0){A.set(r,s);return}s.value<v.value||A.set(r,{value:s.value,at:Math.max(v.at,s.at)})},x=r=>{let s=S.get(r);if(s!==void 0)return s.count+=1,s;let g={count:1,floor:void 0};return S.set(r,g),g},u=(r,s)=>{s.count-=1,s.count===0&&S.delete(r)},d=(r,s)=>{r.floor={value:r.floor===void 0?s:Math.max(r.floor.value,s),answeredAt:performance.now()}},R=(r,s)=>{let g=T.get(r);return g===void 0?!1:s<g?!0:(T.delete(r),!1)},m=(r,s)=>{let g=performance.now();return T.set(r,g+a),g-P>=Ue&&(P=g,t.warn("Session generation store unavailable; skipping the sign-out generation check:",s)),"unavailable"},h=(r,s,g)=>new Promise((v,G)=>{let{operation:O}=r,de=r.operation==="advance"?r.from+1:0,Ee=performance.now(),j=x(g),U=!1,le=setTimeout(()=>{U=!0,v({kind:"unavailable",error:new C(`sessionGeneration.store.${O} did not settle within ${y} ms`)})},y);new Promise(_=>_(r.operation==="advance"?o.advance(s,r.from):o.current(s))).then(_=>{if(clearTimeout(le),!($(_)&&_>=de)){u(g,j),U||(U=!0,G(new TypeError(`sessionGeneration.store.${O} must resolve to an integer >= ${de}; got ${I(_)}`)));return}O==="advance"&&(d(j,_),k.delete(g)),f(g,{value:_,at:Ee},j.floor),u(g,j),!U&&(U=!0,T.delete(g),v({kind:"value",value:_}))},_=>{if(clearTimeout(le),u(g,j),!U){if(U=!0,_ instanceof C){v({kind:"unavailable",error:_});return}G(_)}})}),w=(r,s,g)=>{let v=k.get(s);if(v!==void 0&&g-v.startedAt<a)return v.read;let G={read:h({operation:"current"},r,s),startedAt:g};k.set(s,G);let O=()=>{k.get(s)===G&&k.delete(s)};return G.read.then(O,O),G.read},i=async(r,s,g)=>{let v=await h({operation:"current"},r,s);return v.kind==="unavailable"?m(s,v.error):g===v.value?"current":"stale"};return{check:async(r,s)=>{if(!($(s)&&Q(r)))return"stale";let g=performance.now(),v=l(r),G=p(v,g);if(G!==void 0){if(s===G.value)return"current";if(s<G.value)return"stale"}if(R(v,g))return"unavailable";if(G!==void 0)return await i(r,v,s);let O=await w(r,v,g);return O.kind==="unavailable"?m(v,O.error):s===O.value?"current":s<O.value?"stale":await i(r,v,s)},stamp:async r=>{if(!Q(r))throw me(r);let s=await h({operation:"current"},r,l(r));if(s.kind==="unavailable")throw s.error;return s.value},advance:async(r,s)=>{if(!Q(r))return{kind:"failed",error:me(r)};if(!$e(s))return{kind:"failed",error:qe(s)};try{let g=await h({operation:"advance",from:s},r,l(r));return g.kind==="value"?{kind:"advanced",generation:g.value}:{kind:"unavailable",error:g.error}}catch(g){return{kind:"failed",error:g}}}}};var F=class extends Error{constructor(t){super(t),this.name="TokenRefreshError"}},V=class extends F{constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},q=class extends Error{constructor(t){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=t}},Ke=["access_token","expires_in"],Z=(e,t,n)=>{let o=t.sessionKey,a=async k=>{let S=k.get(o)?.refreshToken;if(!S)throw new Error("Refresh token not found in session");try{let P="https://www.googleapis.com/oauth2/v4/token",l={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:S},f=await(e.fetch??globalThis.fetch)(P,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(l)});if(!f.ok){let m=await f.json().catch(()=>{});if(f.status===400&&typeof m=="object"&&!!m&&"error"in m&&m.error==="invalid_grant")throw new V;let w=typeof m=="object"&&m&&"error_description"in m?String(m.error_description):"Unknown error";throw new F(`Google token refresh failed: ${f.status} ${w}`)}let x=await f.json(),u=Ke.filter(m=>!x?.[m]);if(u.length>0)throw n.error("Invalid token response from Google; missing or empty keys:",u.join(", ")),new Error("Invalid token response from Google");let{access_token:d,expires_in:R}=x;return{accessToken:d,refreshToken:S,expirationDateMs:Number(Date.now())+R*1e3}}catch(P){if(P instanceof F)throw P;let l=P instanceof Error?P.message:"Unknown error";throw new F(`Failed to refresh Google access token: ${l}`)}},y=async k=>{let S=k.get(o).provider;if(!S)throw new Error("Provider not found in session");if(S===De)return await a(k);throw new Error("Provider not supported")};return{authenticate:async(k,T,S)=>{S.failureRedirect!==null&&t.returnToPolicy.checkRedirectMode(k,S);let P=l=>S.failureRedirect===null?new q(l):t.returnToPolicy.signInRedirect(S.returnTo,l!==void 0?{headers:{"Set-Cookie":l}}:void 0);try{if(e.mockUser?.enabled(k)){let{accessToken:d,refreshToken:R,expirationDateMs:m}=e.mockUser.resolve(k);return{accessToken:d,refreshToken:R,expirationDateMs:m}}let l=T.get(o),p=t.sessionGenerationGate;if(l!==void 0&&p!==null&&await p.check(M(l),T.get(N))==="stale")throw P(await t.destroySession(T));if(!(l?.accessToken&&l.expirationDateMs))throw P();let{accessToken:f,refreshToken:x,expirationDateMs:u}=l;if(u<Date.now())throw x?new Error("Expired"):P();return{accessToken:f,refreshToken:x,expirationDateMs:u}}catch(l){if(l instanceof Error&&l.message==="Expired")try{let p=await y(T),f=T.get(o);return T.set(o,{...f,...p}),p}catch(p){if(p instanceof V)n.warn("Google refresh token invalid or revoked");else{let x=p instanceof Error?p.message:"Unknown error";n.error("Failed to refresh token:",x)}let f=await t.destroySession(T);throw P(f)}throw l}},refreshedAccessToken:y}};var J=({refreshToken:e,...t})=>t;var ee=(e,t,n,o)=>{let a=new Map,y=new Map,A=async l=>{let p=JSON.stringify([l.provider,l.id]),f=a.get(p);if(f!==void 0)return f;let x=y.get(p);if(x!==void 0)return x;let u=(async()=>{try{let d=e.getUserPhoto?await e.getUserPhoto(l):"";return a.set(p,d),d}catch(d){throw a.delete(p),d}finally{y.delete(p)}})();return y.set(p,u),u},k=new WeakMap,T=async l=>{e.warmup&&await e.warmup();let p=await t.resolveSession(l);if(p.kind==="revoked")return{kind:"unauthenticated",cookie:await t.destroySession(p.session)};if(p.kind!=="signed-in")return{kind:"unauthenticated"};let{user:f,session:x}=p,u;try{u=await n.authenticate(l,x,{failureRedirect:null})}catch(c){if(c instanceof q)return c.setCookie!==void 0?{kind:"unauthenticated",cookie:c.setCookie}:{kind:"unauthenticated"};throw o.error("Error in authenticateInLoader:",c),c}let d={accessToken:u.accessToken,refreshToken:u.refreshToken,expirationDateMs:u.expirationDateMs,provider:f.provider},R={id:f.id,displayName:f.displayName,name:f.name,emails:f.emails,...d,role:f.role},m=await A(f),h=J({...f,...d,photo:m}),i=u.accessToken!==f.accessToken?await t.saveSession(l,R):void 0;return i!==void 0?{kind:"authenticated",user:h,cookie:i}:{kind:"authenticated",user:h}},S=l=>{let p=k.get(l);if(p!==void 0)return p;let f=T(l);return k.set(l,f),f};async function P(l,p){p.failureRedirect!==null&&t.returnToPolicy.checkRedirectMode(l,p);let f=await S(l);if(f.kind==="authenticated")return f.cookie!==void 0?{user:f.user,cookie:f.cookie}:{user:f.user};if(p.failureRedirect===null)return f.cookie!==void 0?{cookie:f.cookie}:{};throw t.returnToPolicy.signInRedirect(p.returnTo,f.cookie!==void 0?{headers:{"Set-Cookie":f.cookie}}:void 0)}return P};import{GOOGLE_PROVIDER as We}from"@aiquants/auth-core";import{redirect as ne}from"react-router";import{Authenticator as ze}from"remix-auth";import{OAuth2Strategy as je}from"remix-auth-oauth2";var He=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],Ve="google",Je="https://www.googleapis.com/oauth2/v3/userinfo",W=class extends je{constructor({clientId:n,clientSecret:o,redirectURI:a,scopes:y,accessType:A,includeGrantedScopes:k,prompt:T,hd:S,loginHint:P,additionalScopes:l},p){let f=y??He;super({clientId:n,clientSecret:o,redirectURI:a,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:f},p);this.name=Ve;this.scopes=f,this.accessType=A??"online",this.includeGrantedScopes=k??!1,this.prompt=T,this.hd=S,this.loginHint=P,this.additionalScopes=l}authorizationParams(n,o){n.set("access_type",this.accessType),n.set("include_granted_scopes",String(this.includeGrantedScopes));let a=o===void 0||this.additionalScopes===void 0?[]:this.additionalScopes(o);for(let A of a)if(A===""||/\s/u.test(A))throw new RangeError(`[auth-react-router] an additional scope must be a non-empty string without white space; got ${JSON.stringify(A)}`);let y=[...new Set([...this.scopes,...a])];return y.length>0&&n.set("scope",y.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 o=await fetch(Je,{headers:{Authorization:`Bearer ${n.accessToken()}`}});if(!o.ok)throw new Error(`Failed to fetch user profile: ${o.statusText}`);let a=await o.json();return{id:a.sub,displayName:a.name,name:{familyName:a.family_name,givenName:a.given_name},emails:[{value:a.email}],photos:[{value:a.picture}],_json:a}}};var D={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var te="error",L=(e,t)=>`${e}?${new URLSearchParams({[te]:t}).toString()}`;var Re=e=>e instanceof Error&&e.code==="access_denied"?"consentDenied":"googleFailed",re=e=>{let t=e.logger??D,n=e.loginPath??"/auth/login",o=new W({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:y,tokens:A})=>{let{access_token:k,refresh_token:T,expires_in:S,scope:P,id_token:l}=A.data,{_json:{sub:p,email:f,picture:x,hd:u,email_verified:d},photos:R,...m}=await W.userProfile(A),{id:h,displayName:w,name:{familyName:i,givenName:c},emails:E}=m,b=We;if(k===void 0||T===void 0||S===void 0||P===void 0||h===void 0||w===void 0||p===void 0||f===void 0||d===void 0)throw ne(L(n,d===!1?"emailNotVerified":"googleFailed"));t.info("Authenticated on Google: ",m.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(b,k))throw t.error("Backend verification returned false for user:",m.displayName),ne(L(n,"backendFailed"));t.info("Authenticated on Backend: ",m.displayName)}let r=m.emails[0]?.value;if(!await e.isEmailAllowed(r)){let G=new Error("You are not allowed to access this application");throw t.error(G),G}if(e.isUserActive&&!await e.isUserActive({...m,provider:b})){let G=new Error("You are not allowed to access this application");throw t.error("Deactivated account attempted to sign in:",r),G}e.backendAuth&&await e.backendAuth.signup(b,k,m),t.info("Authenticated complete: ",m.displayName);let s=Date.now()+S*1e3;return{...m,...{accessToken:k,refreshToken:T,expirationDateMs:s,provider:b},photo:x}}catch(r){let s=r;typeof r=="object"&&r!==null&&"cause"in r&&(s=r.cause||r),t.error("Error during backend authentication or subsequent processing:",s);let g="unexpected",v=!1;if(typeof r=="object"&&r!==null&&"cause"in r){let G=r.cause;G&&typeof G=="object"&&"message"in G&&typeof G.message=="string"&&G.message.includes("getaddrinfo ENOTFOUND")&&(g="backendUnreachable",v=!0)}throw!v&&r instanceof Error&&r.message.includes("You are not allowed to access this application")&&(g="notAllowed",v=!0),!v&&r instanceof Response&&r.headers.get("Location")?.startsWith(n)?r:ne(L(n,g))}}),a=new ze;return a.use(o),a};import{isSignInFailureKey as Be,resolveAuthMessages as Xe}from"@aiquants/auth-core";import{redirect as K}from"react-router";var oe="returnTo",z=(e,t)=>{let n=e.indexOf("?"),o=n===-1?e:e.slice(0,n),a=new URLSearchParams(n===-1?"":e.slice(n+1));return a.set(oe,t),`${o}?${a.toString()}`};var Ye=new Map([["document",new Set(["none","same-origin","same-site"])],["empty",new Set(["same-origin"])]]),se=e=>{let t=e.headers.get("Sec-Fetch-Dest");if(t!==null){let o=Ye.get(t);if(o===void 0)return`its fetch destination is "${t}"`;let a=e.headers.get("Sec-Fetch-Site");if(a===null)return`its "${t}" request states no site`;if(!o.has(a))return`its "${t}" request comes from a "${a}" page`}let n=e.headers.get("Sec-Purpose");if(n!==null)return`it is speculative ("${n}")`},ie=e=>new Response(e.signOutRefused,{status:403,headers:{"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"}});var ae=(e,t,n,o)=>{let a=e.loginPath??"/auth/login",y=e.postLoginRedirect??"/",A=e.postLogoutRedirect??"/",k=he(e.google.revocationTimeoutMs),T=Xe(e.messages),S=t.returnToPolicy,P=async({request:i})=>{let c=S.requested(i),E=new URL(i.url).searchParams.get(te),b=Be(E)?E:null;if(b===null&&await t.getSessionUser(i))throw K(c??y);return{error:b===null?null:T[b]}},l=async i=>{let c=S.requested(i);try{await n.authenticate("google",i)}catch(E){throw c===void 0||!(E instanceof Response)?E:await S.bindToFlow(E,c,i)}throw K(c===void 0?a:z(a,c))},p=async({request:i})=>(await i.clone().formData()).get("_action")!=="Sign In with Google"?null:await l(i),f=(i,c)=>{switch(i.outcome){case"failed":o.error(`Sign-out could not revoke the Google grant of user ${String(c)}; the session cookie is destroyed, but the grant stays valid until it expires or is revoked elsewhere:`,i.reason);return;case"already-invalid":o.info(`Sign-out found the Google grant of user ${String(c)} already unusable`);return;case"revoked":case"nothing-to-revoke":return}},x=(i,c)=>{i.kind!=="advanced"&&o.error(`Sign-out could not advance the session generation of ${c.provider} user ${c.id}; a session cookie refreshed before this sign-out stays valid until a later sign-out advances the generation or the cookie expires:`,i.error)},u=async(i,c)=>{let E=t.sessionGenerationGate;if(E!==null){if(!$(c)){o.info(`Sign-out found no usable session generation stamp in the session of ${i.provider} user ${i.id}; every guard already rejects that cookie, so the generation is not advanced`);return}x(await E.advance(i,c),i)}},d=async i=>{let c=await t.getSession(i),E=c.get(t.sessionKey),[b]=await Promise.all([ge(E,{fetch:e.fetch??globalThis.fetch,timeoutMs:k}),E===void 0?void 0:u(M(E),c.get(N))]);return f(b,E?.id),await t.destroySession(c)},R=async i=>{let c=await d(i),E=new Headers;return E.append("Set-Cookie",c),K(A,{headers:E})},m=async({request:i})=>{let c=se(i);throw c!==void 0?(o.warn(`Signing out is refused because ${c}`),ie(T)):await R(i)},h=async(i,c)=>{let r=(await t.getSession(i)).get(t.sessionKey)?.refreshToken,s={accessToken:c.accessToken,refreshToken:c.refreshToken||r,expirationDateMs:c.expirationDateMs,provider:c.provider},g={id:c.id,displayName:c.displayName,name:c.name,emails:c.emails,...s,role:c.role};return await t.saveSignedInSession(i,g)};return{loginLoader:P,loginAction:p,startGoogleSignIn:l,logoutLoader:m,logout:d,logoutAndRedirect:R,googleCallbackLoader:async({request:i})=>{let c=await S.flowOf(i),E;try{E=await n.authenticate("google",i)}catch(s){throw s instanceof Response?S.endFailedFlow(s,c,i):(o.error("Authentication error:",s),S.endFailedFlow(K(L(a,Re(s))),c,i))}let b;try{b=await h(i,E)}catch(s){throw o.error("Saving the signed-in session failed:",s),S.endFailedFlow(K(L(a,s instanceof C?"backendUnreachable":"unexpected")),c,i)}let r=new Headers;throw r.append("Set-Cookie",b),c.deletion!==void 0&&r.append("Set-Cookie",c.deletion),K(c.path??y,{headers:r})},messages:T}};import{createCookieSessionStorage as ct,redirect as ut}from"react-router";import{createCookie as Qe,redirect as Y}from"react-router";var Ze="__return_to.",et=300,ke=/^[A-Za-z0-9_-]{1,128}$/,tt=/%(?![0-9A-Fa-f]{2})/,B="https://return-to.invalid",Te=Object.freeze({path:void 0,deletion:void 0}),nt=e=>{if(e.includes("%"))return!1;let t=new URL(e,B);return t.origin===B&&t.pathname===e},rt=e=>{for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=31||n>=127&&n<=159||e[t]==="\\"||e[t]==="#")return!0}return!1},ot=e=>{if(e[0]!=="/"||e[1]==="/"||e[1]==="\\")return{malformed:'it does not start with a single "/"'};if(rt(e))return{malformed:'it holds a control character, a backslash or a "#"'};if(tt.test(e))return{malformed:'it holds a "%" that two hexadecimal digits do not follow'};let t=new URL(e,B);if(t.origin!==B||`${t.pathname}${t.search}`!==e)return{malformed:"the URL parser normalizes it"};let n;try{n=decodeURIComponent(t.pathname)}catch{return{malformed:"its path does not decode as UTF-8"}}return n.startsWith("//")||n.startsWith("/\\")?{malformed:'its decoded path starts with "//" or "/\\"'}:{decodedPath:n}},st=e=>{if(e===null)return null;let t="returnTo.pages must be null or { excludedPathPrefixes: string[], maxLength: number }";if(typeof e!="object"||Array.isArray(e))throw new TypeError(`${t}; got ${JSON.stringify(e)}`);let{excludedPathPrefixes:n,maxLength:o}=e;if(!Array.isArray(n))throw new TypeError(`${t}; got excludedPathPrefixes ${JSON.stringify(n)}`);for(let y of n){if(typeof y!="string")throw new TypeError(`returnTo.pages.excludedPathPrefixes must hold strings; got ${JSON.stringify(y)}`);if(!y.startsWith("/"))throw new RangeError(`returnTo.pages.excludedPathPrefixes must hold path prefixes starting with "/"; got ${JSON.stringify(y)}`)}if(typeof o!="number")throw new TypeError(`${t}; got maxLength ${JSON.stringify(o)}`);if(!Number.isSafeInteger(o)||o<1)throw new RangeError(`returnTo.pages.maxLength must be a safe integer >= 1; got ${String(o)}`);let a=Object.freeze([...n]);return Object.freeze({excludedPathPrefixes:a,maxLength:o,lowerCasePrefixes:Object.freeze(a.map(y=>y.toLowerCase()))})},it=e=>{if(e===void 0)return{allowedPaths:new Set,pages:null};let t=e;if(typeof t!="object"||t===null||!Array.isArray(t.allowedPaths))throw new TypeError(`returnTo must be { allowedPaths: string[], pages: { excludedPathPrefixes: string[], maxLength: number } | null }; got ${JSON.stringify(t)}`);let n=t.allowedPaths;for(let a of n){if(typeof a!="string")throw new TypeError(`returnTo.allowedPaths must hold strings; got ${JSON.stringify(a)}`);if(!nt(a))throw new RangeError(`returnTo.allowedPaths must hold canonical same-origin paths (one leading "/", no query, fragment, percent-encoding, backslash, white space, control or non-ASCII character, or dot segment); got ${JSON.stringify(a)}`)}let o=st(t.pages);if(n.length===0&&o===null)throw new RangeError("returnTo allows no return-to (allowedPaths is empty and pages is null); omit returnTo to allow none");return{allowedPaths:new Set(n),pages:o}},X=e=>{if(typeof e!="string")throw new TypeError(`[auth-react-router] returnTo must be the page's path and query to return to after the sign-in; got ${JSON.stringify(e)}`);return e},at=(e,t)=>e===null?!1:e.split(";").some(n=>n.trim().startsWith(`${t}=`)),ce=(e,t)=>new Response(e.body,{status:e.status,statusText:e.statusText,headers:t}),Ae=(e,t,n,o)=>{let{allowedPaths:a,pages:y}=it(e),A=u=>{if(a.has(u))return{kind:"accepted"};if(y===null)return{kind:"closed"};let d=ot(u);if("malformed"in d)return{kind:"malformed",reason:d.malformed};let R=d.decodedPath.toLowerCase(),m=y.lowerCasePrefixes.findIndex(h=>R.startsWith(h));return m!==-1?{kind:"excluded",prefix:y.excludedPathPrefixes[m]}:u.length>y.maxLength?{kind:"tooLong",length:u.length}:{kind:"accepted"}},k=u=>Qe(`${Ze}${u}`,{secrets:[...t.secrets],httpOnly:!0,sameSite:"lax",path:"/",secure:t.secure,maxAge:et}),T=(u,d,R)=>{let m=u.headers.get("Location");if(m===null)return u;let h=new URL(m,R.url);if(h.origin!==new URL(R.url).origin||h.pathname!==n)return u;let w=new Headers(u.headers);return w.set("Location",`${z(`${h.pathname}${h.search}`,d)}${h.hash}`),ce(u,w)};return{requested:u=>{let d=new URL(u.url).searchParams.getAll(oe);if(d.length!==0){if(d.length===1&&A(d[0]).kind==="accepted")return d[0];throw Y(L(n,"returnToRefused"))}},bindToFlow:async(u,d,R)=>{let m=u.headers.get("Location"),h=m===null?null:new URL(m,R.url).searchParams.get("state");if(h===null)return T(u,d,R);if(!ke.test(h))throw new Error(`The authorization redirect's state cannot name the return-to cookie; got ${JSON.stringify(h)}`);let w=new Headers(u.headers);return w.append("Set-Cookie",await k(h).serialize(d)),ce(u,w)},flowOf:async u=>{let d=new URL(u.url).searchParams.get("state");if(d===null||!ke.test(d))return Te;let R=k(d),m=u.headers.get("Cookie");if(!at(m,R.name))return Te;let h=await R.serialize("",{maxAge:0}),w=await R.parse(m);return typeof w=="string"&&A(w).kind==="accepted"?{path:w,deletion:h}:(o.warn(`The sign-in's return-to cookie ${R.name} names no accepted return-to; the sign-in returns to the post-login path instead`),{path:void 0,deletion:h})},endFailedFlow:(u,d,R)=>{if(d.deletion===void 0)return u;let m=d.path===void 0?u:T(u,d.path,R),h=new Headers(m.headers);return h.append("Set-Cookie",d.deletion),ce(m,h)},signInRedirect:(u,d)=>{let R=A(X(u));switch(R.kind){case"accepted":return Y(z(n,u),d);case"closed":return Y(n,d);case"malformed":return o.warn(`The sign-in redirect leaves its return-to out because ${R.reason}; the sign-in returns to the post-login path instead`),Y(n,d);case"tooLong":return o.warn(`The sign-in redirect leaves its return-to out because its ${R.length} characters exceed returnTo.pages.maxLength; the sign-in returns to the post-login path instead`),Y(n,d);case"excluded":throw new TypeError(`[auth-react-router] a page under the excluded prefix ${JSON.stringify(R.prefix)} redirected to the sign-in page; a route there answers 401 instead (pass failureRedirect: null)`)}},checkRedirectMode:(u,d)=>{if(d.failureRedirect!==n)throw new TypeError(`[auth-react-router] failureRedirect must be the sign-in page ${JSON.stringify(n)}, where the redirect mode sends an unauthenticated request; got ${JSON.stringify(d.failureRedirect)} (pass null to skip redirecting)`);if(X(d.returnTo),u.method!=="GET"&&u.method!=="HEAD")throw new TypeError("[auth-react-router] the redirect mode serves only GET and HEAD loaders; an action answers 401 data")}}};var Pe=3600*24*30,dt=e=>{if(e===void 0)return Pe;if(!Number.isSafeInteger(e)||e<1)throw new RangeError(`session.maxAge must be a safe integer of seconds >= 1; got ${String(e)}`);return e},ve=e=>e.secure??process.env.NODE_ENV==="production",ue=(e,t)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(h=>!h))throw new Error("REMIX_SESSION_SECRET must be set");let n=e.sessionKey??"user";if(n===N)throw new RangeError(`session.sessionKey must not be ${JSON.stringify(N)}, the key the session generation is stored under; got ${JSON.stringify(n)}`);let o=dt(e.maxAge),a=t.loginPath??"/auth/login",y=t.postLoginRedirect??"/",A=t.mockUser,k=t.isUserActive,T=t.logger??D,S=we(t.sessionGeneration,T),P=Ae(t.returnTo,{secrets:e.secrets,secure:ve(e)},a,T),l=ct({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:ve(e),maxAge:o}}),p=async h=>await l.getSession(h.headers.get("Cookie")),f=async h=>{if(A?.enabled(h))return{kind:"signed-in",user:J(A.resolve(h)),session:await p(h)};let w=await p(h),i=w.get(n);if(i===void 0)return{kind:"signed-out"};let c=J(i),[E,b]=await Promise.all([k===void 0?!0:k(c),S===null?"current":S.check(M(i),w.get(N))]);return b==="stale"?{kind:"revoked",session:w}:E?{kind:"signed-in",user:c,session:w}:{kind:"inactive"}},x=async h=>{let w=await f(h);return w.kind==="signed-in"?w.user:void 0},u=async(h,w)=>{let i=await p(h);return i.set(n,w),await l.commitSession(i)},d=async(h,w)=>{let i=S===null?void 0:await S.stamp(M(w)),c=await p(h);return c.set(n,w),i!==void 0&&c.set(N,i),await l.commitSession(c)},R=async(h,w)=>{X(w);let i=await f(h);switch(i.kind){case"signed-in":return i.user;case"revoked":throw P.signInRedirect(w,{headers:{"Set-Cookie":await l.destroySession(i.session)}});case"signed-out":case"inactive":throw P.signInRedirect(w)}};return{sessionStorage:l,sessionKey:n,sessionMaxAgeSeconds:o,sessionGenerationGate:S,returnToPolicy:P,getSession:p,resolveSession:f,getSessionUser:x,saveSession:u,saveSignedInSession:d,requireUser:R,requireAdminUser:async(h,w)=>{let i=await R(h,w);if(i.role!=="admin")throw ut(y);return i},commitSession:l.commitSession,destroySession:l.destroySession}};var lt=e=>{let t=e.logger??D,n=ue(e.session,{sessionGeneration:e.sessionGeneration,logger:t,mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive,returnTo:e.returnTo}),o=re(e),a=Z(e,n,t),y=ee(e,n,a,t),A=ae(e,n,o,t);return{authenticator:o,storage:n,authFns:a,sessionStorage:n.sessionStorage,getSession:n.getSession,getSessionUser:n.getSessionUser,saveSession:n.saveSession,requireUser:n.requireUser,requireAdminUser:n.requireAdminUser,signInRedirect:n.returnToPolicy.signInRedirect,commitSession:n.commitSession,destroySession:n.destroySession,sessionMaxAgeSeconds:n.sessionMaxAgeSeconds,authenticate:a.authenticate,refreshedAccessToken:a.refreshedAccessToken,authenticateInLoader:y,...A}};export{q as AuthRequiredError,fe as DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS,ye as DEFAULT_SESSION_GENERATION_CACHE_TTL_MS,Se as DEFAULT_SESSION_GENERATION_TIMEOUT_MS,Pe as DEFAULT_SESSION_MAX_AGE_SECONDS,V as GoogleInvalidGrantError,C as SessionGenerationUnavailableError,F as TokenRefreshError,ae as createAuthHandlers,lt as createAuthServer,ue as createAuthSessionStorage,Z as createAuthenticate,ee as createAuthenticateInLoader,re as createGoogleAuthenticator,se as signOutRefusal,ie as signOutRefusalResponse};
1
+ import{GOOGLE_PROVIDER as We}from"@aiquants/auth-core";import{GOOGLE_PROVIDER as Ne}from"@aiquants/auth-core";var Ce="https://oauth2.googleapis.com/revoke",he=5e3,j=2147483647,Le="invalid_token",Ue=400,pe=e=>{if(e===void 0)return he;if(!Number.isInteger(e)||e<1||e>j)throw new RangeError(`google.revocationTimeoutMs must be an integer from 1 to ${j} (milliseconds); got ${String(e)}`);return e},Me=e=>{if(typeof e.refreshToken=="string"&&e.refreshToken!=="")return e.refreshToken;if(typeof e.accessToken=="string"&&e.accessToken!=="")return e.accessToken},$e=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},Fe=e=>e instanceof Error?e.cause instanceof Error?`${e.message} (${e.cause.message})`:e.message:String(e),qe=async(e,t,n)=>{try{let o=await t(Ce,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:e}).toString(),signal:n});if(o.ok)return await o.body?.cancel(),{outcome:"revoked"};let i=await $e(o);return o.status===Ue&&i===Le?{outcome:"already-invalid"}:{outcome:"failed",reason:i===void 0?`Google answered ${o.status}`:`Google answered ${o.status} ${i}`}}catch(o){return{outcome:"failed",reason:Fe(o)}}},ge=async(e,t)=>{if(e===void 0)return{outcome:"nothing-to-revoke"};let n=Me(e);if(n===void 0)return{outcome:"nothing-to-revoke"};if(e.provider!==Ne)return{outcome:"failed",reason:`the session's provider "${String(e.provider)}" has no revocation endpoint`};let o=new AbortController;return await new Promise(i=>{let y=setTimeout(()=>{i({outcome:"failed",reason:`Google did not answer within ${t.timeoutMs} ms`}),o.abort()},t.timeoutMs);qe(n,t.fetch,o.signal).then(v=>{clearTimeout(y),i(v)})})};var N="generation",Se=15e3,we=3e3,De=6e4,M=class extends Error{constructor(t,n){super(t,n),this.name="SessionGenerationUnavailableError"}},I=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),Ke=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return I(e);let t="store"in e?e.store:void 0;if(typeof t!="object"||t===null)return`an object whose store is ${I(t)}`;let n="current"in t?t.current:void 0,o="advance"in t?t.advance:void 0;return`an object whose store.current is ${I(n)} and store.advance is ${I(o)}`},He=e=>typeof e=="object"&&e!==null&&"current"in e&&typeof e.current=="function"&&"advance"in e&&typeof e.advance=="function",me=(e,t,n,o)=>{if(t===void 0)return o;if(typeof t!="number"||!Number.isInteger(t)||t<n||t>j)throw new RangeError(`${e} must be an integer from ${n} to ${j} (milliseconds); got ${I(t)}`);return t},je=e=>{if(e===!1)return!1;let t=e;if(typeof t!="object"||t===null||!("store"in t)||!He(t.store))throw new TypeError(`sessionGeneration must be { store, cacheTtlMs?, timeoutMs? } or false; got ${Ke(t)}`);return{store:t.store,cacheTtlMs:me("sessionGeneration.cacheTtlMs","cacheTtlMs"in t?t.cacheTtlMs:void 0,0,Se),timeoutMs:me("sessionGeneration.timeoutMs","timeoutMs"in t?t.timeoutMs:void 0,1,we)}},F=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,Q=e=>typeof e.provider=="string"&&e.provider!==""&&typeof e.id=="string"&&e.id!=="",ye=e=>new TypeError(`a session generation identity needs a non-empty provider and id; got provider ${I(e.provider)} and id ${I(e.id)}`),Ve=e=>F(e)&&F(e+1),Je=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 ${I(e)}`),C=e=>({provider:e.provider,id:e.id}),Re=(e,t)=>{let n=je(e);if(n===!1)return null;let{store:o,cacheTtlMs:i,timeoutMs:y}=n,v=new Map,R=new Map,A=new Map,S=new Map,E=Number.NEGATIVE_INFINITY,h=r=>`${r.provider}\0${r.id}`,m=(r,s)=>{let u=v.get(r);if(u!==void 0){if(s-u.at<i)return u;v.delete(r)}},c=(r,s,u)=>{if(u!==void 0&&s.at<=u.answeredAt&&s.value<u.value)return;let P=m(r,performance.now());if(P===void 0){v.set(r,s);return}s.value<P.value||v.set(r,{value:s.value,at:Math.max(P.at,s.at)})},G=r=>{let s=S.get(r);if(s!==void 0)return s.count+=1,s;let u={count:1,floor:void 0};return S.set(r,u),u},a=(r,s)=>{s.count-=1,s.count===0&&S.delete(r)},d=(r,s)=>{r.floor={value:r.floor===void 0?s:Math.max(r.floor.value,s),answeredAt:performance.now()}},k=(r,s)=>{let u=A.get(r);return u===void 0?!1:s<u?!0:(A.delete(r),!1)},p=(r,s)=>{let u=performance.now();return A.set(r,u+i),u-E>=De&&(E=u,t.warn("Session generation store unavailable; skipping the sign-out generation check:",s)),"unavailable"},T=(r,s,u)=>new Promise((P,b)=>{let{operation:_}=r,le=r.operation==="advance"?r.from+1:0,Ie=performance.now(),H=G(u),U=!1,fe=setTimeout(()=>{U=!0,P({kind:"unavailable",error:new M(`sessionGeneration.store.${_} did not settle within ${y} ms`)})},y);new Promise(x=>x(r.operation==="advance"?o.advance(s,r.from):o.current(s))).then(x=>{if(clearTimeout(fe),!(F(x)&&x>=le)){a(u,H),U||(U=!0,b(new TypeError(`sessionGeneration.store.${_} must resolve to an integer >= ${le}; got ${I(x)}`)));return}_==="advance"&&(d(H,x),R.delete(u)),c(u,{value:x,at:Ie},H.floor),a(u,H),!U&&(U=!0,A.delete(u),P({kind:"value",value:x}))},x=>{if(clearTimeout(fe),a(u,H),!U){if(U=!0,x instanceof M){P({kind:"unavailable",error:x});return}b(x)}})}),O=(r,s,u)=>{let P=R.get(s);if(P!==void 0&&u-P.startedAt<i)return P.read;let b={read:T({operation:"current"},r,s),startedAt:u};R.set(s,b);let _=()=>{R.get(s)===b&&R.delete(s)};return b.read.then(_,_),b.read},g=async(r,s,u)=>{let P=await T({operation:"current"},r,s);return P.kind==="unavailable"?p(s,P.error):u===P.value?"current":"stale"};return{check:async(r,s)=>{if(!(F(s)&&Q(r)))return"stale";let u=performance.now(),P=h(r),b=m(P,u);if(b!==void 0){if(s===b.value)return"current";if(s<b.value)return"stale"}if(k(P,u))return"unavailable";if(b!==void 0)return await g(r,P,s);let _=await O(r,P,u);return _.kind==="unavailable"?p(P,_.error):s===_.value?"current":s<_.value?"stale":await g(r,P,s)},stamp:async r=>{if(!Q(r))throw ye(r);let s=await T({operation:"current"},r,h(r));if(s.kind==="unavailable")throw s.error;return s.value},advance:async(r,s)=>{if(!Q(r))return{kind:"failed",error:ye(r)};if(!Ve(s))return{kind:"failed",error:Je(s)};try{let u=await T({operation:"advance",from:s},r,h(r));return u.kind==="value"?{kind:"advanced",generation:u.value}:{kind:"unavailable",error:u.error}}catch(u){return{kind:"failed",error:u}}}}};var $=class extends Error{constructor(t){super(t),this.name="TokenRefreshError"}},V=class extends ${constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},q=class extends Error{constructor(t){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=t}},ze=["access_token","expires_in"],Z=(e,t,n)=>{let o=t.sessionKey,i=async R=>{let S=R.get(o)?.refreshToken;if(!S)throw new Error("Refresh token not found in session");try{let E="https://www.googleapis.com/oauth2/v4/token",h={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:S},c=await(e.fetch??globalThis.fetch)(E,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(h)});if(!c.ok){let p=await c.json().catch(()=>{});if(c.status===400&&typeof p=="object"&&!!p&&"error"in p&&p.error==="invalid_grant")throw new V;let O=typeof p=="object"&&p&&"error_description"in p?String(p.error_description):"Unknown error";throw new $(`Google token refresh failed: ${c.status} ${O}`)}let G=await c.json(),a=ze.filter(p=>!G?.[p]);if(a.length>0)throw n.error("Invalid token response from Google; missing or empty keys:",a.join(", ")),new Error("Invalid token response from Google");let{access_token:d,expires_in:k}=G;return{accessToken:d,refreshToken:S,expirationDateMs:Number(Date.now())+k*1e3}}catch(E){if(E instanceof $)throw E;let h=E instanceof Error?E.message:"Unknown error";throw new $(`Failed to refresh Google access token: ${h}`)}},y=async R=>{let S=R.get(o).provider;if(!S)throw new Error("Provider not found in session");if(S===We)return await i(R);throw new Error("Provider not supported")};return{authenticate:async(R,A,S)=>{S.failureRedirect!==null&&t.returnToPolicy.checkRedirectMode(R,S);let E=h=>S.failureRedirect===null?new q(h):t.returnToPolicy.signInRedirect(S.returnTo,h!==void 0?{headers:{"Set-Cookie":h}}:void 0);try{if(e.mockUser?.enabled(R)){let{accessToken:d,refreshToken:k,expirationDateMs:p}=e.mockUser.resolve(R);return{accessToken:d,refreshToken:k,expirationDateMs:p}}let h=A.get(o),m=t.sessionGenerationGate;if(h!==void 0&&m!==null&&await m.check(C(h),A.get(N))==="stale")throw E(await t.destroySession(A));if(!(h?.accessToken&&h.expirationDateMs))throw E();let{accessToken:c,refreshToken:G,expirationDateMs:a}=h;if(a<Date.now())throw G?new Error("Expired"):E();return{accessToken:c,refreshToken:G,expirationDateMs:a}}catch(h){if(h instanceof Error&&h.message==="Expired")try{let m=await y(A),c=A.get(o);return A.set(o,{...c,...m}),m}catch(m){if(m instanceof V)n.warn("Google refresh token invalid or revoked");else{let G=m instanceof Error?m.message:"Unknown error";n.error("Failed to refresh token:",G)}let c=await t.destroySession(A);throw E(c)}throw h}},refreshedAccessToken:y}};var J=({refreshToken:e,...t})=>t;var ee=(e,t,n,o)=>{let i=new Map,y=new Map,v=async h=>{let m=JSON.stringify([h.provider,h.id]),c=i.get(m);if(c!==void 0)return c;let G=y.get(m);if(G!==void 0)return G;let a=(async()=>{try{let d=e.getUserPhoto?await e.getUserPhoto(h):"";return i.set(m,d),d}catch(d){throw i.delete(m),d}finally{y.delete(m)}})();return y.set(m,a),a},R=new WeakMap,A=async h=>{e.warmup&&await e.warmup();let m=await t.resolveSession(h);switch(m.kind){case"revoked":return{kind:"unauthenticated",cookie:await t.destroySession(m.session)};case"signed-out":case"inactive":case"other-reader":return{kind:"unauthenticated"};case"signed-in":break}let{user:c,session:G}=m,a;try{a=await n.authenticate(h,G,{failureRedirect:null})}catch(l){if(l instanceof q)return l.setCookie!==void 0?{kind:"unauthenticated",cookie:l.setCookie}:{kind:"unauthenticated"};throw o.error("Error in authenticateInLoader:",l),l}let d={accessToken:a.accessToken,refreshToken:a.refreshToken,expirationDateMs:a.expirationDateMs,provider:c.provider},k={id:c.id,displayName:c.displayName,name:c.name,emails:c.emails,...d,role:c.role},p=await v(c),T=J({...c,...d,photo:p}),g=a.accessToken!==c.accessToken?await t.saveSession(h,k):void 0;return g!==void 0?{kind:"authenticated",user:T,cookie:g}:{kind:"authenticated",user:T}},S=h=>{let m=R.get(h);if(m!==void 0)return m;let c=A(h);return R.set(h,c),c};async function E(h,m){m.failureRedirect!==null&&t.returnToPolicy.checkRedirectMode(h,m);let c=await S(h);if(c.kind==="authenticated")return c.cookie!==void 0?{user:c.user,cookie:c.cookie}:{user:c.user};if(m.failureRedirect===null)return c.cookie!==void 0?{cookie:c.cookie}:{};throw t.returnToPolicy.signInRedirect(m.returnTo,c.cookie!==void 0?{headers:{"Set-Cookie":c.cookie}}:void 0)}return E};import{GOOGLE_PROVIDER as Ze}from"@aiquants/auth-core";import{redirect as ne}from"react-router";import{Authenticator as et}from"remix-auth";import{OAuth2Strategy as Ye}from"remix-auth-oauth2";var Be=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],Xe="google",Qe="https://www.googleapis.com/oauth2/v3/userinfo",W=class extends Ye{constructor({clientId:n,clientSecret:o,redirectURI:i,scopes:y,accessType:v,includeGrantedScopes:R,prompt:A,hd:S,loginHint:E,additionalScopes:h},m){let c=y??Be;super({clientId:n,clientSecret:o,redirectURI:i,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:c},m);this.name=Xe;this.scopes=c,this.accessType=v??"online",this.includeGrantedScopes=R??!1,this.prompt=A,this.hd=S,this.loginHint=E,this.additionalScopes=h}authorizationParams(n,o){n.set("access_type",this.accessType),n.set("include_granted_scopes",String(this.includeGrantedScopes));let i=o===void 0||this.additionalScopes===void 0?[]:this.additionalScopes(o);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 y=[...new Set([...this.scopes,...i])];return y.length>0&&n.set("scope",y.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 o=await fetch(Qe,{headers:{Authorization:`Bearer ${n.accessToken()}`}});if(!o.ok)throw new Error(`Failed to fetch user profile: ${o.statusText}`);let i=await o.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 D={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var te="error",L=(e,t)=>`${e}?${new URLSearchParams({[te]:t}).toString()}`;var ke=e=>e instanceof Error&&e.code==="access_denied"?"consentDenied":"googleFailed",re=e=>{let t=e.logger??D,n=e.loginPath??"/auth/login",o=new W({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:y,tokens:v})=>{let{access_token:R,refresh_token:A,expires_in:S,scope:E,id_token:h}=v.data,{_json:{sub:m,email:c,picture:G,hd:a,email_verified:d},photos:k,...p}=await W.userProfile(v),{id:T,displayName:O,name:{familyName:g,givenName:l},emails:f}=p,w=Ze;if(R===void 0||A===void 0||S===void 0||E===void 0||T===void 0||O===void 0||m===void 0||c===void 0||d===void 0)throw ne(L(n,d===!1?"emailNotVerified":"googleFailed"));t.info("Authenticated on Google: ",p.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(w,R))throw t.error("Backend verification returned false for user:",p.displayName),ne(L(n,"backendFailed"));t.info("Authenticated on Backend: ",p.displayName)}let r=p.emails[0]?.value;if(!await e.isEmailAllowed(r)){let b=new Error("You are not allowed to access this application");throw t.error(b),b}if(e.isUserActive&&!await e.isUserActive({...p,provider:w})){let b=new Error("You are not allowed to access this application");throw t.error("Deactivated account attempted to sign in:",r),b}e.backendAuth&&await e.backendAuth.signup(w,R,p),t.info("Authenticated complete: ",p.displayName);let s=Date.now()+S*1e3;return{...p,...{accessToken:R,refreshToken:A,expirationDateMs:s,provider:w},photo:G}}catch(r){let s=r;typeof r=="object"&&r!==null&&"cause"in r&&(s=r.cause||r),t.error("Error during backend authentication or subsequent processing:",s);let u="unexpected",P=!1;if(typeof r=="object"&&r!==null&&"cause"in r){let b=r.cause;b&&typeof b=="object"&&"message"in b&&typeof b.message=="string"&&b.message.includes("getaddrinfo ENOTFOUND")&&(u="backendUnreachable",P=!0)}throw!P&&r instanceof Error&&r.message.includes("You are not allowed to access this application")&&(u="notAllowed",P=!0),!P&&r instanceof Response&&r.headers.get("Location")?.startsWith(n)?r:ne(L(n,u))}}),i=new et;return i.use(o),i};import{isSignInFailureKey as nt,resolveAuthMessages as rt}from"@aiquants/auth-core";import{redirect as K}from"react-router";var oe="returnTo",z=(e,t)=>{let n=e.indexOf("?"),o=n===-1?e:e.slice(0,n),i=new URLSearchParams(n===-1?"":e.slice(n+1));return i.set(oe,t),`${o}?${i.toString()}`};var tt=new Map([["document",new Set(["none","same-origin","same-site"])],["empty",new Set(["same-origin"])]]),se=e=>{let t=e.headers.get("Sec-Fetch-Dest");if(t!==null){let o=tt.get(t);if(o===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(!o.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}")`},ie=e=>new Response(e.signOutRefused,{status:403,headers:{"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"}});var ae=(e,t,n,o)=>{let i=e.loginPath??"/auth/login",y=e.postLoginRedirect??"/",v=e.postLogoutRedirect??"/",R=pe(e.google.revocationTimeoutMs),A=rt(e.messages),S=t.returnToPolicy,E=async({request:g})=>{let l=S.requested(g),f=new URL(g.url).searchParams.get(te),w=nt(f)?f:null;if(w===null&&await t.getSessionUser(g))throw K(l??y);return{error:w===null?null:A[w]}},h=async g=>{let l=S.requested(g);try{await n.authenticate("google",g)}catch(f){throw l===void 0||!(f instanceof Response)?f:await S.bindToFlow(f,l,g)}throw K(l===void 0?i:z(i,l))},m=async({request:g})=>(await g.clone().formData()).get("_action")!=="Sign In with Google"?null:await h(g),c=(g,l)=>{switch(g.outcome){case"failed":o.error(`Sign-out could not revoke the Google grant of user ${String(l)}; the session cookie is destroyed, but the grant stays valid until it expires or is revoked elsewhere:`,g.reason);return;case"already-invalid":o.info(`Sign-out found the Google grant of user ${String(l)} already unusable`);return;case"revoked":case"nothing-to-revoke":return}},G=(g,l)=>{g.kind!=="advanced"&&o.error(`Sign-out could not advance the session generation of ${l.provider} user ${l.id}; a session cookie refreshed before this sign-out stays valid until a later sign-out advances the generation or the cookie expires:`,g.error)},a=async(g,l)=>{let f=t.sessionGenerationGate;if(f!==null){if(!F(l)){o.info(`Sign-out found no usable session generation stamp in the session of ${g.provider} user ${g.id}; every guard already rejects that cookie, so the generation is not advanced`);return}G(await f.advance(g,l),g)}},d=async g=>{let l=await t.getSession(g),f=l.get(t.sessionKey),[w]=await Promise.all([ge(f,{fetch:e.fetch??globalThis.fetch,timeoutMs:R}),f===void 0?void 0:a(C(f),l.get(N))]);return c(w,f?.id),await t.destroySession(l)},k=async g=>{let l=await d(g),f=new Headers;return f.append("Set-Cookie",l),K(v,{headers:f})},p=async({request:g})=>{let l=se(g);throw l!==void 0?(o.warn(`Signing out is refused because ${l}`),ie(A)):await k(g)},T=async(g,l)=>{let r=(await t.getSession(g)).get(t.sessionKey)?.refreshToken,s={accessToken:l.accessToken,refreshToken:l.refreshToken||r,expirationDateMs:l.expirationDateMs,provider:l.provider},u={id:l.id,displayName:l.displayName,name:l.name,emails:l.emails,...s,role:l.role};return await t.saveSignedInSession(g,u)};return{loginLoader:E,loginAction:m,startGoogleSignIn:h,logoutLoader:p,logout:d,logoutAndRedirect:k,googleCallbackLoader:async({request:g})=>{let l=await S.flowOf(g),f;try{f=await n.authenticate("google",g)}catch(s){throw s instanceof Response?S.endFailedFlow(s,l,g):(o.error("Authentication error:",s),S.endFailedFlow(K(L(i,ke(s))),l,g))}let w;try{w=await T(g,f)}catch(s){throw o.error("Saving the signed-in session failed:",s),S.endFailedFlow(K(L(i,s instanceof M?"backendUnreachable":"unexpected")),l,g)}let r=new Headers;throw r.append("Set-Cookie",w),l.deletion!==void 0&&r.append("Set-Cookie",l.deletion),K(l.path??y,{headers:r})},messages:A}};import{isWriteMethod as yt,readerStampRefusalResponse as St,readReaderStamp as wt}from"@aiquants/auth-core";import{createCookieSessionStorage as Rt,redirect as kt}from"react-router";import{ANONYMOUS_READER_STAMP as Te,isReaderStamp as ot}from"@aiquants/auth-core";var st="aiquants-reader-stamp",ce={name:"HMAC",hash:"SHA-256"},Pe=new TextEncoder,Ae=({provider:e,id:t})=>Pe.encode(`${st}\0${JSON.stringify([e,t])}`),ve=e=>btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,""),it=e=>Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),t=>t.charCodeAt(0)),Ee=e=>{if(e.length===0)throw new RangeError("the reader stamps need at least one session secret");let t,n=()=>(t??(t=Promise.all(e.map(o=>crypto.subtle.importKey("raw",Pe.encode(o),ce,!1,["sign","verify"])))),t);return{stampOf:async o=>{if(o===null)return Te;let[i]=await n();return ve(new Uint8Array(await crypto.subtle.sign(ce.name,i,Ae(o))))},matches:async(o,i)=>{if(o===Te||!ot(o))return!1;let y=it(o);if(ve(y)!==o)return!1;let v=Ae(i);for(let R of await n())if(await crypto.subtle.verify(ce.name,R,y,v))return!0;return!1}}};import{createCookie as at,redirect as Y}from"react-router";var ct="__return_to.",dt=300,Ge=/^[A-Za-z0-9_-]{1,128}$/,ut=/%(?![0-9A-Fa-f]{2})/,B="https://return-to.invalid",be=Object.freeze({path:void 0,deletion:void 0}),lt=e=>{if(e.includes("%"))return!1;let t=new URL(e,B);return t.origin===B&&t.pathname===e},ft=e=>{for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=31||n>=127&&n<=159||e[t]==="\\"||e[t]==="#")return!0}return!1},ht=e=>{if(e[0]!=="/"||e[1]==="/"||e[1]==="\\")return{malformed:'it does not start with a single "/"'};if(ft(e))return{malformed:'it holds a control character, a backslash or a "#"'};if(ut.test(e))return{malformed:'it holds a "%" that two hexadecimal digits do not follow'};let t=new URL(e,B);if(t.origin!==B||`${t.pathname}${t.search}`!==e)return{malformed:"the URL parser normalizes it"};let n;try{n=decodeURIComponent(t.pathname)}catch{return{malformed:"its path does not decode as UTF-8"}}return n.startsWith("//")||n.startsWith("/\\")?{malformed:'its decoded path starts with "//" or "/\\"'}:{decodedPath:n}},pt=e=>{if(e===null)return null;let t="returnTo.pages must be null or { excludedPathPrefixes: string[], maxLength: number }";if(typeof e!="object"||Array.isArray(e))throw new TypeError(`${t}; got ${JSON.stringify(e)}`);let{excludedPathPrefixes:n,maxLength:o}=e;if(!Array.isArray(n))throw new TypeError(`${t}; got excludedPathPrefixes ${JSON.stringify(n)}`);for(let y of n){if(typeof y!="string")throw new TypeError(`returnTo.pages.excludedPathPrefixes must hold strings; got ${JSON.stringify(y)}`);if(!y.startsWith("/"))throw new RangeError(`returnTo.pages.excludedPathPrefixes must hold path prefixes starting with "/"; got ${JSON.stringify(y)}`)}if(typeof o!="number")throw new TypeError(`${t}; got maxLength ${JSON.stringify(o)}`);if(!Number.isSafeInteger(o)||o<1)throw new RangeError(`returnTo.pages.maxLength must be a safe integer >= 1; got ${String(o)}`);let i=Object.freeze([...n]);return Object.freeze({excludedPathPrefixes:i,maxLength:o,lowerCasePrefixes:Object.freeze(i.map(y=>y.toLowerCase()))})},gt=e=>{if(e===void 0)return{allowedPaths:new Set,pages:null};let t=e;if(typeof t!="object"||t===null||!Array.isArray(t.allowedPaths))throw new TypeError(`returnTo must be { allowedPaths: string[], pages: { excludedPathPrefixes: string[], maxLength: number } | null }; got ${JSON.stringify(t)}`);let n=t.allowedPaths;for(let i of n){if(typeof i!="string")throw new TypeError(`returnTo.allowedPaths must hold strings; got ${JSON.stringify(i)}`);if(!lt(i))throw new RangeError(`returnTo.allowedPaths must hold canonical same-origin paths (one leading "/", no query, fragment, percent-encoding, backslash, white space, control or non-ASCII character, or dot segment); got ${JSON.stringify(i)}`)}let o=pt(t.pages);if(n.length===0&&o===null)throw new RangeError("returnTo allows no return-to (allowedPaths is empty and pages is null); omit returnTo to allow none");return{allowedPaths:new Set(n),pages:o}},X=e=>{if(typeof e!="string")throw new TypeError(`[auth-react-router] returnTo must be the page's path and query to return to after the sign-in; got ${JSON.stringify(e)}`);return e},mt=(e,t)=>e===null?!1:e.split(";").some(n=>n.trim().startsWith(`${t}=`)),de=(e,t)=>new Response(e.body,{status:e.status,statusText:e.statusText,headers:t}),Oe=(e,t,n,o)=>{let{allowedPaths:i,pages:y}=gt(e),v=a=>{if(i.has(a))return{kind:"accepted"};if(y===null)return{kind:"closed"};let d=ht(a);if("malformed"in d)return{kind:"malformed",reason:d.malformed};let k=d.decodedPath.toLowerCase(),p=y.lowerCasePrefixes.findIndex(T=>k.startsWith(T));return p!==-1?{kind:"excluded",prefix:y.excludedPathPrefixes[p]}:a.length>y.maxLength?{kind:"tooLong",length:a.length}:{kind:"accepted"}},R=a=>at(`${ct}${a}`,{secrets:[...t.secrets],httpOnly:!0,sameSite:"lax",path:"/",secure:t.secure,maxAge:dt}),A=(a,d,k)=>{let p=a.headers.get("Location");if(p===null)return a;let T=new URL(p,k.url);if(T.origin!==new URL(k.url).origin||T.pathname!==n)return a;let O=new Headers(a.headers);return O.set("Location",`${z(`${T.pathname}${T.search}`,d)}${T.hash}`),de(a,O)};return{requested:a=>{let d=new URL(a.url).searchParams.getAll(oe);if(d.length!==0){if(d.length===1&&v(d[0]).kind==="accepted")return d[0];throw Y(L(n,"returnToRefused"))}},bindToFlow:async(a,d,k)=>{let p=a.headers.get("Location"),T=p===null?null:new URL(p,k.url).searchParams.get("state");if(T===null)return A(a,d,k);if(!Ge.test(T))throw new Error(`The authorization redirect's state cannot name the return-to cookie; got ${JSON.stringify(T)}`);let O=new Headers(a.headers);return O.append("Set-Cookie",await R(T).serialize(d)),de(a,O)},flowOf:async a=>{let d=new URL(a.url).searchParams.get("state");if(d===null||!Ge.test(d))return be;let k=R(d),p=a.headers.get("Cookie");if(!mt(p,k.name))return be;let T=await k.serialize("",{maxAge:0}),O=await k.parse(p);return typeof O=="string"&&v(O).kind==="accepted"?{path:O,deletion:T}:(o.warn(`The sign-in's return-to cookie ${k.name} names no accepted return-to; the sign-in returns to the post-login path instead`),{path:void 0,deletion:T})},endFailedFlow:(a,d,k)=>{if(d.deletion===void 0)return a;let p=d.path===void 0?a:A(a,d.path,k),T=new Headers(p.headers);return T.append("Set-Cookie",d.deletion),de(p,T)},signInRedirect:(a,d)=>{let k=v(X(a));switch(k.kind){case"accepted":return Y(z(n,a),d);case"closed":return Y(n,d);case"malformed":return o.warn(`The sign-in redirect leaves its return-to out because ${k.reason}; the sign-in returns to the post-login path instead`),Y(n,d);case"tooLong":return o.warn(`The sign-in redirect leaves its return-to out because its ${k.length} characters exceed returnTo.pages.maxLength; the sign-in returns to the post-login path instead`),Y(n,d);case"excluded":throw new TypeError(`[auth-react-router] a page under the excluded prefix ${JSON.stringify(k.prefix)} redirected to the sign-in page; a route there answers 401 instead (pass failureRedirect: null)`)}},checkRedirectMode:(a,d)=>{if(d.failureRedirect!==n)throw new TypeError(`[auth-react-router] failureRedirect must be the sign-in page ${JSON.stringify(n)}, where the redirect mode sends an unauthenticated request; got ${JSON.stringify(d.failureRedirect)} (pass null to skip redirecting)`);if(X(d.returnTo),a.method!=="GET"&&a.method!=="HEAD")throw new TypeError("[auth-react-router] the redirect mode serves only GET and HEAD loaders; an action answers 401 data")}}};var _e=3600*24*30,Tt=e=>{if(e===void 0)return _e;if(!Number.isSafeInteger(e)||e<1)throw new RangeError(`session.maxAge must be a safe integer of seconds >= 1; got ${String(e)}`);return e},xe=e=>e.secure??process.env.NODE_ENV==="production",ue=(e,t)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(f=>!f))throw new Error("REMIX_SESSION_SECRET must be set");let n=e.sessionKey??"user";if(n===N)throw new RangeError(`session.sessionKey must not be ${JSON.stringify(N)}, the key the session generation is stored under; got ${JSON.stringify(n)}`);let o=Tt(e.maxAge),i=t.loginPath??"/auth/login",y=t.postLoginRedirect??"/",v=t.mockUser,R=t.isUserActive,A=t.logger??D,S=Re(t.sessionGeneration,A),E=Oe(t.returnTo,{secrets:e.secrets,secure:xe(e)},i,A),h=t.readerCheck;if(typeof h!="boolean")throw new TypeError(`readerCheck must be true or false; got ${I(h)}`);let m=Ee(e.secrets),c=Rt({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:xe(e),maxAge:o}}),G=async f=>await c.getSession(f.headers.get("Cookie")),a=async f=>{if(v?.enabled(f))return{kind:"signed-in",user:J(v.resolve(f)),session:await G(f)};let w=await G(f),r=w.get(n);if(r===void 0)return{kind:"signed-out"};let s=J(r),[u,P]=await Promise.all([R===void 0?!0:R(s),S===null?"current":S.check(C(r),w.get(N))]);return P==="stale"?{kind:"revoked",session:w}:u?{kind:"signed-in",user:s,session:w}:{kind:"inactive"}},d=async f=>{if(!(h&&yt(f.method)))return await a(f);let w=new URL(f.url),r=wt(w.searchParams);if(r.kind!=="stamped")throw St(r.kind);let s=await a(f);if(s.kind!=="signed-in")return s;let u=C(s.user);return await m.matches(r.stamp,u)?s:(A.warn(`Refused a ${f.method} to ${w.pathname} that a page of another reader sent under the session of ${u.provider} user ${u.id}`),{kind:"other-reader"})},k=async f=>{let w=await d(f);return w.kind==="signed-in"?w.user:void 0},p=async(f,w)=>{let r=await G(f);return r.set(n,w),await c.commitSession(r)},T=async(f,w)=>{let r=S===null?void 0:await S.stamp(C(w)),s=await G(f);return s.set(n,w),r!==void 0&&s.set(N,r),await c.commitSession(s)},O=async(f,w)=>{X(w);let r=await d(f);switch(r.kind){case"signed-in":return r.user;case"revoked":throw E.signInRedirect(w,{headers:{"Set-Cookie":await c.destroySession(r.session)}});case"signed-out":case"inactive":case"other-reader":throw E.signInRedirect(w)}};return{sessionStorage:c,sessionKey:n,sessionMaxAgeSeconds:o,sessionGenerationGate:S,returnToPolicy:E,getSession:G,resolveSession:d,getSessionUser:k,saveSession:p,saveSignedInSession:T,requireUser:O,requireAdminUser:async(f,w)=>{let r=await O(f,w);if(r.role!=="admin")throw kt(y);return r},readerStampOf:async f=>await m.stampOf(f===void 0?null:C(f)),commitSession:c.commitSession,destroySession:c.destroySession}};var At=e=>{let t=e.logger??D,n=ue(e.session,{sessionGeneration:e.sessionGeneration,readerCheck:e.readerCheck,logger:t,mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive,returnTo:e.returnTo}),o=re(e),i=Z(e,n,t),y=ee(e,n,i,t),v=ae(e,n,o,t);return{authenticator:o,storage:n,authFns:i,sessionStorage:n.sessionStorage,getSession:n.getSession,getSessionUser:n.getSessionUser,readerStampOf:n.readerStampOf,saveSession:n.saveSession,requireUser:n.requireUser,requireAdminUser:n.requireAdminUser,signInRedirect:n.returnToPolicy.signInRedirect,commitSession:n.commitSession,destroySession:n.destroySession,sessionMaxAgeSeconds:n.sessionMaxAgeSeconds,authenticate:i.authenticate,refreshedAccessToken:i.refreshedAccessToken,authenticateInLoader:y,...v}};export{q as AuthRequiredError,he as DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS,Se as DEFAULT_SESSION_GENERATION_CACHE_TTL_MS,we as DEFAULT_SESSION_GENERATION_TIMEOUT_MS,_e as DEFAULT_SESSION_MAX_AGE_SECONDS,V as GoogleInvalidGrantError,M as SessionGenerationUnavailableError,$ as TokenRefreshError,ae as createAuthHandlers,At as createAuthServer,ue as createAuthSessionStorage,Z as createAuthenticate,ee as createAuthenticateInLoader,re as createGoogleAuthenticator,se as signOutRefusal,ie as signOutRefusalResponse};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiquants/auth-react-router",
3
- "version": "0.44.0",
3
+ "version": "0.45.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"
@@ -51,10 +51,11 @@
51
51
  },
52
52
  "license": "MIT",
53
53
  "dependencies": {
54
+ "@aiquants/route-submit-target": "^0.1.0",
54
55
  "tailwind-variants": "^3.2.2"
55
56
  },
56
57
  "devDependencies": {
57
- "@aiquants/auth-core": "0.9.0",
58
+ "@aiquants/auth-core": "0.9.1",
58
59
  "@aiquants/console-ui": "0.8.0",
59
60
  "@aiquants/fuzzy-search": "3.2.1",
60
61
  "@aiquants/select-box": "0.22.2",
@@ -77,7 +78,7 @@
77
78
  "vitest": "^4.1.8"
78
79
  },
79
80
  "peerDependencies": {
80
- "@aiquants/auth-core": "^0.9.0",
81
+ "@aiquants/auth-core": "^0.9.1",
81
82
  "@aiquants/console-ui": "^0.8.0",
82
83
  "@aiquants/fuzzy-search": "^3.2.1",
83
84
  "@aiquants/select-box": "^0.22.0",