@aiquants/auth-react-router 0.34.0 → 0.36.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -3
- package/dist/server.d.mts +4 -4
- package/dist/server.d.ts +4 -4
- package/dist/server.js +1 -1
- package/dist/server.mjs +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -43,10 +43,10 @@ export const authServer = createAuthServer({
|
|
|
43
43
|
google: { clientId: env.GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_CLIENT_SECRET, redirectURI: env.GOOGLE_OAUTH_REDIRECT_URL },
|
|
44
44
|
session: { secrets: [env.REMIX_SESSION_SECRET] },
|
|
45
45
|
isEmailAllowed: emailDomainAllowlist(parseAllowlistCsv(env.AUTHZ_ALLOWED_EMAILS), parseAllowlistCsv(env.AUTHZ_ALLOWED_DOMAINS)),
|
|
46
|
-
isUserActive: async (profile) => isAccountEnabled(profile), // optional: deactivation revokes live sessions
|
|
46
|
+
isUserActive: async (profile) => isAccountEnabled(profile), // optional: deactivation revokes live sessions; look the person up by (profile.provider, profile.id)
|
|
47
47
|
sessionGeneration: { store: sessionGenerationStore }, // REQUIRED: sign-out generation store shared by every process (or false)
|
|
48
48
|
backendAuth: { verify: verifyBackend, signup: (p, t) => signupBackend(p, t) }, // FastAPI verify/signup
|
|
49
|
-
getUserPhoto: async (
|
|
49
|
+
getUserPhoto: async (profile) => (await getOpenids({ provider: profile.provider, openid: profile.id }))[0]?.picture ?? "", // your identity store, keyed by (provider, id)
|
|
50
50
|
warmup: async () => { await Promise.all([ensurePrimaryConnection(), ensureSecondaryConnection()]) },
|
|
51
51
|
mockUser: mockUserPort, // test backdoor (E2E) — omit in production-only apps
|
|
52
52
|
})
|
|
@@ -552,7 +552,7 @@ package's own `react: ">=18"`; a host that mounts `/admin` must satisfy the stri
|
|
|
552
552
|
without its `=` padding, 43 characters, 43 to 129 once URL-encoded. React Router 7 and 8 sign the same way, and the package's
|
|
553
553
|
tests pin the name and the shape. Change `cookieName`, the default name or the signing scheme only together with every such
|
|
554
554
|
proxy's rule: a mismatch raises no error anywhere, the proxy just stops recognising the browser.
|
|
555
|
-
- **Verify order**: Google profile check → `backendAuth.verify` → allowlist → `backendAuth.signup` (every login). Failures redirect to `<loginPath>?error=<encoded error message>` (messages overridable via `messages`).
|
|
555
|
+
- **Verify order**: Google profile check → `backendAuth.verify` → allowlist → `backendAuth.signup` (every login). Failures redirect to `<loginPath>?error=<encoded error message>` (messages overridable via `messages`; a key that `AuthMessages` lacks, or a text that is not a non-blank string, throws a `RangeError` when `createGoogleAuthenticator` builds the authenticator).
|
|
556
556
|
- **Token refresh**: expiry check → Google `oauth2/v4/token` rotate → session update; `invalid_grant` destroys the session and redirects to login with `Set-Cookie`.
|
|
557
557
|
- **Loader guard**: `authenticateInLoader(request, { failureRedirect })` returns `{ user, cookie? }` with `user` **required** when `failureRedirect` is a string (any authentication failure throws a redirect), and `{ user?, cookie? }` when it is `null` (no-redirect mode). Passing `""` throws a `TypeError` before any work — it is a mistake, not a request for the default.
|
|
558
558
|
- **One authentication per request**: the guard performs its work at most once per `Request` instance and shares a mode-neutral result, so a root loader (`null`) and a leaf loader (`"/auth/login"`) in the same React Router data pass share a single pass — one warmup, one token refresh, one `Set-Cookie`. The failure policy is applied per caller on top of the shared result, so it must never be part of the cache key.
|
|
@@ -714,6 +714,11 @@ package's own `react: ">=18"`; a host that mounts `/admin` must satisfy the stri
|
|
|
714
714
|
|
|
715
715
|
`isUserActive` is evaluated at login **and on every session resolution**, so disabling an account revokes already-issued session cookies. Return `false` only for a *known-disabled* account — returning `false` for an unknown identity would block first-time sign-up.
|
|
716
716
|
|
|
717
|
+
`isUserActive` and `getUserPhoto` receive an `IdentityProfile` (`@aiquants/auth-core`): the profile with the `provider`
|
|
718
|
+
it signed in with. The person is the pair (`provider`, `id`), so look the person up by both — an id alone may name
|
|
719
|
+
another person at another provider. At login the Google strategy adds `GOOGLE_PROVIDER`; at session resolution the
|
|
720
|
+
session's user is passed as it is. The photo cache and its in-flight dedup are keyed by the same pair.
|
|
721
|
+
|
|
717
722
|
`sessionGeneration.store` (`SessionGenerationStore`) is `{ current(identity), advance(identity, from) }` over storage
|
|
718
723
|
every process shares (a database table keyed by `identity.provider` + `identity.id`, for example;
|
|
719
724
|
`SessionGenerationIdentity` is `{ provider, id }`). `current` resolves to the identity's generation, `0` until its first
|
package/dist/server.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as _aiquants_auth_core from "@aiquants/auth-core";
|
|
2
|
-
import { SessionProfile, MyGoogleProfile, GoogleProfileBase, AuthMessages } from "@aiquants/auth-core";
|
|
2
|
+
import { SessionProfile, MyGoogleProfile, IdentityProfile, GoogleProfileBase, AuthMessages } 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";
|
|
@@ -29,7 +29,7 @@ type BackendAuthPort = {
|
|
|
29
29
|
verify: (provider: string, accessToken: string) => Promise<boolean>;
|
|
30
30
|
signup: (provider: string, accessToken: string, profile: GoogleProfileBase) => Promise<unknown>;
|
|
31
31
|
};
|
|
32
|
-
type UserPhotoPort = (
|
|
32
|
+
type UserPhotoPort = (profile: IdentityProfile) => Promise<string>;
|
|
33
33
|
type WarmupPort = () => Promise<void>;
|
|
34
34
|
type MockUserPort = {
|
|
35
35
|
enabled: (request: Request) => boolean;
|
|
@@ -60,7 +60,7 @@ type AuthServerConfig = {
|
|
|
60
60
|
google: GoogleOAuthConfig;
|
|
61
61
|
session: SessionConfig;
|
|
62
62
|
isEmailAllowed: (email: string | null | undefined) => boolean | Promise<boolean>;
|
|
63
|
-
isUserActive?: (profile:
|
|
63
|
+
isUserActive?: (profile: IdentityProfile) => boolean | Promise<boolean>;
|
|
64
64
|
sessionGeneration: SessionGenerationConfig | false;
|
|
65
65
|
backendAuth?: BackendAuthPort;
|
|
66
66
|
getUserPhoto?: UserPhotoPort;
|
|
@@ -103,7 +103,7 @@ type AuthSessionStorageOptions = {
|
|
|
103
103
|
readonly mockUser?: MockUserPort;
|
|
104
104
|
readonly loginPath?: string;
|
|
105
105
|
readonly postLoginRedirect?: string;
|
|
106
|
-
readonly isUserActive?: (profile:
|
|
106
|
+
readonly isUserActive?: (profile: IdentityProfile) => boolean | Promise<boolean>;
|
|
107
107
|
};
|
|
108
108
|
type SessionResolution = {
|
|
109
109
|
readonly kind: "signed-in";
|
package/dist/server.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as _aiquants_auth_core from "@aiquants/auth-core";
|
|
2
|
-
import { SessionProfile, MyGoogleProfile, GoogleProfileBase, AuthMessages } from "@aiquants/auth-core";
|
|
2
|
+
import { SessionProfile, MyGoogleProfile, IdentityProfile, GoogleProfileBase, AuthMessages } 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";
|
|
@@ -29,7 +29,7 @@ type BackendAuthPort = {
|
|
|
29
29
|
verify: (provider: string, accessToken: string) => Promise<boolean>;
|
|
30
30
|
signup: (provider: string, accessToken: string, profile: GoogleProfileBase) => Promise<unknown>;
|
|
31
31
|
};
|
|
32
|
-
type UserPhotoPort = (
|
|
32
|
+
type UserPhotoPort = (profile: IdentityProfile) => Promise<string>;
|
|
33
33
|
type WarmupPort = () => Promise<void>;
|
|
34
34
|
type MockUserPort = {
|
|
35
35
|
enabled: (request: Request) => boolean;
|
|
@@ -60,7 +60,7 @@ type AuthServerConfig = {
|
|
|
60
60
|
google: GoogleOAuthConfig;
|
|
61
61
|
session: SessionConfig;
|
|
62
62
|
isEmailAllowed: (email: string | null | undefined) => boolean | Promise<boolean>;
|
|
63
|
-
isUserActive?: (profile:
|
|
63
|
+
isUserActive?: (profile: IdentityProfile) => boolean | Promise<boolean>;
|
|
64
64
|
sessionGeneration: SessionGenerationConfig | false;
|
|
65
65
|
backendAuth?: BackendAuthPort;
|
|
66
66
|
getUserPhoto?: UserPhotoPort;
|
|
@@ -103,7 +103,7 @@ type AuthSessionStorageOptions = {
|
|
|
103
103
|
readonly mockUser?: MockUserPort;
|
|
104
104
|
readonly loginPath?: string;
|
|
105
105
|
readonly postLoginRedirect?: string;
|
|
106
|
-
readonly isUserActive?: (profile:
|
|
106
|
+
readonly isUserActive?: (profile: IdentityProfile) => boolean | Promise<boolean>;
|
|
107
107
|
};
|
|
108
108
|
type SessionResolution = {
|
|
109
109
|
readonly kind: "signed-in";
|
package/dist/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var oe=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var Ie=Object.getOwnPropertyNames;var xe=Object.prototype.hasOwnProperty;var Ue=(e,t)=>{for(var n in t)oe(e,n,{get:t[n],enumerable:!0})},Ne=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ie(t))!xe.call(e,s)&&s!==n&&oe(e,s,{get:()=>t[s],enumerable:!(r=Oe(t,s))||r.enumerable});return e};var Me=e=>Ne(oe({},"__esModule",{value:!0}),e);var ct={};Ue(ct,{AuthRequiredError:()=>$,DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS:()=>he,DEFAULT_SESSION_GENERATION_CACHE_TTL_MS:()=>se,DEFAULT_SESSION_GENERATION_TIMEOUT_MS:()=>ie,DEFAULT_SESSION_MAX_AGE_SECONDS:()=>le,GoogleInvalidGrantError:()=>D,SessionGenerationUnavailableError:()=>F,TokenRefreshError:()=>M,createAuthHandlers:()=>ne,createAuthServer:()=>_e,createAuthSessionStorage:()=>Z,createAuthenticate:()=>B,createAuthenticateInLoader:()=>J,createGoogleAuthenticator:()=>z,signOutRefusal:()=>ee,signOutRefusalResponse:()=>te});module.exports=Me(ct);var ae=require("react-router");var Le="https://oauth2.googleapis.com/revoke",he=5e3;var Ce="google",$e="invalid_token";var ge=e=>{if(e===void 0)return 5e3;if(!Number.isInteger(e)||e<1||e>2147483647)throw new RangeError(`google.revocationTimeoutMs must be an integer from 1 to 2147483647 (milliseconds); got ${String(e)}`);return e},Fe=e=>{if(typeof e.refreshToken=="string"&&e.refreshToken!=="")return e.refreshToken;if(typeof e.accessToken=="string"&&e.accessToken!=="")return e.accessToken},qe=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},De=e=>e instanceof Error?e.cause instanceof Error?`${e.message} (${e.cause.message})`:e.message:String(e),je=async(e,t,n)=>{try{let r=await t(Le,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:e}).toString(),signal:n});if(r.ok)return await r.body?.cancel(),{outcome:"revoked"};let s=await qe(r);return r.status===400&&s===$e?{outcome:"already-invalid"}:{outcome:"failed",reason:s===void 0?`Google answered ${r.status}`:`Google answered ${r.status} ${s}`}}catch(r){return{outcome:"failed",reason:De(r)}}},me=async(e,t)=>{if(e===void 0)return{outcome:"nothing-to-revoke"};let n=Fe(e);if(n===void 0)return{outcome:"nothing-to-revoke"};if(e.provider!==Ce)return{outcome:"failed",reason:`the session's provider "${String(e.provider)}" has no revocation endpoint`};let r=new AbortController;return await new Promise(s=>{let k=setTimeout(()=>{s({outcome:"failed",reason:`Google did not answer within ${t.timeoutMs} ms`}),r.abort()},t.timeoutMs);je(n,t.fetch,r.signal).then(R=>{clearTimeout(k),s(R)})})};var U="generation",se=15e3,ie=3e3,Ke=6e4,F=class extends Error{constructor(t,n){super(t,n),this.name="SessionGenerationUnavailableError"}},x=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),Ve=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return x(e);let t="store"in e?e.store:void 0;if(typeof t!="object"||t===null)return`an object whose store is ${x(t)}`;let n="current"in t?t.current:void 0,r="advance"in t?t.advance:void 0;return`an object whose store.current is ${x(n)} and store.advance is ${x(r)}`},Ye=e=>typeof e=="object"&&e!==null&&"current"in e&&typeof e.current=="function"&&"advance"in e&&typeof e.advance=="function",Se=(e,t,n,r)=>{if(t===void 0)return r;if(typeof t!="number"||!Number.isInteger(t)||t<n||t>2147483647)throw new RangeError(`${e} must be an integer from ${n} to ${2147483647} (milliseconds); got ${x(t)}`);return t},We=e=>{if(e===!1)return!1;let t=e;if(typeof t!="object"||t===null||!("store"in t)||!Ye(t.store))throw new TypeError(`sessionGeneration must be { store, cacheTtlMs?, timeoutMs? } or false; got ${Ve(t)}`);return{store:t.store,cacheTtlMs:Se("sessionGeneration.cacheTtlMs","cacheTtlMs"in t?t.cacheTtlMs:void 0,0,se),timeoutMs:Se("sessionGeneration.timeoutMs","timeoutMs"in t?t.timeoutMs:void 0,1,ie)}},q=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,re=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 ${x(e.provider)} and id ${x(e.id)}`),Xe=e=>q(e)&&q(e+1),Be=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 ${x(e)}`),C=e=>({provider:e.provider,id:e.id}),we=(e,t)=>{let n=We(e);if(n===!1)return null;let{store:r,cacheTtlMs:s,timeoutMs:k}=n,R=new Map,G=new Map,m=new Map,y=new Map,A=Number.NEGATIVE_INFINITY,i=c=>`${c.provider}\0${c.id}`,f=(c,o)=>{let h=R.get(c);if(h!==void 0){if(o-h.at<s)return h;R.delete(c)}},a=(c,o,h)=>{if(h!==void 0&&o.at<=h.answeredAt&&o.value<h.value)return;let P=f(c,performance.now());if(P===void 0){R.set(c,o);return}o.value<P.value||R.set(c,{value:o.value,at:Math.max(P.at,o.at)})},u=c=>{let o=y.get(c);if(o!==void 0)return o.count+=1,o;let h={count:1,floor:void 0};return y.set(c,h),h},p=(c,o)=>{o.count-=1,o.count===0&&y.delete(c)},T=(c,o)=>{c.floor={value:c.floor===void 0?o:Math.max(c.floor.value,o),answeredAt:performance.now()}},S=(c,o)=>{let h=m.get(c);return h===void 0?!1:o<h?!0:(m.delete(c),!1)},w=(c,o)=>{let h=performance.now();return m.set(c,h+s),h-A>=Ke&&(A=h,t.warn("Session generation store unavailable; skipping the sign-out generation check:",o)),"unavailable"},g=(c,o,h)=>new Promise((P,_)=>{let{operation:E}=c,O=c.operation==="advance"?c.from+1:0,be=performance.now(),V=u(h),L=!1,pe=setTimeout(()=>{L=!0,P({kind:"unavailable",error:new F(`sessionGeneration.store.${E} did not settle within ${k} ms`)})},k);new Promise(b=>b(c.operation==="advance"?r.advance(o,c.from):r.current(o))).then(b=>{if(clearTimeout(pe),!(q(b)&&b>=O)){p(h,V),L||(L=!0,_(new TypeError(`sessionGeneration.store.${E} must resolve to an integer >= ${O}; got ${x(b)}`)));return}E==="advance"&&(T(V,b),G.delete(h)),a(h,{value:b,at:be},V.floor),p(h,V),!L&&(L=!0,m.delete(h),P({kind:"value",value:b}))},b=>{if(clearTimeout(pe),p(h,V),!L){if(L=!0,b instanceof F){P({kind:"unavailable",error:b});return}_(b)}})}),l=(c,o,h)=>{let P=G.get(o);if(P!==void 0&&h-P.startedAt<s)return P.read;let _={read:g({operation:"current"},c,o),startedAt:h};G.set(o,_);let E=()=>{G.get(o)===_&&G.delete(o)};return _.read.then(E,E),_.read},d=async(c,o,h)=>{let P=await g({operation:"current"},c,o);return P.kind==="unavailable"?w(o,P.error):h===P.value?"current":"stale"};return{check:async(c,o)=>{if(!(q(o)&&re(c)))return"stale";let h=performance.now(),P=i(c),_=f(P,h);if(_!==void 0){if(o===_.value)return"current";if(o<_.value)return"stale"}if(S(P,h))return"unavailable";if(_!==void 0)return await d(c,P,o);let E=await l(c,P,h);return E.kind==="unavailable"?w(P,E.error):o===E.value?"current":o<E.value?"stale":await d(c,P,o)},stamp:async c=>{if(!re(c))throw ye(c);let o=await g({operation:"current"},c,i(c));if(o.kind==="unavailable")throw o.error;return o.value},advance:async(c,o)=>{if(!re(c))return{kind:"failed",error:ye(c)};if(!Xe(o))return{kind:"failed",error:Be(o)};try{let h=await g({operation:"advance",from:o},c,i(c));return h.kind==="value"?{kind:"advanced",generation:h.value}:{kind:"unavailable",error:h.error}}catch(h){return{kind:"failed",error:h}}}}};var M=class extends Error{constructor(t){super(t),this.name="TokenRefreshError"}},D=class extends M{constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},$=class extends Error{constructor(t){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=t}},Je=["access_token","expires_in"],B=(e,t,n)=>{let r=e.loginPath??"/auth/login",s=t.sessionKey,k=async m=>{let A=m.get(s)?.refreshToken;if(!A)throw new Error("Refresh token not found in session");try{let i="https://www.googleapis.com/oauth2/v4/token",f={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:A},u=await(e.fetch??globalThis.fetch)(i,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(f)});if(!u.ok){let g=await u.json().catch(()=>{});if(u.status===400&&typeof g=="object"&&!!g&&"error"in g&&g.error==="invalid_grant")throw new D;let d=typeof g=="object"&&g&&"error_description"in g?String(g.error_description):"Unknown error";throw new M(`Google token refresh failed: ${u.status} ${d}`)}let p=await u.json(),T=Je.filter(g=>!p?.[g]);if(T.length>0)throw n.error("Invalid token response from Google; missing or empty keys:",T.join(", ")),new Error("Invalid token response from Google");let{access_token:S,expires_in:w}=p;return{accessToken:S,refreshToken:A,expirationDateMs:Number(Date.now())+w*1e3}}catch(i){if(i instanceof M)throw i;let f=i instanceof Error?i.message:"Unknown error";throw new M(`Failed to refresh Google access token: ${f}`)}},R=async m=>{let A=m.get(s).provider;if(!A)throw new Error("Provider not found in session");if(A==="google")return await k(m);throw new Error("Provider not supported")};return{authenticate:async(m,y,A)=>{let{failureRedirect:i}=A||{},f=a=>{if(i===null)return new $(a);if(i==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let u=i??r;return a!==void 0?(0,ae.redirect)(u,{headers:{"Set-Cookie":a}}):(0,ae.redirect)(u)};try{if(e.mockUser?.enabled(m)){let{accessToken:w,refreshToken:g,expirationDateMs:l}=e.mockUser.resolve(m);return{accessToken:w,refreshToken:g,expirationDateMs:l}}let a=y.get(s),u=t.sessionGenerationGate;if(a!==void 0&&u!==null&&await u.check(C(a),y.get(U))==="stale")throw f(await t.destroySession(y));if(!(a?.accessToken&&a.expirationDateMs))throw f();let{accessToken:p,refreshToken:T,expirationDateMs:S}=a;if(S<Date.now())throw T?new Error("Expired"):f();return{accessToken:p,refreshToken:T,expirationDateMs:S}}catch(a){if(a instanceof Error&&a.message==="Expired")try{let u=await R(y),p=y.get(s);return y.set(s,{...p,...u}),u}catch(u){if(u instanceof D)n.warn("Google refresh token invalid or revoked");else{let T=u instanceof Error?u.message:"Unknown error";n.error("Failed to refresh token:",T)}let p=await t.destroySession(y);throw f(p)}throw a}},refreshedAccessToken:R}};var ce=require("react-router");var Y=({refreshToken:e,...t})=>t;var J=(e,t,n,r)=>{let s=new Map,k=new Map,R=async i=>{let f=s.get(i);if(f!==void 0)return f;let a=k.get(i);if(a!==void 0)return a;let u=(async()=>{try{let p=e.getUserPhoto?await e.getUserPhoto(i):"";return s.set(i,p),p}catch(p){throw s.delete(i),p}finally{k.delete(i)}})();return k.set(i,u),u},G=new WeakMap,m=async i=>{e.warmup&&await e.warmup();let f=await t.resolveSession(i);if(f.kind==="revoked")return{kind:"unauthenticated",cookie:await t.destroySession(f.session)};if(f.kind!=="signed-in")return{kind:"unauthenticated"};let{user:a,session:u}=f,p;try{p=await n.authenticate(i,u,{failureRedirect:null})}catch(v){if(v instanceof $)return v.setCookie!==void 0?{kind:"unauthenticated",cookie:v.setCookie}:{kind:"unauthenticated"};throw r.error("Error in authenticateInLoader:",v),v}let T={accessToken:p.accessToken,refreshToken:p.refreshToken,expirationDateMs:p.expirationDateMs,provider:a.provider},S={id:a.id,displayName:a.displayName,name:a.name,emails:a.emails,...T,role:a.role},w=await R(a.id),g=Y({...a,...T,photo:w}),d=p.accessToken!==a.accessToken?await t.saveSession(i,S):void 0;return d!==void 0?{kind:"authenticated",user:g,cookie:d}:{kind:"authenticated",user:g}},y=i=>{let f=G.get(i);if(f!==void 0)return f;let a=m(i);return G.set(i,a),a};async function A(i,f){let{failureRedirect:a}=f;if(a==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let u=await y(i);if(u.kind==="authenticated")return u.cookie!==void 0?{user:u.user,cookie:u.cookie}:{user:u.user};if(a===null)return u.cookie!==void 0?{cookie:u.cookie}:{};throw u.cookie!==void 0?(0,ce.redirect)(a,{headers:{"Set-Cookie":u.cookie}}):(0,ce.redirect)(a)}return A};var ve=require("@aiquants/auth-core"),X=require("react-router"),Re=require("remix-auth");var ke=require("remix-auth-oauth2"),ze=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],Qe="google",Ze="https://www.googleapis.com/oauth2/v3/userinfo",W=class extends ke.OAuth2Strategy{constructor({clientId:n,clientSecret:r,redirectURI:s,scopes:k,accessType:R,includeGrantedScopes:G,prompt:m,hd:y,loginHint:A,additionalScopes:i},f){let a=k??ze;super({clientId:n,clientSecret:r,redirectURI:s,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:a},f);this.name=Qe;this.scopes=a,this.accessType=R??"online",this.includeGrantedScopes=G??!1,this.prompt=m,this.hd=y,this.loginHint=A,this.additionalScopes=i}authorizationParams(n,r){n.set("access_type",this.accessType),n.set("include_granted_scopes",String(this.includeGrantedScopes));let s=r===void 0||this.additionalScopes===void 0?[]:this.additionalScopes(r);for(let R of s)if(R===""||/\s/u.test(R))throw new RangeError(`[auth-react-router] an additional scope must be a non-empty string without white space; got ${JSON.stringify(R)}`);let k=[...new Set([...this.scopes,...s])];return k.length>0&&n.set("scope",k.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 r=await fetch(Ze,{headers:{Authorization:`Bearer ${n.accessToken()}`}});if(!r.ok)throw new Error(`Failed to fetch user profile: ${r.statusText}`);let s=await r.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 j={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var z=e=>{let t=e.logger??j,n=(0,ve.resolveAuthMessages)(e.messages),r=e.loginPath??"/auth/login",s=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:R,tokens:G})=>{let{access_token:m,refresh_token:y,expires_in:A,scope:i,id_token:f}=G.data,{_json:{sub:a,email:u,picture:p,hd:T,email_verified:S},photos:w,...g}=await W.userProfile(G),{id:l,displayName:d,name:{familyName:v,givenName:I},emails:N}=g,c="google";if(m===void 0||y===void 0||A===void 0||i===void 0||l===void 0||d===void 0||a===void 0||u===void 0||S===void 0){if(S===!1){let h=encodeURIComponent(n.emailNotVerified);throw(0,X.redirect)(`${r}?error=${h}`)}let o=encodeURIComponent(n.googleFailed);throw(0,X.redirect)(`${r}?error=${o}`)}t.info("Authenticated on Google: ",g.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(c,m)){t.error("Backend verification returned false for user:",g.displayName);let O=encodeURIComponent(n.backendFailed);throw(0,X.redirect)(`${r}?error=${O}`)}t.info("Authenticated on Backend: ",g.displayName)}let o=g.emails[0]?.value;if(!await e.isEmailAllowed(o)){let E=new Error("You are not allowed to access this application");throw t.error(E),E}if(e.isUserActive&&!await e.isUserActive(g)){let E=new Error("You are not allowed to access this application");throw t.error("Deactivated account attempted to sign in:",o),E}e.backendAuth&&await e.backendAuth.signup(c,m,g),t.info("Authenticated complete: ",g.displayName);let h=Date.now()+A*1e3;return{...g,...{accessToken:m,refreshToken:y,expirationDateMs:h,provider:c},photo:p}}catch(o){let h=o;typeof o=="object"&&o!==null&&"cause"in o&&(h=o.cause||o),t.error("Error during backend authentication or subsequent processing:",h);let P=n.unexpected,_=!1;if(typeof o=="object"&&o!==null&&"cause"in o){let O=o.cause;O&&typeof O=="object"&&"message"in O&&typeof O.message=="string"&&O.message.includes("getaddrinfo ENOTFOUND")&&(P=n.backendUnreachable,_=!0)}if(!_&&o instanceof Error&&o.message.includes("You are not allowed to access this application")&&(P=n.notAllowed,_=!0),!_&&o instanceof Response&&o.headers.get("Location")?.startsWith(r))throw o;let E=encodeURIComponent(P);throw(0,X.redirect)(`${r}?error=${E}`)}}),k=new Re.Authenticator;return k.use(s),k};var K=require("react-router");var ue="returnTo",Q=(e,t)=>{let n=e.indexOf("?"),r=n===-1?e:e.slice(0,n),s=new URLSearchParams(n===-1?"":e.slice(n+1));return s.set(ue,t),`${r}?${s.toString()}`};var Ge=require("react-router");var et="__return_to.",tt=300,Ae=/^[A-Za-z0-9_-]{1,128}$/,Te="https://return-to.invalid",Pe=Object.freeze({path:void 0,deletion:void 0}),nt=e=>{if(e.includes("%"))return!1;let t=new URL(e,Te);return t.origin===Te&&t.pathname===e},ot=e=>{if(e===void 0)return new Set;let t=e;if(typeof t!="object"||t===null||!Array.isArray(t.allowedPaths))throw new TypeError(`returnTo must be { allowedPaths: string[] }; got ${JSON.stringify(t)}`);let n=t.allowedPaths;if(n.length===0)throw new RangeError("returnTo.allowedPaths must name at least one path; omit returnTo to allow none");for(let r of n){if(typeof r!="string")throw new TypeError(`returnTo.allowedPaths must hold strings; got ${JSON.stringify(r)}`);if(!nt(r))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(r)}`)}return new Set(n)},rt=()=>new Response("The sign-in's return-to is not a path this application allows.",{status:400,headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-store"}}),st=(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}),Ee=(e,t,n,r)=>{let s=ot(e),k=i=>(0,Ge.createCookie)(`${et}${i}`,{secrets:[...t.secrets],httpOnly:!0,sameSite:"lax",path:"/",secure:t.secure,maxAge:tt}),R=(i,f,a)=>{let u=i.headers.get("Location");if(u===null)return i;let p=new URL(u,a.url);if(p.origin!==new URL(a.url).origin||p.pathname!==n)return i;let T=new Headers(i.headers);return T.set("Location",`${Q(`${p.pathname}${p.search}`,f)}${p.hash}`),de(i,T)};return{requested:i=>{let f=new URL(i.url).searchParams.getAll(ue);if(f.length!==0){if(f.length===1&&s.has(f[0]))return f[0];throw rt()}},bindToFlow:async(i,f,a)=>{let u=i.headers.get("Location"),p=u===null?null:new URL(u,a.url).searchParams.get("state");if(p===null)return R(i,f,a);if(!Ae.test(p))throw new Error(`The authorization redirect's state cannot name the return-to cookie; got ${JSON.stringify(p)}`);let T=new Headers(i.headers);return T.append("Set-Cookie",await k(p).serialize(f)),de(i,T)},flowOf:async i=>{let f=new URL(i.url).searchParams.get("state");if(f===null||!Ae.test(f))return Pe;let a=k(f),u=i.headers.get("Cookie");if(!st(u,a.name))return Pe;let p=await a.serialize("",{maxAge:0}),T=await a.parse(u);return typeof T=="string"&&s.has(T)?{path:T,deletion:p}:(r.warn(`The sign-in's return-to cookie ${a.name} names no allowed path; the sign-in returns to the post-login path instead`),{path:void 0,deletion:p})},endFailedFlow:(i,f,a)=>{if(f.deletion===void 0)return i;let u=f.path===void 0?i:R(i,f.path,a),p=new Headers(u.headers);return p.append("Set-Cookie",f.deletion),de(u,p)}}};var H=require("react-router");var le=3600*24*30,it=e=>{if(e===void 0)return le;if(!Number.isSafeInteger(e)||e<1)throw new RangeError(`session.maxAge must be a safe integer of seconds >= 1; got ${String(e)}`);return e},fe=e=>e.secure??process.env.NODE_ENV==="production",Z=(e,t)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(S=>!S))throw new Error("REMIX_SESSION_SECRET must be set");let n=e.sessionKey??"user";if(n===U)throw new RangeError(`session.sessionKey must not be ${JSON.stringify(U)}, the key the session generation is stored under; got ${JSON.stringify(n)}`);let r=it(e.maxAge),s=t.loginPath??"/auth/login",k=t.postLoginRedirect??"/",R=t.mockUser,G=t.isUserActive,m=we(t.sessionGeneration,t.logger??j),y=(0,H.createCookieSessionStorage)({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:fe(e),maxAge:r}}),A=async S=>await y.getSession(S.headers.get("Cookie")),i=async S=>{if(R?.enabled(S))return{kind:"signed-in",user:Y(R.resolve(S)),session:await A(S)};let w=await A(S),g=w.get(n);if(g===void 0)return{kind:"signed-out"};let l=Y(g),[d,v]=await Promise.all([G===void 0?!0:G(l),m===null?"current":m.check(C(g),w.get(U))]);return v==="stale"?{kind:"revoked",session:w}:d?{kind:"signed-in",user:l,session:w}:{kind:"inactive"}},f=async S=>{let w=await i(S);return w.kind==="signed-in"?w.user:void 0},a=async(S,w)=>{let g=await A(S);return g.set(n,w),await y.commitSession(g)},u=async(S,w)=>{let g=m===null?void 0:await m.stamp(C(w)),l=await A(S);return l.set(n,w),g!==void 0&&l.set(U,g),await y.commitSession(l)},p=async S=>{let w=await i(S);switch(w.kind){case"signed-in":return w.user;case"revoked":throw(0,H.redirect)(s,{headers:{"Set-Cookie":await y.destroySession(w.session)}});case"signed-out":case"inactive":throw(0,H.redirect)(s)}};return{sessionStorage:y,sessionKey:n,sessionMaxAgeSeconds:r,sessionGenerationGate:m,getSession:A,resolveSession:i,getSessionUser:f,saveSession:a,saveSignedInSession:u,requireUser:p,requireAdminUser:async S=>{let w=await p(S);if(w.role!=="admin")throw(0,H.redirect)(k);return w},commitSession:y.commitSession,destroySession:y.destroySession}};var at=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 r=at.get(t);if(r===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(!r.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(`Signing out is refused because ${e}: only a navigation that does not come from another site, or a script's request from this origin, signs out.`,{status:403,headers:{"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"}});var ne=(e,t,n,r)=>{let s=e.loginPath??"/auth/login",k=e.postLoginRedirect??"/",R=e.postLogoutRedirect??"/",G=ge(e.google.revocationTimeoutMs),m=Ee(e.returnTo,{secrets:e.session.secrets,secure:fe(e.session)},s,r),y=async({request:l})=>{let d=m.requested(l);if(await t.getSessionUser(l))throw(0,K.redirect)(d??k);return{error:new URL(l.url).searchParams.get("error")}},A=async l=>{let d=m.requested(l);try{await n.authenticate("google",l)}catch(v){throw d===void 0||!(v instanceof Response)?v:await m.bindToFlow(v,d,l)}throw(0,K.redirect)(d===void 0?s:Q(s,d))},i=async({request:l})=>(await l.clone().formData()).get("_action")!=="Sign In with Google"?null:await A(l),f=(l,d)=>{switch(l.outcome){case"failed":r.error(`Sign-out could not revoke the Google grant of user ${String(d)}; the session cookie is destroyed, but the grant stays valid until it expires or is revoked elsewhere:`,l.reason);return;case"already-invalid":r.info(`Sign-out found the Google grant of user ${String(d)} already unusable`);return;case"revoked":case"nothing-to-revoke":return}},a=(l,d)=>{l.kind!=="advanced"&&r.error(`Sign-out could not advance the session generation of ${d.provider} user ${d.id}; a session cookie refreshed before this sign-out stays valid until a later sign-out advances the generation or the cookie expires:`,l.error)},u=async(l,d)=>{let v=t.sessionGenerationGate;if(v!==null){if(!q(d)){r.info(`Sign-out found no usable session generation stamp in the session of ${l.provider} user ${l.id}; every guard already rejects that cookie, so the generation is not advanced`);return}a(await v.advance(l,d),l)}},p=async l=>{let d=await t.getSession(l),v=d.get(t.sessionKey),[I]=await Promise.all([me(v,{fetch:e.fetch??globalThis.fetch,timeoutMs:G}),v===void 0?void 0:u(C(v),d.get(U))]);return f(I,v?.id),await t.destroySession(d)},T=async l=>{let d=await p(l),v=new Headers;return v.append("Set-Cookie",d),(0,K.redirect)(R,{headers:v})},S=async({request:l})=>{let d=ee(l);throw d!==void 0?te(d):await T(l)},w=async l=>{let d=await n.authenticate("google",l),N=(await t.getSession(l)).get(t.sessionKey)?.refreshToken,c={accessToken:d.accessToken,refreshToken:d.refreshToken||N,expirationDateMs:d.expirationDateMs,provider:d.provider},o={id:d.id,displayName:d.displayName,name:d.name,emails:d.emails,...c,role:d.role};return await t.saveSignedInSession(l,o)};return{loginLoader:y,loginAction:i,startGoogleSignIn:A,logoutLoader:S,logout:p,logoutAndRedirect:T,googleCallbackLoader:async({request:l})=>{let d=await m.flowOf(l),v;try{v=await w(l)}catch(N){throw N instanceof Response?m.endFailedFlow(N,d,l):(r.error("Authentication error:",N),m.endFailedFlow((0,K.redirect)(s),d,l))}let I=new Headers;throw I.append("Set-Cookie",v),d.deletion!==void 0&&I.append("Set-Cookie",d.deletion),(0,K.redirect)(d.path??k,{headers:I})}}};var _e=e=>{let t=e.logger??j,n=Z(e.session,{sessionGeneration:e.sessionGeneration,logger:t,mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive}),r=z(e),s=B(e,n,t),k=J(e,n,s,t),R=ne(e,n,r,t);return{authenticator:r,storage:n,authFns:s,sessionStorage:n.sessionStorage,getSession:n.getSession,getSessionUser:n.getSessionUser,saveSession:n.saveSession,requireUser:n.requireUser,requireAdminUser:n.requireAdminUser,commitSession:n.commitSession,destroySession:n.destroySession,sessionMaxAgeSeconds:n.sessionMaxAgeSeconds,authenticate:s.authenticate,refreshedAccessToken:s.refreshedAccessToken,authenticateInLoader:k,...R}};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 se=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Le=Object.prototype.hasOwnProperty;var Me=(e,t)=>{for(var n in t)se(e,n,{get:t[n],enumerable:!0})},Ce=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ue(t))!Le.call(e,s)&&s!==n&&se(e,s,{get:()=>t[s],enumerable:!(r=Ne(t,s))||r.enumerable});return e};var $e=e=>Ce(se({},"__esModule",{value:!0}),e);var dt={};Me(dt,{AuthRequiredError:()=>$,DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS:()=>ie,DEFAULT_SESSION_GENERATION_CACHE_TTL_MS:()=>ce,DEFAULT_SESSION_GENERATION_TIMEOUT_MS:()=>ue,DEFAULT_SESSION_MAX_AGE_SECONDS:()=>he,GoogleInvalidGrantError:()=>D,SessionGenerationUnavailableError:()=>F,TokenRefreshError:()=>L,createAuthHandlers:()=>re,createAuthServer:()=>Ie,createAuthSessionStorage:()=>te,createAuthenticate:()=>X,createAuthenticateInLoader:()=>B,createGoogleAuthenticator:()=>Z,signOutRefusal:()=>ne,signOutRefusalResponse:()=>oe});module.exports=$e(dt);var Ae=require("@aiquants/auth-core"),de=require("react-router");var Se=require("@aiquants/auth-core"),Fe="https://oauth2.googleapis.com/revoke",ie=5e3,Y=2147483647,qe="invalid_token",De=400,ye=e=>{if(e===void 0)return ie;if(!Number.isInteger(e)||e<1||e>Y)throw new RangeError(`google.revocationTimeoutMs must be an integer from 1 to ${Y} (milliseconds); got ${String(e)}`);return e},je=e=>{if(typeof e.refreshToken=="string"&&e.refreshToken!=="")return e.refreshToken;if(typeof e.accessToken=="string"&&e.accessToken!=="")return e.accessToken},He=async e=>{let t=await e.json().catch(()=>{});return typeof t=="object"&&t!==null&&"error"in t&&typeof t.error=="string"?t.error:void 0},Ke=e=>e instanceof Error?e.cause instanceof Error?`${e.message} (${e.cause.message})`:e.message:String(e),Ve=async(e,t,n)=>{try{let r=await t(Fe,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:e}).toString(),signal:n});if(r.ok)return await r.body?.cancel(),{outcome:"revoked"};let s=await He(r);return r.status===De&&s===qe?{outcome:"already-invalid"}:{outcome:"failed",reason:s===void 0?`Google answered ${r.status}`:`Google answered ${r.status} ${s}`}}catch(r){return{outcome:"failed",reason:Ke(r)}}},we=async(e,t)=>{if(e===void 0)return{outcome:"nothing-to-revoke"};let n=je(e);if(n===void 0)return{outcome:"nothing-to-revoke"};if(e.provider!==Se.GOOGLE_PROVIDER)return{outcome:"failed",reason:`the session's provider "${String(e.provider)}" has no revocation endpoint`};let r=new AbortController;return await new Promise(s=>{let v=setTimeout(()=>{s({outcome:"failed",reason:`Google did not answer within ${t.timeoutMs} ms`}),r.abort()},t.timeoutMs);Ve(n,t.fetch,r.signal).then(A=>{clearTimeout(v),s(A)})})};var N="generation",ce=15e3,ue=3e3,Ye=6e4,F=class extends Error{constructor(t,n){super(t,n),this.name="SessionGenerationUnavailableError"}},x=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),Je=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return x(e);let t="store"in e?e.store:void 0;if(typeof t!="object"||t===null)return`an object whose store is ${x(t)}`;let n="current"in t?t.current:void 0,r="advance"in t?t.advance:void 0;return`an object whose store.current is ${x(n)} and store.advance is ${x(r)}`},We=e=>typeof e=="object"&&e!==null&&"current"in e&&typeof e.current=="function"&&"advance"in e&&typeof e.advance=="function",ke=(e,t,n,r)=>{if(t===void 0)return r;if(typeof t!="number"||!Number.isInteger(t)||t<n||t>Y)throw new RangeError(`${e} must be an integer from ${n} to ${Y} (milliseconds); got ${x(t)}`);return t},ze=e=>{if(e===!1)return!1;let t=e;if(typeof t!="object"||t===null||!("store"in t)||!We(t.store))throw new TypeError(`sessionGeneration must be { store, cacheTtlMs?, timeoutMs? } or false; got ${Je(t)}`);return{store:t.store,cacheTtlMs:ke("sessionGeneration.cacheTtlMs","cacheTtlMs"in t?t.cacheTtlMs:void 0,0,ce),timeoutMs:ke("sessionGeneration.timeoutMs","timeoutMs"in t?t.timeoutMs:void 0,1,ue)}},q=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,ae=e=>typeof e.provider=="string"&&e.provider!==""&&typeof e.id=="string"&&e.id!=="",ve=e=>new TypeError(`a session generation identity needs a non-empty provider and id; got provider ${x(e.provider)} and id ${x(e.id)}`),Xe=e=>q(e)&&q(e+1),Be=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 ${x(e)}`),C=e=>({provider:e.provider,id:e.id}),Re=(e,t)=>{let n=ze(e);if(n===!1)return null;let{store:r,cacheTtlMs:s,timeoutMs:v}=n,A=new Map,G=new Map,m=new Map,w=new Map,T=Number.NEGATIVE_INFINITY,i=c=>`${c.provider}\0${c.id}`,u=(c,o)=>{let p=A.get(c);if(p!==void 0){if(o-p.at<s)return p;A.delete(c)}},a=(c,o,p)=>{if(p!==void 0&&o.at<=p.answeredAt&&o.value<p.value)return;let P=u(c,performance.now());if(P===void 0){A.set(c,o);return}o.value<P.value||A.set(c,{value:o.value,at:Math.max(P.at,o.at)})},d=c=>{let o=w.get(c);if(o!==void 0)return o.count+=1,o;let p={count:1,floor:void 0};return w.set(c,p),p},h=(c,o)=>{o.count-=1,o.count===0&&w.delete(c)},S=(c,o)=>{c.floor={value:c.floor===void 0?o:Math.max(c.floor.value,o),answeredAt:performance.now()}},y=(c,o)=>{let p=m.get(c);return p===void 0?!1:o<p?!0:(m.delete(c),!1)},k=(c,o)=>{let p=performance.now();return m.set(c,p+s),p-T>=Ye&&(T=p,t.warn("Session generation store unavailable; skipping the sign-out generation check:",o)),"unavailable"},g=(c,o,p)=>new Promise((P,_)=>{let{operation:E}=c,O=c.operation==="advance"?c.from+1:0,xe=performance.now(),V=d(p),M=!1,me=setTimeout(()=>{M=!0,P({kind:"unavailable",error:new F(`sessionGeneration.store.${E} did not settle within ${v} ms`)})},v);new Promise(b=>b(c.operation==="advance"?r.advance(o,c.from):r.current(o))).then(b=>{if(clearTimeout(me),!(q(b)&&b>=O)){h(p,V),M||(M=!0,_(new TypeError(`sessionGeneration.store.${E} must resolve to an integer >= ${O}; got ${x(b)}`)));return}E==="advance"&&(S(V,b),G.delete(p)),a(p,{value:b,at:xe},V.floor),h(p,V),!M&&(M=!0,m.delete(p),P({kind:"value",value:b}))},b=>{if(clearTimeout(me),h(p,V),!M){if(M=!0,b instanceof F){P({kind:"unavailable",error:b});return}_(b)}})}),f=(c,o,p)=>{let P=G.get(o);if(P!==void 0&&p-P.startedAt<s)return P.read;let _={read:g({operation:"current"},c,o),startedAt:p};G.set(o,_);let E=()=>{G.get(o)===_&&G.delete(o)};return _.read.then(E,E),_.read},l=async(c,o,p)=>{let P=await g({operation:"current"},c,o);return P.kind==="unavailable"?k(o,P.error):p===P.value?"current":"stale"};return{check:async(c,o)=>{if(!(q(o)&&ae(c)))return"stale";let p=performance.now(),P=i(c),_=u(P,p);if(_!==void 0){if(o===_.value)return"current";if(o<_.value)return"stale"}if(y(P,p))return"unavailable";if(_!==void 0)return await l(c,P,o);let E=await f(c,P,p);return E.kind==="unavailable"?k(P,E.error):o===E.value?"current":o<E.value?"stale":await l(c,P,o)},stamp:async c=>{if(!ae(c))throw ve(c);let o=await g({operation:"current"},c,i(c));if(o.kind==="unavailable")throw o.error;return o.value},advance:async(c,o)=>{if(!ae(c))return{kind:"failed",error:ve(c)};if(!Xe(o))return{kind:"failed",error:Be(o)};try{let p=await g({operation:"advance",from:o},c,i(c));return p.kind==="value"?{kind:"advanced",generation:p.value}:{kind:"unavailable",error:p.error}}catch(p){return{kind:"failed",error:p}}}}};var L=class extends Error{constructor(t){super(t),this.name="TokenRefreshError"}},D=class extends L{constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},$=class extends Error{constructor(t){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=t}},Qe=["access_token","expires_in"],X=(e,t,n)=>{let r=e.loginPath??"/auth/login",s=t.sessionKey,v=async m=>{let T=m.get(s)?.refreshToken;if(!T)throw new Error("Refresh token not found in session");try{let i="https://www.googleapis.com/oauth2/v4/token",u={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:T},d=await(e.fetch??globalThis.fetch)(i,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(u)});if(!d.ok){let g=await d.json().catch(()=>{});if(d.status===400&&typeof g=="object"&&!!g&&"error"in g&&g.error==="invalid_grant")throw new D;let l=typeof g=="object"&&g&&"error_description"in g?String(g.error_description):"Unknown error";throw new L(`Google token refresh failed: ${d.status} ${l}`)}let h=await d.json(),S=Qe.filter(g=>!h?.[g]);if(S.length>0)throw n.error("Invalid token response from Google; missing or empty keys:",S.join(", ")),new Error("Invalid token response from Google");let{access_token:y,expires_in:k}=h;return{accessToken:y,refreshToken:T,expirationDateMs:Number(Date.now())+k*1e3}}catch(i){if(i instanceof L)throw i;let u=i instanceof Error?i.message:"Unknown error";throw new L(`Failed to refresh Google access token: ${u}`)}},A=async m=>{let T=m.get(s).provider;if(!T)throw new Error("Provider not found in session");if(T===Ae.GOOGLE_PROVIDER)return await v(m);throw new Error("Provider not supported")};return{authenticate:async(m,w,T)=>{let{failureRedirect:i}=T||{},u=a=>{if(i===null)return new $(a);if(i==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let d=i??r;return a!==void 0?(0,de.redirect)(d,{headers:{"Set-Cookie":a}}):(0,de.redirect)(d)};try{if(e.mockUser?.enabled(m)){let{accessToken:k,refreshToken:g,expirationDateMs:f}=e.mockUser.resolve(m);return{accessToken:k,refreshToken:g,expirationDateMs:f}}let a=w.get(s),d=t.sessionGenerationGate;if(a!==void 0&&d!==null&&await d.check(C(a),w.get(N))==="stale")throw u(await t.destroySession(w));if(!(a?.accessToken&&a.expirationDateMs))throw u();let{accessToken:h,refreshToken:S,expirationDateMs:y}=a;if(y<Date.now())throw S?new Error("Expired"):u();return{accessToken:h,refreshToken:S,expirationDateMs:y}}catch(a){if(a instanceof Error&&a.message==="Expired")try{let d=await A(w),h=w.get(s);return w.set(s,{...h,...d}),d}catch(d){if(d instanceof D)n.warn("Google refresh token invalid or revoked");else{let S=d instanceof Error?d.message:"Unknown error";n.error("Failed to refresh token:",S)}let h=await t.destroySession(w);throw u(h)}throw a}},refreshedAccessToken:A}};var le=require("react-router");var J=({refreshToken:e,...t})=>t;var B=(e,t,n,r)=>{let s=new Map,v=new Map,A=async i=>{let u=JSON.stringify([i.provider,i.id]),a=s.get(u);if(a!==void 0)return a;let d=v.get(u);if(d!==void 0)return d;let h=(async()=>{try{let S=e.getUserPhoto?await e.getUserPhoto(i):"";return s.set(u,S),S}catch(S){throw s.delete(u),S}finally{v.delete(u)}})();return v.set(u,h),h},G=new WeakMap,m=async i=>{e.warmup&&await e.warmup();let u=await t.resolveSession(i);if(u.kind==="revoked")return{kind:"unauthenticated",cookie:await t.destroySession(u.session)};if(u.kind!=="signed-in")return{kind:"unauthenticated"};let{user:a,session:d}=u,h;try{h=await n.authenticate(i,d,{failureRedirect:null})}catch(R){if(R instanceof $)return R.setCookie!==void 0?{kind:"unauthenticated",cookie:R.setCookie}:{kind:"unauthenticated"};throw r.error("Error in authenticateInLoader:",R),R}let S={accessToken:h.accessToken,refreshToken:h.refreshToken,expirationDateMs:h.expirationDateMs,provider:a.provider},y={id:a.id,displayName:a.displayName,name:a.name,emails:a.emails,...S,role:a.role},k=await A(a),g=J({...a,...S,photo:k}),l=h.accessToken!==a.accessToken?await t.saveSession(i,y):void 0;return l!==void 0?{kind:"authenticated",user:g,cookie:l}:{kind:"authenticated",user:g}},w=i=>{let u=G.get(i);if(u!==void 0)return u;let a=m(i);return G.set(i,a),a};async function T(i,u){let{failureRedirect:a}=u;if(a==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let d=await w(i);if(d.kind==="authenticated")return d.cookie!==void 0?{user:d.user,cookie:d.cookie}:{user:d.user};if(a===null)return d.cookie!==void 0?{cookie:d.cookie}:{};throw d.cookie!==void 0?(0,le.redirect)(a,{headers:{"Set-Cookie":d.cookie}}):(0,le.redirect)(a)}return T};var Q=require("@aiquants/auth-core"),z=require("react-router"),Pe=require("remix-auth");var Te=require("remix-auth-oauth2"),Ze=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],et="google",tt="https://www.googleapis.com/oauth2/v3/userinfo",W=class extends Te.OAuth2Strategy{constructor({clientId:n,clientSecret:r,redirectURI:s,scopes:v,accessType:A,includeGrantedScopes:G,prompt:m,hd:w,loginHint:T,additionalScopes:i},u){let a=v??Ze;super({clientId:n,clientSecret:r,redirectURI:s,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:a},u);this.name=et;this.scopes=a,this.accessType=A??"online",this.includeGrantedScopes=G??!1,this.prompt=m,this.hd=w,this.loginHint=T,this.additionalScopes=i}authorizationParams(n,r){n.set("access_type",this.accessType),n.set("include_granted_scopes",String(this.includeGrantedScopes));let s=r===void 0||this.additionalScopes===void 0?[]:this.additionalScopes(r);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 v=[...new Set([...this.scopes,...s])];return v.length>0&&n.set("scope",v.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 r=await fetch(tt,{headers:{Authorization:`Bearer ${n.accessToken()}`}});if(!r.ok)throw new Error(`Failed to fetch user profile: ${r.statusText}`);let s=await r.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 j={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var Z=e=>{let t=e.logger??j,n=(0,Q.resolveAuthMessages)(e.messages),r=e.loginPath??"/auth/login",s=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:A,tokens:G})=>{let{access_token:m,refresh_token:w,expires_in:T,scope:i,id_token:u}=G.data,{_json:{sub:a,email:d,picture:h,hd:S,email_verified:y},photos:k,...g}=await W.userProfile(G),{id:f,displayName:l,name:{familyName:R,givenName:I},emails:U}=g,c=Q.GOOGLE_PROVIDER;if(m===void 0||w===void 0||T===void 0||i===void 0||f===void 0||l===void 0||a===void 0||d===void 0||y===void 0){if(y===!1){let p=encodeURIComponent(n.emailNotVerified);throw(0,z.redirect)(`${r}?error=${p}`)}let o=encodeURIComponent(n.googleFailed);throw(0,z.redirect)(`${r}?error=${o}`)}t.info("Authenticated on Google: ",g.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(c,m)){t.error("Backend verification returned false for user:",g.displayName);let O=encodeURIComponent(n.backendFailed);throw(0,z.redirect)(`${r}?error=${O}`)}t.info("Authenticated on Backend: ",g.displayName)}let o=g.emails[0]?.value;if(!await e.isEmailAllowed(o)){let E=new Error("You are not allowed to access this application");throw t.error(E),E}if(e.isUserActive&&!await e.isUserActive({...g,provider:c})){let E=new Error("You are not allowed to access this application");throw t.error("Deactivated account attempted to sign in:",o),E}e.backendAuth&&await e.backendAuth.signup(c,m,g),t.info("Authenticated complete: ",g.displayName);let p=Date.now()+T*1e3;return{...g,...{accessToken:m,refreshToken:w,expirationDateMs:p,provider:c},photo:h}}catch(o){let p=o;typeof o=="object"&&o!==null&&"cause"in o&&(p=o.cause||o),t.error("Error during backend authentication or subsequent processing:",p);let P=n.unexpected,_=!1;if(typeof o=="object"&&o!==null&&"cause"in o){let O=o.cause;O&&typeof O=="object"&&"message"in O&&typeof O.message=="string"&&O.message.includes("getaddrinfo ENOTFOUND")&&(P=n.backendUnreachable,_=!0)}if(!_&&o instanceof Error&&o.message.includes("You are not allowed to access this application")&&(P=n.notAllowed,_=!0),!_&&o instanceof Response&&o.headers.get("Location")?.startsWith(r))throw o;let E=encodeURIComponent(P);throw(0,z.redirect)(`${r}?error=${E}`)}}),v=new Pe.Authenticator;return v.use(s),v};var K=require("react-router");var fe="returnTo",ee=(e,t)=>{let n=e.indexOf("?"),r=n===-1?e:e.slice(0,n),s=new URLSearchParams(n===-1?"":e.slice(n+1));return s.set(fe,t),`${r}?${s.toString()}`};var be=require("react-router");var nt="__return_to.",ot=300,Ge=/^[A-Za-z0-9_-]{1,128}$/,Ee="https://return-to.invalid",_e=Object.freeze({path:void 0,deletion:void 0}),rt=e=>{if(e.includes("%"))return!1;let t=new URL(e,Ee);return t.origin===Ee&&t.pathname===e},st=e=>{if(e===void 0)return new Set;let t=e;if(typeof t!="object"||t===null||!Array.isArray(t.allowedPaths))throw new TypeError(`returnTo must be { allowedPaths: string[] }; got ${JSON.stringify(t)}`);let n=t.allowedPaths;if(n.length===0)throw new RangeError("returnTo.allowedPaths must name at least one path; omit returnTo to allow none");for(let r of n){if(typeof r!="string")throw new TypeError(`returnTo.allowedPaths must hold strings; got ${JSON.stringify(r)}`);if(!rt(r))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(r)}`)}return new Set(n)},it=()=>new Response("The sign-in's return-to is not a path this application allows.",{status:400,headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-store"}}),at=(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}),Oe=(e,t,n,r)=>{let s=st(e),v=i=>(0,be.createCookie)(`${nt}${i}`,{secrets:[...t.secrets],httpOnly:!0,sameSite:"lax",path:"/",secure:t.secure,maxAge:ot}),A=(i,u,a)=>{let d=i.headers.get("Location");if(d===null)return i;let h=new URL(d,a.url);if(h.origin!==new URL(a.url).origin||h.pathname!==n)return i;let S=new Headers(i.headers);return S.set("Location",`${ee(`${h.pathname}${h.search}`,u)}${h.hash}`),pe(i,S)};return{requested:i=>{let u=new URL(i.url).searchParams.getAll(fe);if(u.length!==0){if(u.length===1&&s.has(u[0]))return u[0];throw it()}},bindToFlow:async(i,u,a)=>{let d=i.headers.get("Location"),h=d===null?null:new URL(d,a.url).searchParams.get("state");if(h===null)return A(i,u,a);if(!Ge.test(h))throw new Error(`The authorization redirect's state cannot name the return-to cookie; got ${JSON.stringify(h)}`);let S=new Headers(i.headers);return S.append("Set-Cookie",await v(h).serialize(u)),pe(i,S)},flowOf:async i=>{let u=new URL(i.url).searchParams.get("state");if(u===null||!Ge.test(u))return _e;let a=v(u),d=i.headers.get("Cookie");if(!at(d,a.name))return _e;let h=await a.serialize("",{maxAge:0}),S=await a.parse(d);return typeof S=="string"&&s.has(S)?{path:S,deletion:h}:(r.warn(`The sign-in's return-to cookie ${a.name} names no allowed path; the sign-in returns to the post-login path instead`),{path:void 0,deletion:h})},endFailedFlow:(i,u,a)=>{if(u.deletion===void 0)return i;let d=u.path===void 0?i:A(i,u.path,a),h=new Headers(d.headers);return h.append("Set-Cookie",u.deletion),pe(d,h)}}};var H=require("react-router");var he=3600*24*30,ct=e=>{if(e===void 0)return he;if(!Number.isSafeInteger(e)||e<1)throw new RangeError(`session.maxAge must be a safe integer of seconds >= 1; got ${String(e)}`);return e},ge=e=>e.secure??process.env.NODE_ENV==="production",te=(e,t)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(y=>!y))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 r=ct(e.maxAge),s=t.loginPath??"/auth/login",v=t.postLoginRedirect??"/",A=t.mockUser,G=t.isUserActive,m=Re(t.sessionGeneration,t.logger??j),w=(0,H.createCookieSessionStorage)({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:ge(e),maxAge:r}}),T=async y=>await w.getSession(y.headers.get("Cookie")),i=async y=>{if(A?.enabled(y))return{kind:"signed-in",user:J(A.resolve(y)),session:await T(y)};let k=await T(y),g=k.get(n);if(g===void 0)return{kind:"signed-out"};let f=J(g),[l,R]=await Promise.all([G===void 0?!0:G(f),m===null?"current":m.check(C(g),k.get(N))]);return R==="stale"?{kind:"revoked",session:k}:l?{kind:"signed-in",user:f,session:k}:{kind:"inactive"}},u=async y=>{let k=await i(y);return k.kind==="signed-in"?k.user:void 0},a=async(y,k)=>{let g=await T(y);return g.set(n,k),await w.commitSession(g)},d=async(y,k)=>{let g=m===null?void 0:await m.stamp(C(k)),f=await T(y);return f.set(n,k),g!==void 0&&f.set(N,g),await w.commitSession(f)},h=async y=>{let k=await i(y);switch(k.kind){case"signed-in":return k.user;case"revoked":throw(0,H.redirect)(s,{headers:{"Set-Cookie":await w.destroySession(k.session)}});case"signed-out":case"inactive":throw(0,H.redirect)(s)}};return{sessionStorage:w,sessionKey:n,sessionMaxAgeSeconds:r,sessionGenerationGate:m,getSession:T,resolveSession:i,getSessionUser:u,saveSession:a,saveSignedInSession:d,requireUser:h,requireAdminUser:async y=>{let k=await h(y);if(k.role!=="admin")throw(0,H.redirect)(v);return k},commitSession:w.commitSession,destroySession:w.destroySession}};var ut=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 r=ut.get(t);if(r===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(!r.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}")`},oe=e=>new Response(`Signing out is refused because ${e}: only a navigation that does not come from another site, or a script's request from this origin, signs out.`,{status:403,headers:{"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"}});var re=(e,t,n,r)=>{let s=e.loginPath??"/auth/login",v=e.postLoginRedirect??"/",A=e.postLogoutRedirect??"/",G=ye(e.google.revocationTimeoutMs),m=Oe(e.returnTo,{secrets:e.session.secrets,secure:ge(e.session)},s,r),w=async({request:f})=>{let l=m.requested(f);if(await t.getSessionUser(f))throw(0,K.redirect)(l??v);return{error:new URL(f.url).searchParams.get("error")}},T=async f=>{let l=m.requested(f);try{await n.authenticate("google",f)}catch(R){throw l===void 0||!(R instanceof Response)?R:await m.bindToFlow(R,l,f)}throw(0,K.redirect)(l===void 0?s:ee(s,l))},i=async({request:f})=>(await f.clone().formData()).get("_action")!=="Sign In with Google"?null:await T(f),u=(f,l)=>{switch(f.outcome){case"failed":r.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:`,f.reason);return;case"already-invalid":r.info(`Sign-out found the Google grant of user ${String(l)} already unusable`);return;case"revoked":case"nothing-to-revoke":return}},a=(f,l)=>{f.kind!=="advanced"&&r.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:`,f.error)},d=async(f,l)=>{let R=t.sessionGenerationGate;if(R!==null){if(!q(l)){r.info(`Sign-out found no usable session generation stamp in the session of ${f.provider} user ${f.id}; every guard already rejects that cookie, so the generation is not advanced`);return}a(await R.advance(f,l),f)}},h=async f=>{let l=await t.getSession(f),R=l.get(t.sessionKey),[I]=await Promise.all([we(R,{fetch:e.fetch??globalThis.fetch,timeoutMs:G}),R===void 0?void 0:d(C(R),l.get(N))]);return u(I,R?.id),await t.destroySession(l)},S=async f=>{let l=await h(f),R=new Headers;return R.append("Set-Cookie",l),(0,K.redirect)(A,{headers:R})},y=async({request:f})=>{let l=ne(f);throw l!==void 0?oe(l):await S(f)},k=async f=>{let l=await n.authenticate("google",f),U=(await t.getSession(f)).get(t.sessionKey)?.refreshToken,c={accessToken:l.accessToken,refreshToken:l.refreshToken||U,expirationDateMs:l.expirationDateMs,provider:l.provider},o={id:l.id,displayName:l.displayName,name:l.name,emails:l.emails,...c,role:l.role};return await t.saveSignedInSession(f,o)};return{loginLoader:w,loginAction:i,startGoogleSignIn:T,logoutLoader:y,logout:h,logoutAndRedirect:S,googleCallbackLoader:async({request:f})=>{let l=await m.flowOf(f),R;try{R=await k(f)}catch(U){throw U instanceof Response?m.endFailedFlow(U,l,f):(r.error("Authentication error:",U),m.endFailedFlow((0,K.redirect)(s),l,f))}let I=new Headers;throw I.append("Set-Cookie",R),l.deletion!==void 0&&I.append("Set-Cookie",l.deletion),(0,K.redirect)(l.path??v,{headers:I})}}};var Ie=e=>{let t=e.logger??j,n=te(e.session,{sessionGeneration:e.sessionGeneration,logger:t,mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive}),r=Z(e),s=X(e,n,t),v=B(e,n,s,t),A=re(e,n,r,t);return{authenticator:r,storage:n,authFns:s,sessionStorage:n.sessionStorage,getSession:n.getSession,getSessionUser:n.getSessionUser,saveSession:n.saveSession,requireUser:n.requireUser,requireAdminUser:n.requireAdminUser,commitSession:n.commitSession,destroySession:n.destroySession,sessionMaxAgeSeconds:n.sessionMaxAgeSeconds,authenticate:s.authenticate,refreshedAccessToken:s.refreshedAccessToken,authenticateInLoader:v,...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});
|
package/dist/server.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{redirect as ge}from"react-router";var Ae="https://oauth2.googleapis.com/revoke",Te=5e3;var Pe="google",Ge="invalid_token";var ce=e=>{if(e===void 0)return 5e3;if(!Number.isInteger(e)||e<1||e>2147483647)throw new RangeError(`google.revocationTimeoutMs must be an integer from 1 to 2147483647 (milliseconds); got ${String(e)}`);return e},Ee=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},be=e=>e instanceof Error?e.cause instanceof Error?`${e.message} (${e.cause.message})`:e.message:String(e),Oe=async(e,t,n)=>{try{let s=await t(Ae,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:e}).toString(),signal:n});if(s.ok)return await s.body?.cancel(),{outcome:"revoked"};let a=await _e(s);return s.status===400&&a===Ge?{outcome:"already-invalid"}:{outcome:"failed",reason:a===void 0?`Google answered ${s.status}`:`Google answered ${s.status} ${a}`}}catch(s){return{outcome:"failed",reason:be(s)}}},ue=async(e,t)=>{if(e===void 0)return{outcome:"nothing-to-revoke"};let n=Ee(e);if(n===void 0)return{outcome:"nothing-to-revoke"};if(e.provider!==Pe)return{outcome:"failed",reason:`the session's provider "${String(e.provider)}" has no revocation endpoint`};let s=new AbortController;return await new Promise(a=>{let k=setTimeout(()=>{a({outcome:"failed",reason:`Google did not answer within ${t.timeoutMs} ms`}),s.abort()},t.timeoutMs);Oe(n,t.fetch,s.signal).then(R=>{clearTimeout(k),a(R)})})};var U="generation",fe=15e3,pe=3e3,xe=6e4,j=class extends Error{constructor(t,n){super(t,n),this.name="SessionGenerationUnavailableError"}},x=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),Ue=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return x(e);let t="store"in e?e.store:void 0;if(typeof t!="object"||t===null)return`an object whose store is ${x(t)}`;let n="current"in t?t.current:void 0,s="advance"in t?t.advance:void 0;return`an object whose store.current is ${x(n)} and store.advance is ${x(s)}`},Ne=e=>typeof e=="object"&&e!==null&&"current"in e&&typeof e.current=="function"&&"advance"in e&&typeof e.advance=="function",de=(e,t,n,s)=>{if(t===void 0)return s;if(typeof t!="number"||!Number.isInteger(t)||t<n||t>2147483647)throw new RangeError(`${e} must be an integer from ${n} to ${2147483647} (milliseconds); got ${x(t)}`);return t},Me=e=>{if(e===!1)return!1;let t=e;if(typeof t!="object"||t===null||!("store"in t)||!Ne(t.store))throw new TypeError(`sessionGeneration must be { store, cacheTtlMs?, timeoutMs? } or false; got ${Ue(t)}`);return{store:t.store,cacheTtlMs:de("sessionGeneration.cacheTtlMs","cacheTtlMs"in t?t.cacheTtlMs:void 0,0,fe),timeoutMs:de("sessionGeneration.timeoutMs","timeoutMs"in t?t.timeoutMs:void 0,1,pe)}},$=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,B=e=>typeof e.provider=="string"&&e.provider!==""&&typeof e.id=="string"&&e.id!=="",le=e=>new TypeError(`a session generation identity needs a non-empty provider and id; got provider ${x(e.provider)} and id ${x(e.id)}`),Le=e=>$(e)&&$(e+1),Ce=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 ${x(e)}`),L=e=>({provider:e.provider,id:e.id}),he=(e,t)=>{let n=Me(e);if(n===!1)return null;let{store:s,cacheTtlMs:a,timeoutMs:k}=n,R=new Map,G=new Map,m=new Map,y=new Map,A=Number.NEGATIVE_INFINITY,r=c=>`${c.provider}\0${c.id}`,f=(c,o)=>{let h=R.get(c);if(h!==void 0){if(o-h.at<a)return h;R.delete(c)}},i=(c,o,h)=>{if(h!==void 0&&o.at<=h.answeredAt&&o.value<h.value)return;let P=f(c,performance.now());if(P===void 0){R.set(c,o);return}o.value<P.value||R.set(c,{value:o.value,at:Math.max(P.at,o.at)})},u=c=>{let o=y.get(c);if(o!==void 0)return o.count+=1,o;let h={count:1,floor:void 0};return y.set(c,h),h},p=(c,o)=>{o.count-=1,o.count===0&&y.delete(c)},T=(c,o)=>{c.floor={value:c.floor===void 0?o:Math.max(c.floor.value,o),answeredAt:performance.now()}},S=(c,o)=>{let h=m.get(c);return h===void 0?!1:o<h?!0:(m.delete(c),!1)},w=(c,o)=>{let h=performance.now();return m.set(c,h+a),h-A>=xe&&(A=h,t.warn("Session generation store unavailable; skipping the sign-out generation check:",o)),"unavailable"},g=(c,o,h)=>new Promise((P,_)=>{let{operation:E}=c,O=c.operation==="advance"?c.from+1:0,Re=performance.now(),D=u(h),M=!1,ae=setTimeout(()=>{M=!0,P({kind:"unavailable",error:new j(`sessionGeneration.store.${E} did not settle within ${k} ms`)})},k);new Promise(b=>b(c.operation==="advance"?s.advance(o,c.from):s.current(o))).then(b=>{if(clearTimeout(ae),!($(b)&&b>=O)){p(h,D),M||(M=!0,_(new TypeError(`sessionGeneration.store.${E} must resolve to an integer >= ${O}; got ${x(b)}`)));return}E==="advance"&&(T(D,b),G.delete(h)),i(h,{value:b,at:Re},D.floor),p(h,D),!M&&(M=!0,m.delete(h),P({kind:"value",value:b}))},b=>{if(clearTimeout(ae),p(h,D),!M){if(M=!0,b instanceof j){P({kind:"unavailable",error:b});return}_(b)}})}),l=(c,o,h)=>{let P=G.get(o);if(P!==void 0&&h-P.startedAt<a)return P.read;let _={read:g({operation:"current"},c,o),startedAt:h};G.set(o,_);let E=()=>{G.get(o)===_&&G.delete(o)};return _.read.then(E,E),_.read},d=async(c,o,h)=>{let P=await g({operation:"current"},c,o);return P.kind==="unavailable"?w(o,P.error):h===P.value?"current":"stale"};return{check:async(c,o)=>{if(!($(o)&&B(c)))return"stale";let h=performance.now(),P=r(c),_=f(P,h);if(_!==void 0){if(o===_.value)return"current";if(o<_.value)return"stale"}if(S(P,h))return"unavailable";if(_!==void 0)return await d(c,P,o);let E=await l(c,P,h);return E.kind==="unavailable"?w(P,E.error):o===E.value?"current":o<E.value?"stale":await d(c,P,o)},stamp:async c=>{if(!B(c))throw le(c);let o=await g({operation:"current"},c,r(c));if(o.kind==="unavailable")throw o.error;return o.value},advance:async(c,o)=>{if(!B(c))return{kind:"failed",error:le(c)};if(!Le(o))return{kind:"failed",error:Ce(o)};try{let h=await g({operation:"advance",from:o},c,r(c));return h.kind==="value"?{kind:"advanced",generation:h.value}:{kind:"unavailable",error:h.error}}catch(h){return{kind:"failed",error:h}}}}};var C=class extends Error{constructor(t){super(t),this.name="TokenRefreshError"}},H=class extends C{constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},F=class extends Error{constructor(t){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=t}},$e=["access_token","expires_in"],J=(e,t,n)=>{let s=e.loginPath??"/auth/login",a=t.sessionKey,k=async m=>{let A=m.get(a)?.refreshToken;if(!A)throw new Error("Refresh token not found in session");try{let r="https://www.googleapis.com/oauth2/v4/token",f={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:A},u=await(e.fetch??globalThis.fetch)(r,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(f)});if(!u.ok){let g=await u.json().catch(()=>{});if(u.status===400&&typeof g=="object"&&!!g&&"error"in g&&g.error==="invalid_grant")throw new H;let d=typeof g=="object"&&g&&"error_description"in g?String(g.error_description):"Unknown error";throw new C(`Google token refresh failed: ${u.status} ${d}`)}let p=await u.json(),T=$e.filter(g=>!p?.[g]);if(T.length>0)throw n.error("Invalid token response from Google; missing or empty keys:",T.join(", ")),new Error("Invalid token response from Google");let{access_token:S,expires_in:w}=p;return{accessToken:S,refreshToken:A,expirationDateMs:Number(Date.now())+w*1e3}}catch(r){if(r instanceof C)throw r;let f=r instanceof Error?r.message:"Unknown error";throw new C(`Failed to refresh Google access token: ${f}`)}},R=async m=>{let A=m.get(a).provider;if(!A)throw new Error("Provider not found in session");if(A==="google")return await k(m);throw new Error("Provider not supported")};return{authenticate:async(m,y,A)=>{let{failureRedirect:r}=A||{},f=i=>{if(r===null)return new F(i);if(r==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let u=r??s;return i!==void 0?ge(u,{headers:{"Set-Cookie":i}}):ge(u)};try{if(e.mockUser?.enabled(m)){let{accessToken:w,refreshToken:g,expirationDateMs:l}=e.mockUser.resolve(m);return{accessToken:w,refreshToken:g,expirationDateMs:l}}let i=y.get(a),u=t.sessionGenerationGate;if(i!==void 0&&u!==null&&await u.check(L(i),y.get(U))==="stale")throw f(await t.destroySession(y));if(!(i?.accessToken&&i.expirationDateMs))throw f();let{accessToken:p,refreshToken:T,expirationDateMs:S}=i;if(S<Date.now())throw T?new Error("Expired"):f();return{accessToken:p,refreshToken:T,expirationDateMs:S}}catch(i){if(i instanceof Error&&i.message==="Expired")try{let u=await R(y),p=y.get(a);return y.set(a,{...p,...u}),u}catch(u){if(u instanceof H)n.warn("Google refresh token invalid or revoked");else{let T=u instanceof Error?u.message:"Unknown error";n.error("Failed to refresh token:",T)}let p=await t.destroySession(y);throw f(p)}throw i}},refreshedAccessToken:R}};import{redirect as me}from"react-router";var K=({refreshToken:e,...t})=>t;var z=(e,t,n,s)=>{let a=new Map,k=new Map,R=async r=>{let f=a.get(r);if(f!==void 0)return f;let i=k.get(r);if(i!==void 0)return i;let u=(async()=>{try{let p=e.getUserPhoto?await e.getUserPhoto(r):"";return a.set(r,p),p}catch(p){throw a.delete(r),p}finally{k.delete(r)}})();return k.set(r,u),u},G=new WeakMap,m=async r=>{e.warmup&&await e.warmup();let f=await t.resolveSession(r);if(f.kind==="revoked")return{kind:"unauthenticated",cookie:await t.destroySession(f.session)};if(f.kind!=="signed-in")return{kind:"unauthenticated"};let{user:i,session:u}=f,p;try{p=await n.authenticate(r,u,{failureRedirect:null})}catch(v){if(v instanceof F)return v.setCookie!==void 0?{kind:"unauthenticated",cookie:v.setCookie}:{kind:"unauthenticated"};throw s.error("Error in authenticateInLoader:",v),v}let T={accessToken:p.accessToken,refreshToken:p.refreshToken,expirationDateMs:p.expirationDateMs,provider:i.provider},S={id:i.id,displayName:i.displayName,name:i.name,emails:i.emails,...T,role:i.role},w=await R(i.id),g=K({...i,...T,photo:w}),d=p.accessToken!==i.accessToken?await t.saveSession(r,S):void 0;return d!==void 0?{kind:"authenticated",user:g,cookie:d}:{kind:"authenticated",user:g}},y=r=>{let f=G.get(r);if(f!==void 0)return f;let i=m(r);return G.set(r,i),i};async function A(r,f){let{failureRedirect:i}=f;if(i==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let u=await y(r);if(u.kind==="authenticated")return u.cookie!==void 0?{user:u.user,cookie:u.cookie}:{user:u.user};if(i===null)return u.cookie!==void 0?{cookie:u.cookie}:{};throw u.cookie!==void 0?me(i,{headers:{"Set-Cookie":u.cookie}}):me(i)}return A};import{resolveAuthMessages as He}from"@aiquants/auth-core";import{redirect as W}from"react-router";import{Authenticator as Ke}from"remix-auth";import{OAuth2Strategy as Fe}from"remix-auth-oauth2";var qe=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],De="google",je="https://www.googleapis.com/oauth2/v3/userinfo",V=class extends Fe{constructor({clientId:n,clientSecret:s,redirectURI:a,scopes:k,accessType:R,includeGrantedScopes:G,prompt:m,hd:y,loginHint:A,additionalScopes:r},f){let i=k??qe;super({clientId:n,clientSecret:s,redirectURI:a,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:i},f);this.name=De;this.scopes=i,this.accessType=R??"online",this.includeGrantedScopes=G??!1,this.prompt=m,this.hd=y,this.loginHint=A,this.additionalScopes=r}authorizationParams(n,s){n.set("access_type",this.accessType),n.set("include_granted_scopes",String(this.includeGrantedScopes));let a=s===void 0||this.additionalScopes===void 0?[]:this.additionalScopes(s);for(let R of a)if(R===""||/\s/u.test(R))throw new RangeError(`[auth-react-router] an additional scope must be a non-empty string without white space; got ${JSON.stringify(R)}`);let k=[...new Set([...this.scopes,...a])];return k.length>0&&n.set("scope",k.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 s=await fetch(je,{headers:{Authorization:`Bearer ${n.accessToken()}`}});if(!s.ok)throw new Error(`Failed to fetch user profile: ${s.statusText}`);let a=await s.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 q={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var Q=e=>{let t=e.logger??q,n=He(e.messages),s=e.loginPath??"/auth/login",a=new V({clientId:e.google.clientId,clientSecret:e.google.clientSecret,redirectURI:e.google.redirectURI,scopes:e.google.scopes,accessType:e.google.accessType??"offline",includeGrantedScopes:e.google.includeGrantedScopes??!0,prompt:e.google.prompt??"consent",additionalScopes:e.google.additionalScopes},async({request:R,tokens:G})=>{let{access_token:m,refresh_token:y,expires_in:A,scope:r,id_token:f}=G.data,{_json:{sub:i,email:u,picture:p,hd:T,email_verified:S},photos:w,...g}=await V.userProfile(G),{id:l,displayName:d,name:{familyName:v,givenName:I},emails:N}=g,c="google";if(m===void 0||y===void 0||A===void 0||r===void 0||l===void 0||d===void 0||i===void 0||u===void 0||S===void 0){if(S===!1){let h=encodeURIComponent(n.emailNotVerified);throw W(`${s}?error=${h}`)}let o=encodeURIComponent(n.googleFailed);throw W(`${s}?error=${o}`)}t.info("Authenticated on Google: ",g.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(c,m)){t.error("Backend verification returned false for user:",g.displayName);let O=encodeURIComponent(n.backendFailed);throw W(`${s}?error=${O}`)}t.info("Authenticated on Backend: ",g.displayName)}let o=g.emails[0]?.value;if(!await e.isEmailAllowed(o)){let E=new Error("You are not allowed to access this application");throw t.error(E),E}if(e.isUserActive&&!await e.isUserActive(g)){let E=new Error("You are not allowed to access this application");throw t.error("Deactivated account attempted to sign in:",o),E}e.backendAuth&&await e.backendAuth.signup(c,m,g),t.info("Authenticated complete: ",g.displayName);let h=Date.now()+A*1e3;return{...g,...{accessToken:m,refreshToken:y,expirationDateMs:h,provider:c},photo:p}}catch(o){let h=o;typeof o=="object"&&o!==null&&"cause"in o&&(h=o.cause||o),t.error("Error during backend authentication or subsequent processing:",h);let P=n.unexpected,_=!1;if(typeof o=="object"&&o!==null&&"cause"in o){let O=o.cause;O&&typeof O=="object"&&"message"in O&&typeof O.message=="string"&&O.message.includes("getaddrinfo ENOTFOUND")&&(P=n.backendUnreachable,_=!0)}if(!_&&o instanceof Error&&o.message.includes("You are not allowed to access this application")&&(P=n.notAllowed,_=!0),!_&&o instanceof Response&&o.headers.get("Location")?.startsWith(s))throw o;let E=encodeURIComponent(P);throw W(`${s}?error=${E}`)}}),k=new Ke;return k.use(a),k};import{redirect as Y}from"react-router";var Z="returnTo",X=(e,t)=>{let n=e.indexOf("?"),s=n===-1?e:e.slice(0,n),a=new URLSearchParams(n===-1?"":e.slice(n+1));return a.set(Z,t),`${s}?${a.toString()}`};import{createCookie as Ve}from"react-router";var Ye="__return_to.",We=300,Se=/^[A-Za-z0-9_-]{1,128}$/,ye="https://return-to.invalid",we=Object.freeze({path:void 0,deletion:void 0}),Xe=e=>{if(e.includes("%"))return!1;let t=new URL(e,ye);return t.origin===ye&&t.pathname===e},Be=e=>{if(e===void 0)return new Set;let t=e;if(typeof t!="object"||t===null||!Array.isArray(t.allowedPaths))throw new TypeError(`returnTo must be { allowedPaths: string[] }; got ${JSON.stringify(t)}`);let n=t.allowedPaths;if(n.length===0)throw new RangeError("returnTo.allowedPaths must name at least one path; omit returnTo to allow none");for(let s of n){if(typeof s!="string")throw new TypeError(`returnTo.allowedPaths must hold strings; got ${JSON.stringify(s)}`);if(!Xe(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)}`)}return new Set(n)},Je=()=>new Response("The sign-in's return-to is not a path this application allows.",{status:400,headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-store"}}),ze=(e,t)=>e===null?!1:e.split(";").some(n=>n.trim().startsWith(`${t}=`)),ee=(e,t)=>new Response(e.body,{status:e.status,statusText:e.statusText,headers:t}),ke=(e,t,n,s)=>{let a=Be(e),k=r=>Ve(`${Ye}${r}`,{secrets:[...t.secrets],httpOnly:!0,sameSite:"lax",path:"/",secure:t.secure,maxAge:We}),R=(r,f,i)=>{let u=r.headers.get("Location");if(u===null)return r;let p=new URL(u,i.url);if(p.origin!==new URL(i.url).origin||p.pathname!==n)return r;let T=new Headers(r.headers);return T.set("Location",`${X(`${p.pathname}${p.search}`,f)}${p.hash}`),ee(r,T)};return{requested:r=>{let f=new URL(r.url).searchParams.getAll(Z);if(f.length!==0){if(f.length===1&&a.has(f[0]))return f[0];throw Je()}},bindToFlow:async(r,f,i)=>{let u=r.headers.get("Location"),p=u===null?null:new URL(u,i.url).searchParams.get("state");if(p===null)return R(r,f,i);if(!Se.test(p))throw new Error(`The authorization redirect's state cannot name the return-to cookie; got ${JSON.stringify(p)}`);let T=new Headers(r.headers);return T.append("Set-Cookie",await k(p).serialize(f)),ee(r,T)},flowOf:async r=>{let f=new URL(r.url).searchParams.get("state");if(f===null||!Se.test(f))return we;let i=k(f),u=r.headers.get("Cookie");if(!ze(u,i.name))return we;let p=await i.serialize("",{maxAge:0}),T=await i.parse(u);return typeof T=="string"&&a.has(T)?{path:T,deletion:p}:(s.warn(`The sign-in's return-to cookie ${i.name} names no allowed path; the sign-in returns to the post-login path instead`),{path:void 0,deletion:p})},endFailedFlow:(r,f,i)=>{if(f.deletion===void 0)return r;let u=f.path===void 0?r:R(r,f.path,i),p=new Headers(u.headers);return p.append("Set-Cookie",f.deletion),ee(u,p)}}};import{createCookieSessionStorage as Qe,redirect as te}from"react-router";var ve=3600*24*30,Ze=e=>{if(e===void 0)return ve;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",oe=(e,t)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(S=>!S))throw new Error("REMIX_SESSION_SECRET must be set");let n=e.sessionKey??"user";if(n===U)throw new RangeError(`session.sessionKey must not be ${JSON.stringify(U)}, the key the session generation is stored under; got ${JSON.stringify(n)}`);let s=Ze(e.maxAge),a=t.loginPath??"/auth/login",k=t.postLoginRedirect??"/",R=t.mockUser,G=t.isUserActive,m=he(t.sessionGeneration,t.logger??q),y=Qe({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:ne(e),maxAge:s}}),A=async S=>await y.getSession(S.headers.get("Cookie")),r=async S=>{if(R?.enabled(S))return{kind:"signed-in",user:K(R.resolve(S)),session:await A(S)};let w=await A(S),g=w.get(n);if(g===void 0)return{kind:"signed-out"};let l=K(g),[d,v]=await Promise.all([G===void 0?!0:G(l),m===null?"current":m.check(L(g),w.get(U))]);return v==="stale"?{kind:"revoked",session:w}:d?{kind:"signed-in",user:l,session:w}:{kind:"inactive"}},f=async S=>{let w=await r(S);return w.kind==="signed-in"?w.user:void 0},i=async(S,w)=>{let g=await A(S);return g.set(n,w),await y.commitSession(g)},u=async(S,w)=>{let g=m===null?void 0:await m.stamp(L(w)),l=await A(S);return l.set(n,w),g!==void 0&&l.set(U,g),await y.commitSession(l)},p=async S=>{let w=await r(S);switch(w.kind){case"signed-in":return w.user;case"revoked":throw te(a,{headers:{"Set-Cookie":await y.destroySession(w.session)}});case"signed-out":case"inactive":throw te(a)}};return{sessionStorage:y,sessionKey:n,sessionMaxAgeSeconds:s,sessionGenerationGate:m,getSession:A,resolveSession:r,getSessionUser:f,saveSession:i,saveSignedInSession:u,requireUser:p,requireAdminUser:async S=>{let w=await p(S);if(w.role!=="admin")throw te(k);return w},commitSession:y.commitSession,destroySession:y.destroySession}};var et=new Map([["document",new Set(["none","same-origin","same-site"])],["empty",new Set(["same-origin"])]]),re=e=>{let t=e.headers.get("Sec-Fetch-Dest");if(t!==null){let s=et.get(t);if(s===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(!s.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}")`},se=e=>new Response(`Signing out is refused because ${e}: only a navigation that does not come from another site, or a script's request from this origin, signs out.`,{status:403,headers:{"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"}});var ie=(e,t,n,s)=>{let a=e.loginPath??"/auth/login",k=e.postLoginRedirect??"/",R=e.postLogoutRedirect??"/",G=ce(e.google.revocationTimeoutMs),m=ke(e.returnTo,{secrets:e.session.secrets,secure:ne(e.session)},a,s),y=async({request:l})=>{let d=m.requested(l);if(await t.getSessionUser(l))throw Y(d??k);return{error:new URL(l.url).searchParams.get("error")}},A=async l=>{let d=m.requested(l);try{await n.authenticate("google",l)}catch(v){throw d===void 0||!(v instanceof Response)?v:await m.bindToFlow(v,d,l)}throw Y(d===void 0?a:X(a,d))},r=async({request:l})=>(await l.clone().formData()).get("_action")!=="Sign In with Google"?null:await A(l),f=(l,d)=>{switch(l.outcome){case"failed":s.error(`Sign-out could not revoke the Google grant of user ${String(d)}; the session cookie is destroyed, but the grant stays valid until it expires or is revoked elsewhere:`,l.reason);return;case"already-invalid":s.info(`Sign-out found the Google grant of user ${String(d)} already unusable`);return;case"revoked":case"nothing-to-revoke":return}},i=(l,d)=>{l.kind!=="advanced"&&s.error(`Sign-out could not advance the session generation of ${d.provider} user ${d.id}; a session cookie refreshed before this sign-out stays valid until a later sign-out advances the generation or the cookie expires:`,l.error)},u=async(l,d)=>{let v=t.sessionGenerationGate;if(v!==null){if(!$(d)){s.info(`Sign-out found no usable session generation stamp in the session of ${l.provider} user ${l.id}; every guard already rejects that cookie, so the generation is not advanced`);return}i(await v.advance(l,d),l)}},p=async l=>{let d=await t.getSession(l),v=d.get(t.sessionKey),[I]=await Promise.all([ue(v,{fetch:e.fetch??globalThis.fetch,timeoutMs:G}),v===void 0?void 0:u(L(v),d.get(U))]);return f(I,v?.id),await t.destroySession(d)},T=async l=>{let d=await p(l),v=new Headers;return v.append("Set-Cookie",d),Y(R,{headers:v})},S=async({request:l})=>{let d=re(l);throw d!==void 0?se(d):await T(l)},w=async l=>{let d=await n.authenticate("google",l),N=(await t.getSession(l)).get(t.sessionKey)?.refreshToken,c={accessToken:d.accessToken,refreshToken:d.refreshToken||N,expirationDateMs:d.expirationDateMs,provider:d.provider},o={id:d.id,displayName:d.displayName,name:d.name,emails:d.emails,...c,role:d.role};return await t.saveSignedInSession(l,o)};return{loginLoader:y,loginAction:r,startGoogleSignIn:A,logoutLoader:S,logout:p,logoutAndRedirect:T,googleCallbackLoader:async({request:l})=>{let d=await m.flowOf(l),v;try{v=await w(l)}catch(N){throw N instanceof Response?m.endFailedFlow(N,d,l):(s.error("Authentication error:",N),m.endFailedFlow(Y(a),d,l))}let I=new Headers;throw I.append("Set-Cookie",v),d.deletion!==void 0&&I.append("Set-Cookie",d.deletion),Y(d.path??k,{headers:I})}}};var tt=e=>{let t=e.logger??q,n=oe(e.session,{sessionGeneration:e.sessionGeneration,logger:t,mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive}),s=Q(e),a=J(e,n,t),k=z(e,n,a,t),R=ie(e,n,s,t);return{authenticator:s,storage:n,authFns:a,sessionStorage:n.sessionStorage,getSession:n.getSession,getSessionUser:n.getSessionUser,saveSession:n.saveSession,requireUser:n.requireUser,requireAdminUser:n.requireAdminUser,commitSession:n.commitSession,destroySession:n.destroySession,sessionMaxAgeSeconds:n.sessionMaxAgeSeconds,authenticate:a.authenticate,refreshedAccessToken:a.refreshedAccessToken,authenticateInLoader:k,...R}};export{F as AuthRequiredError,Te as DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS,fe as DEFAULT_SESSION_GENERATION_CACHE_TTL_MS,pe as DEFAULT_SESSION_GENERATION_TIMEOUT_MS,ve as DEFAULT_SESSION_MAX_AGE_SECONDS,H as GoogleInvalidGrantError,j as SessionGenerationUnavailableError,C as TokenRefreshError,ie as createAuthHandlers,tt as createAuthServer,oe as createAuthSessionStorage,J as createAuthenticate,z as createAuthenticateInLoader,Q as createGoogleAuthenticator,re as signOutRefusal,se as signOutRefusalResponse};
|
|
1
|
+
import{GOOGLE_PROVIDER as Fe}from"@aiquants/auth-core";import{redirect as Se}from"react-router";import{GOOGLE_PROVIDER as Pe}from"@aiquants/auth-core";var Ge="https://oauth2.googleapis.com/revoke",ue=5e3,j=2147483647,Ee="invalid_token",_e=400,de=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},be=e=>{if(typeof e.refreshToken=="string"&&e.refreshToken!=="")return e.refreshToken;if(typeof e.accessToken=="string"&&e.accessToken!=="")return e.accessToken},Oe=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},Ie=e=>e instanceof Error?e.cause instanceof Error?`${e.message} (${e.cause.message})`:e.message:String(e),xe=async(e,t,n)=>{try{let r=await t(Ge,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:e}).toString(),signal:n});if(r.ok)return await r.body?.cancel(),{outcome:"revoked"};let a=await Oe(r);return r.status===_e&&a===Ee?{outcome:"already-invalid"}:{outcome:"failed",reason:a===void 0?`Google answered ${r.status}`:`Google answered ${r.status} ${a}`}}catch(r){return{outcome:"failed",reason:Ie(r)}}},le=async(e,t)=>{if(e===void 0)return{outcome:"nothing-to-revoke"};let n=be(e);if(n===void 0)return{outcome:"nothing-to-revoke"};if(e.provider!==Pe)return{outcome:"failed",reason:`the session's provider "${String(e.provider)}" has no revocation endpoint`};let r=new AbortController;return await new Promise(a=>{let v=setTimeout(()=>{a({outcome:"failed",reason:`Google did not answer within ${t.timeoutMs} ms`}),r.abort()},t.timeoutMs);xe(n,t.fetch,r.signal).then(A=>{clearTimeout(v),a(A)})})};var N="generation",he=15e3,ge=3e3,Ne=6e4,H=class extends Error{constructor(t,n){super(t,n),this.name="SessionGenerationUnavailableError"}},x=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),Ue=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return x(e);let t="store"in e?e.store:void 0;if(typeof t!="object"||t===null)return`an object whose store is ${x(t)}`;let n="current"in t?t.current:void 0,r="advance"in t?t.advance:void 0;return`an object whose store.current is ${x(n)} and store.advance is ${x(r)}`},Le=e=>typeof e=="object"&&e!==null&&"current"in e&&typeof e.current=="function"&&"advance"in e&&typeof e.advance=="function",fe=(e,t,n,r)=>{if(t===void 0)return r;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 ${x(t)}`);return t},Me=e=>{if(e===!1)return!1;let t=e;if(typeof t!="object"||t===null||!("store"in t)||!Le(t.store))throw new TypeError(`sessionGeneration must be { store, cacheTtlMs?, timeoutMs? } or false; got ${Ue(t)}`);return{store:t.store,cacheTtlMs:fe("sessionGeneration.cacheTtlMs","cacheTtlMs"in t?t.cacheTtlMs:void 0,0,he),timeoutMs:fe("sessionGeneration.timeoutMs","timeoutMs"in t?t.timeoutMs:void 0,1,ge)}},$=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,X=e=>typeof e.provider=="string"&&e.provider!==""&&typeof e.id=="string"&&e.id!=="",pe=e=>new TypeError(`a session generation identity needs a non-empty provider and id; got provider ${x(e.provider)} and id ${x(e.id)}`),Ce=e=>$(e)&&$(e+1),$e=e=>new TypeError(`a session generation advance needs the signed-out session's stamp, an integer from 0 to ${Number.MAX_SAFE_INTEGER-1}; got ${x(e)}`),M=e=>({provider:e.provider,id:e.id}),me=(e,t)=>{let n=Me(e);if(n===!1)return null;let{store:r,cacheTtlMs:a,timeoutMs:v}=n,A=new Map,G=new Map,m=new Map,w=new Map,T=Number.NEGATIVE_INFINITY,s=c=>`${c.provider}\0${c.id}`,u=(c,o)=>{let p=A.get(c);if(p!==void 0){if(o-p.at<a)return p;A.delete(c)}},i=(c,o,p)=>{if(p!==void 0&&o.at<=p.answeredAt&&o.value<p.value)return;let P=u(c,performance.now());if(P===void 0){A.set(c,o);return}o.value<P.value||A.set(c,{value:o.value,at:Math.max(P.at,o.at)})},d=c=>{let o=w.get(c);if(o!==void 0)return o.count+=1,o;let p={count:1,floor:void 0};return w.set(c,p),p},h=(c,o)=>{o.count-=1,o.count===0&&w.delete(c)},S=(c,o)=>{c.floor={value:c.floor===void 0?o:Math.max(c.floor.value,o),answeredAt:performance.now()}},y=(c,o)=>{let p=m.get(c);return p===void 0?!1:o<p?!0:(m.delete(c),!1)},k=(c,o)=>{let p=performance.now();return m.set(c,p+a),p-T>=Ne&&(T=p,t.warn("Session generation store unavailable; skipping the sign-out generation check:",o)),"unavailable"},g=(c,o,p)=>new Promise((P,_)=>{let{operation:E}=c,O=c.operation==="advance"?c.from+1:0,Te=performance.now(),D=d(p),L=!1,ce=setTimeout(()=>{L=!0,P({kind:"unavailable",error:new H(`sessionGeneration.store.${E} did not settle within ${v} ms`)})},v);new Promise(b=>b(c.operation==="advance"?r.advance(o,c.from):r.current(o))).then(b=>{if(clearTimeout(ce),!($(b)&&b>=O)){h(p,D),L||(L=!0,_(new TypeError(`sessionGeneration.store.${E} must resolve to an integer >= ${O}; got ${x(b)}`)));return}E==="advance"&&(S(D,b),G.delete(p)),i(p,{value:b,at:Te},D.floor),h(p,D),!L&&(L=!0,m.delete(p),P({kind:"value",value:b}))},b=>{if(clearTimeout(ce),h(p,D),!L){if(L=!0,b instanceof H){P({kind:"unavailable",error:b});return}_(b)}})}),f=(c,o,p)=>{let P=G.get(o);if(P!==void 0&&p-P.startedAt<a)return P.read;let _={read:g({operation:"current"},c,o),startedAt:p};G.set(o,_);let E=()=>{G.get(o)===_&&G.delete(o)};return _.read.then(E,E),_.read},l=async(c,o,p)=>{let P=await g({operation:"current"},c,o);return P.kind==="unavailable"?k(o,P.error):p===P.value?"current":"stale"};return{check:async(c,o)=>{if(!($(o)&&X(c)))return"stale";let p=performance.now(),P=s(c),_=u(P,p);if(_!==void 0){if(o===_.value)return"current";if(o<_.value)return"stale"}if(y(P,p))return"unavailable";if(_!==void 0)return await l(c,P,o);let E=await f(c,P,p);return E.kind==="unavailable"?k(P,E.error):o===E.value?"current":o<E.value?"stale":await l(c,P,o)},stamp:async c=>{if(!X(c))throw pe(c);let o=await g({operation:"current"},c,s(c));if(o.kind==="unavailable")throw o.error;return o.value},advance:async(c,o)=>{if(!X(c))return{kind:"failed",error:pe(c)};if(!Ce(o))return{kind:"failed",error:$e(o)};try{let p=await g({operation:"advance",from:o},c,s(c));return p.kind==="value"?{kind:"advanced",generation:p.value}:{kind:"unavailable",error:p.error}}catch(p){return{kind:"failed",error:p}}}}};var C=class extends Error{constructor(t){super(t),this.name="TokenRefreshError"}},K=class extends C{constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},F=class extends Error{constructor(t){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=t}},qe=["access_token","expires_in"],B=(e,t,n)=>{let r=e.loginPath??"/auth/login",a=t.sessionKey,v=async m=>{let T=m.get(a)?.refreshToken;if(!T)throw new Error("Refresh token not found in session");try{let s="https://www.googleapis.com/oauth2/v4/token",u={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:T},d=await(e.fetch??globalThis.fetch)(s,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(u)});if(!d.ok){let g=await d.json().catch(()=>{});if(d.status===400&&typeof g=="object"&&!!g&&"error"in g&&g.error==="invalid_grant")throw new K;let l=typeof g=="object"&&g&&"error_description"in g?String(g.error_description):"Unknown error";throw new C(`Google token refresh failed: ${d.status} ${l}`)}let h=await d.json(),S=qe.filter(g=>!h?.[g]);if(S.length>0)throw n.error("Invalid token response from Google; missing or empty keys:",S.join(", ")),new Error("Invalid token response from Google");let{access_token:y,expires_in:k}=h;return{accessToken:y,refreshToken:T,expirationDateMs:Number(Date.now())+k*1e3}}catch(s){if(s instanceof C)throw s;let u=s instanceof Error?s.message:"Unknown error";throw new C(`Failed to refresh Google access token: ${u}`)}},A=async m=>{let T=m.get(a).provider;if(!T)throw new Error("Provider not found in session");if(T===Fe)return await v(m);throw new Error("Provider not supported")};return{authenticate:async(m,w,T)=>{let{failureRedirect:s}=T||{},u=i=>{if(s===null)return new F(i);if(s==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let d=s??r;return i!==void 0?Se(d,{headers:{"Set-Cookie":i}}):Se(d)};try{if(e.mockUser?.enabled(m)){let{accessToken:k,refreshToken:g,expirationDateMs:f}=e.mockUser.resolve(m);return{accessToken:k,refreshToken:g,expirationDateMs:f}}let i=w.get(a),d=t.sessionGenerationGate;if(i!==void 0&&d!==null&&await d.check(M(i),w.get(N))==="stale")throw u(await t.destroySession(w));if(!(i?.accessToken&&i.expirationDateMs))throw u();let{accessToken:h,refreshToken:S,expirationDateMs:y}=i;if(y<Date.now())throw S?new Error("Expired"):u();return{accessToken:h,refreshToken:S,expirationDateMs:y}}catch(i){if(i instanceof Error&&i.message==="Expired")try{let d=await A(w),h=w.get(a);return w.set(a,{...h,...d}),d}catch(d){if(d instanceof K)n.warn("Google refresh token invalid or revoked");else{let S=d instanceof Error?d.message:"Unknown error";n.error("Failed to refresh token:",S)}let h=await t.destroySession(w);throw u(h)}throw i}},refreshedAccessToken:A}};import{redirect as ye}from"react-router";var V=({refreshToken:e,...t})=>t;var Q=(e,t,n,r)=>{let a=new Map,v=new Map,A=async s=>{let u=JSON.stringify([s.provider,s.id]),i=a.get(u);if(i!==void 0)return i;let d=v.get(u);if(d!==void 0)return d;let h=(async()=>{try{let S=e.getUserPhoto?await e.getUserPhoto(s):"";return a.set(u,S),S}catch(S){throw a.delete(u),S}finally{v.delete(u)}})();return v.set(u,h),h},G=new WeakMap,m=async s=>{e.warmup&&await e.warmup();let u=await t.resolveSession(s);if(u.kind==="revoked")return{kind:"unauthenticated",cookie:await t.destroySession(u.session)};if(u.kind!=="signed-in")return{kind:"unauthenticated"};let{user:i,session:d}=u,h;try{h=await n.authenticate(s,d,{failureRedirect:null})}catch(R){if(R instanceof F)return R.setCookie!==void 0?{kind:"unauthenticated",cookie:R.setCookie}:{kind:"unauthenticated"};throw r.error("Error in authenticateInLoader:",R),R}let S={accessToken:h.accessToken,refreshToken:h.refreshToken,expirationDateMs:h.expirationDateMs,provider:i.provider},y={id:i.id,displayName:i.displayName,name:i.name,emails:i.emails,...S,role:i.role},k=await A(i),g=V({...i,...S,photo:k}),l=h.accessToken!==i.accessToken?await t.saveSession(s,y):void 0;return l!==void 0?{kind:"authenticated",user:g,cookie:l}:{kind:"authenticated",user:g}},w=s=>{let u=G.get(s);if(u!==void 0)return u;let i=m(s);return G.set(s,i),i};async function T(s,u){let{failureRedirect:i}=u;if(i==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let d=await w(s);if(d.kind==="authenticated")return d.cookie!==void 0?{user:d.user,cookie:d.cookie}:{user:d.user};if(i===null)return d.cookie!==void 0?{cookie:d.cookie}:{};throw d.cookie!==void 0?ye(i,{headers:{"Set-Cookie":d.cookie}}):ye(i)}return T};import{GOOGLE_PROVIDER as Ve,resolveAuthMessages as Ye}from"@aiquants/auth-core";import{redirect as W}from"react-router";import{Authenticator as Je}from"remix-auth";import{OAuth2Strategy as De}from"remix-auth-oauth2";var je=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],He="google",Ke="https://www.googleapis.com/oauth2/v3/userinfo",Y=class extends De{constructor({clientId:n,clientSecret:r,redirectURI:a,scopes:v,accessType:A,includeGrantedScopes:G,prompt:m,hd:w,loginHint:T,additionalScopes:s},u){let i=v??je;super({clientId:n,clientSecret:r,redirectURI:a,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:i},u);this.name=He;this.scopes=i,this.accessType=A??"online",this.includeGrantedScopes=G??!1,this.prompt=m,this.hd=w,this.loginHint=T,this.additionalScopes=s}authorizationParams(n,r){n.set("access_type",this.accessType),n.set("include_granted_scopes",String(this.includeGrantedScopes));let a=r===void 0||this.additionalScopes===void 0?[]:this.additionalScopes(r);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 v=[...new Set([...this.scopes,...a])];return v.length>0&&n.set("scope",v.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 r=await fetch(Ke,{headers:{Authorization:`Bearer ${n.accessToken()}`}});if(!r.ok)throw new Error(`Failed to fetch user profile: ${r.statusText}`);let a=await r.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 q={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var Z=e=>{let t=e.logger??q,n=Ye(e.messages),r=e.loginPath??"/auth/login",a=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:A,tokens:G})=>{let{access_token:m,refresh_token:w,expires_in:T,scope:s,id_token:u}=G.data,{_json:{sub:i,email:d,picture:h,hd:S,email_verified:y},photos:k,...g}=await Y.userProfile(G),{id:f,displayName:l,name:{familyName:R,givenName:I},emails:U}=g,c=Ve;if(m===void 0||w===void 0||T===void 0||s===void 0||f===void 0||l===void 0||i===void 0||d===void 0||y===void 0){if(y===!1){let p=encodeURIComponent(n.emailNotVerified);throw W(`${r}?error=${p}`)}let o=encodeURIComponent(n.googleFailed);throw W(`${r}?error=${o}`)}t.info("Authenticated on Google: ",g.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(c,m)){t.error("Backend verification returned false for user:",g.displayName);let O=encodeURIComponent(n.backendFailed);throw W(`${r}?error=${O}`)}t.info("Authenticated on Backend: ",g.displayName)}let o=g.emails[0]?.value;if(!await e.isEmailAllowed(o)){let E=new Error("You are not allowed to access this application");throw t.error(E),E}if(e.isUserActive&&!await e.isUserActive({...g,provider:c})){let E=new Error("You are not allowed to access this application");throw t.error("Deactivated account attempted to sign in:",o),E}e.backendAuth&&await e.backendAuth.signup(c,m,g),t.info("Authenticated complete: ",g.displayName);let p=Date.now()+T*1e3;return{...g,...{accessToken:m,refreshToken:w,expirationDateMs:p,provider:c},photo:h}}catch(o){let p=o;typeof o=="object"&&o!==null&&"cause"in o&&(p=o.cause||o),t.error("Error during backend authentication or subsequent processing:",p);let P=n.unexpected,_=!1;if(typeof o=="object"&&o!==null&&"cause"in o){let O=o.cause;O&&typeof O=="object"&&"message"in O&&typeof O.message=="string"&&O.message.includes("getaddrinfo ENOTFOUND")&&(P=n.backendUnreachable,_=!0)}if(!_&&o instanceof Error&&o.message.includes("You are not allowed to access this application")&&(P=n.notAllowed,_=!0),!_&&o instanceof Response&&o.headers.get("Location")?.startsWith(r))throw o;let E=encodeURIComponent(P);throw W(`${r}?error=${E}`)}}),v=new Je;return v.use(a),v};import{redirect as J}from"react-router";var ee="returnTo",z=(e,t)=>{let n=e.indexOf("?"),r=n===-1?e:e.slice(0,n),a=new URLSearchParams(n===-1?"":e.slice(n+1));return a.set(ee,t),`${r}?${a.toString()}`};import{createCookie as We}from"react-router";var ze="__return_to.",Xe=300,we=/^[A-Za-z0-9_-]{1,128}$/,ke="https://return-to.invalid",ve=Object.freeze({path:void 0,deletion:void 0}),Be=e=>{if(e.includes("%"))return!1;let t=new URL(e,ke);return t.origin===ke&&t.pathname===e},Qe=e=>{if(e===void 0)return new Set;let t=e;if(typeof t!="object"||t===null||!Array.isArray(t.allowedPaths))throw new TypeError(`returnTo must be { allowedPaths: string[] }; got ${JSON.stringify(t)}`);let n=t.allowedPaths;if(n.length===0)throw new RangeError("returnTo.allowedPaths must name at least one path; omit returnTo to allow none");for(let r of n){if(typeof r!="string")throw new TypeError(`returnTo.allowedPaths must hold strings; got ${JSON.stringify(r)}`);if(!Be(r))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(r)}`)}return new Set(n)},Ze=()=>new Response("The sign-in's return-to is not a path this application allows.",{status:400,headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-store"}}),et=(e,t)=>e===null?!1:e.split(";").some(n=>n.trim().startsWith(`${t}=`)),te=(e,t)=>new Response(e.body,{status:e.status,statusText:e.statusText,headers:t}),Re=(e,t,n,r)=>{let a=Qe(e),v=s=>We(`${ze}${s}`,{secrets:[...t.secrets],httpOnly:!0,sameSite:"lax",path:"/",secure:t.secure,maxAge:Xe}),A=(s,u,i)=>{let d=s.headers.get("Location");if(d===null)return s;let h=new URL(d,i.url);if(h.origin!==new URL(i.url).origin||h.pathname!==n)return s;let S=new Headers(s.headers);return S.set("Location",`${z(`${h.pathname}${h.search}`,u)}${h.hash}`),te(s,S)};return{requested:s=>{let u=new URL(s.url).searchParams.getAll(ee);if(u.length!==0){if(u.length===1&&a.has(u[0]))return u[0];throw Ze()}},bindToFlow:async(s,u,i)=>{let d=s.headers.get("Location"),h=d===null?null:new URL(d,i.url).searchParams.get("state");if(h===null)return A(s,u,i);if(!we.test(h))throw new Error(`The authorization redirect's state cannot name the return-to cookie; got ${JSON.stringify(h)}`);let S=new Headers(s.headers);return S.append("Set-Cookie",await v(h).serialize(u)),te(s,S)},flowOf:async s=>{let u=new URL(s.url).searchParams.get("state");if(u===null||!we.test(u))return ve;let i=v(u),d=s.headers.get("Cookie");if(!et(d,i.name))return ve;let h=await i.serialize("",{maxAge:0}),S=await i.parse(d);return typeof S=="string"&&a.has(S)?{path:S,deletion:h}:(r.warn(`The sign-in's return-to cookie ${i.name} names no allowed path; the sign-in returns to the post-login path instead`),{path:void 0,deletion:h})},endFailedFlow:(s,u,i)=>{if(u.deletion===void 0)return s;let d=u.path===void 0?s:A(s,u.path,i),h=new Headers(d.headers);return h.append("Set-Cookie",u.deletion),te(d,h)}}};import{createCookieSessionStorage as tt,redirect as ne}from"react-router";var Ae=3600*24*30,nt=e=>{if(e===void 0)return Ae;if(!Number.isSafeInteger(e)||e<1)throw new RangeError(`session.maxAge must be a safe integer of seconds >= 1; got ${String(e)}`);return e},oe=e=>e.secure??process.env.NODE_ENV==="production",re=(e,t)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(y=>!y))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 r=nt(e.maxAge),a=t.loginPath??"/auth/login",v=t.postLoginRedirect??"/",A=t.mockUser,G=t.isUserActive,m=me(t.sessionGeneration,t.logger??q),w=tt({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:oe(e),maxAge:r}}),T=async y=>await w.getSession(y.headers.get("Cookie")),s=async y=>{if(A?.enabled(y))return{kind:"signed-in",user:V(A.resolve(y)),session:await T(y)};let k=await T(y),g=k.get(n);if(g===void 0)return{kind:"signed-out"};let f=V(g),[l,R]=await Promise.all([G===void 0?!0:G(f),m===null?"current":m.check(M(g),k.get(N))]);return R==="stale"?{kind:"revoked",session:k}:l?{kind:"signed-in",user:f,session:k}:{kind:"inactive"}},u=async y=>{let k=await s(y);return k.kind==="signed-in"?k.user:void 0},i=async(y,k)=>{let g=await T(y);return g.set(n,k),await w.commitSession(g)},d=async(y,k)=>{let g=m===null?void 0:await m.stamp(M(k)),f=await T(y);return f.set(n,k),g!==void 0&&f.set(N,g),await w.commitSession(f)},h=async y=>{let k=await s(y);switch(k.kind){case"signed-in":return k.user;case"revoked":throw ne(a,{headers:{"Set-Cookie":await w.destroySession(k.session)}});case"signed-out":case"inactive":throw ne(a)}};return{sessionStorage:w,sessionKey:n,sessionMaxAgeSeconds:r,sessionGenerationGate:m,getSession:T,resolveSession:s,getSessionUser:u,saveSession:i,saveSignedInSession:d,requireUser:h,requireAdminUser:async y=>{let k=await h(y);if(k.role!=="admin")throw ne(v);return k},commitSession:w.commitSession,destroySession:w.destroySession}};var ot=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 r=ot.get(t);if(r===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(!r.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(`Signing out is refused because ${e}: only a navigation that does not come from another site, or a script's request from this origin, signs out.`,{status:403,headers:{"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"}});var ae=(e,t,n,r)=>{let a=e.loginPath??"/auth/login",v=e.postLoginRedirect??"/",A=e.postLogoutRedirect??"/",G=de(e.google.revocationTimeoutMs),m=Re(e.returnTo,{secrets:e.session.secrets,secure:oe(e.session)},a,r),w=async({request:f})=>{let l=m.requested(f);if(await t.getSessionUser(f))throw J(l??v);return{error:new URL(f.url).searchParams.get("error")}},T=async f=>{let l=m.requested(f);try{await n.authenticate("google",f)}catch(R){throw l===void 0||!(R instanceof Response)?R:await m.bindToFlow(R,l,f)}throw J(l===void 0?a:z(a,l))},s=async({request:f})=>(await f.clone().formData()).get("_action")!=="Sign In with Google"?null:await T(f),u=(f,l)=>{switch(f.outcome){case"failed":r.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:`,f.reason);return;case"already-invalid":r.info(`Sign-out found the Google grant of user ${String(l)} already unusable`);return;case"revoked":case"nothing-to-revoke":return}},i=(f,l)=>{f.kind!=="advanced"&&r.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:`,f.error)},d=async(f,l)=>{let R=t.sessionGenerationGate;if(R!==null){if(!$(l)){r.info(`Sign-out found no usable session generation stamp in the session of ${f.provider} user ${f.id}; every guard already rejects that cookie, so the generation is not advanced`);return}i(await R.advance(f,l),f)}},h=async f=>{let l=await t.getSession(f),R=l.get(t.sessionKey),[I]=await Promise.all([le(R,{fetch:e.fetch??globalThis.fetch,timeoutMs:G}),R===void 0?void 0:d(M(R),l.get(N))]);return u(I,R?.id),await t.destroySession(l)},S=async f=>{let l=await h(f),R=new Headers;return R.append("Set-Cookie",l),J(A,{headers:R})},y=async({request:f})=>{let l=se(f);throw l!==void 0?ie(l):await S(f)},k=async f=>{let l=await n.authenticate("google",f),U=(await t.getSession(f)).get(t.sessionKey)?.refreshToken,c={accessToken:l.accessToken,refreshToken:l.refreshToken||U,expirationDateMs:l.expirationDateMs,provider:l.provider},o={id:l.id,displayName:l.displayName,name:l.name,emails:l.emails,...c,role:l.role};return await t.saveSignedInSession(f,o)};return{loginLoader:w,loginAction:s,startGoogleSignIn:T,logoutLoader:y,logout:h,logoutAndRedirect:S,googleCallbackLoader:async({request:f})=>{let l=await m.flowOf(f),R;try{R=await k(f)}catch(U){throw U instanceof Response?m.endFailedFlow(U,l,f):(r.error("Authentication error:",U),m.endFailedFlow(J(a),l,f))}let I=new Headers;throw I.append("Set-Cookie",R),l.deletion!==void 0&&I.append("Set-Cookie",l.deletion),J(l.path??v,{headers:I})}}};var rt=e=>{let t=e.logger??q,n=re(e.session,{sessionGeneration:e.sessionGeneration,logger:t,mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive}),r=Z(e),a=B(e,n,t),v=Q(e,n,a,t),A=ae(e,n,r,t);return{authenticator:r,storage:n,authFns:a,sessionStorage:n.sessionStorage,getSession:n.getSession,getSessionUser:n.getSessionUser,saveSession:n.saveSession,requireUser:n.requireUser,requireAdminUser:n.requireAdminUser,commitSession:n.commitSession,destroySession:n.destroySession,sessionMaxAgeSeconds:n.sessionMaxAgeSeconds,authenticate:a.authenticate,refreshedAccessToken:a.refreshedAccessToken,authenticateInLoader:v,...A}};export{F as AuthRequiredError,ue as DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS,he as DEFAULT_SESSION_GENERATION_CACHE_TTL_MS,ge as DEFAULT_SESSION_GENERATION_TIMEOUT_MS,Ae as DEFAULT_SESSION_MAX_AGE_SECONDS,K as GoogleInvalidGrantError,H as SessionGenerationUnavailableError,C as TokenRefreshError,ae as createAuthHandlers,rt as createAuthServer,re as createAuthSessionStorage,B as createAuthenticate,Q as createAuthenticateInLoader,Z 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.
|
|
3
|
+
"version": "0.36.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"
|
|
@@ -54,8 +54,8 @@
|
|
|
54
54
|
"tailwind-variants": "^3.2.2"
|
|
55
55
|
},
|
|
56
56
|
"devDependencies": {
|
|
57
|
-
"@aiquants/auth-core": "0.
|
|
58
|
-
"@aiquants/console-ui": "0.6.
|
|
57
|
+
"@aiquants/auth-core": "0.8.0",
|
|
58
|
+
"@aiquants/console-ui": "0.6.4",
|
|
59
59
|
"@aiquants/fuzzy-search": "3.2.1",
|
|
60
60
|
"@aiquants/select-box": "0.22.1",
|
|
61
61
|
"@aiquants/virtualscroll": "3.24.0",
|
|
@@ -77,7 +77,7 @@
|
|
|
77
77
|
"vitest": "^4.1.8"
|
|
78
78
|
},
|
|
79
79
|
"peerDependencies": {
|
|
80
|
-
"@aiquants/auth-core": "^0.
|
|
80
|
+
"@aiquants/auth-core": "^0.8.0",
|
|
81
81
|
"@aiquants/console-ui": "^0.6.0",
|
|
82
82
|
"@aiquants/fuzzy-search": "^3.2.1",
|
|
83
83
|
"@aiquants/select-box": "^0.22.0",
|