@aiquants/auth-react-router 0.25.0 → 0.26.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 +79 -9
- package/dist/return-to.d.mts +3 -0
- package/dist/return-to.d.ts +3 -0
- package/dist/return-to.js +1 -0
- package/dist/return-to.mjs +1 -0
- package/dist/server.d.mts +11 -1
- package/dist/server.d.ts +11 -1
- package/dist/server.js +1 -1
- package/dist/server.mjs +1 -1
- package/package.json +11 -4
package/README.md
CHANGED
|
@@ -49,13 +49,48 @@ export const authServer = createAuthServer({
|
|
|
49
49
|
warmup: async () => { await Promise.all([ensurePrimaryConnection(), ensureSecondaryConnection()]) },
|
|
50
50
|
mockUser: mockUserPort, // test backdoor (E2E) — omit in production-only apps
|
|
51
51
|
})
|
|
52
|
-
export const { authenticator, sessionStorage, getSession, getSessionUser, saveSession, requireUser, requireAdminUser, commitSession, destroySession, authenticate, refreshedAccessToken, authenticateInLoader, loginLoader, loginAction, logoutLoader, logout, logoutAndRedirect, googleCallbackLoader } = authServer
|
|
52
|
+
export const { authenticator, sessionStorage, getSession, getSessionUser, saveSession, requireUser, requireAdminUser, commitSession, destroySession, sessionMaxAgeSeconds, authenticate, refreshedAccessToken, authenticateInLoader, loginLoader, loginAction, startGoogleSignIn, logoutLoader, logout, logoutAndRedirect, googleCallbackLoader } = authServer
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
A sign-in can return to a page of the host instead of `postLoginRedirect` (a landing page that tells the host's other tabs
|
|
56
|
+
that the user signed in again, say). List the exact paths a sign-in may return to; the sign-in page's address names one in
|
|
57
|
+
`returnTo` (`RETURN_TO_SEARCH_PARAM`), and any other value is refused with 400:
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
createAuthServer({
|
|
61
|
+
...,
|
|
62
|
+
returnTo: { allowedPaths: ["/auth/signed-in"] }, // exact same-origin paths; omit to allow none
|
|
63
|
+
})
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
// In the browser (the entry imports nothing, so a chunk that links to the sign-in page carries nothing else)
|
|
68
|
+
import { signInPathWithReturnTo } from "@aiquants/auth-react-router/return-to"
|
|
69
|
+
|
|
70
|
+
window.open(signInPathWithReturnTo("/auth/login", "/auth/signed-in"), "_blank") // "/auth/login?returnTo=%2Fauth%2Fsigned-in"
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
A host route that starts the Google sign-in from its own loader (a re-authorization link, say) calls `startGoogleSignIn`,
|
|
74
|
+
so the return-to is honoured there too:
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
|
78
|
+
if (isReauthorization(request)) return await authServer.startGoogleSignIn(request) // always throws: 400, or the redirect to Google
|
|
79
|
+
return authServer.loginLoader({ request })
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
A page that tells users how long a session lasts reads the lifetime the session cookie is given, never a copy of it:
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
export const loader = async ({ request }: LoaderFunctionArgs) => ({ ...(await authServer.loginLoader({ request })), sessionMaxAgeSeconds: authServer.sessionMaxAgeSeconds })
|
|
53
87
|
```
|
|
54
88
|
|
|
55
89
|
Optional settings for sign-out and the token requests:
|
|
56
90
|
|
|
57
91
|
```ts
|
|
58
92
|
createAuthServer({
|
|
93
|
+
session: { secrets: [...], maxAge: 7 * 24 * 60 * 60 }, // the session cookie's lifetime in seconds (default DEFAULT_SESSION_MAX_AGE_SECONDS, 30 days)
|
|
59
94
|
google: { ..., revocationTimeoutMs: 3_000 }, // how long sign-out waits for Google's revocation (default 5000)
|
|
60
95
|
fetch: instrumentedFetch, // the fetch for the token refresh and the revocation (default: global fetch)
|
|
61
96
|
sessionGeneration: {
|
|
@@ -349,10 +384,22 @@ package's own `react: ">=18"`; a host that mounts `/admin` must satisfy the stri
|
|
|
349
384
|
|
|
350
385
|
## Behavior Contract
|
|
351
386
|
|
|
352
|
-
- **Session cookie**: `__session` (httpOnly/lax
|
|
387
|
+
- **Session cookie**: `__session` (httpOnly/lax) with key `"user"`, value = `{ id, displayName, name, emails, accessToken, refreshToken?, expirationDateMs?, provider, role? }` — never `photo`/`_json`/`photos` — and, when `sessionGeneration` is enabled, key `"generation"` = the identity's sign-out generation at sign-in.
|
|
353
388
|
With the check enabled a cookie without a valid `"generation"` is rejected, so every user signs in once after a host
|
|
354
|
-
turns it on. Changing the cookie name, the `"user"` key or the profile shape invalidates all live
|
|
389
|
+
turns it on. Changing the cookie name, the `"user"` key or the profile shape invalidates all live sessions.
|
|
355
390
|
`session.sessionKey` must not be `"generation"` (`RangeError` when the server is built).
|
|
391
|
+
- **Session lifetime**: the cookie's `Max-Age` is `session.maxAge` seconds, `DEFAULT_SESSION_MAX_AGE_SECONDS` (30 days) when
|
|
392
|
+
it is omitted; anything other than a safe integer >= 1 throws `RangeError` when the server is built. Every write of the
|
|
393
|
+
session (a sign-in, a token refresh) sets it again, so the cookie lasts that long from its last write. The resolved value is
|
|
394
|
+
`sessionMaxAgeSeconds` on the server bundle and on `storage`, for a page that tells users how long a session lasts. A
|
|
395
|
+
session also ends earlier: when Google refuses to refresh the access token (the refresh token expired or was revoked), at a
|
|
396
|
+
sign-out on any device (the sign-out generation below), and when `isUserActive` reports the account deactivated.
|
|
397
|
+
- **The cookie's name and value shape are a contract with reverse proxies**: a proxy in front of the host may key per-browser
|
|
398
|
+
limits on this cookie, reading the name `__session` and the value `<payload>.<signature>` exactly as the `Cookie` header carries
|
|
399
|
+
it: the URL-encoded payload, a `.`, and the signature React Router's `sign()` appends — the base64 of an HMAC-SHA256 (32 bytes)
|
|
400
|
+
without its `=` padding, 43 characters, 43 to 129 once URL-encoded. React Router 7 and 8 sign the same way, and the package's
|
|
401
|
+
tests pin the name and the shape. Change `cookieName`, the default name or the signing scheme only together with every such
|
|
402
|
+
proxy's rule: a mismatch raises no error anywhere, the proxy just stops recognising the browser.
|
|
356
403
|
- **Verify order**: Google profile check → `backendAuth.verify` → allowlist → `backendAuth.signup` (every login). Failures redirect to `<loginPath>?error=<encoded error message>` (messages overridable via `messages`).
|
|
357
404
|
- **Token refresh**: expiry check → Google `oauth2/v4/token` rotate → session update; `invalid_grant` destroys the session and redirects to login with `Set-Cookie`.
|
|
358
405
|
- **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.
|
|
@@ -379,12 +426,35 @@ package's own `react: ">=18"`; a host that mounts `/admin` must satisfy the stri
|
|
|
379
426
|
- The `Set-Cookie` values of `saveSession` / `commitSession` / `storage.saveSignedInSession` and the `cookie` of
|
|
380
427
|
`authenticateInLoader`: the session cookie is signed, not encrypted, so the token can be read out of it. Put them
|
|
381
428
|
in a `Set-Cookie` header only.
|
|
382
|
-
- **`loginAction` never hands out the signed-in profile**: for `_action === "Sign In with Google"` it
|
|
383
|
-
|
|
384
|
-
carries `code` and the `state` of the user's state cookie, remix-auth
|
|
385
|
-
the profile with the user's tokens; `
|
|
386
|
-
|
|
387
|
-
`null`.
|
|
429
|
+
- **`loginAction` never hands out the signed-in profile**: for `_action === "Sign In with Google"` it starts the sign-in
|
|
430
|
+
through `startGoogleSignIn`, which always ends by throwing. The strategy normally throws the redirect to Google's
|
|
431
|
+
authorization endpoint. When the POST's URL carries `code` and the `state` of the user's state cookie, remix-auth
|
|
432
|
+
exchanges the code inside the action and returns the profile with the user's tokens; `startGoogleSignIn` discards it,
|
|
433
|
+
saves no session and throws a redirect to `loginPath` (keeping the return-to, if any): a sign-in completes only through
|
|
434
|
+
`googleCallbackLoader`. `loginAction`'s type is `Promise<null>`: any other `_action` returns `null`.
|
|
435
|
+
- **Per-flow return-to** (`returnTo: { allowedPaths }`, optional): a sign-in returns to the path its sign-in page's address
|
|
436
|
+
names in `returnTo` (`RETURN_TO_SEARCH_PARAM`; build the address with `signInPathWithReturnTo` from
|
|
437
|
+
`@aiquants/auth-react-router/return-to`) instead of `postLoginRedirect`.
|
|
438
|
+
- **Allowed paths only**: the value is compared exactly with `allowedPaths`. An absolute URL, a protocol-relative `//host`,
|
|
439
|
+
a backslash, a value that still holds a percent-encoding after the address is decoded, a dot segment, white space, a
|
|
440
|
+
trailing slash, a different case, a query or fragment inside the value, an empty value, a second `returnTo` and any path
|
|
441
|
+
not listed are refused with 400 (plain text, `Cache-Control: no-store`, no `Set-Cookie`) by `loginLoader`, `loginAction`
|
|
442
|
+
and `startGoogleSignIn`, before the session is read and before Google is involved. Without `returnTo` in the config,
|
|
443
|
+
every return-to is refused. When the server is built, `allowedPaths` must be a non-empty array (`TypeError` for the
|
|
444
|
+
shape, `RangeError` when empty) of canonical paths: one leading `/`, no query, fragment, percent-encoding, backslash,
|
|
445
|
+
white space, control or non-ASCII character, or dot segment (`RangeError` otherwise).
|
|
446
|
+
- **Bound to the flow**: `startGoogleSignIn` adds to the strategy's redirect to Google a cookie named
|
|
447
|
+
`__return_to.<state>` after the flow's OAuth `state` (signed with the session secrets, `HttpOnly`, `SameSite=Lax`,
|
|
448
|
+
`Path=/`, `Secure` as the session cookie, `Max-Age` 300 seconds like the strategy's own state cookie). Each flow has its
|
|
449
|
+
own cookie, so sign-ins in several tabs never take each other's return-to.
|
|
450
|
+
- **Callback**: `googleCallbackLoader` reads the cookie of its request's `state`, redirects to its path with the session
|
|
451
|
+
cookie, and deletes it. A cookie whose signature does not match, or whose path is no longer allowed, is deleted and
|
|
452
|
+
logged with `logger.warn`, and the sign-in goes to `postLoginRedirect`; a cookie of another flow is left alone. A failed
|
|
453
|
+
callback deletes the cookie and carries the path into its redirect to `loginPath` (`?error=...&returnTo=...`), so the
|
|
454
|
+
next try from that page returns to it as well.
|
|
455
|
+
- **Signed-in users**: `loginLoader` redirects a user who is already signed in to the page's return-to (else to
|
|
456
|
+
`postLoginRedirect`), so a landing page reached from a second window still runs.
|
|
457
|
+
- Name only pages that take nothing from the sign-in's address, and never a page that acts on arrival without the user.
|
|
388
458
|
- **Sign-out revokes the Google grant before it answers**: `logout` (and `logoutAndRedirect` / `logoutLoader`, which call it)
|
|
389
459
|
POSTs the session's refresh token, or its access token when there is none, to `https://oauth2.googleapis.com/revoke` (in the
|
|
390
460
|
form body, never the URL), waits until that settles, then destroys the session. The wait is bounded by
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var s=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var u=Object.prototype.hasOwnProperty;var A=(t,r)=>{for(var e in r)s(t,e,{get:r[e],enumerable:!0})},_=(t,r,e,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of T(r))!u.call(t,n)&&n!==e&&s(t,n,{get:()=>r[n],enumerable:!(o=i(r,n))||o.enumerable});return t};var S=t=>_(s({},"__esModule",{value:!0}),t);var a={};A(a,{RETURN_TO_SEARCH_PARAM:()=>R,signInPathWithReturnTo:()=>c});module.exports=S(a);var R="returnTo",c=(t,r)=>{let e=t.indexOf("?"),o=e===-1?t:t.slice(0,e),n=new URLSearchParams(e===-1?"":t.slice(e+1));return n.set(R,r),`${o}?${n.toString()}`};0&&(module.exports={RETURN_TO_SEARCH_PARAM,signInPathWithReturnTo});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var n="returnTo",R=(t,o)=>{let r=t.indexOf("?"),s=r===-1?t:t.slice(0,r),e=new URLSearchParams(r===-1?"":t.slice(r+1));return e.set(n,o),`${s}?${e.toString()}`};export{n as RETURN_TO_SEARCH_PARAM,R as signInPathWithReturnTo};
|
package/dist/server.d.mts
CHANGED
|
@@ -53,6 +53,9 @@ type SessionGenerationConfig = {
|
|
|
53
53
|
readonly cacheTtlMs?: number;
|
|
54
54
|
readonly timeoutMs?: number;
|
|
55
55
|
};
|
|
56
|
+
type ReturnToConfig = {
|
|
57
|
+
readonly allowedPaths: readonly string[];
|
|
58
|
+
};
|
|
56
59
|
type AuthServerConfig = {
|
|
57
60
|
google: GoogleOAuthConfig;
|
|
58
61
|
session: SessionConfig;
|
|
@@ -65,6 +68,7 @@ type AuthServerConfig = {
|
|
|
65
68
|
mockUser?: MockUserPort;
|
|
66
69
|
loginPath?: string;
|
|
67
70
|
postLoginRedirect?: string;
|
|
71
|
+
returnTo?: ReturnToConfig;
|
|
68
72
|
postLogoutRedirect?: string;
|
|
69
73
|
messages?: Partial<AuthMessages>;
|
|
70
74
|
logger?: LoggerPort;
|
|
@@ -91,6 +95,7 @@ type SessionGenerationGate = {
|
|
|
91
95
|
readonly stamp: (identity: SessionGenerationIdentity) => Promise<number>;
|
|
92
96
|
readonly advance: (identity: SessionGenerationIdentity, from: number) => Promise<AdvanceOutcome>;
|
|
93
97
|
};
|
|
98
|
+
declare const DEFAULT_SESSION_MAX_AGE_SECONDS: number;
|
|
94
99
|
type AuthSessionStorage = ReturnType<typeof createAuthSessionStorage>;
|
|
95
100
|
type AuthSessionStorageOptions = {
|
|
96
101
|
readonly sessionGeneration: SessionGenerationConfig | false;
|
|
@@ -115,6 +120,7 @@ type SessionResolution = {
|
|
|
115
120
|
declare const createAuthSessionStorage: (config: SessionConfig, options: AuthSessionStorageOptions) => {
|
|
116
121
|
sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
|
|
117
122
|
sessionKey: string;
|
|
123
|
+
sessionMaxAgeSeconds: number;
|
|
118
124
|
sessionGenerationGate: SessionGenerationGate | null;
|
|
119
125
|
getSession: (request: Request) => Promise<Session<react_router.SessionData, react_router.SessionData>>;
|
|
120
126
|
resolveSession: (request: Request) => Promise<SessionResolution>;
|
|
@@ -136,6 +142,7 @@ declare const createAuthServer: (config: AuthServerConfig) => {
|
|
|
136
142
|
loginAction: ({ request }: {
|
|
137
143
|
request: Request;
|
|
138
144
|
}) => Promise<null>;
|
|
145
|
+
startGoogleSignIn: (request: Request) => Promise<never>;
|
|
139
146
|
logoutLoader: ({ request }: {
|
|
140
147
|
request: Request;
|
|
141
148
|
}) => Promise<never>;
|
|
@@ -148,6 +155,7 @@ declare const createAuthServer: (config: AuthServerConfig) => {
|
|
|
148
155
|
storage: {
|
|
149
156
|
sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
|
|
150
157
|
sessionKey: string;
|
|
158
|
+
sessionMaxAgeSeconds: number;
|
|
151
159
|
sessionGenerationGate: SessionGenerationGate | null;
|
|
152
160
|
getSession: (request: Request) => Promise<react_router.Session<react_router.SessionData, react_router.SessionData>>;
|
|
153
161
|
resolveSession: (request: Request) => Promise<SessionResolution>;
|
|
@@ -181,6 +189,7 @@ declare const createAuthServer: (config: AuthServerConfig) => {
|
|
|
181
189
|
requireAdminUser: (request: Request) => Promise<SessionUser>;
|
|
182
190
|
commitSession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
|
|
183
191
|
destroySession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
|
|
192
|
+
sessionMaxAgeSeconds: number;
|
|
184
193
|
authenticate: (request: Request, session: react_router.Session, options?: {
|
|
185
194
|
failureRedirect?: string | null;
|
|
186
195
|
}) => Promise<{
|
|
@@ -258,6 +267,7 @@ declare const createAuthHandlers: (config: AuthServerConfig, storage: AuthSessio
|
|
|
258
267
|
loginAction: ({ request }: {
|
|
259
268
|
request: Request;
|
|
260
269
|
}) => Promise<null>;
|
|
270
|
+
startGoogleSignIn: (request: Request) => Promise<never>;
|
|
261
271
|
logoutLoader: ({ request }: {
|
|
262
272
|
request: Request;
|
|
263
273
|
}) => Promise<never>;
|
|
@@ -269,4 +279,4 @@ declare const createAuthHandlers: (config: AuthServerConfig, storage: AuthSessio
|
|
|
269
279
|
};
|
|
270
280
|
declare const signOutRefusal: (request: Request) => string | undefined;
|
|
271
281
|
declare const signOutRefusalResponse: (reason: string) => Response;
|
|
272
|
-
export { AuthRequiredError, type AuthServer, type AuthServerConfig, type AuthSessionStorage, type BackendAuthPort, DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS, DEFAULT_SESSION_GENERATION_CACHE_TTL_MS, DEFAULT_SESSION_GENERATION_TIMEOUT_MS, type FetchPort, GoogleInvalidGrantError, type GoogleOAuthConfig, type LoaderUser, type LoggerPort, type MockUserPort, type SessionConfig, type SessionGenerationConfig, type SessionGenerationIdentity, type SessionGenerationStore, SessionGenerationUnavailableError, type SessionUser, TokenRefreshError, type UserPhotoPort, type WarmupPort, createAuthHandlers, createAuthServer, createAuthSessionStorage, createAuthenticate, createAuthenticateInLoader, createGoogleAuthenticator, signOutRefusal, signOutRefusalResponse };
|
|
282
|
+
export { AuthRequiredError, type AuthServer, type AuthServerConfig, type AuthSessionStorage, type BackendAuthPort, DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS, DEFAULT_SESSION_GENERATION_CACHE_TTL_MS, DEFAULT_SESSION_GENERATION_TIMEOUT_MS, DEFAULT_SESSION_MAX_AGE_SECONDS, type FetchPort, GoogleInvalidGrantError, type GoogleOAuthConfig, type LoaderUser, type LoggerPort, type MockUserPort, type ReturnToConfig, type SessionConfig, type SessionGenerationConfig, type SessionGenerationIdentity, type SessionGenerationStore, SessionGenerationUnavailableError, type SessionUser, TokenRefreshError, type UserPhotoPort, type WarmupPort, createAuthHandlers, createAuthServer, createAuthSessionStorage, createAuthenticate, createAuthenticateInLoader, createGoogleAuthenticator, signOutRefusal, signOutRefusalResponse };
|
package/dist/server.d.ts
CHANGED
|
@@ -53,6 +53,9 @@ type SessionGenerationConfig = {
|
|
|
53
53
|
readonly cacheTtlMs?: number;
|
|
54
54
|
readonly timeoutMs?: number;
|
|
55
55
|
};
|
|
56
|
+
type ReturnToConfig = {
|
|
57
|
+
readonly allowedPaths: readonly string[];
|
|
58
|
+
};
|
|
56
59
|
type AuthServerConfig = {
|
|
57
60
|
google: GoogleOAuthConfig;
|
|
58
61
|
session: SessionConfig;
|
|
@@ -65,6 +68,7 @@ type AuthServerConfig = {
|
|
|
65
68
|
mockUser?: MockUserPort;
|
|
66
69
|
loginPath?: string;
|
|
67
70
|
postLoginRedirect?: string;
|
|
71
|
+
returnTo?: ReturnToConfig;
|
|
68
72
|
postLogoutRedirect?: string;
|
|
69
73
|
messages?: Partial<AuthMessages>;
|
|
70
74
|
logger?: LoggerPort;
|
|
@@ -91,6 +95,7 @@ type SessionGenerationGate = {
|
|
|
91
95
|
readonly stamp: (identity: SessionGenerationIdentity) => Promise<number>;
|
|
92
96
|
readonly advance: (identity: SessionGenerationIdentity, from: number) => Promise<AdvanceOutcome>;
|
|
93
97
|
};
|
|
98
|
+
declare const DEFAULT_SESSION_MAX_AGE_SECONDS: number;
|
|
94
99
|
type AuthSessionStorage = ReturnType<typeof createAuthSessionStorage>;
|
|
95
100
|
type AuthSessionStorageOptions = {
|
|
96
101
|
readonly sessionGeneration: SessionGenerationConfig | false;
|
|
@@ -115,6 +120,7 @@ type SessionResolution = {
|
|
|
115
120
|
declare const createAuthSessionStorage: (config: SessionConfig, options: AuthSessionStorageOptions) => {
|
|
116
121
|
sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
|
|
117
122
|
sessionKey: string;
|
|
123
|
+
sessionMaxAgeSeconds: number;
|
|
118
124
|
sessionGenerationGate: SessionGenerationGate | null;
|
|
119
125
|
getSession: (request: Request) => Promise<Session<react_router.SessionData, react_router.SessionData>>;
|
|
120
126
|
resolveSession: (request: Request) => Promise<SessionResolution>;
|
|
@@ -136,6 +142,7 @@ declare const createAuthServer: (config: AuthServerConfig) => {
|
|
|
136
142
|
loginAction: ({ request }: {
|
|
137
143
|
request: Request;
|
|
138
144
|
}) => Promise<null>;
|
|
145
|
+
startGoogleSignIn: (request: Request) => Promise<never>;
|
|
139
146
|
logoutLoader: ({ request }: {
|
|
140
147
|
request: Request;
|
|
141
148
|
}) => Promise<never>;
|
|
@@ -148,6 +155,7 @@ declare const createAuthServer: (config: AuthServerConfig) => {
|
|
|
148
155
|
storage: {
|
|
149
156
|
sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
|
|
150
157
|
sessionKey: string;
|
|
158
|
+
sessionMaxAgeSeconds: number;
|
|
151
159
|
sessionGenerationGate: SessionGenerationGate | null;
|
|
152
160
|
getSession: (request: Request) => Promise<react_router.Session<react_router.SessionData, react_router.SessionData>>;
|
|
153
161
|
resolveSession: (request: Request) => Promise<SessionResolution>;
|
|
@@ -181,6 +189,7 @@ declare const createAuthServer: (config: AuthServerConfig) => {
|
|
|
181
189
|
requireAdminUser: (request: Request) => Promise<SessionUser>;
|
|
182
190
|
commitSession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
|
|
183
191
|
destroySession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
|
|
192
|
+
sessionMaxAgeSeconds: number;
|
|
184
193
|
authenticate: (request: Request, session: react_router.Session, options?: {
|
|
185
194
|
failureRedirect?: string | null;
|
|
186
195
|
}) => Promise<{
|
|
@@ -258,6 +267,7 @@ declare const createAuthHandlers: (config: AuthServerConfig, storage: AuthSessio
|
|
|
258
267
|
loginAction: ({ request }: {
|
|
259
268
|
request: Request;
|
|
260
269
|
}) => Promise<null>;
|
|
270
|
+
startGoogleSignIn: (request: Request) => Promise<never>;
|
|
261
271
|
logoutLoader: ({ request }: {
|
|
262
272
|
request: Request;
|
|
263
273
|
}) => Promise<never>;
|
|
@@ -269,4 +279,4 @@ declare const createAuthHandlers: (config: AuthServerConfig, storage: AuthSessio
|
|
|
269
279
|
};
|
|
270
280
|
declare const signOutRefusal: (request: Request) => string | undefined;
|
|
271
281
|
declare const signOutRefusalResponse: (reason: string) => Response;
|
|
272
|
-
export { AuthRequiredError, type AuthServer, type AuthServerConfig, type AuthSessionStorage, type BackendAuthPort, DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS, DEFAULT_SESSION_GENERATION_CACHE_TTL_MS, DEFAULT_SESSION_GENERATION_TIMEOUT_MS, type FetchPort, GoogleInvalidGrantError, type GoogleOAuthConfig, type LoaderUser, type LoggerPort, type MockUserPort, type SessionConfig, type SessionGenerationConfig, type SessionGenerationIdentity, type SessionGenerationStore, SessionGenerationUnavailableError, type SessionUser, TokenRefreshError, type UserPhotoPort, type WarmupPort, createAuthHandlers, createAuthServer, createAuthSessionStorage, createAuthenticate, createAuthenticateInLoader, createGoogleAuthenticator, signOutRefusal, signOutRefusalResponse };
|
|
282
|
+
export { AuthRequiredError, type AuthServer, type AuthServerConfig, type AuthSessionStorage, type BackendAuthPort, DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS, DEFAULT_SESSION_GENERATION_CACHE_TTL_MS, DEFAULT_SESSION_GENERATION_TIMEOUT_MS, DEFAULT_SESSION_MAX_AGE_SECONDS, type FetchPort, GoogleInvalidGrantError, type GoogleOAuthConfig, type LoaderUser, type LoggerPort, type MockUserPort, type ReturnToConfig, type SessionConfig, type SessionGenerationConfig, type SessionGenerationIdentity, type SessionGenerationStore, SessionGenerationUnavailableError, type SessionUser, TokenRefreshError, type UserPhotoPort, type WarmupPort, createAuthHandlers, createAuthServer, createAuthSessionStorage, createAuthenticate, createAuthenticateInLoader, createGoogleAuthenticator, signOutRefusal, signOutRefusalResponse };
|
package/dist/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var oe=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var Ae=Object.prototype.hasOwnProperty;var Ge=(e,t)=>{for(var n in t)oe(e,n,{get:t[n],enumerable:!0})},Te=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ve(t))!Ae.call(e,i)&&i!==n&&oe(e,i,{get:()=>t[i],enumerable:!(a=ke(t,i))||a.enumerable});return e};var Re=e=>Te(oe({},"__esModule",{value:!0}),e);var He={};Ge(He,{AuthRequiredError:()=>N,DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS:()=>ue,DEFAULT_SESSION_GENERATION_CACHE_TTL_MS:()=>re,DEFAULT_SESSION_GENERATION_TIMEOUT_MS:()=>se,GoogleInvalidGrantError:()=>F,SessionGenerationUnavailableError:()=>C,TokenRefreshError:()=>M,createAuthHandlers:()=>Q,createAuthServer:()=>ye,createAuthSessionStorage:()=>Z,createAuthenticate:()=>B,createAuthenticateInLoader:()=>X,createGoogleAuthenticator:()=>J,signOutRefusal:()=>W,signOutRefusalResponse:()=>z});module.exports=Re(He);var ie=require("react-router");var Pe="https://oauth2.googleapis.com/revoke",ue=5e3;var Ee="google",_e="invalid_token";var de=e=>{if(e===void 0)return 5e3;if(!Number.isInteger(e)||e<1||e>2147483647)throw new RangeError(`google.revocationTimeoutMs must be an integer from 1 to 2147483647 (milliseconds); got ${String(e)}`);return e},be=e=>{if(typeof e.refreshToken=="string"&&e.refreshToken!=="")return e.refreshToken;if(typeof e.accessToken=="string"&&e.accessToken!=="")return e.accessToken},Ie=async e=>{let t=await e.json().catch(()=>{});return typeof t=="object"&&t!==null&&"error"in t&&typeof t.error=="string"?t.error:void 0},Oe=e=>e instanceof Error?e.cause instanceof Error?`${e.message} (${e.cause.message})`:e.message:String(e),xe=async(e,t,n)=>{try{let a=await t(Pe,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:e}).toString(),signal:n});if(a.ok)return await a.body?.cancel(),{outcome:"revoked"};let i=await Ie(a);return a.status===400&&i===_e?{outcome:"already-invalid"}:{outcome:"failed",reason:i===void 0?`Google answered ${a.status}`:`Google answered ${a.status} ${i}`}}catch(a){return{outcome:"failed",reason:Oe(a)}}},le=async(e,t)=>{if(e===void 0)return{outcome:"nothing-to-revoke"};let n=be(e);if(n===void 0)return{outcome:"nothing-to-revoke"};if(e.provider!==Ee)return{outcome:"failed",reason:`the session's provider "${String(e.provider)}" has no revocation endpoint`};let a=new AbortController;return await new Promise(i=>{let w=setTimeout(()=>{i({outcome:"failed",reason:`Google did not answer within ${t.timeoutMs} ms`}),a.abort()},t.timeoutMs);xe(n,t.fetch,a.signal).then(v=>{clearTimeout(w),i(v)})})};var x="generation",re=15e3,se=3e3,Ue=6e4,C=class extends Error{constructor(t,n){super(t,n),this.name="SessionGenerationUnavailableError"}},O=e=>typeof e=="string"?JSON.stringify(e):typeof e=="function"?"a function":typeof e=="object"&&e!==null?Array.isArray(e)?"an array":"an object":typeof e=="bigint"?`${e}n`:String(e),Le=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return O(e);let t="store"in e?e.store:void 0;if(typeof t!="object"||t===null)return`an object whose store is ${O(t)}`;let n="current"in t?t.current:void 0,a="advance"in t?t.advance:void 0;return`an object whose store.current is ${O(n)} and store.advance is ${O(a)}`},Ne=e=>typeof e=="object"&&e!==null&&"current"in e&&typeof e.current=="function"&&"advance"in e&&typeof e.advance=="function",fe=(e,t,n,a)=>{if(t===void 0)return a;if(typeof t!="number"||!Number.isInteger(t)||t<n||t>2147483647)throw new RangeError(`${e} must be an integer from ${n} to ${2147483647} (milliseconds); got ${O(t)}`);return t},Ce=e=>{if(e===!1)return!1;let t=e;if(typeof t!="object"||t===null||!("store"in t)||!Ne(t.store))throw new TypeError(`sessionGeneration must be { store, cacheTtlMs?, timeoutMs? } or false; got ${Le(t)}`);return{store:t.store,cacheTtlMs:fe("sessionGeneration.cacheTtlMs","cacheTtlMs"in t?t.cacheTtlMs:void 0,0,re),timeoutMs:fe("sessionGeneration.timeoutMs","timeoutMs"in t?t.timeoutMs:void 0,1,se)}},$=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,ne=e=>typeof e.provider=="string"&&e.provider!==""&&typeof e.id=="string"&&e.id!=="",pe=e=>new TypeError(`a session generation identity needs a non-empty provider and id; got provider ${O(e.provider)} and id ${O(e.id)}`),$e=e=>$(e)&&$(e+1),Fe=e=>new TypeError(`a session generation advance needs the signed-out session's stamp, an integer from 0 to ${Number.MAX_SAFE_INTEGER-1}; got ${O(e)}`),L=e=>({provider:e.provider,id:e.id}),ge=(e,t)=>{let n=Ce(e);if(n===!1)return null;let{store:a,cacheTtlMs:i,timeoutMs:w}=n,v=new Map,A=new Map,m=new Map,h=new Map,k=Number.NEGATIVE_INFINITY,f=u=>`${u.provider}\0${u.id}`,g=(u,o)=>{let l=v.get(u);if(l!==void 0){if(o-l.at<i)return l;v.delete(u)}},d=(u,o,l)=>{if(l!==void 0&&o.at<=l.answeredAt&&o.value<l.value)return;let y=g(u,performance.now());if(y===void 0){v.set(u,o);return}o.value<y.value||v.set(u,{value:o.value,at:Math.max(y.at,o.at)})},p=u=>{let o=h.get(u);if(o!==void 0)return o.count+=1,o;let l={count:1,floor:void 0};return h.set(u,l),l},S=(u,o)=>{o.count-=1,o.count===0&&h.delete(u)},P=(u,o)=>{u.floor={value:u.floor===void 0?o:Math.max(u.floor.value,o),answeredAt:performance.now()}},s=(u,o)=>{let l=m.get(u);return l===void 0?!1:o<l?!0:(m.delete(u),!1)},r=(u,o)=>{let l=performance.now();return m.set(u,l+i),l-k>=Ue&&(k=l,t.warn("Session generation store unavailable; skipping the sign-out generation check:",o)),"unavailable"},c=(u,o,l)=>new Promise((y,R)=>{let{operation:G}=u,I=u.operation==="advance"?u.from+1:0,we=performance.now(),V=p(l),U=!1,ce=setTimeout(()=>{U=!0,y({kind:"unavailable",error:new C(`sessionGeneration.store.${G} did not settle within ${w} ms`)})},w);new Promise(_=>_(u.operation==="advance"?a.advance(o,u.from):a.current(o))).then(_=>{if(clearTimeout(ce),!($(_)&&_>=I)){S(l,V),U||(U=!0,R(new TypeError(`sessionGeneration.store.${G} must resolve to an integer >= ${I}; got ${O(_)}`)));return}G==="advance"&&(P(V,_),A.delete(l)),d(l,{value:_,at:we},V.floor),S(l,V),!U&&(U=!0,m.delete(l),y({kind:"value",value:_}))},_=>{if(clearTimeout(ce),S(l,V),!U){if(U=!0,_ instanceof C){y({kind:"unavailable",error:_});return}R(_)}})}),T=(u,o,l)=>{let y=A.get(o);if(y!==void 0&&l-y.startedAt<i)return y.read;let R={read:c({operation:"current"},u,o),startedAt:l};A.set(o,R);let G=()=>{A.get(o)===R&&A.delete(o)};return R.read.then(G,G),R.read},E=async(u,o,l)=>{let y=await c({operation:"current"},u,o);return y.kind==="unavailable"?r(o,y.error):l===y.value?"current":"stale"};return{check:async(u,o)=>{if(!($(o)&&ne(u)))return"stale";let l=performance.now(),y=f(u),R=g(y,l);if(R!==void 0){if(o===R.value)return"current";if(o<R.value)return"stale"}if(s(y,l))return"unavailable";if(R!==void 0)return await E(u,y,o);let G=await T(u,y,l);return G.kind==="unavailable"?r(y,G.error):o===G.value?"current":o<G.value?"stale":await E(u,y,o)},stamp:async u=>{if(!ne(u))throw pe(u);let o=await c({operation:"current"},u,f(u));if(o.kind==="unavailable")throw o.error;return o.value},advance:async(u,o)=>{if(!ne(u))return{kind:"failed",error:pe(u)};if(!$e(o))return{kind:"failed",error:Fe(o)};try{let l=await c({operation:"advance",from:o},u,f(u));return l.kind==="value"?{kind:"advanced",generation:l.value}:{kind:"unavailable",error:l.error}}catch(l){return{kind:"failed",error:l}}}}};var M=class extends Error{constructor(t){super(t),this.name="TokenRefreshError"}},F=class extends M{constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},N=class extends Error{constructor(t){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=t}},qe=["access_token","expires_in"],B=(e,t,n)=>{let a=e.loginPath??"/auth/login",i=t.sessionKey,w=async m=>{let k=m.get(i)?.refreshToken;if(!k)throw new Error("Refresh token not found in session");try{let f="https://www.googleapis.com/oauth2/v4/token",g={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:k},p=await(e.fetch??globalThis.fetch)(f,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(g)});if(!p.ok){let c=await p.json().catch(()=>{});if(p.status===400&&typeof c=="object"&&!!c&&"error"in c&&c.error==="invalid_grant")throw new F;let E=typeof c=="object"&&c&&"error_description"in c?String(c.error_description):"Unknown error";throw new M(`Google token refresh failed: ${p.status} ${E}`)}let S=await p.json(),P=qe.filter(c=>!S?.[c]);if(P.length>0)throw n.error("Invalid token response from Google; missing or empty keys:",P.join(", ")),new Error("Invalid token response from Google");let{access_token:s,expires_in:r}=S;return{accessToken:s,refreshToken:k,expirationDateMs:Number(Date.now())+r*1e3}}catch(f){if(f instanceof M)throw f;let g=f instanceof Error?f.message:"Unknown error";throw new M(`Failed to refresh Google access token: ${g}`)}},v=async m=>{let k=m.get(i).provider;if(!k)throw new Error("Provider not found in session");if(k==="google")return await w(m);throw new Error("Provider not supported")};return{authenticate:async(m,h,k)=>{let{failureRedirect:f}=k||{},g=d=>{if(f===null)return new N(d);if(f==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let p=f??a;return d!==void 0?(0,ie.redirect)(p,{headers:{"Set-Cookie":d}}):(0,ie.redirect)(p)};try{if(e.mockUser?.enabled(m)){let{accessToken:r,refreshToken:c,expirationDateMs:T}=e.mockUser.resolve(m);return{accessToken:r,refreshToken:c,expirationDateMs:T}}let d=h.get(i),p=t.sessionGenerationGate;if(d!==void 0&&p!==null&&await p.check(L(d),h.get(x))==="stale")throw g(await t.destroySession(h));if(!(d?.accessToken&&d.expirationDateMs))throw g();let{accessToken:S,refreshToken:P,expirationDateMs:s}=d;if(s<Date.now())throw P?new Error("Expired"):g();return{accessToken:S,refreshToken:P,expirationDateMs:s}}catch(d){if(d instanceof Error&&d.message==="Expired")try{let p=await v(h),S=h.get(i);return h.set(i,{...S,...p}),p}catch(p){if(p instanceof F)n.warn("Google refresh token invalid or revoked");else{let P=p instanceof Error?p.message:"Unknown error";n.error("Failed to refresh token:",P)}let S=await t.destroySession(h);throw g(S)}throw d}},refreshedAccessToken:v}};var ae=require("react-router");var K=({refreshToken:e,...t})=>t;var X=(e,t,n,a)=>{let i=new Map,w=new Map,v=async f=>{let g=i.get(f);if(g!==void 0)return g;let d=w.get(f);if(d!==void 0)return d;let p=(async()=>{try{let S=e.getUserPhoto?await e.getUserPhoto(f):"";return i.set(f,S),S}catch(S){throw i.delete(f),S}finally{w.delete(f)}})();return w.set(f,p),p},A=new WeakMap,m=async f=>{e.warmup&&await e.warmup();let g=await t.resolveSession(f);if(g.kind==="revoked")return{kind:"unauthenticated",cookie:await t.destroySession(g.session)};if(g.kind!=="signed-in")return{kind:"unauthenticated"};let{user:d,session:p}=g,S;try{S=await n.authenticate(f,p,{failureRedirect:null})}catch(b){if(b instanceof N)return b.setCookie!==void 0?{kind:"unauthenticated",cookie:b.setCookie}:{kind:"unauthenticated"};throw a.error("Error in authenticateInLoader:",b),b}let P={accessToken:S.accessToken,refreshToken:S.refreshToken,expirationDateMs:S.expirationDateMs,provider:d.provider},s={id:d.id,displayName:d.displayName,name:d.name,emails:d.emails,...P,role:d.role},r=await v(d.id),c=K({...d,...P,photo:r}),E=S.accessToken!==d.accessToken?await t.saveSession(f,s):void 0;return E!==void 0?{kind:"authenticated",user:c,cookie:E}:{kind:"authenticated",user:c}},h=f=>{let g=A.get(f);if(g!==void 0)return g;let d=m(f);return A.set(f,d),d};async function k(f,g){let{failureRedirect:d}=g;if(d==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let p=await h(f);if(p.kind==="authenticated")return p.cookie!==void 0?{user:p.user,cookie:p.cookie}:{user:p.user};if(d===null)return p.cookie!==void 0?{cookie:p.cookie}:{};throw p.cookie!==void 0?(0,ae.redirect)(d,{headers:{"Set-Cookie":p.cookie}}):(0,ae.redirect)(d)}return k};var me=require("@aiquants/auth-core"),Y=require("react-router"),Se=require("remix-auth");var he=require("remix-auth-oauth2"),De=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],je="google",Ve="https://www.googleapis.com/oauth2/v3/userinfo",H=class extends he.OAuth2Strategy{constructor({clientId:n,clientSecret:a,redirectURI:i,scopes:w,accessType:v,includeGrantedScopes:A,prompt:m,hd:h,loginHint:k,additionalScopes:f},g){let d=w??De;super({clientId:n,clientSecret:a,redirectURI:i,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:d},g);this.name=je;this.scopes=d,this.accessType=v??"online",this.includeGrantedScopes=A??!1,this.prompt=m,this.hd=h,this.loginHint=k,this.additionalScopes=f}authorizationParams(n,a){n.set("access_type",this.accessType),n.set("include_granted_scopes",String(this.includeGrantedScopes));let i=a===void 0||this.additionalScopes===void 0?[]:this.additionalScopes(a);for(let v of i)if(v===""||/\s/u.test(v))throw new RangeError(`[auth-react-router] an additional scope must be a non-empty string without white space; got ${JSON.stringify(v)}`);let w=[...new Set([...this.scopes,...i])];return w.length>0&&n.set("scope",w.join(" ")),this.prompt&&n.set("prompt",this.prompt),this.hd&&n.set("hd",this.hd),this.loginHint&&n.set("login_hint",this.loginHint),n}static async userProfile(n){let a=await fetch(Ve,{headers:{Authorization:`Bearer ${n.accessToken()}`}});if(!a.ok)throw new Error(`Failed to fetch user profile: ${a.statusText}`);let i=await a.json();return{id:i.sub,displayName:i.name,name:{familyName:i.family_name,givenName:i.given_name},emails:[{value:i.email}],photos:[{value:i.picture}],_json:i}}};var q={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var J=e=>{let t=e.logger??q,n=(0,me.resolveAuthMessages)(e.messages),a=e.loginPath??"/auth/login",i=new H({clientId:e.google.clientId,clientSecret:e.google.clientSecret,redirectURI:e.google.redirectURI,scopes:e.google.scopes,accessType:e.google.accessType??"offline",includeGrantedScopes:e.google.includeGrantedScopes??!0,prompt:e.google.prompt??"consent",additionalScopes:e.google.additionalScopes},async({request:v,tokens:A})=>{let{access_token:m,refresh_token:h,expires_in:k,scope:f,id_token:g}=A.data,{_json:{sub:d,email:p,picture:S,hd:P,email_verified:s},photos:r,...c}=await H.userProfile(A),{id:T,displayName:E,name:{familyName:b,givenName:ee},emails:te}=c,u="google";if(m===void 0||h===void 0||k===void 0||f===void 0||T===void 0||E===void 0||d===void 0||p===void 0||s===void 0){if(s===!1){let l=encodeURIComponent(n.emailNotVerified);throw(0,Y.redirect)(`${a}?error=${l}`)}let o=encodeURIComponent(n.googleFailed);throw(0,Y.redirect)(`${a}?error=${o}`)}t.info("Authenticated on Google: ",c.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(u,m)){t.error("Backend verification returned false for user:",c.displayName);let I=encodeURIComponent(n.backendFailed);throw(0,Y.redirect)(`${a}?error=${I}`)}t.info("Authenticated on Backend: ",c.displayName)}let o=c.emails[0]?.value;if(!await e.isEmailAllowed(o)){let G=new Error("You are not allowed to access this application");throw t.error(G),G}if(e.isUserActive&&!await e.isUserActive(c)){let G=new Error("You are not allowed to access this application");throw t.error("Deactivated account attempted to sign in:",o),G}e.backendAuth&&await e.backendAuth.signup(u,m,c),t.info("Authenticated complete: ",c.displayName);let l=Date.now()+k*1e3;return{...c,...{accessToken:m,refreshToken:h,expirationDateMs:l,provider:u},photo:S}}catch(o){let l=o;typeof o=="object"&&o!==null&&"cause"in o&&(l=o.cause||o),t.error("Error during backend authentication or subsequent processing:",l);let y=n.unexpected,R=!1;if(typeof o=="object"&&o!==null&&"cause"in o){let I=o.cause;I&&typeof I=="object"&&"message"in I&&typeof I.message=="string"&&I.message.includes("getaddrinfo ENOTFOUND")&&(y=n.backendUnreachable,R=!0)}if(!R&&o instanceof Error&&o.message.includes("You are not allowed to access this application")&&(y=n.notAllowed,R=!0),!R&&o instanceof Response&&o.headers.get("Location")?.startsWith(a))throw o;let G=encodeURIComponent(y);throw(0,Y.redirect)(`${a}?error=${G}`)}}),w=new Se.Authenticator;return w.use(i),w};var D=require("react-router");var Ke=new Map([["document",new Set(["none","same-origin","same-site"])],["empty",new Set(["same-origin"])]]),W=e=>{let t=e.headers.get("Sec-Fetch-Dest");if(t!==null){let a=Ke.get(t);if(a===void 0)return`its fetch destination is "${t}"`;let i=e.headers.get("Sec-Fetch-Site");if(i===null)return`its "${t}" request states no site`;if(!a.has(i))return`its "${t}" request comes from a "${i}" page`}let n=e.headers.get("Sec-Purpose");if(n!==null)return`it is speculative ("${n}")`},z=e=>new Response(`Signing out is refused because ${e}: only a navigation that does not come from another site, or a script's request from this origin, signs out.`,{status:403,headers:{"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"}});var Q=(e,t,n,a)=>{let i=e.loginPath??"/auth/login",w=e.postLoginRedirect??"/",v=e.postLogoutRedirect??"/",A=de(e.google.revocationTimeoutMs),m=async({request:s})=>{if(await t.getSessionUser(s))throw(0,D.redirect)(w);return{error:new URL(s.url).searchParams.get("error")}},h=async({request:s})=>{if((await s.clone().formData()).get("_action")!=="Sign In with Google")return null;throw await n.authenticate("google",s),(0,D.redirect)(i)},k=(s,r)=>{switch(s.outcome){case"failed":a.error(`Sign-out could not revoke the Google grant of user ${String(r)}; the session cookie is destroyed, but the grant stays valid until it expires or is revoked elsewhere:`,s.reason);return;case"already-invalid":a.info(`Sign-out found the Google grant of user ${String(r)} already unusable`);return;case"revoked":case"nothing-to-revoke":return}},f=(s,r)=>{s.kind!=="advanced"&&a.error(`Sign-out could not advance the session generation of ${r.provider} user ${r.id}; a session cookie refreshed before this sign-out stays valid until a later sign-out advances the generation or the cookie expires:`,s.error)},g=async(s,r)=>{let c=t.sessionGenerationGate;if(c!==null){if(!$(r)){a.info(`Sign-out found no usable session generation stamp in the session of ${s.provider} user ${s.id}; every guard already rejects that cookie, so the generation is not advanced`);return}f(await c.advance(s,r),s)}},d=async s=>{let r=await t.getSession(s),c=r.get(t.sessionKey),[T]=await Promise.all([le(c,{fetch:e.fetch??globalThis.fetch,timeoutMs:A}),c===void 0?void 0:g(L(c),r.get(x))]);return k(T,c?.id),await t.destroySession(r)},p=async s=>{let r=await d(s),c=new Headers;return c.append("Set-Cookie",r),(0,D.redirect)(v,{headers:c})};return{loginLoader:m,loginAction:h,logoutLoader:async({request:s})=>{let r=W(s);throw r!==void 0?z(r):await p(s)},logout:d,logoutAndRedirect:p,googleCallbackLoader:async({request:s})=>{try{let r=await n.authenticate("google",s),E=(await t.getSession(s)).get(t.sessionKey)?.refreshToken,b={accessToken:r.accessToken,refreshToken:r.refreshToken||E,expirationDateMs:r.expirationDateMs,provider:r.provider},ee={id:r.id,displayName:r.displayName,name:r.name,emails:r.emails,...b,role:r.role},te=await t.saveSignedInSession(s,ee);throw(0,D.redirect)(w,{headers:{"Set-Cookie":te}})}catch(r){throw r instanceof Response?r:(a.error("Authentication error:",r),(0,D.redirect)(i))}}}};var j=require("react-router");var Z=(e,t)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(s=>!s))throw new Error("REMIX_SESSION_SECRET must be set");let n=e.sessionKey??"user";if(n===x)throw new RangeError(`session.sessionKey must not be ${JSON.stringify(x)}, the key the session generation is stored under; got ${JSON.stringify(n)}`);let a=e.maxAge??3600*24*30,i=t.loginPath??"/auth/login",w=t.postLoginRedirect??"/",v=t.mockUser,A=t.isUserActive,m=ge(t.sessionGeneration,t.logger??q),h=(0,j.createCookieSessionStorage)({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:e.secure??process.env.NODE_ENV==="production",maxAge:a}}),k=async s=>await h.getSession(s.headers.get("Cookie")),f=async s=>{if(v?.enabled(s))return{kind:"signed-in",user:K(v.resolve(s)),session:await k(s)};let r=await k(s),c=r.get(n);if(c===void 0)return{kind:"signed-out"};let T=K(c),[E,b]=await Promise.all([A===void 0?!0:A(T),m===null?"current":m.check(L(c),r.get(x))]);return b==="stale"?{kind:"revoked",session:r}:E?{kind:"signed-in",user:T,session:r}:{kind:"inactive"}},g=async s=>{let r=await f(s);return r.kind==="signed-in"?r.user:void 0},d=async(s,r)=>{let c=await k(s);return c.set(n,r),await h.commitSession(c)},p=async(s,r)=>{let c=m===null?void 0:await m.stamp(L(r)),T=await k(s);return T.set(n,r),c!==void 0&&T.set(x,c),await h.commitSession(T)},S=async s=>{let r=await f(s);switch(r.kind){case"signed-in":return r.user;case"revoked":throw(0,j.redirect)(i,{headers:{"Set-Cookie":await h.destroySession(r.session)}});case"signed-out":case"inactive":throw(0,j.redirect)(i)}};return{sessionStorage:h,sessionKey:n,sessionGenerationGate:m,getSession:k,resolveSession:f,getSessionUser:g,saveSession:d,saveSignedInSession:p,requireUser:S,requireAdminUser:async s=>{let r=await S(s);if(r.role!=="admin")throw(0,j.redirect)(w);return r},commitSession:h.commitSession,destroySession:h.destroySession}};var ye=e=>{let t=e.logger??q,n=Z(e.session,{sessionGeneration:e.sessionGeneration,logger:t,mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive}),a=J(e),i=B(e,n,t),w=X(e,n,i,t),v=Q(e,n,a,t);return{authenticator:a,storage:n,authFns:i,sessionStorage:n.sessionStorage,getSession:n.getSession,getSessionUser:n.getSessionUser,saveSession:n.saveSession,requireUser:n.requireUser,requireAdminUser:n.requireAdminUser,commitSession:n.commitSession,destroySession:n.destroySession,authenticate:i.authenticate,refreshedAccessToken:i.refreshedAccessToken,authenticateInLoader:w,...v}};0&&(module.exports={AuthRequiredError,DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS,DEFAULT_SESSION_GENERATION_CACHE_TTL_MS,DEFAULT_SESSION_GENERATION_TIMEOUT_MS,GoogleInvalidGrantError,SessionGenerationUnavailableError,TokenRefreshError,createAuthHandlers,createAuthServer,createAuthSessionStorage,createAuthenticate,createAuthenticateInLoader,createGoogleAuthenticator,signOutRefusal,signOutRefusalResponse});
|
|
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});
|
package/dist/server.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{redirect as le}from"react-router";var ge="https://oauth2.googleapis.com/revoke",he=5e3;var me="google",Se="invalid_token";var re=e=>{if(e===void 0)return 5e3;if(!Number.isInteger(e)||e<1||e>2147483647)throw new RangeError(`google.revocationTimeoutMs must be an integer from 1 to 2147483647 (milliseconds); got ${String(e)}`);return e},ye=e=>{if(typeof e.refreshToken=="string"&&e.refreshToken!=="")return e.refreshToken;if(typeof e.accessToken=="string"&&e.accessToken!=="")return e.accessToken},we=async e=>{let t=await e.json().catch(()=>{});return typeof t=="object"&&t!==null&&"error"in t&&typeof t.error=="string"?t.error:void 0},ke=e=>e instanceof Error?e.cause instanceof Error?`${e.message} (${e.cause.message})`:e.message:String(e),ve=async(e,t,n)=>{try{let c=await t(ge,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:e}).toString(),signal:n});if(c.ok)return await c.body?.cancel(),{outcome:"revoked"};let u=await we(c);return c.status===400&&u===Se?{outcome:"already-invalid"}:{outcome:"failed",reason:u===void 0?`Google answered ${c.status}`:`Google answered ${c.status} ${u}`}}catch(c){return{outcome:"failed",reason:ke(c)}}},se=async(e,t)=>{if(e===void 0)return{outcome:"nothing-to-revoke"};let n=ye(e);if(n===void 0)return{outcome:"nothing-to-revoke"};if(e.provider!==me)return{outcome:"failed",reason:`the session's provider "${String(e.provider)}" has no revocation endpoint`};let c=new AbortController;return await new Promise(u=>{let w=setTimeout(()=>{u({outcome:"failed",reason:`Google did not answer within ${t.timeoutMs} ms`}),c.abort()},t.timeoutMs);ve(n,t.fetch,c.signal).then(v=>{clearTimeout(w),u(v)})})};var x="generation",ce=15e3,ue=3e3,Ge=6e4,q=class extends Error{constructor(t,n){super(t,n),this.name="SessionGenerationUnavailableError"}},O=e=>typeof e=="string"?JSON.stringify(e):typeof e=="function"?"a function":typeof e=="object"&&e!==null?Array.isArray(e)?"an array":"an object":typeof e=="bigint"?`${e}n`:String(e),Te=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return O(e);let t="store"in e?e.store:void 0;if(typeof t!="object"||t===null)return`an object whose store is ${O(t)}`;let n="current"in t?t.current:void 0,c="advance"in t?t.advance:void 0;return`an object whose store.current is ${O(n)} and store.advance is ${O(c)}`},Re=e=>typeof e=="object"&&e!==null&&"current"in e&&typeof e.current=="function"&&"advance"in e&&typeof e.advance=="function",ie=(e,t,n,c)=>{if(t===void 0)return c;if(typeof t!="number"||!Number.isInteger(t)||t<n||t>2147483647)throw new RangeError(`${e} must be an integer from ${n} to ${2147483647} (milliseconds); got ${O(t)}`);return t},Pe=e=>{if(e===!1)return!1;let t=e;if(typeof t!="object"||t===null||!("store"in t)||!Re(t.store))throw new TypeError(`sessionGeneration must be { store, cacheTtlMs?, timeoutMs? } or false; got ${Te(t)}`);return{store:t.store,cacheTtlMs:ie("sessionGeneration.cacheTtlMs","cacheTtlMs"in t?t.cacheTtlMs:void 0,0,ce),timeoutMs:ie("sessionGeneration.timeoutMs","timeoutMs"in t?t.timeoutMs:void 0,1,ue)}},N=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,X=e=>typeof e.provider=="string"&&e.provider!==""&&typeof e.id=="string"&&e.id!=="",ae=e=>new TypeError(`a session generation identity needs a non-empty provider and id; got provider ${O(e.provider)} and id ${O(e.id)}`),Ee=e=>N(e)&&N(e+1),_e=e=>new TypeError(`a session generation advance needs the signed-out session's stamp, an integer from 0 to ${Number.MAX_SAFE_INTEGER-1}; got ${O(e)}`),U=e=>({provider:e.provider,id:e.id}),de=(e,t)=>{let n=Pe(e);if(n===!1)return null;let{store:c,cacheTtlMs:u,timeoutMs:w}=n,v=new Map,A=new Map,m=new Map,h=new Map,k=Number.NEGATIVE_INFINITY,f=a=>`${a.provider}\0${a.id}`,g=(a,o)=>{let l=v.get(a);if(l!==void 0){if(o-l.at<u)return l;v.delete(a)}},d=(a,o,l)=>{if(l!==void 0&&o.at<=l.answeredAt&&o.value<l.value)return;let y=g(a,performance.now());if(y===void 0){v.set(a,o);return}o.value<y.value||v.set(a,{value:o.value,at:Math.max(y.at,o.at)})},p=a=>{let o=h.get(a);if(o!==void 0)return o.count+=1,o;let l={count:1,floor:void 0};return h.set(a,l),l},S=(a,o)=>{o.count-=1,o.count===0&&h.delete(a)},P=(a,o)=>{a.floor={value:a.floor===void 0?o:Math.max(a.floor.value,o),answeredAt:performance.now()}},s=(a,o)=>{let l=m.get(a);return l===void 0?!1:o<l?!0:(m.delete(a),!1)},r=(a,o)=>{let l=performance.now();return m.set(a,l+u),l-k>=Ge&&(k=l,t.warn("Session generation store unavailable; skipping the sign-out generation check:",o)),"unavailable"},i=(a,o,l)=>new Promise((y,R)=>{let{operation:G}=a,I=a.operation==="advance"?a.from+1:0,pe=performance.now(),F=p(l),M=!1,ne=setTimeout(()=>{M=!0,y({kind:"unavailable",error:new q(`sessionGeneration.store.${G} did not settle within ${w} ms`)})},w);new Promise(_=>_(a.operation==="advance"?c.advance(o,a.from):c.current(o))).then(_=>{if(clearTimeout(ne),!(N(_)&&_>=I)){S(l,F),M||(M=!0,R(new TypeError(`sessionGeneration.store.${G} must resolve to an integer >= ${I}; got ${O(_)}`)));return}G==="advance"&&(P(F,_),A.delete(l)),d(l,{value:_,at:pe},F.floor),S(l,F),!M&&(M=!0,m.delete(l),y({kind:"value",value:_}))},_=>{if(clearTimeout(ne),S(l,F),!M){if(M=!0,_ instanceof q){y({kind:"unavailable",error:_});return}R(_)}})}),T=(a,o,l)=>{let y=A.get(o);if(y!==void 0&&l-y.startedAt<u)return y.read;let R={read:i({operation:"current"},a,o),startedAt:l};A.set(o,R);let G=()=>{A.get(o)===R&&A.delete(o)};return R.read.then(G,G),R.read},E=async(a,o,l)=>{let y=await i({operation:"current"},a,o);return y.kind==="unavailable"?r(o,y.error):l===y.value?"current":"stale"};return{check:async(a,o)=>{if(!(N(o)&&X(a)))return"stale";let l=performance.now(),y=f(a),R=g(y,l);if(R!==void 0){if(o===R.value)return"current";if(o<R.value)return"stale"}if(s(y,l))return"unavailable";if(R!==void 0)return await E(a,y,o);let G=await T(a,y,l);return G.kind==="unavailable"?r(y,G.error):o===G.value?"current":o<G.value?"stale":await E(a,y,o)},stamp:async a=>{if(!X(a))throw ae(a);let o=await i({operation:"current"},a,f(a));if(o.kind==="unavailable")throw o.error;return o.value},advance:async(a,o)=>{if(!X(a))return{kind:"failed",error:ae(a)};if(!Ee(o))return{kind:"failed",error:_e(o)};try{let l=await i({operation:"advance",from:o},a,f(a));return l.kind==="value"?{kind:"advanced",generation:l.value}:{kind:"unavailable",error:l.error}}catch(l){return{kind:"failed",error:l}}}}};var L=class extends Error{constructor(t){super(t),this.name="TokenRefreshError"}},D=class extends L{constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},C=class extends Error{constructor(t){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=t}},be=["access_token","expires_in"],J=(e,t,n)=>{let c=e.loginPath??"/auth/login",u=t.sessionKey,w=async m=>{let k=m.get(u)?.refreshToken;if(!k)throw new Error("Refresh token not found in session");try{let f="https://www.googleapis.com/oauth2/v4/token",g={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:k},p=await(e.fetch??globalThis.fetch)(f,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(g)});if(!p.ok){let i=await p.json().catch(()=>{});if(p.status===400&&typeof i=="object"&&!!i&&"error"in i&&i.error==="invalid_grant")throw new D;let E=typeof i=="object"&&i&&"error_description"in i?String(i.error_description):"Unknown error";throw new L(`Google token refresh failed: ${p.status} ${E}`)}let S=await p.json(),P=be.filter(i=>!S?.[i]);if(P.length>0)throw n.error("Invalid token response from Google; missing or empty keys:",P.join(", ")),new Error("Invalid token response from Google");let{access_token:s,expires_in:r}=S;return{accessToken:s,refreshToken:k,expirationDateMs:Number(Date.now())+r*1e3}}catch(f){if(f instanceof L)throw f;let g=f instanceof Error?f.message:"Unknown error";throw new L(`Failed to refresh Google access token: ${g}`)}},v=async m=>{let k=m.get(u).provider;if(!k)throw new Error("Provider not found in session");if(k==="google")return await w(m);throw new Error("Provider not supported")};return{authenticate:async(m,h,k)=>{let{failureRedirect:f}=k||{},g=d=>{if(f===null)return new C(d);if(f==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let p=f??c;return d!==void 0?le(p,{headers:{"Set-Cookie":d}}):le(p)};try{if(e.mockUser?.enabled(m)){let{accessToken:r,refreshToken:i,expirationDateMs:T}=e.mockUser.resolve(m);return{accessToken:r,refreshToken:i,expirationDateMs:T}}let d=h.get(u),p=t.sessionGenerationGate;if(d!==void 0&&p!==null&&await p.check(U(d),h.get(x))==="stale")throw g(await t.destroySession(h));if(!(d?.accessToken&&d.expirationDateMs))throw g();let{accessToken:S,refreshToken:P,expirationDateMs:s}=d;if(s<Date.now())throw P?new Error("Expired"):g();return{accessToken:S,refreshToken:P,expirationDateMs:s}}catch(d){if(d instanceof Error&&d.message==="Expired")try{let p=await v(h),S=h.get(u);return h.set(u,{...S,...p}),p}catch(p){if(p instanceof D)n.warn("Google refresh token invalid or revoked");else{let P=p instanceof Error?p.message:"Unknown error";n.error("Failed to refresh token:",P)}let S=await t.destroySession(h);throw g(S)}throw d}},refreshedAccessToken:v}};import{redirect as fe}from"react-router";var j=({refreshToken:e,...t})=>t;var W=(e,t,n,c)=>{let u=new Map,w=new Map,v=async f=>{let g=u.get(f);if(g!==void 0)return g;let d=w.get(f);if(d!==void 0)return d;let p=(async()=>{try{let S=e.getUserPhoto?await e.getUserPhoto(f):"";return u.set(f,S),S}catch(S){throw u.delete(f),S}finally{w.delete(f)}})();return w.set(f,p),p},A=new WeakMap,m=async f=>{e.warmup&&await e.warmup();let g=await t.resolveSession(f);if(g.kind==="revoked")return{kind:"unauthenticated",cookie:await t.destroySession(g.session)};if(g.kind!=="signed-in")return{kind:"unauthenticated"};let{user:d,session:p}=g,S;try{S=await n.authenticate(f,p,{failureRedirect:null})}catch(b){if(b instanceof C)return b.setCookie!==void 0?{kind:"unauthenticated",cookie:b.setCookie}:{kind:"unauthenticated"};throw c.error("Error in authenticateInLoader:",b),b}let P={accessToken:S.accessToken,refreshToken:S.refreshToken,expirationDateMs:S.expirationDateMs,provider:d.provider},s={id:d.id,displayName:d.displayName,name:d.name,emails:d.emails,...P,role:d.role},r=await v(d.id),i=j({...d,...P,photo:r}),E=S.accessToken!==d.accessToken?await t.saveSession(f,s):void 0;return E!==void 0?{kind:"authenticated",user:i,cookie:E}:{kind:"authenticated",user:i}},h=f=>{let g=A.get(f);if(g!==void 0)return g;let d=m(f);return A.set(f,d),d};async function k(f,g){let{failureRedirect:d}=g;if(d==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let p=await h(f);if(p.kind==="authenticated")return p.cookie!==void 0?{user:p.user,cookie:p.cookie}:{user:p.user};if(d===null)return p.cookie!==void 0?{cookie:p.cookie}:{};throw p.cookie!==void 0?fe(d,{headers:{"Set-Cookie":p.cookie}}):fe(d)}return k};import{resolveAuthMessages as Ue}from"@aiquants/auth-core";import{redirect as H}from"react-router";import{Authenticator as Le}from"remix-auth";import{OAuth2Strategy as Ie}from"remix-auth-oauth2";var Oe=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],xe="google",Me="https://www.googleapis.com/oauth2/v3/userinfo",V=class extends Ie{constructor({clientId:n,clientSecret:c,redirectURI:u,scopes:w,accessType:v,includeGrantedScopes:A,prompt:m,hd:h,loginHint:k,additionalScopes:f},g){let d=w??Oe;super({clientId:n,clientSecret:c,redirectURI:u,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:d},g);this.name=xe;this.scopes=d,this.accessType=v??"online",this.includeGrantedScopes=A??!1,this.prompt=m,this.hd=h,this.loginHint=k,this.additionalScopes=f}authorizationParams(n,c){n.set("access_type",this.accessType),n.set("include_granted_scopes",String(this.includeGrantedScopes));let u=c===void 0||this.additionalScopes===void 0?[]:this.additionalScopes(c);for(let v of u)if(v===""||/\s/u.test(v))throw new RangeError(`[auth-react-router] an additional scope must be a non-empty string without white space; got ${JSON.stringify(v)}`);let w=[...new Set([...this.scopes,...u])];return w.length>0&&n.set("scope",w.join(" ")),this.prompt&&n.set("prompt",this.prompt),this.hd&&n.set("hd",this.hd),this.loginHint&&n.set("login_hint",this.loginHint),n}static async userProfile(n){let c=await fetch(Me,{headers:{Authorization:`Bearer ${n.accessToken()}`}});if(!c.ok)throw new Error(`Failed to fetch user profile: ${c.statusText}`);let u=await c.json();return{id:u.sub,displayName:u.name,name:{familyName:u.family_name,givenName:u.given_name},emails:[{value:u.email}],photos:[{value:u.picture}],_json:u}}};var $={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var z=e=>{let t=e.logger??$,n=Ue(e.messages),c=e.loginPath??"/auth/login",u=new V({clientId:e.google.clientId,clientSecret:e.google.clientSecret,redirectURI:e.google.redirectURI,scopes:e.google.scopes,accessType:e.google.accessType??"offline",includeGrantedScopes:e.google.includeGrantedScopes??!0,prompt:e.google.prompt??"consent",additionalScopes:e.google.additionalScopes},async({request:v,tokens:A})=>{let{access_token:m,refresh_token:h,expires_in:k,scope:f,id_token:g}=A.data,{_json:{sub:d,email:p,picture:S,hd:P,email_verified:s},photos:r,...i}=await V.userProfile(A),{id:T,displayName:E,name:{familyName:b,givenName:Y},emails:B}=i,a="google";if(m===void 0||h===void 0||k===void 0||f===void 0||T===void 0||E===void 0||d===void 0||p===void 0||s===void 0){if(s===!1){let l=encodeURIComponent(n.emailNotVerified);throw H(`${c}?error=${l}`)}let o=encodeURIComponent(n.googleFailed);throw H(`${c}?error=${o}`)}t.info("Authenticated on Google: ",i.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(a,m)){t.error("Backend verification returned false for user:",i.displayName);let I=encodeURIComponent(n.backendFailed);throw H(`${c}?error=${I}`)}t.info("Authenticated on Backend: ",i.displayName)}let o=i.emails[0]?.value;if(!await e.isEmailAllowed(o)){let G=new Error("You are not allowed to access this application");throw t.error(G),G}if(e.isUserActive&&!await e.isUserActive(i)){let G=new Error("You are not allowed to access this application");throw t.error("Deactivated account attempted to sign in:",o),G}e.backendAuth&&await e.backendAuth.signup(a,m,i),t.info("Authenticated complete: ",i.displayName);let l=Date.now()+k*1e3;return{...i,...{accessToken:m,refreshToken:h,expirationDateMs:l,provider:a},photo:S}}catch(o){let l=o;typeof o=="object"&&o!==null&&"cause"in o&&(l=o.cause||o),t.error("Error during backend authentication or subsequent processing:",l);let y=n.unexpected,R=!1;if(typeof o=="object"&&o!==null&&"cause"in o){let I=o.cause;I&&typeof I=="object"&&"message"in I&&typeof I.message=="string"&&I.message.includes("getaddrinfo ENOTFOUND")&&(y=n.backendUnreachable,R=!0)}if(!R&&o instanceof Error&&o.message.includes("You are not allowed to access this application")&&(y=n.notAllowed,R=!0),!R&&o instanceof Response&&o.headers.get("Location")?.startsWith(c))throw o;let G=encodeURIComponent(y);throw H(`${c}?error=${G}`)}}),w=new Le;return w.use(u),w};import{redirect as K}from"react-router";var Ne=new Map([["document",new Set(["none","same-origin","same-site"])],["empty",new Set(["same-origin"])]]),Q=e=>{let t=e.headers.get("Sec-Fetch-Dest");if(t!==null){let c=Ne.get(t);if(c===void 0)return`its fetch destination is "${t}"`;let u=e.headers.get("Sec-Fetch-Site");if(u===null)return`its "${t}" request states no site`;if(!c.has(u))return`its "${t}" request comes from a "${u}" page`}let n=e.headers.get("Sec-Purpose");if(n!==null)return`it is speculative ("${n}")`},Z=e=>new Response(`Signing out is refused because ${e}: only a navigation that does not come from another site, or a script's request from this origin, signs out.`,{status:403,headers:{"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"}});var ee=(e,t,n,c)=>{let u=e.loginPath??"/auth/login",w=e.postLoginRedirect??"/",v=e.postLogoutRedirect??"/",A=re(e.google.revocationTimeoutMs),m=async({request:s})=>{if(await t.getSessionUser(s))throw K(w);return{error:new URL(s.url).searchParams.get("error")}},h=async({request:s})=>{if((await s.clone().formData()).get("_action")!=="Sign In with Google")return null;throw await n.authenticate("google",s),K(u)},k=(s,r)=>{switch(s.outcome){case"failed":c.error(`Sign-out could not revoke the Google grant of user ${String(r)}; the session cookie is destroyed, but the grant stays valid until it expires or is revoked elsewhere:`,s.reason);return;case"already-invalid":c.info(`Sign-out found the Google grant of user ${String(r)} already unusable`);return;case"revoked":case"nothing-to-revoke":return}},f=(s,r)=>{s.kind!=="advanced"&&c.error(`Sign-out could not advance the session generation of ${r.provider} user ${r.id}; a session cookie refreshed before this sign-out stays valid until a later sign-out advances the generation or the cookie expires:`,s.error)},g=async(s,r)=>{let i=t.sessionGenerationGate;if(i!==null){if(!N(r)){c.info(`Sign-out found no usable session generation stamp in the session of ${s.provider} user ${s.id}; every guard already rejects that cookie, so the generation is not advanced`);return}f(await i.advance(s,r),s)}},d=async s=>{let r=await t.getSession(s),i=r.get(t.sessionKey),[T]=await Promise.all([se(i,{fetch:e.fetch??globalThis.fetch,timeoutMs:A}),i===void 0?void 0:g(U(i),r.get(x))]);return k(T,i?.id),await t.destroySession(r)},p=async s=>{let r=await d(s),i=new Headers;return i.append("Set-Cookie",r),K(v,{headers:i})};return{loginLoader:m,loginAction:h,logoutLoader:async({request:s})=>{let r=Q(s);throw r!==void 0?Z(r):await p(s)},logout:d,logoutAndRedirect:p,googleCallbackLoader:async({request:s})=>{try{let r=await n.authenticate("google",s),E=(await t.getSession(s)).get(t.sessionKey)?.refreshToken,b={accessToken:r.accessToken,refreshToken:r.refreshToken||E,expirationDateMs:r.expirationDateMs,provider:r.provider},Y={id:r.id,displayName:r.displayName,name:r.name,emails:r.emails,...b,role:r.role},B=await t.saveSignedInSession(s,Y);throw K(w,{headers:{"Set-Cookie":B}})}catch(r){throw r instanceof Response?r:(c.error("Authentication error:",r),K(u))}}}};import{createCookieSessionStorage as Ce,redirect as te}from"react-router";var oe=(e,t)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(s=>!s))throw new Error("REMIX_SESSION_SECRET must be set");let n=e.sessionKey??"user";if(n===x)throw new RangeError(`session.sessionKey must not be ${JSON.stringify(x)}, the key the session generation is stored under; got ${JSON.stringify(n)}`);let c=e.maxAge??3600*24*30,u=t.loginPath??"/auth/login",w=t.postLoginRedirect??"/",v=t.mockUser,A=t.isUserActive,m=de(t.sessionGeneration,t.logger??$),h=Ce({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:e.secure??process.env.NODE_ENV==="production",maxAge:c}}),k=async s=>await h.getSession(s.headers.get("Cookie")),f=async s=>{if(v?.enabled(s))return{kind:"signed-in",user:j(v.resolve(s)),session:await k(s)};let r=await k(s),i=r.get(n);if(i===void 0)return{kind:"signed-out"};let T=j(i),[E,b]=await Promise.all([A===void 0?!0:A(T),m===null?"current":m.check(U(i),r.get(x))]);return b==="stale"?{kind:"revoked",session:r}:E?{kind:"signed-in",user:T,session:r}:{kind:"inactive"}},g=async s=>{let r=await f(s);return r.kind==="signed-in"?r.user:void 0},d=async(s,r)=>{let i=await k(s);return i.set(n,r),await h.commitSession(i)},p=async(s,r)=>{let i=m===null?void 0:await m.stamp(U(r)),T=await k(s);return T.set(n,r),i!==void 0&&T.set(x,i),await h.commitSession(T)},S=async s=>{let r=await f(s);switch(r.kind){case"signed-in":return r.user;case"revoked":throw te(u,{headers:{"Set-Cookie":await h.destroySession(r.session)}});case"signed-out":case"inactive":throw te(u)}};return{sessionStorage:h,sessionKey:n,sessionGenerationGate:m,getSession:k,resolveSession:f,getSessionUser:g,saveSession:d,saveSignedInSession:p,requireUser:S,requireAdminUser:async s=>{let r=await S(s);if(r.role!=="admin")throw te(w);return r},commitSession:h.commitSession,destroySession:h.destroySession}};var $e=e=>{let t=e.logger??$,n=oe(e.session,{sessionGeneration:e.sessionGeneration,logger:t,mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive}),c=z(e),u=J(e,n,t),w=W(e,n,u,t),v=ee(e,n,c,t);return{authenticator:c,storage:n,authFns:u,sessionStorage:n.sessionStorage,getSession:n.getSession,getSessionUser:n.getSessionUser,saveSession:n.saveSession,requireUser:n.requireUser,requireAdminUser:n.requireAdminUser,commitSession:n.commitSession,destroySession:n.destroySession,authenticate:u.authenticate,refreshedAccessToken:u.refreshedAccessToken,authenticateInLoader:w,...v}};export{C as AuthRequiredError,he as DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS,ce as DEFAULT_SESSION_GENERATION_CACHE_TTL_MS,ue as DEFAULT_SESSION_GENERATION_TIMEOUT_MS,D as GoogleInvalidGrantError,q as SessionGenerationUnavailableError,L as TokenRefreshError,ee as createAuthHandlers,$e as createAuthServer,oe as createAuthSessionStorage,J as createAuthenticate,W as createAuthenticateInLoader,z as createGoogleAuthenticator,Q as signOutRefusal,Z as signOutRefusalResponse};
|
|
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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aiquants/auth-react-router",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.26.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"
|
|
@@ -24,6 +24,11 @@
|
|
|
24
24
|
"import": "./dist/admin.mjs",
|
|
25
25
|
"require": "./dist/admin.js"
|
|
26
26
|
},
|
|
27
|
+
"./return-to": {
|
|
28
|
+
"types": "./dist/return-to.d.ts",
|
|
29
|
+
"import": "./dist/return-to.mjs",
|
|
30
|
+
"require": "./dist/return-to.js"
|
|
31
|
+
},
|
|
27
32
|
"./styles/auth-react-router.standalone.css": "./dist/styles/auth-react-router.standalone.css"
|
|
28
33
|
},
|
|
29
34
|
"files": [
|
|
@@ -52,7 +57,7 @@
|
|
|
52
57
|
"@aiquants/auth-core": "0.6.1",
|
|
53
58
|
"@aiquants/fuzzy-search": "3.2.0",
|
|
54
59
|
"@aiquants/select-box": "0.16.3",
|
|
55
|
-
"@aiquants/virtualscroll": "3.
|
|
60
|
+
"@aiquants/virtualscroll": "3.19.0",
|
|
56
61
|
"@tailwindcss/cli": "^4.1.18",
|
|
57
62
|
"@testing-library/react": "^16.3.2",
|
|
58
63
|
"@types/node": "^25.9.1",
|
|
@@ -74,7 +79,7 @@
|
|
|
74
79
|
"@aiquants/auth-core": "^0.6.1",
|
|
75
80
|
"@aiquants/fuzzy-search": "^3.2.0",
|
|
76
81
|
"@aiquants/select-box": "^0.16.3",
|
|
77
|
-
"@aiquants/virtualscroll": "^3.
|
|
82
|
+
"@aiquants/virtualscroll": "^3.19.0",
|
|
78
83
|
"react": ">=18",
|
|
79
84
|
"react-dom": ">=18",
|
|
80
85
|
"react-icons": ">=5",
|
|
@@ -90,7 +95,9 @@
|
|
|
90
95
|
"access": "public"
|
|
91
96
|
},
|
|
92
97
|
"scripts": {
|
|
93
|
-
"build": "
|
|
98
|
+
"build": "pnpm -w run workspace:build \"$PNPM_SCRIPT_SRC_DIR\"",
|
|
99
|
+
"prebuild:self": "pnpm -w run workspace:sync \"$PNPM_SCRIPT_SRC_DIR\"",
|
|
100
|
+
"build:self": "tsup && pnpm build:css && node ../../.config/scripts/strip-dts-comments.mjs dist",
|
|
94
101
|
"build:css": "tailwindcss -i src/styles/standalone.entry.css -o dist/styles/auth-react-router.standalone.css --minify",
|
|
95
102
|
"watch:css": "tailwindcss -i src/styles/standalone.entry.css -o dist/styles/auth-react-router.standalone.css --minify --watch",
|
|
96
103
|
"build:watch": "tsup --watch --onSuccess \"pnpm build:css\"",
|