@aiquants/auth-react-router 0.21.0 → 0.22.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 CHANGED
@@ -51,6 +51,29 @@ export const authServer = createAuthServer({
51
51
  export const { authenticator, sessionStorage, getSession, getSessionUser, saveSession, requireUser, requireAdminUser, commitSession, destroySession, authenticate, refreshedAccessToken, authenticateInLoader, loginLoader, loginAction, logoutLoader, logout, logoutAndRedirect, googleCallbackLoader } = authServer
52
52
  ```
53
53
 
54
+ Optional settings for sign-out and the token requests:
55
+
56
+ ```ts
57
+ createAuthServer({
58
+ google: { ..., revocationTimeoutMs: 3_000 }, // how long sign-out waits for Google's revocation (default 5000)
59
+ fetch: instrumentedFetch, // the fetch for the token refresh and the revocation (default: global fetch)
60
+ ...
61
+ })
62
+ ```
63
+
64
+ A host that writes its own sign-out route (to add headers to the answer, say) applies the same request rule as
65
+ `logoutLoader` before signing out:
66
+
67
+ ```ts
68
+ import { signOutRefusal, signOutRefusalResponse } from "@aiquants/auth-react-router/server"
69
+
70
+ export const loader = async ({ request }: LoaderFunctionArgs) => {
71
+ const refusal = signOutRefusal(request)
72
+ if (refusal !== undefined) throw signOutRefusalResponse(refusal) // 403, no Set-Cookie, session and grant untouched
73
+ throw await authServer.logoutAndRedirect(request) // revokes the grant, then deletes the session cookie
74
+ }
75
+ ```
76
+
54
77
  Client:
55
78
 
56
79
  ```tsx
@@ -300,6 +323,65 @@ package's own `react: ">=18"`; a host that mounts `/admin` must satisfy the stri
300
323
  - **One authentication per request**: the guard performs its work at most once per `Request` instance and shares a mode-neutral result, so a root loader (`null`) and a leaf loader (`"/auth/login"`) in the same React Router data pass share a single pass — one warmup, one token refresh, one `Set-Cookie`. The failure policy is applied per caller on top of the shared result, so it must never be part of the cache key.
301
324
  - **Infrastructure failures are never laundered into logouts**: anything that is not an authentication failure (an unexpected error inside the auth step, a `getUserPhoto` port outage, a `saveSession` failure) propagates unchanged in **both** modes. The session is not destroyed and no redirect is produced.
302
325
  - Photo lookups are cached with in-flight dedup per factory instance.
326
+ - **Profiles handed to route code carry no refresh token**: `authenticateInLoader` returns `user: LoaderUser`
327
+ (`Omit<MyGoogleProfile, "refreshToken">`) and `getSessionUser` / `requireUser` / `requireAdminUser` return `SessionUser`
328
+ (`Omit<SessionProfile, "refreshToken">`); the key is absent at runtime as well, for the `mockUser` backdoor's user and for
329
+ the profile handed to `isUserActive` too. `loginAction`'s data is always `null`. Loader and action data reach the
330
+ document's HTML and the `.data` answers, so only the package reads the refresh token, from the `HttpOnly` session
331
+ cookie: to refresh an expired access token and to revoke the grant. The access token stays (pages use it in the
332
+ browser).
333
+ - These public routes still hand out the raw refresh token, so nothing they return may go into loader or action data:
334
+ - `getSession` and `sessionStorage` (on the bundle, on `storage` and on the result of `createAuthSessionStorage`): the
335
+ raw session, whose stored profile holds the token.
336
+ - `authenticate` / `refreshedAccessToken` (on the bundle and on the `authFns` bundle, both built by
337
+ `createAuthenticate`): the `{ accessToken, refreshToken, expirationDateMs }` they return.
338
+ - `authenticator` (from `createGoogleAuthenticator`): the `MyGoogleProfile` its `authenticate("google", request)`
339
+ resolves to when it completes the code exchange.
340
+ - The `Set-Cookie` values of `saveSession` / `commitSession` and the `cookie` of `authenticateInLoader`: the session
341
+ cookie is signed, not encrypted, so the token can be read out of it. Put them in a `Set-Cookie` header only.
342
+ - **`loginAction` never hands out the signed-in profile**: for `_action === "Sign In with Google"` it always ends by
343
+ throwing a redirect. The strategy normally throws the redirect to Google's authorization endpoint. When the POST's URL
344
+ carries `code` and the `state` of the user's state cookie, remix-auth exchanges the code inside the action and returns
345
+ the profile with the user's tokens; `loginAction` discards it, saves no session and throws a redirect to `loginPath`
346
+ (a sign-in completes only through `googleCallbackLoader`). Its type is `Promise<null>`: any other `_action` returns
347
+ `null`.
348
+ - **Sign-out revokes the Google grant before it answers**: `logout` (and `logoutAndRedirect` / `logoutLoader`, which call it)
349
+ POSTs the session's refresh token, or its access token when there is none, to `https://oauth2.googleapis.com/revoke` (in the
350
+ form body, never the URL), waits until that settles, then destroys the session. The wait is bounded by
351
+ `google.revocationTimeoutMs` (default `DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS`, 5000 ms; any value other than an integer from
352
+ 1 to 2147483647 throws `RangeError` when the server is built). A revocation that Google refuses, that cannot reach Google
353
+ or that times out is logged with `logger.error` (never the token) and the session is destroyed anyway; Google's
354
+ `400 invalid_token` (the token is already unusable) is logged with `logger.info`. A session of another provider is never
355
+ sent to Google.
356
+ - Revoking withdraws the user's grant to the OAuth client, so the user's sessions in other browsers end at their next
357
+ token refresh (within about an hour), and a service sharing the OAuth client loses the grant as well.
358
+ - Revocation alone does not close one race: a token refresh that reached Google before the revocation can still set a
359
+ refreshed session cookie after the sign-out's answer. Its access token is unexpired, and the package does not contact
360
+ Google while it is, so `authenticateInLoader` accepts that cookie until the token expires (about an hour), and the
361
+ session getters (`getSessionUser` / `requireUser` / `requireAdminUser`), which never look at the expiry, accept it until
362
+ the first `authenticateInLoader` after the expiry fails to refresh (`invalid_grant`) and deletes it. Closing that race
363
+ needs server-side session state, which this package does not keep.
364
+ - **`logoutLoader` refuses sign-outs the user did not ask for**, judged by the request's fetch metadata
365
+ (`signOutRefusal`). It signs out a `Sec-Fetch-Dest: document` request only when its `Sec-Fetch-Site` is `none` (a typed
366
+ address or a bookmark), `same-origin` or `same-site`, and a `Sec-Fetch-Dest: empty` request only when it is
367
+ `same-origin` (the router's data request; a script's request from another origin of the same site carries the
368
+ `SameSite=Lax` cookie too). Every other destination, a navigation from another site (`cross-site`: sign-out revokes the
369
+ grant and so ends the user's sessions on every device, which another site's link or script must not be able to cause),
370
+ a request that states a destination but no `Sec-Fetch-Site`, and any request carrying `Sec-Purpose` (a prefetch or
371
+ prerender) is answered with 403 (`signOutRefusalResponse`: plain text, `Cache-Control: no-store`, no `Set-Cookie`), and
372
+ neither the session nor the grant is touched. A request without fetch metadata signs out. Without this, an
373
+ `<img src="/auth/logout">` in any rendered document signs the reader out. `logout` and `logoutAndRedirect` do not check
374
+ the request: a route that calls them applies `signOutRefusal` first.
375
+ - **The rule needs HTTPS**: browsers send the `Sec-Fetch-*` headers only to potentially trustworthy URLs (`https:`, or
376
+ `http:` to a loopback host such as `localhost`). A site served over plain HTTP from any other host receives none, so
377
+ every sign-out there is judged as a request without fetch metadata and the rule refuses only a request carrying
378
+ `Sec-Purpose`: an `<img src="/auth/logout">` in a rendered document, or a link on another site, signs the user out.
379
+ - Requests without fetch metadata also come from browsers older than it and from clients that are not browsers. They
380
+ sign out so that those users keep a working sign-out, which leaves them open to every sign-out the rule refuses
381
+ except one carrying `Sec-Purpose`.
382
+ - **`config.fetch`** (`FetchPort`) is the `fetch` for the two requests the package sends with a session's tokens: the token
383
+ refresh and the revocation. Default: the global `fetch`, looked up at each request. The sign-in exchange (authorization
384
+ code and userinfo) always uses the global `fetch`.
303
385
 
304
386
  ## DI Ports Absorbing Per-App Differences
305
387
 
package/dist/server.d.mts CHANGED
@@ -1,9 +1,11 @@
1
+ import * as _aiquants_auth_core from "@aiquants/auth-core";
2
+ import { SessionProfile, MyGoogleProfile, GoogleProfileBase, AuthMessages } from "@aiquants/auth-core";
1
3
  import * as react_router from "react-router";
2
4
  import { Session } from "react-router";
3
5
  import * as remix_auth from "remix-auth";
4
6
  import { Authenticator } from "remix-auth";
5
- import * as _aiquants_auth_core from "@aiquants/auth-core";
6
- import { GoogleProfileBase, SessionProfile, AuthMessages, MyGoogleProfile } from "@aiquants/auth-core";
7
+ type SessionUser = Omit<SessionProfile, "refreshToken">;
8
+ type LoaderUser = Omit<MyGoogleProfile, "refreshToken">;
7
9
  type GoogleOAuthConfig = {
8
10
  clientId: string;
9
11
  clientSecret: string;
@@ -12,7 +14,9 @@ type GoogleOAuthConfig = {
12
14
  accessType?: "online" | "offline";
13
15
  includeGrantedScopes?: boolean;
14
16
  prompt?: "none" | "consent" | "select_account";
17
+ revocationTimeoutMs?: number;
15
18
  };
19
+ type FetchPort = (url: string, init: RequestInit) => Promise<Response>;
16
20
  type SessionConfig = {
17
21
  secrets: string[];
18
22
  cookieName?: string;
@@ -49,6 +53,7 @@ type AuthServerConfig = {
49
53
  postLogoutRedirect?: string;
50
54
  messages?: Partial<AuthMessages>;
51
55
  logger?: LoggerPort;
56
+ fetch?: FetchPort;
52
57
  };
53
58
  type AuthServer = ReturnType<typeof createAuthServer>;
54
59
  declare const createAuthServer: (config: AuthServerConfig) => {
@@ -59,7 +64,7 @@ declare const createAuthServer: (config: AuthServerConfig) => {
59
64
  }>;
60
65
  loginAction: ({ request }: {
61
66
  request: Request;
62
- }) => Promise<_aiquants_auth_core.MyGoogleProfile | null>;
67
+ }) => Promise<null>;
63
68
  logoutLoader: ({ request }: {
64
69
  request: Request;
65
70
  }) => Promise<never>;
@@ -73,11 +78,10 @@ declare const createAuthServer: (config: AuthServerConfig) => {
73
78
  sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
74
79
  sessionKey: string;
75
80
  getSession: (request: Request) => Promise<react_router.Session<react_router.SessionData, react_router.SessionData>>;
76
- getSessionUser: (request: Request) => Promise<_aiquants_auth_core.SessionProfile | undefined>;
81
+ getSessionUser: (request: Request) => Promise<SessionUser | undefined>;
77
82
  saveSession: (request: Request, user: _aiquants_auth_core.SessionProfile) => Promise<string>;
78
- requireUser: (request: Request) => Promise<_aiquants_auth_core.SessionProfile>;
79
- requireAdminUser: (request: Request) => Promise<_aiquants_auth_core.SessionProfile>;
80
- logout: (request: Request) => Promise<string>;
83
+ requireUser: (request: Request) => Promise<SessionUser>;
84
+ requireAdminUser: (request: Request) => Promise<SessionUser>;
81
85
  commitSession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
82
86
  destroySession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
83
87
  };
@@ -97,10 +101,10 @@ declare const createAuthServer: (config: AuthServerConfig) => {
97
101
  };
98
102
  sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
99
103
  getSession: (request: Request) => Promise<react_router.Session<react_router.SessionData, react_router.SessionData>>;
100
- getSessionUser: (request: Request) => Promise<_aiquants_auth_core.SessionProfile | undefined>;
104
+ getSessionUser: (request: Request) => Promise<SessionUser | undefined>;
101
105
  saveSession: (request: Request, user: _aiquants_auth_core.SessionProfile) => Promise<string>;
102
- requireUser: (request: Request) => Promise<_aiquants_auth_core.SessionProfile>;
103
- requireAdminUser: (request: Request) => Promise<_aiquants_auth_core.SessionProfile>;
106
+ requireUser: (request: Request) => Promise<SessionUser>;
107
+ requireAdminUser: (request: Request) => Promise<SessionUser>;
104
108
  commitSession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
105
109
  destroySession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
106
110
  authenticate: (request: Request, session: react_router.Session, options?: {
@@ -119,13 +123,13 @@ declare const createAuthServer: (config: AuthServerConfig) => {
119
123
  (request: Request, options: {
120
124
  failureRedirect: string;
121
125
  }): Promise<{
122
- user: _aiquants_auth_core.MyGoogleProfile;
126
+ user: LoaderUser;
123
127
  cookie?: string;
124
128
  }>;
125
129
  (request: Request, options: {
126
130
  failureRedirect: null;
127
131
  }): Promise<{
128
- user?: _aiquants_auth_core.MyGoogleProfile;
132
+ user?: LoaderUser;
129
133
  cookie?: string;
130
134
  }>;
131
135
  };
@@ -140,11 +144,10 @@ declare const createAuthSessionStorage: (config: SessionConfig, options?: {
140
144
  sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
141
145
  sessionKey: string;
142
146
  getSession: (request: Request) => Promise<react_router.Session<react_router.SessionData, react_router.SessionData>>;
143
- getSessionUser: (request: Request) => Promise<SessionProfile | undefined>;
147
+ getSessionUser: (request: Request) => Promise<SessionUser | undefined>;
144
148
  saveSession: (request: Request, user: SessionProfile) => Promise<string>;
145
- requireUser: (request: Request) => Promise<SessionProfile>;
146
- requireAdminUser: (request: Request) => Promise<SessionProfile>;
147
- logout: (request: Request) => Promise<string>;
149
+ requireUser: (request: Request) => Promise<SessionUser>;
150
+ requireAdminUser: (request: Request) => Promise<SessionUser>;
148
151
  commitSession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
149
152
  destroySession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
150
153
  };
@@ -177,17 +180,18 @@ declare const createAuthenticateInLoader: (config: AuthServerConfig, storage: Au
177
180
  (request: Request, options: {
178
181
  failureRedirect: string;
179
182
  }): Promise<{
180
- user: MyGoogleProfile;
183
+ user: LoaderUser;
181
184
  cookie?: string;
182
185
  }>;
183
186
  (request: Request, options: {
184
187
  failureRedirect: null;
185
188
  }): Promise<{
186
- user?: MyGoogleProfile;
189
+ user?: LoaderUser;
187
190
  cookie?: string;
188
191
  }>;
189
192
  };
190
193
  declare const createGoogleAuthenticator: (config: AuthServerConfig) => Authenticator<MyGoogleProfile>;
194
+ declare const DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS = 5000;
191
195
  declare const createAuthHandlers: (config: AuthServerConfig, storage: AuthSessionStorage, authenticator: Authenticator<MyGoogleProfile>, logger: LoggerPort) => {
192
196
  loginLoader: ({ request }: {
193
197
  request: Request;
@@ -196,7 +200,7 @@ declare const createAuthHandlers: (config: AuthServerConfig, storage: AuthSessio
196
200
  }>;
197
201
  loginAction: ({ request }: {
198
202
  request: Request;
199
- }) => Promise<MyGoogleProfile | null>;
203
+ }) => Promise<null>;
200
204
  logoutLoader: ({ request }: {
201
205
  request: Request;
202
206
  }) => Promise<never>;
@@ -206,4 +210,6 @@ declare const createAuthHandlers: (config: AuthServerConfig, storage: AuthSessio
206
210
  request: Request;
207
211
  }) => Promise<never>;
208
212
  };
209
- export { AuthRequiredError, type AuthServer, type AuthServerConfig, type AuthSessionStorage, type BackendAuthPort, GoogleInvalidGrantError, type GoogleOAuthConfig, type LoggerPort, type MockUserPort, type SessionConfig, TokenRefreshError, type UserPhotoPort, type WarmupPort, createAuthHandlers, createAuthServer, createAuthSessionStorage, createAuthenticate, createAuthenticateInLoader, createGoogleAuthenticator };
213
+ declare const signOutRefusal: (request: Request) => string | undefined;
214
+ declare const signOutRefusalResponse: (reason: string) => Response;
215
+ export { AuthRequiredError, type AuthServer, type AuthServerConfig, type AuthSessionStorage, type BackendAuthPort, DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS, type FetchPort, GoogleInvalidGrantError, type GoogleOAuthConfig, type LoaderUser, type LoggerPort, type MockUserPort, type SessionConfig, type SessionUser, TokenRefreshError, type UserPhotoPort, type WarmupPort, createAuthHandlers, createAuthServer, createAuthSessionStorage, createAuthenticate, createAuthenticateInLoader, createGoogleAuthenticator, signOutRefusal, signOutRefusalResponse };
package/dist/server.d.ts CHANGED
@@ -1,9 +1,11 @@
1
+ import * as _aiquants_auth_core from "@aiquants/auth-core";
2
+ import { SessionProfile, MyGoogleProfile, GoogleProfileBase, AuthMessages } from "@aiquants/auth-core";
1
3
  import * as react_router from "react-router";
2
4
  import { Session } from "react-router";
3
5
  import * as remix_auth from "remix-auth";
4
6
  import { Authenticator } from "remix-auth";
5
- import * as _aiquants_auth_core from "@aiquants/auth-core";
6
- import { GoogleProfileBase, SessionProfile, AuthMessages, MyGoogleProfile } from "@aiquants/auth-core";
7
+ type SessionUser = Omit<SessionProfile, "refreshToken">;
8
+ type LoaderUser = Omit<MyGoogleProfile, "refreshToken">;
7
9
  type GoogleOAuthConfig = {
8
10
  clientId: string;
9
11
  clientSecret: string;
@@ -12,7 +14,9 @@ type GoogleOAuthConfig = {
12
14
  accessType?: "online" | "offline";
13
15
  includeGrantedScopes?: boolean;
14
16
  prompt?: "none" | "consent" | "select_account";
17
+ revocationTimeoutMs?: number;
15
18
  };
19
+ type FetchPort = (url: string, init: RequestInit) => Promise<Response>;
16
20
  type SessionConfig = {
17
21
  secrets: string[];
18
22
  cookieName?: string;
@@ -49,6 +53,7 @@ type AuthServerConfig = {
49
53
  postLogoutRedirect?: string;
50
54
  messages?: Partial<AuthMessages>;
51
55
  logger?: LoggerPort;
56
+ fetch?: FetchPort;
52
57
  };
53
58
  type AuthServer = ReturnType<typeof createAuthServer>;
54
59
  declare const createAuthServer: (config: AuthServerConfig) => {
@@ -59,7 +64,7 @@ declare const createAuthServer: (config: AuthServerConfig) => {
59
64
  }>;
60
65
  loginAction: ({ request }: {
61
66
  request: Request;
62
- }) => Promise<_aiquants_auth_core.MyGoogleProfile | null>;
67
+ }) => Promise<null>;
63
68
  logoutLoader: ({ request }: {
64
69
  request: Request;
65
70
  }) => Promise<never>;
@@ -73,11 +78,10 @@ declare const createAuthServer: (config: AuthServerConfig) => {
73
78
  sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
74
79
  sessionKey: string;
75
80
  getSession: (request: Request) => Promise<react_router.Session<react_router.SessionData, react_router.SessionData>>;
76
- getSessionUser: (request: Request) => Promise<_aiquants_auth_core.SessionProfile | undefined>;
81
+ getSessionUser: (request: Request) => Promise<SessionUser | undefined>;
77
82
  saveSession: (request: Request, user: _aiquants_auth_core.SessionProfile) => Promise<string>;
78
- requireUser: (request: Request) => Promise<_aiquants_auth_core.SessionProfile>;
79
- requireAdminUser: (request: Request) => Promise<_aiquants_auth_core.SessionProfile>;
80
- logout: (request: Request) => Promise<string>;
83
+ requireUser: (request: Request) => Promise<SessionUser>;
84
+ requireAdminUser: (request: Request) => Promise<SessionUser>;
81
85
  commitSession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
82
86
  destroySession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
83
87
  };
@@ -97,10 +101,10 @@ declare const createAuthServer: (config: AuthServerConfig) => {
97
101
  };
98
102
  sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
99
103
  getSession: (request: Request) => Promise<react_router.Session<react_router.SessionData, react_router.SessionData>>;
100
- getSessionUser: (request: Request) => Promise<_aiquants_auth_core.SessionProfile | undefined>;
104
+ getSessionUser: (request: Request) => Promise<SessionUser | undefined>;
101
105
  saveSession: (request: Request, user: _aiquants_auth_core.SessionProfile) => Promise<string>;
102
- requireUser: (request: Request) => Promise<_aiquants_auth_core.SessionProfile>;
103
- requireAdminUser: (request: Request) => Promise<_aiquants_auth_core.SessionProfile>;
106
+ requireUser: (request: Request) => Promise<SessionUser>;
107
+ requireAdminUser: (request: Request) => Promise<SessionUser>;
104
108
  commitSession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
105
109
  destroySession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
106
110
  authenticate: (request: Request, session: react_router.Session, options?: {
@@ -119,13 +123,13 @@ declare const createAuthServer: (config: AuthServerConfig) => {
119
123
  (request: Request, options: {
120
124
  failureRedirect: string;
121
125
  }): Promise<{
122
- user: _aiquants_auth_core.MyGoogleProfile;
126
+ user: LoaderUser;
123
127
  cookie?: string;
124
128
  }>;
125
129
  (request: Request, options: {
126
130
  failureRedirect: null;
127
131
  }): Promise<{
128
- user?: _aiquants_auth_core.MyGoogleProfile;
132
+ user?: LoaderUser;
129
133
  cookie?: string;
130
134
  }>;
131
135
  };
@@ -140,11 +144,10 @@ declare const createAuthSessionStorage: (config: SessionConfig, options?: {
140
144
  sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
141
145
  sessionKey: string;
142
146
  getSession: (request: Request) => Promise<react_router.Session<react_router.SessionData, react_router.SessionData>>;
143
- getSessionUser: (request: Request) => Promise<SessionProfile | undefined>;
147
+ getSessionUser: (request: Request) => Promise<SessionUser | undefined>;
144
148
  saveSession: (request: Request, user: SessionProfile) => Promise<string>;
145
- requireUser: (request: Request) => Promise<SessionProfile>;
146
- requireAdminUser: (request: Request) => Promise<SessionProfile>;
147
- logout: (request: Request) => Promise<string>;
149
+ requireUser: (request: Request) => Promise<SessionUser>;
150
+ requireAdminUser: (request: Request) => Promise<SessionUser>;
148
151
  commitSession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
149
152
  destroySession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
150
153
  };
@@ -177,17 +180,18 @@ declare const createAuthenticateInLoader: (config: AuthServerConfig, storage: Au
177
180
  (request: Request, options: {
178
181
  failureRedirect: string;
179
182
  }): Promise<{
180
- user: MyGoogleProfile;
183
+ user: LoaderUser;
181
184
  cookie?: string;
182
185
  }>;
183
186
  (request: Request, options: {
184
187
  failureRedirect: null;
185
188
  }): Promise<{
186
- user?: MyGoogleProfile;
189
+ user?: LoaderUser;
187
190
  cookie?: string;
188
191
  }>;
189
192
  };
190
193
  declare const createGoogleAuthenticator: (config: AuthServerConfig) => Authenticator<MyGoogleProfile>;
194
+ declare const DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS = 5000;
191
195
  declare const createAuthHandlers: (config: AuthServerConfig, storage: AuthSessionStorage, authenticator: Authenticator<MyGoogleProfile>, logger: LoggerPort) => {
192
196
  loginLoader: ({ request }: {
193
197
  request: Request;
@@ -196,7 +200,7 @@ declare const createAuthHandlers: (config: AuthServerConfig, storage: AuthSessio
196
200
  }>;
197
201
  loginAction: ({ request }: {
198
202
  request: Request;
199
- }) => Promise<MyGoogleProfile | null>;
203
+ }) => Promise<null>;
200
204
  logoutLoader: ({ request }: {
201
205
  request: Request;
202
206
  }) => Promise<never>;
@@ -206,4 +210,6 @@ declare const createAuthHandlers: (config: AuthServerConfig, storage: AuthSessio
206
210
  request: Request;
207
211
  }) => Promise<never>;
208
212
  };
209
- export { AuthRequiredError, type AuthServer, type AuthServerConfig, type AuthSessionStorage, type BackendAuthPort, GoogleInvalidGrantError, type GoogleOAuthConfig, type LoggerPort, type MockUserPort, type SessionConfig, TokenRefreshError, type UserPhotoPort, type WarmupPort, createAuthHandlers, createAuthServer, createAuthSessionStorage, createAuthenticate, createAuthenticateInLoader, createGoogleAuthenticator };
213
+ declare const signOutRefusal: (request: Request) => string | undefined;
214
+ declare const signOutRefusalResponse: (reason: string) => Response;
215
+ export { AuthRequiredError, type AuthServer, type AuthServerConfig, type AuthSessionStorage, type BackendAuthPort, DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS, type FetchPort, GoogleInvalidGrantError, type GoogleOAuthConfig, type LoaderUser, type LoggerPort, type MockUserPort, type SessionConfig, 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 $=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var Q=Object.prototype.hasOwnProperty;var X=(e,s)=>{for(var r in s)$(e,r,{get:s[r],enumerable:!0})},Z=(e,s,r,u)=>{if(s&&typeof s=="object"||typeof s=="function")for(let i of J(s))!Q.call(e,i)&&i!==r&&$(e,i,{get:()=>s[i],enumerable:!(u=V(s,i))||u.enumerable});return e};var ee=e=>Z($({},"__esModule",{value:!0}),e);var se={};X(se,{AuthRequiredError:()=>R,GoogleInvalidGrantError:()=>G,TokenRefreshError:()=>w,createAuthHandlers:()=>O,createAuthServer:()=>Y,createAuthSessionStorage:()=>F,createAuthenticate:()=>C,createAuthenticateInLoader:()=>I,createGoogleAuthenticator:()=>D});module.exports=ee(se);var H=require("react-router"),w=class extends Error{constructor(s){super(s),this.name="TokenRefreshError"}},G=class extends w{constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},R=class extends Error{constructor(s){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=s}},C=(e,s,r)=>{let u=e.loginPath??"/auth/login",i=s.sessionKey,m=async d=>{let g=d.get(i)?.refreshToken;if(!g)throw new Error("Refresh token not found in session");try{let a="https://www.googleapis.com/oauth2/v4/token",l={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:g},t=await fetch(a,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(l)});if(!t.ok){let h=await t.json().catch(()=>{});if(t.status===400&&typeof h=="object"&&!!h&&"error"in h&&h.error==="invalid_grant")throw new G;let k=typeof h=="object"&&h&&"error_description"in h?String(h.error_description):"Unknown error";throw new w(`Google token refresh failed: ${t.status} ${k}`)}let o=await t.json(),{access_token:n,expires_in:c}=o;if(!(n&&c))throw r.error("Invalid token response from Google:",o),new Error("Invalid token response from Google");return{accessToken:n,refreshToken:g,expirationDateMs:Number(Date.now())+c*1e3}}catch(a){if(a instanceof w)throw a;let l=a instanceof Error?a.message:"Unknown error";throw new w(`Failed to refresh Google access token: ${l}`)}},y=async d=>{let g=d.get(i).provider;if(!g)throw new Error("Provider not found in session");if(g==="google")return await m(d);throw new Error("Provider not supported")};return{authenticate:async(d,p,g)=>{let{failureRedirect:a}=g||{},l=t=>{if(a===null)return new R(t);if(a==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let o=a??u;return t!==void 0?(0,H.redirect)(o,{headers:{"Set-Cookie":t}}):(0,H.redirect)(o)};try{if(e.mockUser?.enabled(d))return{accessToken:"mock-access-token",refreshToken:"mock-refresh-token",expirationDateMs:Date.now()+36e5};let t=p.get(i);if(!(t?.accessToken&&t.expirationDateMs))throw l();let{accessToken:o,refreshToken:n,expirationDateMs:c}=t;if(c<Date.now())throw n?new Error("Expired"):l();return{accessToken:o,refreshToken:n,expirationDateMs:c}}catch(t){if(t instanceof Error&&t.message==="Expired")try{let o=await y(p),n=p.get(i);return p.set(i,{...n,...o}),o}catch(o){if(o instanceof G)r.warn("Google refresh token invalid or revoked");else{let c=o instanceof Error?o.message:"Unknown error";r.error("Failed to refresh token:",c)}let n=await s.destroySession(p);throw l(n)}throw t}},refreshedAccessToken:y}};var B=require("react-router");var I=(e,s,r,u)=>{let i=new Map,m=new Map,y=async a=>{let l=i.get(a);if(l!==void 0)return l;let t=m.get(a);if(t!==void 0)return t;let o=(async()=>{try{let n=e.getUserPhoto?await e.getUserPhoto(a):"";return i.set(a,n),n}catch(n){throw i.delete(a),n}finally{m.delete(a)}})();return m.set(a,o),o},S=new WeakMap,d=async a=>{e.warmup&&await e.warmup();let l=await s.getSession(a),t=await s.getSessionUser(a);if(t===void 0)return{kind:"unauthenticated"};let o;try{o=await r.authenticate(a,l,{failureRedirect:null})}catch(A){if(A instanceof R)return A.setCookie!==void 0?{kind:"unauthenticated",cookie:A.setCookie}:{kind:"unauthenticated"};throw u.error("Error in authenticateInLoader:",A),A}let n={accessToken:o.accessToken,refreshToken:o.refreshToken,expirationDateMs:o.expirationDateMs,provider:t.provider},c={id:t.id,displayName:t.displayName,name:t.name,emails:t.emails,...n,role:t.role},h=await y(t.id),x={...t,...n,photo:h},T=o.accessToken!==t.accessToken?await s.saveSession(a,c):void 0;return T!==void 0?{kind:"authenticated",user:x,cookie:T}:{kind:"authenticated",user:x}},p=a=>{let l=S.get(a);if(l!==void 0)return l;let t=d(a);return S.set(a,t),t};async function g(a,l){let{failureRedirect:t}=l;if(t==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let o=await p(a);if(o.kind==="authenticated")return o.cookie!==void 0?{user:o.user,cookie:o.cookie}:{user:o.user};if(t===null)return o.cookie!==void 0?{cookie:o.cookie}:{};throw o.cookie!==void 0?(0,B.redirect)(t,{headers:{"Set-Cookie":o.cookie}}):(0,B.redirect)(t)}return g};var z=require("@aiquants/auth-core"),M=require("react-router"),W=require("remix-auth");var K=require("remix-auth-oauth2"),te=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],oe="google",re="https://www.googleapis.com/oauth2/v3/userinfo",L=class extends K.OAuth2Strategy{constructor({clientId:r,clientSecret:u,redirectURI:i,scopes:m,accessType:y,includeGrantedScopes:S,prompt:d,hd:p,loginHint:g},a){let l=m??te;super({clientId:r,clientSecret:u,redirectURI:i,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:l},a);this.name=oe;this.scopes=l,this.accessType=y??"online",this.includeGrantedScopes=S??!1,this.prompt=d,this.hd=p,this.loginHint=g}authorizationParams(r,u){return r.set("access_type",this.accessType),r.set("include_granted_scopes",String(this.includeGrantedScopes)),this.scopes&&this.scopes.length>0&&r.set("scope",this.scopes.join(" ")),this.prompt&&r.set("prompt",this.prompt),this.hd&&r.set("hd",this.hd),this.loginHint&&r.set("login_hint",this.loginHint),r}static async userProfile(r){let u=await fetch(re,{headers:{Authorization:`Bearer ${r.accessToken()}`}});if(!u.ok)throw new Error(`Failed to fetch user profile: ${u.statusText}`);let i=await u.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 N={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var D=e=>{let s=e.logger??N,r=(0,z.resolveAuthMessages)(e.messages),u=e.loginPath??"/auth/login",i=new L({clientId:e.google.clientId,clientSecret:e.google.clientSecret,redirectURI:e.google.redirectURI,scopes:e.google.scopes,accessType:e.google.accessType??"offline",includeGrantedScopes:e.google.includeGrantedScopes??!0,prompt:e.google.prompt??"consent"},async({request:y,tokens:S})=>{let{access_token:d,refresh_token:p,expires_in:g,scope:a,id_token:l}=S.data,{_json:{sub:t,email:o,picture:n,hd:c,email_verified:h},photos:x,...k}=await L.userProfile(S),{id:T,displayName:A,name:{familyName:ne,givenName:ie},emails:ae}=k,j="google";if(d===void 0||p===void 0||g===void 0||a===void 0||T===void 0||A===void 0||t===void 0||o===void 0||h===void 0){if(h===!1){let U=encodeURIComponent(r.emailNotVerified);throw(0,M.redirect)(`${u}?error=${U}`)}let f=encodeURIComponent(r.googleFailed);throw(0,M.redirect)(`${u}?error=${f}`)}s.info("Authenticated on Google: ",k.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(j,d)){s.error("Backend verification returned false for user:",k.displayName);let v=encodeURIComponent(r.backendFailed);throw(0,M.redirect)(`${u}?error=${v}`)}s.info("Authenticated on Backend: ",k.displayName)}let f=k.emails[0]?.value;if(!await e.isEmailAllowed(f)){let P=new Error("You are not allowed to access this application");throw s.error(P),P}if(e.isUserActive&&!await e.isUserActive(k)){let P=new Error("You are not allowed to access this application");throw s.error("Deactivated account attempted to sign in:",f),P}e.backendAuth&&await e.backendAuth.signup(j,d,k),s.info("Authenticated complete: ",k.displayName);let U=Date.now()+g*1e3;return{...k,...{accessToken:d,refreshToken:p,expirationDateMs:U,provider:j},photo:n}}catch(f){let U=f;typeof f=="object"&&f!==null&&"cause"in f&&(U=f.cause||f),s.error("Error during backend authentication or subsequent processing:",U);let q=r.unexpected,_=!1;if(typeof f=="object"&&f!==null&&"cause"in f){let v=f.cause;v&&typeof v=="object"&&"message"in v&&typeof v.message=="string"&&v.message.includes("getaddrinfo ENOTFOUND")&&(q=r.backendUnreachable,_=!0)}if(!_&&f instanceof Error&&f.message.includes("You are not allowed to access this application")&&(q=r.notAllowed,_=!0),!_&&f instanceof Response&&f.headers.get("Location")?.startsWith(u))throw f;let P=encodeURIComponent(q);throw(0,M.redirect)(`${u}?error=${P}`)}}),m=new W.Authenticator;return m.use(i),m};var E=require("react-router"),O=(e,s,r,u)=>{let i=e.loginPath??"/auth/login",m=e.postLoginRedirect??"/",y=e.postLogoutRedirect??"/",S=async({request:t})=>{if(await s.getSessionUser(t))throw(0,E.redirect)(m);return{error:new URL(t.url).searchParams.get("error")}},d=async({request:t})=>{let o=await t.clone().formData(),n=String(o.get("_action")),c=null;return n==="Sign In with Google"?c=await r.authenticate("google",t):c=null,c},p=async t=>await s.logout(t),g=async t=>{let o=await p(t),n=new Headers;return n.append("Set-Cookie",o),(0,E.redirect)(y,{headers:n})};return{loginLoader:S,loginAction:d,logoutLoader:async({request:t})=>{throw await g(t)},logout:p,logoutAndRedirect:g,googleCallbackLoader:async({request:t})=>{try{let o=await r.authenticate("google",t),h=(await s.getSession(t)).get(s.sessionKey)?.refreshToken,x={accessToken:o.accessToken,refreshToken:o.refreshToken||h,expirationDateMs:o.expirationDateMs,provider:o.provider},k={id:o.id,displayName:o.displayName,name:o.name,emails:o.emails,...x,role:o.role},T=await s.saveSession(t,k);throw(0,E.redirect)(m,{headers:{"Set-Cookie":T}})}catch(o){throw o instanceof Response?o:(u.error("Authentication error:",o),(0,E.redirect)(i))}}}};var b=require("react-router"),F=(e,s)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(n=>!n))throw new Error("REMIX_SESSION_SECRET must be set");let r=e.sessionKey??"user",u=e.maxAge??3600*24*30,i=s?.loginPath??"/auth/login",m=s?.postLoginRedirect??"/",y=s?.mockUser,S=s?.isUserActive,d=(0,b.createCookieSessionStorage)({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:e.secure??process.env.NODE_ENV==="production",maxAge:u}}),p=async n=>await d.getSession(n.headers.get("Cookie")),g=async n=>{if(y?.enabled(n))return y.resolve(n);let h=(await p(n)).get(r);if(h!==void 0&&!(S&&!await S(h)))return h},a=async(n,c)=>{let h=await p(n);return h.set(r,c),await d.commitSession(h)},l=async n=>{let c=await g(n);if(c===void 0)throw(0,b.redirect)(i);return c};return{sessionStorage:d,sessionKey:r,getSession:p,getSessionUser:g,saveSession:a,requireUser:l,requireAdminUser:async n=>{let c=await l(n);if(c?.role!=="admin")throw(0,b.redirect)(m);return c},logout:async n=>{let c=await p(n);return await d.destroySession(c)},commitSession:d.commitSession,destroySession:d.destroySession}};var Y=e=>{let s=e.logger??N,r=F(e.session,{mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive}),u=D(e),i=C(e,r,s),m=I(e,r,i,s),y=O(e,r,u,s);return{authenticator:u,storage:r,authFns:i,sessionStorage:r.sessionStorage,getSession:r.getSession,getSessionUser:r.getSessionUser,saveSession:r.saveSession,requireUser:r.requireUser,requireAdminUser:r.requireAdminUser,commitSession:r.commitSession,destroySession:r.destroySession,authenticate:i.authenticate,refreshedAccessToken:i.refreshedAccessToken,authenticateInLoader:m,...y}};0&&(module.exports={AuthRequiredError,GoogleInvalidGrantError,TokenRefreshError,createAuthHandlers,createAuthServer,createAuthSessionStorage,createAuthenticate,createAuthenticateInLoader,createGoogleAuthenticator});
1
+ "use strict";var V=Object.defineProperty;var oe=Object.getOwnPropertyDescriptor;var re=Object.getOwnPropertyNames;var se=Object.prototype.hasOwnProperty;var ne=(e,t)=>{for(var o in t)V(e,o,{get:t[o],enumerable:!0})},ie=(e,t,o,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of re(t))!se.call(e,s)&&s!==o&&V(e,s,{get:()=>t[s],enumerable:!(i=oe(t,s))||i.enumerable});return e};var ae=e=>ie(V({},"__esModule",{value:!0}),e);var we={};ne(we,{AuthRequiredError:()=>_,DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS:()=>Q,GoogleInvalidGrantError:()=>E,TokenRefreshError:()=>v,createAuthHandlers:()=>j,createAuthServer:()=>te,createAuthSessionStorage:()=>H,createAuthenticate:()=>N,createAuthenticateInLoader:()=>C,createGoogleAuthenticator:()=>D,signOutRefusal:()=>$,signOutRefusalResponse:()=>F});module.exports=ae(we);var B=require("react-router"),v=class extends Error{constructor(t){super(t),this.name="TokenRefreshError"}},E=class extends v{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}},ce=["access_token","expires_in"],N=(e,t,o)=>{let i=e.loginPath??"/auth/login",s=t.sessionKey,p=async d=>{let g=d.get(s)?.refreshToken;if(!g)throw new Error("Refresh token not found in session");try{let c="https://www.googleapis.com/oauth2/v4/token",l={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:g},r=await(e.fetch??globalThis.fetch)(c,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(l)});if(!r.ok){let h=await r.json().catch(()=>{});if(r.status===400&&typeof h=="object"&&!!h&&"error"in h&&h.error==="invalid_grant")throw new E;let w=typeof h=="object"&&h&&"error_description"in h?String(h.error_description):"Unknown error";throw new v(`Google token refresh failed: ${r.status} ${w}`)}let n=await r.json(),a=ce.filter(h=>!n?.[h]);if(a.length>0)throw o.error("Invalid token response from Google; missing or empty keys:",a.join(", ")),new Error("Invalid token response from Google");let{access_token:y,expires_in:A}=n;return{accessToken:y,refreshToken:g,expirationDateMs:Number(Date.now())+A*1e3}}catch(c){if(c instanceof v)throw c;let l=c instanceof Error?c.message:"Unknown error";throw new v(`Failed to refresh Google access token: ${l}`)}},S=async d=>{let g=d.get(s).provider;if(!g)throw new Error("Provider not found in session");if(g==="google")return await p(d);throw new Error("Provider not supported")};return{authenticate:async(d,f,g)=>{let{failureRedirect:c}=g||{},l=u=>{if(c===null)return new _(u);if(c==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let r=c??i;return u!==void 0?(0,B.redirect)(r,{headers:{"Set-Cookie":u}}):(0,B.redirect)(r)};try{if(e.mockUser?.enabled(d))return{accessToken:"mock-access-token",refreshToken:"mock-refresh-token",expirationDateMs:Date.now()+36e5};let u=f.get(s);if(!(u?.accessToken&&u.expirationDateMs))throw l();let{accessToken:r,refreshToken:n,expirationDateMs:a}=u;if(a<Date.now())throw n?new Error("Expired"):l();return{accessToken:r,refreshToken:n,expirationDateMs:a}}catch(u){if(u instanceof Error&&u.message==="Expired")try{let r=await S(f),n=f.get(s);return f.set(s,{...n,...r}),r}catch(r){if(r instanceof E)o.warn("Google refresh token invalid or revoked");else{let a=r instanceof Error?r.message:"Unknown error";o.error("Failed to refresh token:",a)}let n=await t.destroySession(f);throw l(n)}throw u}},refreshedAccessToken:S}};var Y=require("react-router");var L=({refreshToken:e,...t})=>t;var C=(e,t,o,i)=>{let s=new Map,p=new Map,S=async c=>{let l=s.get(c);if(l!==void 0)return l;let u=p.get(c);if(u!==void 0)return u;let r=(async()=>{try{let n=e.getUserPhoto?await e.getUserPhoto(c):"";return s.set(c,n),n}catch(n){throw s.delete(c),n}finally{p.delete(c)}})();return p.set(c,r),r},k=new WeakMap,d=async c=>{e.warmup&&await e.warmup();let l=await t.getSession(c),u=await t.getSessionUser(c);if(u===void 0)return{kind:"unauthenticated"};let r;try{r=await o.authenticate(c,l,{failureRedirect:null})}catch(w){if(w instanceof _)return w.setCookie!==void 0?{kind:"unauthenticated",cookie:w.setCookie}:{kind:"unauthenticated"};throw i.error("Error in authenticateInLoader:",w),w}let n={accessToken:r.accessToken,refreshToken:r.refreshToken,expirationDateMs:r.expirationDateMs,provider:u.provider},a={id:u.id,displayName:u.displayName,name:u.name,emails:u.emails,...n,role:u.role},y=await S(u.id),A=L({...u,...n,photo:y}),P=r.accessToken!==u.accessToken?await t.saveSession(c,a):void 0;return P!==void 0?{kind:"authenticated",user:A,cookie:P}:{kind:"authenticated",user:A}},f=c=>{let l=k.get(c);if(l!==void 0)return l;let u=d(c);return k.set(c,u),u};async function g(c,l){let{failureRedirect:u}=l;if(u==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let r=await f(c);if(r.kind==="authenticated")return r.cookie!==void 0?{user:r.user,cookie:r.cookie}:{user:r.user};if(u===null)return r.cookie!==void 0?{cookie:r.cookie}:{};throw r.cookie!==void 0?(0,Y.redirect)(u,{headers:{"Set-Cookie":r.cookie}}):(0,Y.redirect)(u)}return g};var W=require("@aiquants/auth-core"),M=require("react-router"),J=require("remix-auth");var z=require("remix-auth-oauth2"),ue=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],le="google",de="https://www.googleapis.com/oauth2/v3/userinfo",O=class extends z.OAuth2Strategy{constructor({clientId:o,clientSecret:i,redirectURI:s,scopes:p,accessType:S,includeGrantedScopes:k,prompt:d,hd:f,loginHint:g},c){let l=p??ue;super({clientId:o,clientSecret:i,redirectURI:s,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:l},c);this.name=le;this.scopes=l,this.accessType=S??"online",this.includeGrantedScopes=k??!1,this.prompt=d,this.hd=f,this.loginHint=g}authorizationParams(o,i){return o.set("access_type",this.accessType),o.set("include_granted_scopes",String(this.includeGrantedScopes)),this.scopes&&this.scopes.length>0&&o.set("scope",this.scopes.join(" ")),this.prompt&&o.set("prompt",this.prompt),this.hd&&o.set("hd",this.hd),this.loginHint&&o.set("login_hint",this.loginHint),o}static async userProfile(o){let i=await fetch(de,{headers:{Authorization:`Bearer ${o.accessToken()}`}});if(!i.ok)throw new Error(`Failed to fetch user profile: ${i.statusText}`);let s=await i.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 q={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var D=e=>{let t=e.logger??q,o=(0,W.resolveAuthMessages)(e.messages),i=e.loginPath??"/auth/login",s=new O({clientId:e.google.clientId,clientSecret:e.google.clientSecret,redirectURI:e.google.redirectURI,scopes:e.google.scopes,accessType:e.google.accessType??"offline",includeGrantedScopes:e.google.includeGrantedScopes??!0,prompt:e.google.prompt??"consent"},async({request:S,tokens:k})=>{let{access_token:d,refresh_token:f,expires_in:g,scope:c,id_token:l}=k.data,{_json:{sub:u,email:r,picture:n,hd:a,email_verified:y},photos:A,...h}=await O.userProfile(k),{id:P,displayName:w,name:{familyName:X,givenName:Ae},emails:ve}=h,K="google";if(d===void 0||f===void 0||g===void 0||c===void 0||P===void 0||w===void 0||u===void 0||r===void 0||y===void 0){if(y===!1){let U=encodeURIComponent(o.emailNotVerified);throw(0,M.redirect)(`${i}?error=${U}`)}let m=encodeURIComponent(o.googleFailed);throw(0,M.redirect)(`${i}?error=${m}`)}t.info("Authenticated on Google: ",h.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(K,d)){t.error("Backend verification returned false for user:",h.displayName);let T=encodeURIComponent(o.backendFailed);throw(0,M.redirect)(`${i}?error=${T}`)}t.info("Authenticated on Backend: ",h.displayName)}let m=h.emails[0]?.value;if(!await e.isEmailAllowed(m)){let R=new Error("You are not allowed to access this application");throw t.error(R),R}if(e.isUserActive&&!await e.isUserActive(h)){let R=new Error("You are not allowed to access this application");throw t.error("Deactivated account attempted to sign in:",m),R}e.backendAuth&&await e.backendAuth.signup(K,d,h),t.info("Authenticated complete: ",h.displayName);let U=Date.now()+g*1e3;return{...h,...{accessToken:d,refreshToken:f,expirationDateMs:U,provider:K},photo:n}}catch(m){let U=m;typeof m=="object"&&m!==null&&"cause"in m&&(U=m.cause||m),t.error("Error during backend authentication or subsequent processing:",U);let I=o.unexpected,G=!1;if(typeof m=="object"&&m!==null&&"cause"in m){let T=m.cause;T&&typeof T=="object"&&"message"in T&&typeof T.message=="string"&&T.message.includes("getaddrinfo ENOTFOUND")&&(I=o.backendUnreachable,G=!0)}if(!G&&m instanceof Error&&m.message.includes("You are not allowed to access this application")&&(I=o.notAllowed,G=!0),!G&&m instanceof Response&&m.headers.get("Location")?.startsWith(i))throw m;let R=encodeURIComponent(I);throw(0,M.redirect)(`${i}?error=${R}`)}}),p=new J.Authenticator;return p.use(s),p};var x=require("react-router");var he="https://oauth2.googleapis.com/revoke",Q=5e3;var pe="google",fe="invalid_token";var Z=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},ge=e=>{if(typeof e.refreshToken=="string"&&e.refreshToken!=="")return e.refreshToken;if(typeof e.accessToken=="string"&&e.accessToken!=="")return e.accessToken},me=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},ye=e=>e instanceof Error?e.cause instanceof Error?`${e.message} (${e.cause.message})`:e.message:String(e),Se=async(e,t,o)=>{try{let i=await t(he,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:e}).toString(),signal:o});if(i.ok)return await i.body?.cancel(),{outcome:"revoked"};let s=await me(i);return i.status===400&&s===fe?{outcome:"already-invalid"}:{outcome:"failed",reason:s===void 0?`Google answered ${i.status}`:`Google answered ${i.status} ${s}`}}catch(i){return{outcome:"failed",reason:ye(i)}}},ee=async(e,t)=>{if(e===void 0)return{outcome:"nothing-to-revoke"};let o=ge(e);if(o===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 i=new AbortController;return await new Promise(s=>{let p=setTimeout(()=>{s({outcome:"failed",reason:`Google did not answer within ${t.timeoutMs} ms`}),i.abort()},t.timeoutMs);Se(o,t.fetch,i.signal).then(S=>{clearTimeout(p),s(S)})})};var ke=new Map([["document",new Set(["none","same-origin","same-site"])],["empty",new Set(["same-origin"])]]),$=e=>{let t=e.headers.get("Sec-Fetch-Dest");if(t!==null){let i=ke.get(t);if(i===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(!i.has(s))return`its "${t}" request comes from a "${s}" page`}let o=e.headers.get("Sec-Purpose");if(o!==null)return`it is speculative ("${o}")`},F=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 j=(e,t,o,i)=>{let s=e.loginPath??"/auth/login",p=e.postLoginRedirect??"/",S=e.postLogoutRedirect??"/",k=Z(e.google.revocationTimeoutMs),d=async({request:n})=>{if(await t.getSessionUser(n))throw(0,x.redirect)(p);return{error:new URL(n.url).searchParams.get("error")}},f=async({request:n})=>{if((await n.clone().formData()).get("_action")!=="Sign In with Google")return null;throw await o.authenticate("google",n),(0,x.redirect)(s)},g=(n,a)=>{switch(n.outcome){case"failed":i.error(`Sign-out could not revoke the Google grant of user ${String(a)}; the session cookie is destroyed, but the grant stays valid until it expires or is revoked elsewhere:`,n.reason);return;case"already-invalid":i.info(`Sign-out found the Google grant of user ${String(a)} already unusable`);return;case"revoked":case"nothing-to-revoke":return}},c=async n=>{let a=await t.getSession(n),y=a.get(t.sessionKey),A=await ee(y,{fetch:e.fetch??globalThis.fetch,timeoutMs:k});return g(A,y?.id),await t.destroySession(a)},l=async n=>{let a=await c(n),y=new Headers;return y.append("Set-Cookie",a),(0,x.redirect)(S,{headers:y})};return{loginLoader:d,loginAction:f,logoutLoader:async({request:n})=>{let a=$(n);throw a!==void 0?F(a):await l(n)},logout:c,logoutAndRedirect:l,googleCallbackLoader:async({request:n})=>{try{let a=await o.authenticate("google",n),h=(await t.getSession(n)).get(t.sessionKey)?.refreshToken,P={accessToken:a.accessToken,refreshToken:a.refreshToken||h,expirationDateMs:a.expirationDateMs,provider:a.provider},w={id:a.id,displayName:a.displayName,name:a.name,emails:a.emails,...P,role:a.role},X=await t.saveSession(n,w);throw(0,x.redirect)(p,{headers:{"Set-Cookie":X}})}catch(a){throw a instanceof Response?a:(i.error("Authentication error:",a),(0,x.redirect)(s))}}}};var b=require("react-router");var H=(e,t)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(r=>!r))throw new Error("REMIX_SESSION_SECRET must be set");let o=e.sessionKey??"user",i=e.maxAge??3600*24*30,s=t?.loginPath??"/auth/login",p=t?.postLoginRedirect??"/",S=t?.mockUser,k=t?.isUserActive,d=(0,b.createCookieSessionStorage)({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:e.secure??process.env.NODE_ENV==="production",maxAge:i}}),f=async r=>await d.getSession(r.headers.get("Cookie")),g=async r=>{if(S?.enabled(r))return L(S.resolve(r));let a=(await f(r)).get(o);if(a===void 0)return;let y=L(a);if(!(k&&!await k(y)))return y},c=async(r,n)=>{let a=await f(r);return a.set(o,n),await d.commitSession(a)},l=async r=>{let n=await g(r);if(n===void 0)throw(0,b.redirect)(s);return n};return{sessionStorage:d,sessionKey:o,getSession:f,getSessionUser:g,saveSession:c,requireUser:l,requireAdminUser:async r=>{let n=await l(r);if(n.role!=="admin")throw(0,b.redirect)(p);return n},commitSession:d.commitSession,destroySession:d.destroySession}};var te=e=>{let t=e.logger??q,o=H(e.session,{mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive}),i=D(e),s=N(e,o,t),p=C(e,o,s,t),S=j(e,o,i,t);return{authenticator:i,storage:o,authFns:s,sessionStorage:o.sessionStorage,getSession:o.getSession,getSessionUser:o.getSessionUser,saveSession:o.saveSession,requireUser:o.requireUser,requireAdminUser:o.requireAdminUser,commitSession:o.commitSession,destroySession:o.destroySession,authenticate:s.authenticate,refreshedAccessToken:s.refreshedAccessToken,authenticateInLoader:p,...S}};0&&(module.exports={AuthRequiredError,DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS,GoogleInvalidGrantError,TokenRefreshError,createAuthHandlers,createAuthServer,createAuthSessionStorage,createAuthenticate,createAuthenticateInLoader,createGoogleAuthenticator,signOutRefusal,signOutRefusalResponse});
package/dist/server.mjs CHANGED
@@ -1 +1 @@
1
- import{redirect as j}from"react-router";var v=class extends Error{constructor(i){super(i),this.name="TokenRefreshError"}},_=class extends v{constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},U=class extends Error{constructor(i){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=i}},I=(e,i,r)=>{let d=e.loginPath??"/auth/login",a=i.sessionKey,m=async l=>{let g=l.get(a)?.refreshToken;if(!g)throw new Error("Refresh token not found in session");try{let n="https://www.googleapis.com/oauth2/v4/token",u={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:g},t=await fetch(n,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(u)});if(!t.ok){let h=await t.json().catch(()=>{});if(t.status===400&&typeof h=="object"&&!!h&&"error"in h&&h.error==="invalid_grant")throw new _;let k=typeof h=="object"&&h&&"error_description"in h?String(h.error_description):"Unknown error";throw new v(`Google token refresh failed: ${t.status} ${k}`)}let o=await t.json(),{access_token:s,expires_in:c}=o;if(!(s&&c))throw r.error("Invalid token response from Google:",o),new Error("Invalid token response from Google");return{accessToken:s,refreshToken:g,expirationDateMs:Number(Date.now())+c*1e3}}catch(n){if(n instanceof v)throw n;let u=n instanceof Error?n.message:"Unknown error";throw new v(`Failed to refresh Google access token: ${u}`)}},y=async l=>{let g=l.get(a).provider;if(!g)throw new Error("Provider not found in session");if(g==="google")return await m(l);throw new Error("Provider not supported")};return{authenticate:async(l,p,g)=>{let{failureRedirect:n}=g||{},u=t=>{if(n===null)return new U(t);if(n==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let o=n??d;return t!==void 0?j(o,{headers:{"Set-Cookie":t}}):j(o)};try{if(e.mockUser?.enabled(l))return{accessToken:"mock-access-token",refreshToken:"mock-refresh-token",expirationDateMs:Date.now()+36e5};let t=p.get(a);if(!(t?.accessToken&&t.expirationDateMs))throw u();let{accessToken:o,refreshToken:s,expirationDateMs:c}=t;if(c<Date.now())throw s?new Error("Expired"):u();return{accessToken:o,refreshToken:s,expirationDateMs:c}}catch(t){if(t instanceof Error&&t.message==="Expired")try{let o=await y(p),s=p.get(a);return p.set(a,{...s,...o}),o}catch(o){if(o instanceof _)r.warn("Google refresh token invalid or revoked");else{let c=o instanceof Error?o.message:"Unknown error";r.error("Failed to refresh token:",c)}let s=await i.destroySession(p);throw u(s)}throw t}},refreshedAccessToken:y}};import{redirect as $}from"react-router";var N=(e,i,r,d)=>{let a=new Map,m=new Map,y=async n=>{let u=a.get(n);if(u!==void 0)return u;let t=m.get(n);if(t!==void 0)return t;let o=(async()=>{try{let s=e.getUserPhoto?await e.getUserPhoto(n):"";return a.set(n,s),s}catch(s){throw a.delete(n),s}finally{m.delete(n)}})();return m.set(n,o),o},S=new WeakMap,l=async n=>{e.warmup&&await e.warmup();let u=await i.getSession(n),t=await i.getSessionUser(n);if(t===void 0)return{kind:"unauthenticated"};let o;try{o=await r.authenticate(n,u,{failureRedirect:null})}catch(w){if(w instanceof U)return w.setCookie!==void 0?{kind:"unauthenticated",cookie:w.setCookie}:{kind:"unauthenticated"};throw d.error("Error in authenticateInLoader:",w),w}let s={accessToken:o.accessToken,refreshToken:o.refreshToken,expirationDateMs:o.expirationDateMs,provider:t.provider},c={id:t.id,displayName:t.displayName,name:t.name,emails:t.emails,...s,role:t.role},h=await y(t.id),R={...t,...s,photo:h},x=o.accessToken!==t.accessToken?await i.saveSession(n,c):void 0;return x!==void 0?{kind:"authenticated",user:R,cookie:x}:{kind:"authenticated",user:R}},p=n=>{let u=S.get(n);if(u!==void 0)return u;let t=l(n);return S.set(n,t),t};async function g(n,u){let{failureRedirect:t}=u;if(t==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let o=await p(n);if(o.kind==="authenticated")return o.cookie!==void 0?{user:o.user,cookie:o.cookie}:{user:o.user};if(t===null)return o.cookie!==void 0?{cookie:o.cookie}:{};throw o.cookie!==void 0?$(t,{headers:{"Set-Cookie":o.cookie}}):$(t)}return g};import{resolveAuthMessages as Y}from"@aiquants/auth-core";import{redirect as b}from"react-router";import{Authenticator as V}from"remix-auth";import{OAuth2Strategy as B}from"remix-auth-oauth2";var K=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],z="google",W="https://www.googleapis.com/oauth2/v3/userinfo",L=class extends B{constructor({clientId:r,clientSecret:d,redirectURI:a,scopes:m,accessType:y,includeGrantedScopes:S,prompt:l,hd:p,loginHint:g},n){let u=m??K;super({clientId:r,clientSecret:d,redirectURI:a,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:u},n);this.name=z;this.scopes=u,this.accessType=y??"online",this.includeGrantedScopes=S??!1,this.prompt=l,this.hd=p,this.loginHint=g}authorizationParams(r,d){return r.set("access_type",this.accessType),r.set("include_granted_scopes",String(this.includeGrantedScopes)),this.scopes&&this.scopes.length>0&&r.set("scope",this.scopes.join(" ")),this.prompt&&r.set("prompt",this.prompt),this.hd&&r.set("hd",this.hd),this.loginHint&&r.set("login_hint",this.loginHint),r}static async userProfile(r){let d=await fetch(W,{headers:{Authorization:`Bearer ${r.accessToken()}`}});if(!d.ok)throw new Error(`Failed to fetch user profile: ${d.statusText}`);let a=await d.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 E={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var D=e=>{let i=e.logger??E,r=Y(e.messages),d=e.loginPath??"/auth/login",a=new L({clientId:e.google.clientId,clientSecret:e.google.clientSecret,redirectURI:e.google.redirectURI,scopes:e.google.scopes,accessType:e.google.accessType??"offline",includeGrantedScopes:e.google.includeGrantedScopes??!0,prompt:e.google.prompt??"consent"},async({request:y,tokens:S})=>{let{access_token:l,refresh_token:p,expires_in:g,scope:n,id_token:u}=S.data,{_json:{sub:t,email:o,picture:s,hd:c,email_verified:h},photos:R,...k}=await L.userProfile(S),{id:x,displayName:w,name:{familyName:X,givenName:Z},emails:ee}=k,C="google";if(l===void 0||p===void 0||g===void 0||n===void 0||x===void 0||w===void 0||t===void 0||o===void 0||h===void 0){if(h===!1){let T=encodeURIComponent(r.emailNotVerified);throw b(`${d}?error=${T}`)}let f=encodeURIComponent(r.googleFailed);throw b(`${d}?error=${f}`)}i.info("Authenticated on Google: ",k.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(C,l)){i.error("Backend verification returned false for user:",k.displayName);let P=encodeURIComponent(r.backendFailed);throw b(`${d}?error=${P}`)}i.info("Authenticated on Backend: ",k.displayName)}let f=k.emails[0]?.value;if(!await e.isEmailAllowed(f)){let A=new Error("You are not allowed to access this application");throw i.error(A),A}if(e.isUserActive&&!await e.isUserActive(k)){let A=new Error("You are not allowed to access this application");throw i.error("Deactivated account attempted to sign in:",f),A}e.backendAuth&&await e.backendAuth.signup(C,l,k),i.info("Authenticated complete: ",k.displayName);let T=Date.now()+g*1e3;return{...k,...{accessToken:l,refreshToken:p,expirationDateMs:T,provider:C},photo:s}}catch(f){let T=f;typeof f=="object"&&f!==null&&"cause"in f&&(T=f.cause||f),i.error("Error during backend authentication or subsequent processing:",T);let M=r.unexpected,G=!1;if(typeof f=="object"&&f!==null&&"cause"in f){let P=f.cause;P&&typeof P=="object"&&"message"in P&&typeof P.message=="string"&&P.message.includes("getaddrinfo ENOTFOUND")&&(M=r.backendUnreachable,G=!0)}if(!G&&f instanceof Error&&f.message.includes("You are not allowed to access this application")&&(M=r.notAllowed,G=!0),!G&&f instanceof Response&&f.headers.get("Location")?.startsWith(d))throw f;let A=encodeURIComponent(M);throw b(`${d}?error=${A}`)}}),m=new V;return m.use(a),m};import{redirect as q}from"react-router";var O=(e,i,r,d)=>{let a=e.loginPath??"/auth/login",m=e.postLoginRedirect??"/",y=e.postLogoutRedirect??"/",S=async({request:t})=>{if(await i.getSessionUser(t))throw q(m);return{error:new URL(t.url).searchParams.get("error")}},l=async({request:t})=>{let o=await t.clone().formData(),s=String(o.get("_action")),c=null;return s==="Sign In with Google"?c=await r.authenticate("google",t):c=null,c},p=async t=>await i.logout(t),g=async t=>{let o=await p(t),s=new Headers;return s.append("Set-Cookie",o),q(y,{headers:s})};return{loginLoader:S,loginAction:l,logoutLoader:async({request:t})=>{throw await g(t)},logout:p,logoutAndRedirect:g,googleCallbackLoader:async({request:t})=>{try{let o=await r.authenticate("google",t),h=(await i.getSession(t)).get(i.sessionKey)?.refreshToken,R={accessToken:o.accessToken,refreshToken:o.refreshToken||h,expirationDateMs:o.expirationDateMs,provider:o.provider},k={id:o.id,displayName:o.displayName,name:o.name,emails:o.emails,...R,role:o.role},x=await i.saveSession(t,k);throw q(m,{headers:{"Set-Cookie":x}})}catch(o){throw o instanceof Response?o:(d.error("Authentication error:",o),q(a))}}}};import{createCookieSessionStorage as J,redirect as H}from"react-router";var F=(e,i)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(s=>!s))throw new Error("REMIX_SESSION_SECRET must be set");let r=e.sessionKey??"user",d=e.maxAge??3600*24*30,a=i?.loginPath??"/auth/login",m=i?.postLoginRedirect??"/",y=i?.mockUser,S=i?.isUserActive,l=J({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:e.secure??process.env.NODE_ENV==="production",maxAge:d}}),p=async s=>await l.getSession(s.headers.get("Cookie")),g=async s=>{if(y?.enabled(s))return y.resolve(s);let h=(await p(s)).get(r);if(h!==void 0&&!(S&&!await S(h)))return h},n=async(s,c)=>{let h=await p(s);return h.set(r,c),await l.commitSession(h)},u=async s=>{let c=await g(s);if(c===void 0)throw H(a);return c};return{sessionStorage:l,sessionKey:r,getSession:p,getSessionUser:g,saveSession:n,requireUser:u,requireAdminUser:async s=>{let c=await u(s);if(c?.role!=="admin")throw H(m);return c},logout:async s=>{let c=await p(s);return await l.destroySession(c)},commitSession:l.commitSession,destroySession:l.destroySession}};var Q=e=>{let i=e.logger??E,r=F(e.session,{mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive}),d=D(e),a=I(e,r,i),m=N(e,r,a,i),y=O(e,r,d,i);return{authenticator:d,storage:r,authFns:a,sessionStorage:r.sessionStorage,getSession:r.getSession,getSessionUser:r.getSessionUser,saveSession:r.saveSession,requireUser:r.requireUser,requireAdminUser:r.requireAdminUser,commitSession:r.commitSession,destroySession:r.destroySession,authenticate:a.authenticate,refreshedAccessToken:a.refreshedAccessToken,authenticateInLoader:m,...y}};export{U as AuthRequiredError,_ as GoogleInvalidGrantError,v as TokenRefreshError,O as createAuthHandlers,Q as createAuthServer,F as createAuthSessionStorage,I as createAuthenticate,N as createAuthenticateInLoader,D as createGoogleAuthenticator};
1
+ import{redirect as V}from"react-router";var T=class extends Error{constructor(t){super(t),this.name="TokenRefreshError"}},x=class extends T{constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},U=class extends Error{constructor(t){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=t}},W=["access_token","expires_in"],C=(e,t,r)=>{let a=e.loginPath??"/auth/login",i=t.sessionKey,p=async d=>{let g=d.get(i)?.refreshToken;if(!g)throw new Error("Refresh token not found in session");try{let c="https://www.googleapis.com/oauth2/v4/token",l={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:g},o=await(e.fetch??globalThis.fetch)(c,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(l)});if(!o.ok){let h=await o.json().catch(()=>{});if(o.status===400&&typeof h=="object"&&!!h&&"error"in h&&h.error==="invalid_grant")throw new x;let w=typeof h=="object"&&h&&"error_description"in h?String(h.error_description):"Unknown error";throw new T(`Google token refresh failed: ${o.status} ${w}`)}let s=await o.json(),n=W.filter(h=>!s?.[h]);if(n.length>0)throw r.error("Invalid token response from Google; missing or empty keys:",n.join(", ")),new Error("Invalid token response from Google");let{access_token:y,expires_in:A}=s;return{accessToken:y,refreshToken:g,expirationDateMs:Number(Date.now())+A*1e3}}catch(c){if(c instanceof T)throw c;let l=c instanceof Error?c.message:"Unknown error";throw new T(`Failed to refresh Google access token: ${l}`)}},S=async d=>{let g=d.get(i).provider;if(!g)throw new Error("Provider not found in session");if(g==="google")return await p(d);throw new Error("Provider not supported")};return{authenticate:async(d,f,g)=>{let{failureRedirect:c}=g||{},l=u=>{if(c===null)return new U(u);if(c==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let o=c??a;return u!==void 0?V(o,{headers:{"Set-Cookie":u}}):V(o)};try{if(e.mockUser?.enabled(d))return{accessToken:"mock-access-token",refreshToken:"mock-refresh-token",expirationDateMs:Date.now()+36e5};let u=f.get(i);if(!(u?.accessToken&&u.expirationDateMs))throw l();let{accessToken:o,refreshToken:s,expirationDateMs:n}=u;if(n<Date.now())throw s?new Error("Expired"):l();return{accessToken:o,refreshToken:s,expirationDateMs:n}}catch(u){if(u instanceof Error&&u.message==="Expired")try{let o=await S(f),s=f.get(i);return f.set(i,{...s,...o}),o}catch(o){if(o instanceof x)r.warn("Google refresh token invalid or revoked");else{let n=o instanceof Error?o.message:"Unknown error";r.error("Failed to refresh token:",n)}let s=await t.destroySession(f);throw l(s)}throw u}},refreshedAccessToken:S}};import{redirect as B}from"react-router";var G=({refreshToken:e,...t})=>t;var q=(e,t,r,a)=>{let i=new Map,p=new Map,S=async c=>{let l=i.get(c);if(l!==void 0)return l;let u=p.get(c);if(u!==void 0)return u;let o=(async()=>{try{let s=e.getUserPhoto?await e.getUserPhoto(c):"";return i.set(c,s),s}catch(s){throw i.delete(c),s}finally{p.delete(c)}})();return p.set(c,o),o},k=new WeakMap,d=async c=>{e.warmup&&await e.warmup();let l=await t.getSession(c),u=await t.getSessionUser(c);if(u===void 0)return{kind:"unauthenticated"};let o;try{o=await r.authenticate(c,l,{failureRedirect:null})}catch(w){if(w instanceof U)return w.setCookie!==void 0?{kind:"unauthenticated",cookie:w.setCookie}:{kind:"unauthenticated"};throw a.error("Error in authenticateInLoader:",w),w}let s={accessToken:o.accessToken,refreshToken:o.refreshToken,expirationDateMs:o.expirationDateMs,provider:u.provider},n={id:u.id,displayName:u.displayName,name:u.name,emails:u.emails,...s,role:u.role},y=await S(u.id),A=G({...u,...s,photo:y}),v=o.accessToken!==u.accessToken?await t.saveSession(c,n):void 0;return v!==void 0?{kind:"authenticated",user:A,cookie:v}:{kind:"authenticated",user:A}},f=c=>{let l=k.get(c);if(l!==void 0)return l;let u=d(c);return k.set(c,u),u};async function g(c,l){let{failureRedirect:u}=l;if(u==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let o=await f(c);if(o.kind==="authenticated")return o.cookie!==void 0?{user:o.user,cookie:o.cookie}:{user:o.user};if(u===null)return o.cookie!==void 0?{cookie:o.cookie}:{};throw o.cookie!==void 0?B(u,{headers:{"Set-Cookie":o.cookie}}):B(u)}return g};import{resolveAuthMessages as te}from"@aiquants/auth-core";import{redirect as I}from"react-router";import{Authenticator as oe}from"remix-auth";import{OAuth2Strategy as J}from"remix-auth-oauth2";var Q=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],Z="google",ee="https://www.googleapis.com/oauth2/v3/userinfo",L=class extends J{constructor({clientId:r,clientSecret:a,redirectURI:i,scopes:p,accessType:S,includeGrantedScopes:k,prompt:d,hd:f,loginHint:g},c){let l=p??Q;super({clientId:r,clientSecret:a,redirectURI:i,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:l},c);this.name=Z;this.scopes=l,this.accessType=S??"online",this.includeGrantedScopes=k??!1,this.prompt=d,this.hd=f,this.loginHint=g}authorizationParams(r,a){return r.set("access_type",this.accessType),r.set("include_granted_scopes",String(this.includeGrantedScopes)),this.scopes&&this.scopes.length>0&&r.set("scope",this.scopes.join(" ")),this.prompt&&r.set("prompt",this.prompt),this.hd&&r.set("hd",this.hd),this.loginHint&&r.set("login_hint",this.loginHint),r}static async userProfile(r){let a=await fetch(ee,{headers:{Authorization:`Bearer ${r.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 b={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var D=e=>{let t=e.logger??b,r=te(e.messages),a=e.loginPath??"/auth/login",i=new L({clientId:e.google.clientId,clientSecret:e.google.clientSecret,redirectURI:e.google.redirectURI,scopes:e.google.scopes,accessType:e.google.accessType??"offline",includeGrantedScopes:e.google.includeGrantedScopes??!0,prompt:e.google.prompt??"consent"},async({request:S,tokens:k})=>{let{access_token:d,refresh_token:f,expires_in:g,scope:c,id_token:l}=k.data,{_json:{sub:u,email:o,picture:s,hd:n,email_verified:y},photos:A,...h}=await L.userProfile(k),{id:v,displayName:w,name:{familyName:K,givenName:fe},emails:ge}=h,N="google";if(d===void 0||f===void 0||g===void 0||c===void 0||v===void 0||w===void 0||u===void 0||o===void 0||y===void 0){if(y===!1){let _=encodeURIComponent(r.emailNotVerified);throw I(`${a}?error=${_}`)}let m=encodeURIComponent(r.googleFailed);throw I(`${a}?error=${m}`)}t.info("Authenticated on Google: ",h.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(N,d)){t.error("Backend verification returned false for user:",h.displayName);let R=encodeURIComponent(r.backendFailed);throw I(`${a}?error=${R}`)}t.info("Authenticated on Backend: ",h.displayName)}let m=h.emails[0]?.value;if(!await e.isEmailAllowed(m)){let P=new Error("You are not allowed to access this application");throw t.error(P),P}if(e.isUserActive&&!await e.isUserActive(h)){let P=new Error("You are not allowed to access this application");throw t.error("Deactivated account attempted to sign in:",m),P}e.backendAuth&&await e.backendAuth.signup(N,d,h),t.info("Authenticated complete: ",h.displayName);let _=Date.now()+g*1e3;return{...h,...{accessToken:d,refreshToken:f,expirationDateMs:_,provider:N},photo:s}}catch(m){let _=m;typeof m=="object"&&m!==null&&"cause"in m&&(_=m.cause||m),t.error("Error during backend authentication or subsequent processing:",_);let M=r.unexpected,E=!1;if(typeof m=="object"&&m!==null&&"cause"in m){let R=m.cause;R&&typeof R=="object"&&"message"in R&&typeof R.message=="string"&&R.message.includes("getaddrinfo ENOTFOUND")&&(M=r.backendUnreachable,E=!0)}if(!E&&m instanceof Error&&m.message.includes("You are not allowed to access this application")&&(M=r.notAllowed,E=!0),!E&&m instanceof Response&&m.headers.get("Location")?.startsWith(a))throw m;let P=encodeURIComponent(M);throw I(`${a}?error=${P}`)}}),p=new oe;return p.use(i),p};import{redirect as O}from"react-router";var re="https://oauth2.googleapis.com/revoke",se=5e3;var ne="google",ie="invalid_token";var Y=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},ae=e=>{if(typeof e.refreshToken=="string"&&e.refreshToken!=="")return e.refreshToken;if(typeof e.accessToken=="string"&&e.accessToken!=="")return e.accessToken},ce=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},ue=e=>e instanceof Error?e.cause instanceof Error?`${e.message} (${e.cause.message})`:e.message:String(e),le=async(e,t,r)=>{try{let a=await t(re,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:e}).toString(),signal:r});if(a.ok)return await a.body?.cancel(),{outcome:"revoked"};let i=await ce(a);return a.status===400&&i===ie?{outcome:"already-invalid"}:{outcome:"failed",reason:i===void 0?`Google answered ${a.status}`:`Google answered ${a.status} ${i}`}}catch(a){return{outcome:"failed",reason:ue(a)}}},X=async(e,t)=>{if(e===void 0)return{outcome:"nothing-to-revoke"};let r=ae(e);if(r===void 0)return{outcome:"nothing-to-revoke"};if(e.provider!==ne)return{outcome:"failed",reason:`the session's provider "${String(e.provider)}" has no revocation endpoint`};let a=new AbortController;return await new Promise(i=>{let p=setTimeout(()=>{i({outcome:"failed",reason:`Google did not answer within ${t.timeoutMs} ms`}),a.abort()},t.timeoutMs);le(r,t.fetch,a.signal).then(S=>{clearTimeout(p),i(S)})})};var de=new Map([["document",new Set(["none","same-origin","same-site"])],["empty",new Set(["same-origin"])]]),$=e=>{let t=e.headers.get("Sec-Fetch-Dest");if(t!==null){let a=de.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 r=e.headers.get("Sec-Purpose");if(r!==null)return`it is speculative ("${r}")`},F=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 j=(e,t,r,a)=>{let i=e.loginPath??"/auth/login",p=e.postLoginRedirect??"/",S=e.postLogoutRedirect??"/",k=Y(e.google.revocationTimeoutMs),d=async({request:s})=>{if(await t.getSessionUser(s))throw O(p);return{error:new URL(s.url).searchParams.get("error")}},f=async({request:s})=>{if((await s.clone().formData()).get("_action")!=="Sign In with Google")return null;throw await r.authenticate("google",s),O(i)},g=(s,n)=>{switch(s.outcome){case"failed":a.error(`Sign-out could not revoke the Google grant of user ${String(n)}; 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(n)} already unusable`);return;case"revoked":case"nothing-to-revoke":return}},c=async s=>{let n=await t.getSession(s),y=n.get(t.sessionKey),A=await X(y,{fetch:e.fetch??globalThis.fetch,timeoutMs:k});return g(A,y?.id),await t.destroySession(n)},l=async s=>{let n=await c(s),y=new Headers;return y.append("Set-Cookie",n),O(S,{headers:y})};return{loginLoader:d,loginAction:f,logoutLoader:async({request:s})=>{let n=$(s);throw n!==void 0?F(n):await l(s)},logout:c,logoutAndRedirect:l,googleCallbackLoader:async({request:s})=>{try{let n=await r.authenticate("google",s),h=(await t.getSession(s)).get(t.sessionKey)?.refreshToken,v={accessToken:n.accessToken,refreshToken:n.refreshToken||h,expirationDateMs:n.expirationDateMs,provider:n.provider},w={id:n.id,displayName:n.displayName,name:n.name,emails:n.emails,...v,role:n.role},K=await t.saveSession(s,w);throw O(p,{headers:{"Set-Cookie":K}})}catch(n){throw n instanceof Response?n:(a.error("Authentication error:",n),O(i))}}}};import{createCookieSessionStorage as he,redirect as z}from"react-router";var H=(e,t)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(o=>!o))throw new Error("REMIX_SESSION_SECRET must be set");let r=e.sessionKey??"user",a=e.maxAge??3600*24*30,i=t?.loginPath??"/auth/login",p=t?.postLoginRedirect??"/",S=t?.mockUser,k=t?.isUserActive,d=he({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:e.secure??process.env.NODE_ENV==="production",maxAge:a}}),f=async o=>await d.getSession(o.headers.get("Cookie")),g=async o=>{if(S?.enabled(o))return G(S.resolve(o));let n=(await f(o)).get(r);if(n===void 0)return;let y=G(n);if(!(k&&!await k(y)))return y},c=async(o,s)=>{let n=await f(o);return n.set(r,s),await d.commitSession(n)},l=async o=>{let s=await g(o);if(s===void 0)throw z(i);return s};return{sessionStorage:d,sessionKey:r,getSession:f,getSessionUser:g,saveSession:c,requireUser:l,requireAdminUser:async o=>{let s=await l(o);if(s.role!=="admin")throw z(p);return s},commitSession:d.commitSession,destroySession:d.destroySession}};var pe=e=>{let t=e.logger??b,r=H(e.session,{mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive}),a=D(e),i=C(e,r,t),p=q(e,r,i,t),S=j(e,r,a,t);return{authenticator:a,storage:r,authFns:i,sessionStorage:r.sessionStorage,getSession:r.getSession,getSessionUser:r.getSessionUser,saveSession:r.saveSession,requireUser:r.requireUser,requireAdminUser:r.requireAdminUser,commitSession:r.commitSession,destroySession:r.destroySession,authenticate:i.authenticate,refreshedAccessToken:i.refreshedAccessToken,authenticateInLoader:p,...S}};export{U as AuthRequiredError,se as DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS,x as GoogleInvalidGrantError,T as TokenRefreshError,j as createAuthHandlers,pe as createAuthServer,H as createAuthSessionStorage,C as createAuthenticate,q as createAuthenticateInLoader,D as createGoogleAuthenticator,$ as signOutRefusal,F as signOutRefusalResponse};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiquants/auth-react-router",
3
- "version": "0.21.0",
3
+ "version": "0.22.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"
@@ -52,7 +52,7 @@
52
52
  "@aiquants/auth-core": "0.6.1",
53
53
  "@aiquants/fuzzy-search": "2.7.0",
54
54
  "@aiquants/select-box": "0.15.0",
55
- "@aiquants/virtualscroll": "3.9.2",
55
+ "@aiquants/virtualscroll": "3.11.0",
56
56
  "@tailwindcss/cli": "^4.1.18",
57
57
  "@testing-library/react": "^16.3.2",
58
58
  "@types/node": "^25.9.1",
@@ -74,7 +74,7 @@
74
74
  "@aiquants/auth-core": "^0.6.1",
75
75
  "@aiquants/fuzzy-search": "^2.7.0",
76
76
  "@aiquants/select-box": "^0.15.0",
77
- "@aiquants/virtualscroll": "^3.9.2",
77
+ "@aiquants/virtualscroll": "^3.11.0",
78
78
  "react": ">=18",
79
79
  "react-dom": ">=18",
80
80
  "react-icons": ">=5",