@aiquants/auth-react-router 0.23.0 → 0.24.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
@@ -43,6 +43,7 @@ export const authServer = createAuthServer({
43
43
  session: { secrets: [env.REMIX_SESSION_SECRET] },
44
44
  isEmailAllowed: emailDomainAllowlist(parseAllowlistCsv(env.ALLOWED_EMAILS), parseAllowlistCsv(env.ALLOWED_DOMAINS)),
45
45
  isUserActive: async (profile) => isAccountEnabled(profile), // optional: deactivation revokes live sessions
46
+ sessionGeneration: { store: sessionGenerationStore }, // REQUIRED: sign-out generation store shared by every process (or false)
46
47
  backendAuth: { verify: verifyBackend, signup: (p, t) => signupBackend(p, t) }, // FastAPI verify/signup
47
48
  getUserPhoto: async (openid) => (await getOpenids({ openid }))[0]?.picture ?? "", // your identity store
48
49
  warmup: async () => { await Promise.all([ensurePrimaryConnection(), ensureSecondaryConnection()]) },
@@ -57,10 +58,22 @@ Optional settings for sign-out and the token requests:
57
58
  createAuthServer({
58
59
  google: { ..., revocationTimeoutMs: 3_000 }, // how long sign-out waits for Google's revocation (default 5000)
59
60
  fetch: instrumentedFetch, // the fetch for the token refresh and the revocation (default: global fetch)
61
+ sessionGeneration: {
62
+ store: sessionGenerationStore,
63
+ cacheTtlMs: 15_000, // how long a generation read from the store is reused per identity (default 15000; 0 = never: every guard call then reads the store, authenticateInLoader twice — see Behavior Contract)
64
+ timeoutMs: 3_000, // how long one store call may take before it counts as unreachable (default 3000)
65
+ },
60
66
  ...
61
67
  })
62
68
  ```
63
69
 
70
+ A sign-in written outside `googleCallbackLoader` (a test fixture that needs a signed-in cookie, say) goes through the
71
+ same write path, so it carries a valid stamp:
72
+
73
+ ```ts
74
+ const setCookie = await authServer.storage.saveSignedInSession(new Request("http://localhost/"), profile)
75
+ ```
76
+
64
77
  A host that writes its own sign-out route (to add headers to the answer, say) applies the same request rule as
65
78
  `logoutLoader` before signing out:
66
79
 
@@ -316,12 +329,15 @@ package's own `react: ">=18"`; a host that mounts `/admin` must satisfy the stri
316
329
 
317
330
  ## Behavior Contract
318
331
 
319
- - **Session cookie byte compatibility**: `__session` (httpOnly/lax/30d), key `"user"`, value = `{ id, displayName, name, emails, accessToken, refreshToken?, expirationDateMs?, provider, role? }` — never `photo`/`_json`/`photos`. Changing this invalidates all live 30-day sessions.
332
+ - **Session cookie**: `__session` (httpOnly/lax/30d) 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.
333
+ With the check enabled a cookie without a valid `"generation"` is rejected, so every user signs in once after a host
334
+ turns it on. Changing the cookie name, the `"user"` key or the profile shape invalidates all live 30-day sessions.
335
+ `session.sessionKey` must not be `"generation"` (`RangeError` when the server is built).
320
336
  - **Verify order**: Google profile check → `backendAuth.verify` → allowlist → `backendAuth.signup` (every login). Failures redirect to `<loginPath>?error=<encoded error message>` (messages overridable via `messages`).
321
337
  - **Token refresh**: expiry check → Google `oauth2/v4/token` rotate → session update; `invalid_grant` destroys the session and redirects to login with `Set-Cookie`.
322
338
  - **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.
323
339
  - **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.
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.
340
+ - **Infrastructure failures are never laundered into logouts**: anything that is not an authentication failure (an unexpected error inside the auth step, a `getUserPhoto` port outage, a `saveSession` failure, a defect of the session generation store) propagates unchanged in **both** modes. The session is not destroyed and no redirect is produced.
325
341
  - Photo lookups are cached with in-flight dedup per factory instance.
326
342
  - **Profiles handed to route code carry no refresh token**: `authenticateInLoader` returns `user: LoaderUser`
327
343
  (`Omit<MyGoogleProfile, "refreshToken">`) and `getSessionUser` / `requireUser` / `requireAdminUser` return `SessionUser`
@@ -337,8 +353,11 @@ package's own `react: ">=18"`; a host that mounts `/admin` must satisfy the stri
337
353
  `createAuthenticate`): the `{ accessToken, refreshToken, expirationDateMs }` they return.
338
354
  - `authenticator` (from `createGoogleAuthenticator`): the `MyGoogleProfile` its `authenticate("google", request)`
339
355
  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.
356
+ - `storage.resolveSession` (the guards' internal resolver, exposed for tests): the `session` of its `signed-in` and
357
+ `revoked` results is the raw session.
358
+ - The `Set-Cookie` values of `saveSession` / `commitSession` / `storage.saveSignedInSession` and the `cookie` of
359
+ `authenticateInLoader`: the session cookie is signed, not encrypted, so the token can be read out of it. Put them
360
+ in a `Set-Cookie` header only.
342
361
  - **`loginAction` never hands out the signed-in profile**: for `_action === "Sign In with Google"` it always ends by
343
362
  throwing a redirect. The strategy normally throws the redirect to Google's authorization endpoint. When the POST's URL
344
363
  carries `code` and the `state` of the user's state cookie, remix-auth exchanges the code inside the action and returns
@@ -357,10 +376,67 @@ package's own `react: ">=18"`; a host that mounts `/admin` must satisfy the stri
357
376
  token refresh (within about an hour), and a service sharing the OAuth client loses the grant as well.
358
377
  - Revocation alone does not close one race: a token refresh that reached Google before the revocation can still set a
359
378
  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.
379
+ Google while it is. The sign-out generation (next item) closes the race: that cookie still carries the stamp of its
380
+ sign-in, and the sign-out has advanced the generation past it. With `sessionGeneration: false` the race stays open:
381
+ `authenticateInLoader` accepts that cookie until the token expires (about an hour), and the session getters
382
+ (`getSessionUser` / `requireUser` / `requireAdminUser`), which never look at the expiry, accept it until the first
383
+ `authenticateInLoader` after the expiry fails to refresh (`invalid_grant`) and deletes it.
384
+ - **Sign-out session generation** (`sessionGeneration: { store, cacheTtlMs?, timeoutMs? } | false`, required): every
385
+ identity (`provider` + the provider's stable user id, the session profile's `id`) has a generation in a store all
386
+ processes share, starting at 0 and raised past the signed-out session's stamp at each sign-out.
387
+ - **Sign-in** (`googleCallbackLoader`, through `storage.saveSignedInSession`) reads the identity's generation afresh
388
+ (never from the cache) and stamps it into the session beside the profile, overwriting any older stamp. A store that
389
+ cannot be read fails the sign-in: it is logged (`Authentication error:`) and redirected to `loginPath`, and no session
390
+ cookie is set. A token refresh (`saveSession`) keeps the stamp of the sign-in.
391
+ - **Every guard checks the stamp**: `getSessionUser` / `requireUser` / `requireAdminUser`, `authenticateInLoader` and
392
+ `authenticate`. A stamp older than the identity's generation, or a missing or invalid one, means the session was
393
+ signed out: `getSessionUser` returns `undefined`; `requireUser` / `requireAdminUser` redirect to `loginPath` with the
394
+ cookie's deletion; `authenticateInLoader` returns the deletion as `cookie` (`null` mode) or throws the redirect
395
+ carrying it; `authenticate` destroys the session (`AuthRequiredError` with `setCookie`, or the redirect with
396
+ `Set-Cookie`). The deletion wins over an `isUserActive` that also answers `false` (that alone keeps the cookie).
397
+ `loginLoader` only reads, so it shows the login page and the next sign-in overwrites the cookie. The `mockUser`
398
+ backdoor is never checked.
399
+ - **Sign-out** (`logout`, and so `logoutAndRedirect` / `logoutLoader`) advances the generation past the session's
400
+ stamp (`store.advance(identity, stamp)` raises it to at least `stamp + 1`) concurrently with the grant revocation,
401
+ and answers once both have settled, so it waits at most
402
+ `max(google.revocationTimeoutMs, sessionGeneration.timeoutMs)`. Raising past the stamp rather than by one means a
403
+ second sign-out with the same cookie, or a replay of a cookie the guards already reject, leaves the generation — and
404
+ every session signed in since — as it is. An advance that fails, times out or is answered with less than
405
+ `stamp + 1` is logged with `logger.error` (the store's error and the user id, never a token) and the session is
406
+ destroyed anyway; a cookie refreshed before that sign-out then stays valid until a later sign-out advances the
407
+ generation or the cookie expires. A session without a usable stamp (every guard already rejects it) advances
408
+ nothing and is logged with `logger.info`. A refused sign-out (`signOutRefusal`) and a request without a session
409
+ advance nothing.
410
+ - **Bound**: after a sign-out, the next request carrying an older cookie is rejected immediately on the process that
411
+ ran the sign-out, and within `cacheTtlMs` (default `DEFAULT_SESSION_GENERATION_CACHE_TTL_MS`, 15000 ms) on any other
412
+ process, which reuses a generation it read, and joins a read in flight, only while that read started less than
413
+ `cacheTtlMs` ago. On the process that ran the sign-out, a store call of that identity that started before the
414
+ sign-out's advance answered never brings the older generation back into the reused value, however late it answers.
415
+ The bound holds while the store answers that identity's calls in time; another identity's outage does not suspend
416
+ it (next item). Times are measured on the monotonic clock (`performance.now()`), so a step of the wall clock does
417
+ not stretch the bound. A server-sent-event stream or any other response opened before the sign-out keeps running
418
+ until it ends: a guard checks a request once, when it arrives.
419
+ - **Unreachable store**: every store call is bounded by `timeoutMs` (default `DEFAULT_SESSION_GENERATION_TIMEOUT_MS`,
420
+ 3000 ms). When the store cannot be reached for an identity (a call rejects with `SessionGenerationUnavailableError`,
421
+ or does not answer in time) the check is skipped and the cookie accepted, with a `logger.warn` at most once a minute
422
+ for the whole server, whichever identity it concerns. For `cacheTtlMs` afterwards, until a store call for that
423
+ identity answers in time again, every check of that identity that would need the store is skipped without calling
424
+ it (the identity's outage window), while a stamp a fresh cached generation decides (equal to it or older) is still
425
+ decided by it. Other identities are checked as usual, so a slow or locked row for one identity does not switch the
426
+ check off for everyone; during a real outage each identity costs at most one `timeoutMs` wait per `cacheTtlMs`. The process
427
+ that ran a sign-out therefore keeps rejecting the signed-out cookie through any other identity's outage window, and
428
+ through that identity's own window while its record of the advance is fresh (`cacheTtlMs` from the advance's
429
+ start); after that, the identity's window skips the check there as on any other process. Any other rejection, or a
430
+ value that is not an integer >= 0 (`TypeError`), is a defect and propagates: the guard rejects, the sign-in fails,
431
+ the sign-out logs it.
432
+ - **`cacheTtlMs: 0`** reuses nothing, joins no read and opens no outage window, so `authenticateInLoader` reads the
433
+ store twice per request (`resolveSession`, then `authenticate`). While the store hangs, every guarded request can
434
+ wait up to 2 × `timeoutMs` before it is let through (a store that fails fast costs two fast failures instead).
435
+ - **Settings**: anything other than `{ store, cacheTtlMs?, timeoutMs? }` (with `store.current` and `store.advance`
436
+ functions) or `false` — a missing key included — throws `TypeError` when the server is built; `cacheTtlMs` must be
437
+ an integer from 0 to 2147483647 and `timeoutMs` one from 1 to 2147483647 (`RangeError` otherwise).
438
+ - **`false`** turns all of it off: nothing is stamped or checked, sign-out advances nothing, and the race above stays
439
+ open.
364
440
  - **`logoutLoader` refuses sign-outs the user did not ask for**, judged by the request's fetch metadata
365
441
  (`signOutRefusal`). It signs out a `Sec-Fetch-Dest: document` request only when its `Sec-Fetch-Site` is `none` (a typed
366
442
  address or a bookmark), `same-origin` or `same-site`, and a `Sec-Fetch-Dest: empty` request only when it is
@@ -395,6 +471,18 @@ package's own `react: ">=18"`; a host that mounts `/admin` must satisfy the stri
395
471
 
396
472
  `isUserActive` is evaluated at login **and on every session resolution**, so disabling an account revokes already-issued session cookies. Return `false` only for a *known-disabled* account — returning `false` for an unknown identity would block first-time sign-up.
397
473
 
474
+ `sessionGeneration.store` (`SessionGenerationStore`) is `{ current(identity), advance(identity, from) }` over storage
475
+ every process shares (a database table keyed by `identity.provider` + `identity.id`, for example;
476
+ `SessionGenerationIdentity` is `{ provider, id }`). `current` resolves to the identity's generation, `0` until its first
477
+ sign-out. `advance` receives `from`, the stamp of the session being signed out (an integer >= 0), raises the stored
478
+ generation to at least `from + 1` — a greater stored value is left as it is, and an identity with no stored generation
479
+ gets `from + 1` (in SQL, an upsert that keeps the greater of the stored value and `from + 1`) — and resolves to the
480
+ stored generation afterwards. An answer below `from + 1` is a defect: the sign-out logs it as a failed advance. A
481
+ generation never decreases. Reject with `SessionGenerationUnavailableError` (an `Error` that takes `{ cause }`)
482
+ **only** when the store cannot be reached — the check of that identity is then skipped — and let every other error
483
+ propagate, so a missing table or a refused login is loud rather than silently skipped. Pass `sessionGeneration: false`
484
+ to run without the check (the sign-out race stays open).
485
+
398
486
  > ⚠️ `isEmailAllowed` may return a `Promise` (to consult a database as well as env vars). Callers **must** `await` it: a `Promise` is always truthy, so a missing `await` makes the allowlist fail **open**, and the type checker cannot catch it.
399
487
 
400
488
  ## Intentional Changes vs Original (§8, approved)
package/dist/server.d.mts CHANGED
@@ -39,11 +39,25 @@ type LoggerPort = {
39
39
  warn: (...args: unknown[]) => void;
40
40
  error: (...args: unknown[]) => void;
41
41
  };
42
+ type SessionGenerationIdentity = {
43
+ readonly provider: string;
44
+ readonly id: string;
45
+ };
46
+ type SessionGenerationStore = {
47
+ current: (identity: SessionGenerationIdentity) => Promise<number>;
48
+ advance: (identity: SessionGenerationIdentity, from: number) => Promise<number>;
49
+ };
50
+ type SessionGenerationConfig = {
51
+ readonly store: SessionGenerationStore;
52
+ readonly cacheTtlMs?: number;
53
+ readonly timeoutMs?: number;
54
+ };
42
55
  type AuthServerConfig = {
43
56
  google: GoogleOAuthConfig;
44
57
  session: SessionConfig;
45
58
  isEmailAllowed: (email: string | null | undefined) => boolean | Promise<boolean>;
46
59
  isUserActive?: (profile: GoogleProfileBase) => boolean | Promise<boolean>;
60
+ sessionGeneration: SessionGenerationConfig | false;
47
61
  backendAuth?: BackendAuthPort;
48
62
  getUserPhoto?: UserPhotoPort;
49
63
  warmup?: WarmupPort;
@@ -55,6 +69,62 @@ type AuthServerConfig = {
55
69
  logger?: LoggerPort;
56
70
  fetch?: FetchPort;
57
71
  };
72
+ declare const DEFAULT_SESSION_GENERATION_CACHE_TTL_MS = 15000;
73
+ declare const DEFAULT_SESSION_GENERATION_TIMEOUT_MS = 3000;
74
+ declare class SessionGenerationUnavailableError extends Error {
75
+ constructor(message: string, options?: ErrorOptions);
76
+ }
77
+ type SessionGenerationVerdict = "current" | "stale" | "unavailable";
78
+ type AdvanceOutcome = {
79
+ readonly kind: "advanced";
80
+ readonly generation: number;
81
+ } | {
82
+ readonly kind: "unavailable";
83
+ readonly error: unknown;
84
+ } | {
85
+ readonly kind: "failed";
86
+ readonly error: unknown;
87
+ };
88
+ type SessionGenerationGate = {
89
+ readonly check: (identity: SessionGenerationIdentity, stamped: unknown) => Promise<SessionGenerationVerdict>;
90
+ readonly stamp: (identity: SessionGenerationIdentity) => Promise<number>;
91
+ readonly advance: (identity: SessionGenerationIdentity, from: number) => Promise<AdvanceOutcome>;
92
+ };
93
+ type AuthSessionStorage = ReturnType<typeof createAuthSessionStorage>;
94
+ type AuthSessionStorageOptions = {
95
+ readonly sessionGeneration: SessionGenerationConfig | false;
96
+ readonly logger?: LoggerPort;
97
+ readonly mockUser?: MockUserPort;
98
+ readonly loginPath?: string;
99
+ readonly postLoginRedirect?: string;
100
+ readonly isUserActive?: (profile: GoogleProfileBase) => boolean | Promise<boolean>;
101
+ };
102
+ type SessionResolution = {
103
+ readonly kind: "signed-in";
104
+ readonly user: SessionUser;
105
+ readonly session: Session;
106
+ } | {
107
+ readonly kind: "signed-out";
108
+ } | {
109
+ readonly kind: "inactive";
110
+ } | {
111
+ readonly kind: "revoked";
112
+ readonly session: Session;
113
+ };
114
+ declare const createAuthSessionStorage: (config: SessionConfig, options: AuthSessionStorageOptions) => {
115
+ sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
116
+ sessionKey: string;
117
+ sessionGenerationGate: SessionGenerationGate | null;
118
+ getSession: (request: Request) => Promise<Session<react_router.SessionData, react_router.SessionData>>;
119
+ resolveSession: (request: Request) => Promise<SessionResolution>;
120
+ getSessionUser: (request: Request) => Promise<SessionUser | undefined>;
121
+ saveSession: (request: Request, user: SessionProfile) => Promise<string>;
122
+ saveSignedInSession: (request: Request, profile: SessionProfile) => Promise<string>;
123
+ requireUser: (request: Request) => Promise<SessionUser>;
124
+ requireAdminUser: (request: Request) => Promise<SessionUser>;
125
+ commitSession: (session: Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
126
+ destroySession: (session: Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
127
+ };
58
128
  type AuthServer = ReturnType<typeof createAuthServer>;
59
129
  declare const createAuthServer: (config: AuthServerConfig) => {
60
130
  loginLoader: ({ request }: {
@@ -77,9 +147,12 @@ declare const createAuthServer: (config: AuthServerConfig) => {
77
147
  storage: {
78
148
  sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
79
149
  sessionKey: string;
150
+ sessionGenerationGate: SessionGenerationGate | null;
80
151
  getSession: (request: Request) => Promise<react_router.Session<react_router.SessionData, react_router.SessionData>>;
152
+ resolveSession: (request: Request) => Promise<SessionResolution>;
81
153
  getSessionUser: (request: Request) => Promise<SessionUser | undefined>;
82
154
  saveSession: (request: Request, user: _aiquants_auth_core.SessionProfile) => Promise<string>;
155
+ saveSignedInSession: (request: Request, profile: _aiquants_auth_core.SessionProfile) => Promise<string>;
83
156
  requireUser: (request: Request) => Promise<SessionUser>;
84
157
  requireAdminUser: (request: Request) => Promise<SessionUser>;
85
158
  commitSession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
@@ -134,23 +207,6 @@ declare const createAuthServer: (config: AuthServerConfig) => {
134
207
  }>;
135
208
  };
136
209
  };
137
- type AuthSessionStorage = ReturnType<typeof createAuthSessionStorage>;
138
- declare const createAuthSessionStorage: (config: SessionConfig, options?: {
139
- mockUser?: MockUserPort;
140
- loginPath?: string;
141
- postLoginRedirect?: string;
142
- isUserActive?: (profile: GoogleProfileBase) => boolean | Promise<boolean>;
143
- }) => {
144
- sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
145
- sessionKey: string;
146
- getSession: (request: Request) => Promise<react_router.Session<react_router.SessionData, react_router.SessionData>>;
147
- getSessionUser: (request: Request) => Promise<SessionUser | undefined>;
148
- saveSession: (request: Request, user: SessionProfile) => Promise<string>;
149
- requireUser: (request: Request) => Promise<SessionUser>;
150
- requireAdminUser: (request: Request) => Promise<SessionUser>;
151
- commitSession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
152
- destroySession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
153
- };
154
210
  declare class TokenRefreshError extends Error {
155
211
  constructor(message: string);
156
212
  }
@@ -212,4 +268,4 @@ declare const createAuthHandlers: (config: AuthServerConfig, storage: AuthSessio
212
268
  };
213
269
  declare const signOutRefusal: (request: Request) => string | undefined;
214
270
  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 };
271
+ 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 };
package/dist/server.d.ts CHANGED
@@ -39,11 +39,25 @@ type LoggerPort = {
39
39
  warn: (...args: unknown[]) => void;
40
40
  error: (...args: unknown[]) => void;
41
41
  };
42
+ type SessionGenerationIdentity = {
43
+ readonly provider: string;
44
+ readonly id: string;
45
+ };
46
+ type SessionGenerationStore = {
47
+ current: (identity: SessionGenerationIdentity) => Promise<number>;
48
+ advance: (identity: SessionGenerationIdentity, from: number) => Promise<number>;
49
+ };
50
+ type SessionGenerationConfig = {
51
+ readonly store: SessionGenerationStore;
52
+ readonly cacheTtlMs?: number;
53
+ readonly timeoutMs?: number;
54
+ };
42
55
  type AuthServerConfig = {
43
56
  google: GoogleOAuthConfig;
44
57
  session: SessionConfig;
45
58
  isEmailAllowed: (email: string | null | undefined) => boolean | Promise<boolean>;
46
59
  isUserActive?: (profile: GoogleProfileBase) => boolean | Promise<boolean>;
60
+ sessionGeneration: SessionGenerationConfig | false;
47
61
  backendAuth?: BackendAuthPort;
48
62
  getUserPhoto?: UserPhotoPort;
49
63
  warmup?: WarmupPort;
@@ -55,6 +69,62 @@ type AuthServerConfig = {
55
69
  logger?: LoggerPort;
56
70
  fetch?: FetchPort;
57
71
  };
72
+ declare const DEFAULT_SESSION_GENERATION_CACHE_TTL_MS = 15000;
73
+ declare const DEFAULT_SESSION_GENERATION_TIMEOUT_MS = 3000;
74
+ declare class SessionGenerationUnavailableError extends Error {
75
+ constructor(message: string, options?: ErrorOptions);
76
+ }
77
+ type SessionGenerationVerdict = "current" | "stale" | "unavailable";
78
+ type AdvanceOutcome = {
79
+ readonly kind: "advanced";
80
+ readonly generation: number;
81
+ } | {
82
+ readonly kind: "unavailable";
83
+ readonly error: unknown;
84
+ } | {
85
+ readonly kind: "failed";
86
+ readonly error: unknown;
87
+ };
88
+ type SessionGenerationGate = {
89
+ readonly check: (identity: SessionGenerationIdentity, stamped: unknown) => Promise<SessionGenerationVerdict>;
90
+ readonly stamp: (identity: SessionGenerationIdentity) => Promise<number>;
91
+ readonly advance: (identity: SessionGenerationIdentity, from: number) => Promise<AdvanceOutcome>;
92
+ };
93
+ type AuthSessionStorage = ReturnType<typeof createAuthSessionStorage>;
94
+ type AuthSessionStorageOptions = {
95
+ readonly sessionGeneration: SessionGenerationConfig | false;
96
+ readonly logger?: LoggerPort;
97
+ readonly mockUser?: MockUserPort;
98
+ readonly loginPath?: string;
99
+ readonly postLoginRedirect?: string;
100
+ readonly isUserActive?: (profile: GoogleProfileBase) => boolean | Promise<boolean>;
101
+ };
102
+ type SessionResolution = {
103
+ readonly kind: "signed-in";
104
+ readonly user: SessionUser;
105
+ readonly session: Session;
106
+ } | {
107
+ readonly kind: "signed-out";
108
+ } | {
109
+ readonly kind: "inactive";
110
+ } | {
111
+ readonly kind: "revoked";
112
+ readonly session: Session;
113
+ };
114
+ declare const createAuthSessionStorage: (config: SessionConfig, options: AuthSessionStorageOptions) => {
115
+ sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
116
+ sessionKey: string;
117
+ sessionGenerationGate: SessionGenerationGate | null;
118
+ getSession: (request: Request) => Promise<Session<react_router.SessionData, react_router.SessionData>>;
119
+ resolveSession: (request: Request) => Promise<SessionResolution>;
120
+ getSessionUser: (request: Request) => Promise<SessionUser | undefined>;
121
+ saveSession: (request: Request, user: SessionProfile) => Promise<string>;
122
+ saveSignedInSession: (request: Request, profile: SessionProfile) => Promise<string>;
123
+ requireUser: (request: Request) => Promise<SessionUser>;
124
+ requireAdminUser: (request: Request) => Promise<SessionUser>;
125
+ commitSession: (session: Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
126
+ destroySession: (session: Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
127
+ };
58
128
  type AuthServer = ReturnType<typeof createAuthServer>;
59
129
  declare const createAuthServer: (config: AuthServerConfig) => {
60
130
  loginLoader: ({ request }: {
@@ -77,9 +147,12 @@ declare const createAuthServer: (config: AuthServerConfig) => {
77
147
  storage: {
78
148
  sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
79
149
  sessionKey: string;
150
+ sessionGenerationGate: SessionGenerationGate | null;
80
151
  getSession: (request: Request) => Promise<react_router.Session<react_router.SessionData, react_router.SessionData>>;
152
+ resolveSession: (request: Request) => Promise<SessionResolution>;
81
153
  getSessionUser: (request: Request) => Promise<SessionUser | undefined>;
82
154
  saveSession: (request: Request, user: _aiquants_auth_core.SessionProfile) => Promise<string>;
155
+ saveSignedInSession: (request: Request, profile: _aiquants_auth_core.SessionProfile) => Promise<string>;
83
156
  requireUser: (request: Request) => Promise<SessionUser>;
84
157
  requireAdminUser: (request: Request) => Promise<SessionUser>;
85
158
  commitSession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
@@ -134,23 +207,6 @@ declare const createAuthServer: (config: AuthServerConfig) => {
134
207
  }>;
135
208
  };
136
209
  };
137
- type AuthSessionStorage = ReturnType<typeof createAuthSessionStorage>;
138
- declare const createAuthSessionStorage: (config: SessionConfig, options?: {
139
- mockUser?: MockUserPort;
140
- loginPath?: string;
141
- postLoginRedirect?: string;
142
- isUserActive?: (profile: GoogleProfileBase) => boolean | Promise<boolean>;
143
- }) => {
144
- sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
145
- sessionKey: string;
146
- getSession: (request: Request) => Promise<react_router.Session<react_router.SessionData, react_router.SessionData>>;
147
- getSessionUser: (request: Request) => Promise<SessionUser | undefined>;
148
- saveSession: (request: Request, user: SessionProfile) => Promise<string>;
149
- requireUser: (request: Request) => Promise<SessionUser>;
150
- requireAdminUser: (request: Request) => Promise<SessionUser>;
151
- commitSession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
152
- destroySession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
153
- };
154
210
  declare class TokenRefreshError extends Error {
155
211
  constructor(message: string);
156
212
  }
@@ -212,4 +268,4 @@ declare const createAuthHandlers: (config: AuthServerConfig, storage: AuthSessio
212
268
  };
213
269
  declare const signOutRefusal: (request: Request) => string | undefined;
214
270
  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 };
271
+ 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 };
package/dist/server.js CHANGED
@@ -1 +1 @@
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});
1
+ "use strict";var oe=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var Ae=Object.prototype.hasOwnProperty;var Ge=(e,t)=>{for(var n in t)oe(e,n,{get:t[n],enumerable:!0})},Te=(e,t,n,c)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ve(t))!Ae.call(e,i)&&i!==n&&oe(e,i,{get:()=>t[i],enumerable:!(c=ke(t,i))||c.enumerable});return e};var Pe=e=>Te(oe({},"__esModule",{value:!0}),e);var He={};Ge(He,{AuthRequiredError:()=>N,DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS:()=>ue,DEFAULT_SESSION_GENERATION_CACHE_TTL_MS:()=>re,DEFAULT_SESSION_GENERATION_TIMEOUT_MS:()=>se,GoogleInvalidGrantError:()=>F,SessionGenerationUnavailableError:()=>C,TokenRefreshError:()=>M,createAuthHandlers:()=>Q,createAuthServer:()=>ye,createAuthSessionStorage:()=>Z,createAuthenticate:()=>B,createAuthenticateInLoader:()=>X,createGoogleAuthenticator:()=>W,signOutRefusal:()=>J,signOutRefusalResponse:()=>z});module.exports=Pe(He);var ie=require("react-router");var Re="https://oauth2.googleapis.com/revoke",ue=5e3;var Ee="google",_e="invalid_token";var de=e=>{if(e===void 0)return 5e3;if(!Number.isInteger(e)||e<1||e>2147483647)throw new RangeError(`google.revocationTimeoutMs must be an integer from 1 to 2147483647 (milliseconds); got ${String(e)}`);return e},be=e=>{if(typeof e.refreshToken=="string"&&e.refreshToken!=="")return e.refreshToken;if(typeof e.accessToken=="string"&&e.accessToken!=="")return e.accessToken},Ie=async e=>{let t=await e.json().catch(()=>{});return typeof t=="object"&&t!==null&&"error"in t&&typeof t.error=="string"?t.error:void 0},Oe=e=>e instanceof Error?e.cause instanceof Error?`${e.message} (${e.cause.message})`:e.message:String(e),xe=async(e,t,n)=>{try{let c=await t(Re,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:e}).toString(),signal:n});if(c.ok)return await c.body?.cancel(),{outcome:"revoked"};let i=await Ie(c);return c.status===400&&i===_e?{outcome:"already-invalid"}:{outcome:"failed",reason:i===void 0?`Google answered ${c.status}`:`Google answered ${c.status} ${i}`}}catch(c){return{outcome:"failed",reason:Oe(c)}}},le=async(e,t)=>{if(e===void 0)return{outcome:"nothing-to-revoke"};let n=be(e);if(n===void 0)return{outcome:"nothing-to-revoke"};if(e.provider!==Ee)return{outcome:"failed",reason:`the session's provider "${String(e.provider)}" has no revocation endpoint`};let c=new AbortController;return await new Promise(i=>{let k=setTimeout(()=>{i({outcome:"failed",reason:`Google did not answer within ${t.timeoutMs} ms`}),c.abort()},t.timeoutMs);xe(n,t.fetch,c.signal).then(v=>{clearTimeout(k),i(v)})})};var x="generation",re=15e3,se=3e3,Ue=6e4,C=class extends Error{constructor(t,n){super(t,n),this.name="SessionGenerationUnavailableError"}},O=e=>typeof e=="string"?JSON.stringify(e):typeof e=="function"?"a function":typeof e=="object"&&e!==null?Array.isArray(e)?"an array":"an object":typeof e=="bigint"?`${e}n`:String(e),Le=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return O(e);let t="store"in e?e.store:void 0;if(typeof t!="object"||t===null)return`an object whose store is ${O(t)}`;let n="current"in t?t.current:void 0,c="advance"in t?t.advance:void 0;return`an object whose store.current is ${O(n)} and store.advance is ${O(c)}`},Ne=e=>typeof e=="object"&&e!==null&&"current"in e&&typeof e.current=="function"&&"advance"in e&&typeof e.advance=="function",fe=(e,t,n,c)=>{if(t===void 0)return c;if(typeof t!="number"||!Number.isInteger(t)||t<n||t>2147483647)throw new RangeError(`${e} must be an integer from ${n} to ${2147483647} (milliseconds); got ${O(t)}`);return t},Ce=e=>{if(e===!1)return!1;let t=e;if(typeof t!="object"||t===null||!("store"in t)||!Ne(t.store))throw new TypeError(`sessionGeneration must be { store, cacheTtlMs?, timeoutMs? } or false; got ${Le(t)}`);return{store:t.store,cacheTtlMs:fe("sessionGeneration.cacheTtlMs","cacheTtlMs"in t?t.cacheTtlMs:void 0,0,re),timeoutMs:fe("sessionGeneration.timeoutMs","timeoutMs"in t?t.timeoutMs:void 0,1,se)}},$=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,ne=e=>typeof e.provider=="string"&&e.provider!==""&&typeof e.id=="string"&&e.id!=="",pe=e=>new TypeError(`a session generation identity needs a non-empty provider and id; got provider ${O(e.provider)} and id ${O(e.id)}`),$e=e=>$(e)&&$(e+1),Fe=e=>new TypeError(`a session generation advance needs the signed-out session's stamp, an integer from 0 to ${Number.MAX_SAFE_INTEGER-1}; got ${O(e)}`),L=e=>({provider:e.provider,id:e.id}),ge=(e,t)=>{let n=Ce(e);if(n===!1)return null;let{store:c,cacheTtlMs:i,timeoutMs:k}=n,v=new Map,A=new Map,S=new Map,h=new Map,w=Number.NEGATIVE_INFINITY,f=a=>`${a.provider}\0${a.id}`,g=(a,o)=>{let d=v.get(a);if(d!==void 0){if(o-d.at<i)return d;v.delete(a)}},l=(a,o,d)=>{if(d!==void 0&&o.at<=d.answeredAt&&o.value<d.value)return;let y=g(a,performance.now());if(y===void 0){v.set(a,o);return}o.value<y.value||v.set(a,{value:o.value,at:Math.max(y.at,o.at)})},p=a=>{let o=h.get(a);if(o!==void 0)return o.count+=1,o;let d={count:1,floor:void 0};return h.set(a,d),d},m=(a,o)=>{o.count-=1,o.count===0&&h.delete(a)},R=(a,o)=>{a.floor={value:a.floor===void 0?o:Math.max(a.floor.value,o),answeredAt:performance.now()}},s=(a,o)=>{let d=S.get(a);return d===void 0?!1:o<d?!0:(S.delete(a),!1)},r=(a,o)=>{let d=performance.now();return S.set(a,d+i),d-w>=Ue&&(w=d,t.warn("Session generation store unavailable; skipping the sign-out generation check:",o)),"unavailable"},u=(a,o,d)=>new Promise((y,T)=>{let{operation:G}=a,I=a.operation==="advance"?a.from+1:0,we=performance.now(),V=p(d),U=!1,ce=setTimeout(()=>{U=!0,y({kind:"unavailable",error:new C(`sessionGeneration.store.${G} did not settle within ${k} ms`)})},k);new Promise(_=>_(a.operation==="advance"?c.advance(o,a.from):c.current(o))).then(_=>{if(clearTimeout(ce),!($(_)&&_>=I)){m(d,V),U||(U=!0,T(new TypeError(`sessionGeneration.store.${G} must resolve to an integer >= ${I}; got ${O(_)}`)));return}G==="advance"&&(R(V,_),A.delete(d)),l(d,{value:_,at:we},V.floor),m(d,V),!U&&(U=!0,S.delete(d),y({kind:"value",value:_}))},_=>{if(clearTimeout(ce),m(d,V),!U){if(U=!0,_ instanceof C){y({kind:"unavailable",error:_});return}T(_)}})}),P=(a,o,d)=>{let y=A.get(o);if(y!==void 0&&d-y.startedAt<i)return y.read;let T={read:u({operation:"current"},a,o),startedAt:d};A.set(o,T);let G=()=>{A.get(o)===T&&A.delete(o)};return T.read.then(G,G),T.read},E=async(a,o,d)=>{let y=await u({operation:"current"},a,o);return y.kind==="unavailable"?r(o,y.error):d===y.value?"current":"stale"};return{check:async(a,o)=>{if(!($(o)&&ne(a)))return"stale";let d=performance.now(),y=f(a),T=g(y,d);if(T!==void 0){if(o===T.value)return"current";if(o<T.value)return"stale"}if(s(y,d))return"unavailable";if(T!==void 0)return await E(a,y,o);let G=await P(a,y,d);return G.kind==="unavailable"?r(y,G.error):o===G.value?"current":o<G.value?"stale":await E(a,y,o)},stamp:async a=>{if(!ne(a))throw pe(a);let o=await u({operation:"current"},a,f(a));if(o.kind==="unavailable")throw o.error;return o.value},advance:async(a,o)=>{if(!ne(a))return{kind:"failed",error:pe(a)};if(!$e(o))return{kind:"failed",error:Fe(o)};try{let d=await u({operation:"advance",from:o},a,f(a));return d.kind==="value"?{kind:"advanced",generation:d.value}:{kind:"unavailable",error:d.error}}catch(d){return{kind:"failed",error:d}}}}};var M=class extends Error{constructor(t){super(t),this.name="TokenRefreshError"}},F=class extends M{constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},N=class extends Error{constructor(t){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=t}},qe=["access_token","expires_in"],B=(e,t,n)=>{let c=e.loginPath??"/auth/login",i=t.sessionKey,k=async S=>{let w=S.get(i)?.refreshToken;if(!w)throw new Error("Refresh token not found in session");try{let f="https://www.googleapis.com/oauth2/v4/token",g={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:w},p=await(e.fetch??globalThis.fetch)(f,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(g)});if(!p.ok){let u=await p.json().catch(()=>{});if(p.status===400&&typeof u=="object"&&!!u&&"error"in u&&u.error==="invalid_grant")throw new F;let E=typeof u=="object"&&u&&"error_description"in u?String(u.error_description):"Unknown error";throw new M(`Google token refresh failed: ${p.status} ${E}`)}let m=await p.json(),R=qe.filter(u=>!m?.[u]);if(R.length>0)throw n.error("Invalid token response from Google; missing or empty keys:",R.join(", ")),new Error("Invalid token response from Google");let{access_token:s,expires_in:r}=m;return{accessToken:s,refreshToken:w,expirationDateMs:Number(Date.now())+r*1e3}}catch(f){if(f instanceof M)throw f;let g=f instanceof Error?f.message:"Unknown error";throw new M(`Failed to refresh Google access token: ${g}`)}},v=async S=>{let w=S.get(i).provider;if(!w)throw new Error("Provider not found in session");if(w==="google")return await k(S);throw new Error("Provider not supported")};return{authenticate:async(S,h,w)=>{let{failureRedirect:f}=w||{},g=l=>{if(f===null)return new N(l);if(f==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let p=f??c;return l!==void 0?(0,ie.redirect)(p,{headers:{"Set-Cookie":l}}):(0,ie.redirect)(p)};try{if(e.mockUser?.enabled(S))return{accessToken:"mock-access-token",refreshToken:"mock-refresh-token",expirationDateMs:Date.now()+36e5};let l=h.get(i),p=t.sessionGenerationGate;if(l!==void 0&&p!==null&&await p.check(L(l),h.get(x))==="stale")throw g(await t.destroySession(h));if(!(l?.accessToken&&l.expirationDateMs))throw g();let{accessToken:m,refreshToken:R,expirationDateMs:s}=l;if(s<Date.now())throw R?new Error("Expired"):g();return{accessToken:m,refreshToken:R,expirationDateMs:s}}catch(l){if(l instanceof Error&&l.message==="Expired")try{let p=await v(h),m=h.get(i);return h.set(i,{...m,...p}),p}catch(p){if(p instanceof F)n.warn("Google refresh token invalid or revoked");else{let R=p instanceof Error?p.message:"Unknown error";n.error("Failed to refresh token:",R)}let m=await t.destroySession(h);throw g(m)}throw l}},refreshedAccessToken:v}};var ae=require("react-router");var K=({refreshToken:e,...t})=>t;var X=(e,t,n,c)=>{let i=new Map,k=new Map,v=async f=>{let g=i.get(f);if(g!==void 0)return g;let l=k.get(f);if(l!==void 0)return l;let p=(async()=>{try{let m=e.getUserPhoto?await e.getUserPhoto(f):"";return i.set(f,m),m}catch(m){throw i.delete(f),m}finally{k.delete(f)}})();return k.set(f,p),p},A=new WeakMap,S=async f=>{e.warmup&&await e.warmup();let g=await t.resolveSession(f);if(g.kind==="revoked")return{kind:"unauthenticated",cookie:await t.destroySession(g.session)};if(g.kind!=="signed-in")return{kind:"unauthenticated"};let{user:l,session:p}=g,m;try{m=await n.authenticate(f,p,{failureRedirect:null})}catch(b){if(b instanceof N)return b.setCookie!==void 0?{kind:"unauthenticated",cookie:b.setCookie}:{kind:"unauthenticated"};throw c.error("Error in authenticateInLoader:",b),b}let R={accessToken:m.accessToken,refreshToken:m.refreshToken,expirationDateMs:m.expirationDateMs,provider:l.provider},s={id:l.id,displayName:l.displayName,name:l.name,emails:l.emails,...R,role:l.role},r=await v(l.id),u=K({...l,...R,photo:r}),E=m.accessToken!==l.accessToken?await t.saveSession(f,s):void 0;return E!==void 0?{kind:"authenticated",user:u,cookie:E}:{kind:"authenticated",user:u}},h=f=>{let g=A.get(f);if(g!==void 0)return g;let l=S(f);return A.set(f,l),l};async function w(f,g){let{failureRedirect:l}=g;if(l==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let p=await h(f);if(p.kind==="authenticated")return p.cookie!==void 0?{user:p.user,cookie:p.cookie}:{user:p.user};if(l===null)return p.cookie!==void 0?{cookie:p.cookie}:{};throw p.cookie!==void 0?(0,ae.redirect)(l,{headers:{"Set-Cookie":p.cookie}}):(0,ae.redirect)(l)}return w};var me=require("@aiquants/auth-core"),Y=require("react-router"),Se=require("remix-auth");var he=require("remix-auth-oauth2"),De=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],je="google",Ve="https://www.googleapis.com/oauth2/v3/userinfo",H=class extends he.OAuth2Strategy{constructor({clientId:n,clientSecret:c,redirectURI:i,scopes:k,accessType:v,includeGrantedScopes:A,prompt:S,hd:h,loginHint:w},f){let g=k??De;super({clientId:n,clientSecret:c,redirectURI:i,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:g},f);this.name=je;this.scopes=g,this.accessType=v??"online",this.includeGrantedScopes=A??!1,this.prompt=S,this.hd=h,this.loginHint=w}authorizationParams(n,c){return n.set("access_type",this.accessType),n.set("include_granted_scopes",String(this.includeGrantedScopes)),this.scopes&&this.scopes.length>0&&n.set("scope",this.scopes.join(" ")),this.prompt&&n.set("prompt",this.prompt),this.hd&&n.set("hd",this.hd),this.loginHint&&n.set("login_hint",this.loginHint),n}static async userProfile(n){let c=await fetch(Ve,{headers:{Authorization:`Bearer ${n.accessToken()}`}});if(!c.ok)throw new Error(`Failed to fetch user profile: ${c.statusText}`);let i=await c.json();return{id:i.sub,displayName:i.name,name:{familyName:i.family_name,givenName:i.given_name},emails:[{value:i.email}],photos:[{value:i.picture}],_json:i}}};var q={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var W=e=>{let t=e.logger??q,n=(0,me.resolveAuthMessages)(e.messages),c=e.loginPath??"/auth/login",i=new H({clientId:e.google.clientId,clientSecret:e.google.clientSecret,redirectURI:e.google.redirectURI,scopes:e.google.scopes,accessType:e.google.accessType??"offline",includeGrantedScopes:e.google.includeGrantedScopes??!0,prompt:e.google.prompt??"consent"},async({request:v,tokens:A})=>{let{access_token:S,refresh_token:h,expires_in:w,scope:f,id_token:g}=A.data,{_json:{sub:l,email:p,picture:m,hd:R,email_verified:s},photos:r,...u}=await H.userProfile(A),{id:P,displayName:E,name:{familyName:b,givenName:ee},emails:te}=u,a="google";if(S===void 0||h===void 0||w===void 0||f===void 0||P===void 0||E===void 0||l===void 0||p===void 0||s===void 0){if(s===!1){let d=encodeURIComponent(n.emailNotVerified);throw(0,Y.redirect)(`${c}?error=${d}`)}let o=encodeURIComponent(n.googleFailed);throw(0,Y.redirect)(`${c}?error=${o}`)}t.info("Authenticated on Google: ",u.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(a,S)){t.error("Backend verification returned false for user:",u.displayName);let I=encodeURIComponent(n.backendFailed);throw(0,Y.redirect)(`${c}?error=${I}`)}t.info("Authenticated on Backend: ",u.displayName)}let o=u.emails[0]?.value;if(!await e.isEmailAllowed(o)){let G=new Error("You are not allowed to access this application");throw t.error(G),G}if(e.isUserActive&&!await e.isUserActive(u)){let G=new Error("You are not allowed to access this application");throw t.error("Deactivated account attempted to sign in:",o),G}e.backendAuth&&await e.backendAuth.signup(a,S,u),t.info("Authenticated complete: ",u.displayName);let d=Date.now()+w*1e3;return{...u,...{accessToken:S,refreshToken:h,expirationDateMs:d,provider:a},photo:m}}catch(o){let d=o;typeof o=="object"&&o!==null&&"cause"in o&&(d=o.cause||o),t.error("Error during backend authentication or subsequent processing:",d);let y=n.unexpected,T=!1;if(typeof o=="object"&&o!==null&&"cause"in o){let I=o.cause;I&&typeof I=="object"&&"message"in I&&typeof I.message=="string"&&I.message.includes("getaddrinfo ENOTFOUND")&&(y=n.backendUnreachable,T=!0)}if(!T&&o instanceof Error&&o.message.includes("You are not allowed to access this application")&&(y=n.notAllowed,T=!0),!T&&o instanceof Response&&o.headers.get("Location")?.startsWith(c))throw o;let G=encodeURIComponent(y);throw(0,Y.redirect)(`${c}?error=${G}`)}}),k=new Se.Authenticator;return k.use(i),k};var D=require("react-router");var Ke=new Map([["document",new Set(["none","same-origin","same-site"])],["empty",new Set(["same-origin"])]]),J=e=>{let t=e.headers.get("Sec-Fetch-Dest");if(t!==null){let c=Ke.get(t);if(c===void 0)return`its fetch destination is "${t}"`;let i=e.headers.get("Sec-Fetch-Site");if(i===null)return`its "${t}" request states no site`;if(!c.has(i))return`its "${t}" request comes from a "${i}" page`}let n=e.headers.get("Sec-Purpose");if(n!==null)return`it is speculative ("${n}")`},z=e=>new Response(`Signing out is refused because ${e}: only a navigation that does not come from another site, or a script's request from this origin, signs out.`,{status:403,headers:{"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"}});var Q=(e,t,n,c)=>{let i=e.loginPath??"/auth/login",k=e.postLoginRedirect??"/",v=e.postLogoutRedirect??"/",A=de(e.google.revocationTimeoutMs),S=async({request:s})=>{if(await t.getSessionUser(s))throw(0,D.redirect)(k);return{error:new URL(s.url).searchParams.get("error")}},h=async({request:s})=>{if((await s.clone().formData()).get("_action")!=="Sign In with Google")return null;throw await n.authenticate("google",s),(0,D.redirect)(i)},w=(s,r)=>{switch(s.outcome){case"failed":c.error(`Sign-out could not revoke the Google grant of user ${String(r)}; the session cookie is destroyed, but the grant stays valid until it expires or is revoked elsewhere:`,s.reason);return;case"already-invalid":c.info(`Sign-out found the Google grant of user ${String(r)} already unusable`);return;case"revoked":case"nothing-to-revoke":return}},f=(s,r)=>{s.kind!=="advanced"&&c.error(`Sign-out could not advance the session generation of ${r.provider} user ${r.id}; a session cookie refreshed before this sign-out stays valid until a later sign-out advances the generation or the cookie expires:`,s.error)},g=async(s,r)=>{let u=t.sessionGenerationGate;if(u!==null){if(!$(r)){c.info(`Sign-out found no usable session generation stamp in the session of ${s.provider} user ${s.id}; every guard already rejects that cookie, so the generation is not advanced`);return}f(await u.advance(s,r),s)}},l=async s=>{let r=await t.getSession(s),u=r.get(t.sessionKey),[P]=await Promise.all([le(u,{fetch:e.fetch??globalThis.fetch,timeoutMs:A}),u===void 0?void 0:g(L(u),r.get(x))]);return w(P,u?.id),await t.destroySession(r)},p=async s=>{let r=await l(s),u=new Headers;return u.append("Set-Cookie",r),(0,D.redirect)(v,{headers:u})};return{loginLoader:S,loginAction:h,logoutLoader:async({request:s})=>{let r=J(s);throw r!==void 0?z(r):await p(s)},logout:l,logoutAndRedirect:p,googleCallbackLoader:async({request:s})=>{try{let r=await n.authenticate("google",s),E=(await t.getSession(s)).get(t.sessionKey)?.refreshToken,b={accessToken:r.accessToken,refreshToken:r.refreshToken||E,expirationDateMs:r.expirationDateMs,provider:r.provider},ee={id:r.id,displayName:r.displayName,name:r.name,emails:r.emails,...b,role:r.role},te=await t.saveSignedInSession(s,ee);throw(0,D.redirect)(k,{headers:{"Set-Cookie":te}})}catch(r){throw r instanceof Response?r:(c.error("Authentication error:",r),(0,D.redirect)(i))}}}};var j=require("react-router");var Z=(e,t)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(s=>!s))throw new Error("REMIX_SESSION_SECRET must be set");let n=e.sessionKey??"user";if(n===x)throw new RangeError(`session.sessionKey must not be ${JSON.stringify(x)}, the key the session generation is stored under; got ${JSON.stringify(n)}`);let c=e.maxAge??3600*24*30,i=t.loginPath??"/auth/login",k=t.postLoginRedirect??"/",v=t.mockUser,A=t.isUserActive,S=ge(t.sessionGeneration,t.logger??q),h=(0,j.createCookieSessionStorage)({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:e.secure??process.env.NODE_ENV==="production",maxAge:c}}),w=async s=>await h.getSession(s.headers.get("Cookie")),f=async s=>{if(v?.enabled(s))return{kind:"signed-in",user:K(v.resolve(s)),session:await w(s)};let r=await w(s),u=r.get(n);if(u===void 0)return{kind:"signed-out"};let P=K(u),[E,b]=await Promise.all([A===void 0?!0:A(P),S===null?"current":S.check(L(u),r.get(x))]);return b==="stale"?{kind:"revoked",session:r}:E?{kind:"signed-in",user:P,session:r}:{kind:"inactive"}},g=async s=>{let r=await f(s);return r.kind==="signed-in"?r.user:void 0},l=async(s,r)=>{let u=await w(s);return u.set(n,r),await h.commitSession(u)},p=async(s,r)=>{let u=S===null?void 0:await S.stamp(L(r)),P=await w(s);return P.set(n,r),u!==void 0&&P.set(x,u),await h.commitSession(P)},m=async s=>{let r=await f(s);switch(r.kind){case"signed-in":return r.user;case"revoked":throw(0,j.redirect)(i,{headers:{"Set-Cookie":await h.destroySession(r.session)}});case"signed-out":case"inactive":throw(0,j.redirect)(i)}};return{sessionStorage:h,sessionKey:n,sessionGenerationGate:S,getSession:w,resolveSession:f,getSessionUser:g,saveSession:l,saveSignedInSession:p,requireUser:m,requireAdminUser:async s=>{let r=await m(s);if(r.role!=="admin")throw(0,j.redirect)(k);return r},commitSession:h.commitSession,destroySession:h.destroySession}};var ye=e=>{let t=e.logger??q,n=Z(e.session,{sessionGeneration:e.sessionGeneration,logger:t,mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive}),c=W(e),i=B(e,n,t),k=X(e,n,i,t),v=Q(e,n,c,t);return{authenticator:c,storage:n,authFns:i,sessionStorage:n.sessionStorage,getSession:n.getSession,getSessionUser:n.getSessionUser,saveSession:n.saveSession,requireUser:n.requireUser,requireAdminUser:n.requireAdminUser,commitSession:n.commitSession,destroySession:n.destroySession,authenticate:i.authenticate,refreshedAccessToken:i.refreshedAccessToken,authenticateInLoader:k,...v}};0&&(module.exports={AuthRequiredError,DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS,DEFAULT_SESSION_GENERATION_CACHE_TTL_MS,DEFAULT_SESSION_GENERATION_TIMEOUT_MS,GoogleInvalidGrantError,SessionGenerationUnavailableError,TokenRefreshError,createAuthHandlers,createAuthServer,createAuthSessionStorage,createAuthenticate,createAuthenticateInLoader,createGoogleAuthenticator,signOutRefusal,signOutRefusalResponse});
package/dist/server.mjs CHANGED
@@ -1 +1 @@
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};
1
+ import{redirect as le}from"react-router";var ge="https://oauth2.googleapis.com/revoke",he=5e3;var me="google",Se="invalid_token";var re=e=>{if(e===void 0)return 5e3;if(!Number.isInteger(e)||e<1||e>2147483647)throw new RangeError(`google.revocationTimeoutMs must be an integer from 1 to 2147483647 (milliseconds); got ${String(e)}`);return e},ye=e=>{if(typeof e.refreshToken=="string"&&e.refreshToken!=="")return e.refreshToken;if(typeof e.accessToken=="string"&&e.accessToken!=="")return e.accessToken},we=async e=>{let t=await e.json().catch(()=>{});return typeof t=="object"&&t!==null&&"error"in t&&typeof t.error=="string"?t.error:void 0},ke=e=>e instanceof Error?e.cause instanceof Error?`${e.message} (${e.cause.message})`:e.message:String(e),ve=async(e,t,n)=>{try{let c=await t(ge,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:e}).toString(),signal:n});if(c.ok)return await c.body?.cancel(),{outcome:"revoked"};let u=await we(c);return c.status===400&&u===Se?{outcome:"already-invalid"}:{outcome:"failed",reason:u===void 0?`Google answered ${c.status}`:`Google answered ${c.status} ${u}`}}catch(c){return{outcome:"failed",reason:ke(c)}}},se=async(e,t)=>{if(e===void 0)return{outcome:"nothing-to-revoke"};let n=ye(e);if(n===void 0)return{outcome:"nothing-to-revoke"};if(e.provider!==me)return{outcome:"failed",reason:`the session's provider "${String(e.provider)}" has no revocation endpoint`};let c=new AbortController;return await new Promise(u=>{let k=setTimeout(()=>{u({outcome:"failed",reason:`Google did not answer within ${t.timeoutMs} ms`}),c.abort()},t.timeoutMs);ve(n,t.fetch,c.signal).then(v=>{clearTimeout(k),u(v)})})};var x="generation",ce=15e3,ue=3e3,Ge=6e4,q=class extends Error{constructor(t,n){super(t,n),this.name="SessionGenerationUnavailableError"}},O=e=>typeof e=="string"?JSON.stringify(e):typeof e=="function"?"a function":typeof e=="object"&&e!==null?Array.isArray(e)?"an array":"an object":typeof e=="bigint"?`${e}n`:String(e),Te=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return O(e);let t="store"in e?e.store:void 0;if(typeof t!="object"||t===null)return`an object whose store is ${O(t)}`;let n="current"in t?t.current:void 0,c="advance"in t?t.advance:void 0;return`an object whose store.current is ${O(n)} and store.advance is ${O(c)}`},Pe=e=>typeof e=="object"&&e!==null&&"current"in e&&typeof e.current=="function"&&"advance"in e&&typeof e.advance=="function",ie=(e,t,n,c)=>{if(t===void 0)return c;if(typeof t!="number"||!Number.isInteger(t)||t<n||t>2147483647)throw new RangeError(`${e} must be an integer from ${n} to ${2147483647} (milliseconds); got ${O(t)}`);return t},Re=e=>{if(e===!1)return!1;let t=e;if(typeof t!="object"||t===null||!("store"in t)||!Pe(t.store))throw new TypeError(`sessionGeneration must be { store, cacheTtlMs?, timeoutMs? } or false; got ${Te(t)}`);return{store:t.store,cacheTtlMs:ie("sessionGeneration.cacheTtlMs","cacheTtlMs"in t?t.cacheTtlMs:void 0,0,ce),timeoutMs:ie("sessionGeneration.timeoutMs","timeoutMs"in t?t.timeoutMs:void 0,1,ue)}},N=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,X=e=>typeof e.provider=="string"&&e.provider!==""&&typeof e.id=="string"&&e.id!=="",ae=e=>new TypeError(`a session generation identity needs a non-empty provider and id; got provider ${O(e.provider)} and id ${O(e.id)}`),Ee=e=>N(e)&&N(e+1),_e=e=>new TypeError(`a session generation advance needs the signed-out session's stamp, an integer from 0 to ${Number.MAX_SAFE_INTEGER-1}; got ${O(e)}`),U=e=>({provider:e.provider,id:e.id}),de=(e,t)=>{let n=Re(e);if(n===!1)return null;let{store:c,cacheTtlMs:u,timeoutMs:k}=n,v=new Map,A=new Map,S=new Map,h=new Map,w=Number.NEGATIVE_INFINITY,f=i=>`${i.provider}\0${i.id}`,g=(i,o)=>{let d=v.get(i);if(d!==void 0){if(o-d.at<u)return d;v.delete(i)}},l=(i,o,d)=>{if(d!==void 0&&o.at<=d.answeredAt&&o.value<d.value)return;let y=g(i,performance.now());if(y===void 0){v.set(i,o);return}o.value<y.value||v.set(i,{value:o.value,at:Math.max(y.at,o.at)})},p=i=>{let o=h.get(i);if(o!==void 0)return o.count+=1,o;let d={count:1,floor:void 0};return h.set(i,d),d},m=(i,o)=>{o.count-=1,o.count===0&&h.delete(i)},R=(i,o)=>{i.floor={value:i.floor===void 0?o:Math.max(i.floor.value,o),answeredAt:performance.now()}},s=(i,o)=>{let d=S.get(i);return d===void 0?!1:o<d?!0:(S.delete(i),!1)},r=(i,o)=>{let d=performance.now();return S.set(i,d+u),d-w>=Ge&&(w=d,t.warn("Session generation store unavailable; skipping the sign-out generation check:",o)),"unavailable"},a=(i,o,d)=>new Promise((y,T)=>{let{operation:G}=i,I=i.operation==="advance"?i.from+1:0,pe=performance.now(),F=p(d),M=!1,ne=setTimeout(()=>{M=!0,y({kind:"unavailable",error:new q(`sessionGeneration.store.${G} did not settle within ${k} ms`)})},k);new Promise(_=>_(i.operation==="advance"?c.advance(o,i.from):c.current(o))).then(_=>{if(clearTimeout(ne),!(N(_)&&_>=I)){m(d,F),M||(M=!0,T(new TypeError(`sessionGeneration.store.${G} must resolve to an integer >= ${I}; got ${O(_)}`)));return}G==="advance"&&(R(F,_),A.delete(d)),l(d,{value:_,at:pe},F.floor),m(d,F),!M&&(M=!0,S.delete(d),y({kind:"value",value:_}))},_=>{if(clearTimeout(ne),m(d,F),!M){if(M=!0,_ instanceof q){y({kind:"unavailable",error:_});return}T(_)}})}),P=(i,o,d)=>{let y=A.get(o);if(y!==void 0&&d-y.startedAt<u)return y.read;let T={read:a({operation:"current"},i,o),startedAt:d};A.set(o,T);let G=()=>{A.get(o)===T&&A.delete(o)};return T.read.then(G,G),T.read},E=async(i,o,d)=>{let y=await a({operation:"current"},i,o);return y.kind==="unavailable"?r(o,y.error):d===y.value?"current":"stale"};return{check:async(i,o)=>{if(!(N(o)&&X(i)))return"stale";let d=performance.now(),y=f(i),T=g(y,d);if(T!==void 0){if(o===T.value)return"current";if(o<T.value)return"stale"}if(s(y,d))return"unavailable";if(T!==void 0)return await E(i,y,o);let G=await P(i,y,d);return G.kind==="unavailable"?r(y,G.error):o===G.value?"current":o<G.value?"stale":await E(i,y,o)},stamp:async i=>{if(!X(i))throw ae(i);let o=await a({operation:"current"},i,f(i));if(o.kind==="unavailable")throw o.error;return o.value},advance:async(i,o)=>{if(!X(i))return{kind:"failed",error:ae(i)};if(!Ee(o))return{kind:"failed",error:_e(o)};try{let d=await a({operation:"advance",from:o},i,f(i));return d.kind==="value"?{kind:"advanced",generation:d.value}:{kind:"unavailable",error:d.error}}catch(d){return{kind:"failed",error:d}}}}};var L=class extends Error{constructor(t){super(t),this.name="TokenRefreshError"}},D=class extends L{constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},C=class extends Error{constructor(t){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=t}},be=["access_token","expires_in"],W=(e,t,n)=>{let c=e.loginPath??"/auth/login",u=t.sessionKey,k=async S=>{let w=S.get(u)?.refreshToken;if(!w)throw new Error("Refresh token not found in session");try{let f="https://www.googleapis.com/oauth2/v4/token",g={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:w},p=await(e.fetch??globalThis.fetch)(f,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(g)});if(!p.ok){let a=await p.json().catch(()=>{});if(p.status===400&&typeof a=="object"&&!!a&&"error"in a&&a.error==="invalid_grant")throw new D;let E=typeof a=="object"&&a&&"error_description"in a?String(a.error_description):"Unknown error";throw new L(`Google token refresh failed: ${p.status} ${E}`)}let m=await p.json(),R=be.filter(a=>!m?.[a]);if(R.length>0)throw n.error("Invalid token response from Google; missing or empty keys:",R.join(", ")),new Error("Invalid token response from Google");let{access_token:s,expires_in:r}=m;return{accessToken:s,refreshToken:w,expirationDateMs:Number(Date.now())+r*1e3}}catch(f){if(f instanceof L)throw f;let g=f instanceof Error?f.message:"Unknown error";throw new L(`Failed to refresh Google access token: ${g}`)}},v=async S=>{let w=S.get(u).provider;if(!w)throw new Error("Provider not found in session");if(w==="google")return await k(S);throw new Error("Provider not supported")};return{authenticate:async(S,h,w)=>{let{failureRedirect:f}=w||{},g=l=>{if(f===null)return new C(l);if(f==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let p=f??c;return l!==void 0?le(p,{headers:{"Set-Cookie":l}}):le(p)};try{if(e.mockUser?.enabled(S))return{accessToken:"mock-access-token",refreshToken:"mock-refresh-token",expirationDateMs:Date.now()+36e5};let l=h.get(u),p=t.sessionGenerationGate;if(l!==void 0&&p!==null&&await p.check(U(l),h.get(x))==="stale")throw g(await t.destroySession(h));if(!(l?.accessToken&&l.expirationDateMs))throw g();let{accessToken:m,refreshToken:R,expirationDateMs:s}=l;if(s<Date.now())throw R?new Error("Expired"):g();return{accessToken:m,refreshToken:R,expirationDateMs:s}}catch(l){if(l instanceof Error&&l.message==="Expired")try{let p=await v(h),m=h.get(u);return h.set(u,{...m,...p}),p}catch(p){if(p instanceof D)n.warn("Google refresh token invalid or revoked");else{let R=p instanceof Error?p.message:"Unknown error";n.error("Failed to refresh token:",R)}let m=await t.destroySession(h);throw g(m)}throw l}},refreshedAccessToken:v}};import{redirect as fe}from"react-router";var j=({refreshToken:e,...t})=>t;var J=(e,t,n,c)=>{let u=new Map,k=new Map,v=async f=>{let g=u.get(f);if(g!==void 0)return g;let l=k.get(f);if(l!==void 0)return l;let p=(async()=>{try{let m=e.getUserPhoto?await e.getUserPhoto(f):"";return u.set(f,m),m}catch(m){throw u.delete(f),m}finally{k.delete(f)}})();return k.set(f,p),p},A=new WeakMap,S=async f=>{e.warmup&&await e.warmup();let g=await t.resolveSession(f);if(g.kind==="revoked")return{kind:"unauthenticated",cookie:await t.destroySession(g.session)};if(g.kind!=="signed-in")return{kind:"unauthenticated"};let{user:l,session:p}=g,m;try{m=await n.authenticate(f,p,{failureRedirect:null})}catch(b){if(b instanceof C)return b.setCookie!==void 0?{kind:"unauthenticated",cookie:b.setCookie}:{kind:"unauthenticated"};throw c.error("Error in authenticateInLoader:",b),b}let R={accessToken:m.accessToken,refreshToken:m.refreshToken,expirationDateMs:m.expirationDateMs,provider:l.provider},s={id:l.id,displayName:l.displayName,name:l.name,emails:l.emails,...R,role:l.role},r=await v(l.id),a=j({...l,...R,photo:r}),E=m.accessToken!==l.accessToken?await t.saveSession(f,s):void 0;return E!==void 0?{kind:"authenticated",user:a,cookie:E}:{kind:"authenticated",user:a}},h=f=>{let g=A.get(f);if(g!==void 0)return g;let l=S(f);return A.set(f,l),l};async function w(f,g){let{failureRedirect:l}=g;if(l==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let p=await h(f);if(p.kind==="authenticated")return p.cookie!==void 0?{user:p.user,cookie:p.cookie}:{user:p.user};if(l===null)return p.cookie!==void 0?{cookie:p.cookie}:{};throw p.cookie!==void 0?fe(l,{headers:{"Set-Cookie":p.cookie}}):fe(l)}return w};import{resolveAuthMessages as Ue}from"@aiquants/auth-core";import{redirect as H}from"react-router";import{Authenticator as Le}from"remix-auth";import{OAuth2Strategy as Ie}from"remix-auth-oauth2";var Oe=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],xe="google",Me="https://www.googleapis.com/oauth2/v3/userinfo",V=class extends Ie{constructor({clientId:n,clientSecret:c,redirectURI:u,scopes:k,accessType:v,includeGrantedScopes:A,prompt:S,hd:h,loginHint:w},f){let g=k??Oe;super({clientId:n,clientSecret:c,redirectURI:u,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:g},f);this.name=xe;this.scopes=g,this.accessType=v??"online",this.includeGrantedScopes=A??!1,this.prompt=S,this.hd=h,this.loginHint=w}authorizationParams(n,c){return n.set("access_type",this.accessType),n.set("include_granted_scopes",String(this.includeGrantedScopes)),this.scopes&&this.scopes.length>0&&n.set("scope",this.scopes.join(" ")),this.prompt&&n.set("prompt",this.prompt),this.hd&&n.set("hd",this.hd),this.loginHint&&n.set("login_hint",this.loginHint),n}static async userProfile(n){let c=await fetch(Me,{headers:{Authorization:`Bearer ${n.accessToken()}`}});if(!c.ok)throw new Error(`Failed to fetch user profile: ${c.statusText}`);let u=await c.json();return{id:u.sub,displayName:u.name,name:{familyName:u.family_name,givenName:u.given_name},emails:[{value:u.email}],photos:[{value:u.picture}],_json:u}}};var $={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var z=e=>{let t=e.logger??$,n=Ue(e.messages),c=e.loginPath??"/auth/login",u=new V({clientId:e.google.clientId,clientSecret:e.google.clientSecret,redirectURI:e.google.redirectURI,scopes:e.google.scopes,accessType:e.google.accessType??"offline",includeGrantedScopes:e.google.includeGrantedScopes??!0,prompt:e.google.prompt??"consent"},async({request:v,tokens:A})=>{let{access_token:S,refresh_token:h,expires_in:w,scope:f,id_token:g}=A.data,{_json:{sub:l,email:p,picture:m,hd:R,email_verified:s},photos:r,...a}=await V.userProfile(A),{id:P,displayName:E,name:{familyName:b,givenName:Y},emails:B}=a,i="google";if(S===void 0||h===void 0||w===void 0||f===void 0||P===void 0||E===void 0||l===void 0||p===void 0||s===void 0){if(s===!1){let d=encodeURIComponent(n.emailNotVerified);throw H(`${c}?error=${d}`)}let o=encodeURIComponent(n.googleFailed);throw H(`${c}?error=${o}`)}t.info("Authenticated on Google: ",a.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(i,S)){t.error("Backend verification returned false for user:",a.displayName);let I=encodeURIComponent(n.backendFailed);throw H(`${c}?error=${I}`)}t.info("Authenticated on Backend: ",a.displayName)}let o=a.emails[0]?.value;if(!await e.isEmailAllowed(o)){let G=new Error("You are not allowed to access this application");throw t.error(G),G}if(e.isUserActive&&!await e.isUserActive(a)){let G=new Error("You are not allowed to access this application");throw t.error("Deactivated account attempted to sign in:",o),G}e.backendAuth&&await e.backendAuth.signup(i,S,a),t.info("Authenticated complete: ",a.displayName);let d=Date.now()+w*1e3;return{...a,...{accessToken:S,refreshToken:h,expirationDateMs:d,provider:i},photo:m}}catch(o){let d=o;typeof o=="object"&&o!==null&&"cause"in o&&(d=o.cause||o),t.error("Error during backend authentication or subsequent processing:",d);let y=n.unexpected,T=!1;if(typeof o=="object"&&o!==null&&"cause"in o){let I=o.cause;I&&typeof I=="object"&&"message"in I&&typeof I.message=="string"&&I.message.includes("getaddrinfo ENOTFOUND")&&(y=n.backendUnreachable,T=!0)}if(!T&&o instanceof Error&&o.message.includes("You are not allowed to access this application")&&(y=n.notAllowed,T=!0),!T&&o instanceof Response&&o.headers.get("Location")?.startsWith(c))throw o;let G=encodeURIComponent(y);throw H(`${c}?error=${G}`)}}),k=new Le;return k.use(u),k};import{redirect as K}from"react-router";var Ne=new Map([["document",new Set(["none","same-origin","same-site"])],["empty",new Set(["same-origin"])]]),Q=e=>{let t=e.headers.get("Sec-Fetch-Dest");if(t!==null){let c=Ne.get(t);if(c===void 0)return`its fetch destination is "${t}"`;let u=e.headers.get("Sec-Fetch-Site");if(u===null)return`its "${t}" request states no site`;if(!c.has(u))return`its "${t}" request comes from a "${u}" page`}let n=e.headers.get("Sec-Purpose");if(n!==null)return`it is speculative ("${n}")`},Z=e=>new Response(`Signing out is refused because ${e}: only a navigation that does not come from another site, or a script's request from this origin, signs out.`,{status:403,headers:{"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"}});var ee=(e,t,n,c)=>{let u=e.loginPath??"/auth/login",k=e.postLoginRedirect??"/",v=e.postLogoutRedirect??"/",A=re(e.google.revocationTimeoutMs),S=async({request:s})=>{if(await t.getSessionUser(s))throw K(k);return{error:new URL(s.url).searchParams.get("error")}},h=async({request:s})=>{if((await s.clone().formData()).get("_action")!=="Sign In with Google")return null;throw await n.authenticate("google",s),K(u)},w=(s,r)=>{switch(s.outcome){case"failed":c.error(`Sign-out could not revoke the Google grant of user ${String(r)}; the session cookie is destroyed, but the grant stays valid until it expires or is revoked elsewhere:`,s.reason);return;case"already-invalid":c.info(`Sign-out found the Google grant of user ${String(r)} already unusable`);return;case"revoked":case"nothing-to-revoke":return}},f=(s,r)=>{s.kind!=="advanced"&&c.error(`Sign-out could not advance the session generation of ${r.provider} user ${r.id}; a session cookie refreshed before this sign-out stays valid until a later sign-out advances the generation or the cookie expires:`,s.error)},g=async(s,r)=>{let a=t.sessionGenerationGate;if(a!==null){if(!N(r)){c.info(`Sign-out found no usable session generation stamp in the session of ${s.provider} user ${s.id}; every guard already rejects that cookie, so the generation is not advanced`);return}f(await a.advance(s,r),s)}},l=async s=>{let r=await t.getSession(s),a=r.get(t.sessionKey),[P]=await Promise.all([se(a,{fetch:e.fetch??globalThis.fetch,timeoutMs:A}),a===void 0?void 0:g(U(a),r.get(x))]);return w(P,a?.id),await t.destroySession(r)},p=async s=>{let r=await l(s),a=new Headers;return a.append("Set-Cookie",r),K(v,{headers:a})};return{loginLoader:S,loginAction:h,logoutLoader:async({request:s})=>{let r=Q(s);throw r!==void 0?Z(r):await p(s)},logout:l,logoutAndRedirect:p,googleCallbackLoader:async({request:s})=>{try{let r=await n.authenticate("google",s),E=(await t.getSession(s)).get(t.sessionKey)?.refreshToken,b={accessToken:r.accessToken,refreshToken:r.refreshToken||E,expirationDateMs:r.expirationDateMs,provider:r.provider},Y={id:r.id,displayName:r.displayName,name:r.name,emails:r.emails,...b,role:r.role},B=await t.saveSignedInSession(s,Y);throw K(k,{headers:{"Set-Cookie":B}})}catch(r){throw r instanceof Response?r:(c.error("Authentication error:",r),K(u))}}}};import{createCookieSessionStorage as Ce,redirect as te}from"react-router";var oe=(e,t)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(s=>!s))throw new Error("REMIX_SESSION_SECRET must be set");let n=e.sessionKey??"user";if(n===x)throw new RangeError(`session.sessionKey must not be ${JSON.stringify(x)}, the key the session generation is stored under; got ${JSON.stringify(n)}`);let c=e.maxAge??3600*24*30,u=t.loginPath??"/auth/login",k=t.postLoginRedirect??"/",v=t.mockUser,A=t.isUserActive,S=de(t.sessionGeneration,t.logger??$),h=Ce({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:e.secure??process.env.NODE_ENV==="production",maxAge:c}}),w=async s=>await h.getSession(s.headers.get("Cookie")),f=async s=>{if(v?.enabled(s))return{kind:"signed-in",user:j(v.resolve(s)),session:await w(s)};let r=await w(s),a=r.get(n);if(a===void 0)return{kind:"signed-out"};let P=j(a),[E,b]=await Promise.all([A===void 0?!0:A(P),S===null?"current":S.check(U(a),r.get(x))]);return b==="stale"?{kind:"revoked",session:r}:E?{kind:"signed-in",user:P,session:r}:{kind:"inactive"}},g=async s=>{let r=await f(s);return r.kind==="signed-in"?r.user:void 0},l=async(s,r)=>{let a=await w(s);return a.set(n,r),await h.commitSession(a)},p=async(s,r)=>{let a=S===null?void 0:await S.stamp(U(r)),P=await w(s);return P.set(n,r),a!==void 0&&P.set(x,a),await h.commitSession(P)},m=async s=>{let r=await f(s);switch(r.kind){case"signed-in":return r.user;case"revoked":throw te(u,{headers:{"Set-Cookie":await h.destroySession(r.session)}});case"signed-out":case"inactive":throw te(u)}};return{sessionStorage:h,sessionKey:n,sessionGenerationGate:S,getSession:w,resolveSession:f,getSessionUser:g,saveSession:l,saveSignedInSession:p,requireUser:m,requireAdminUser:async s=>{let r=await m(s);if(r.role!=="admin")throw te(k);return r},commitSession:h.commitSession,destroySession:h.destroySession}};var $e=e=>{let t=e.logger??$,n=oe(e.session,{sessionGeneration:e.sessionGeneration,logger:t,mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive}),c=z(e),u=W(e,n,t),k=J(e,n,u,t),v=ee(e,n,c,t);return{authenticator:c,storage:n,authFns:u,sessionStorage:n.sessionStorage,getSession:n.getSession,getSessionUser:n.getSessionUser,saveSession:n.saveSession,requireUser:n.requireUser,requireAdminUser:n.requireAdminUser,commitSession:n.commitSession,destroySession:n.destroySession,authenticate:u.authenticate,refreshedAccessToken:u.refreshedAccessToken,authenticateInLoader:k,...v}};export{C as AuthRequiredError,he as DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS,ce as DEFAULT_SESSION_GENERATION_CACHE_TTL_MS,ue as DEFAULT_SESSION_GENERATION_TIMEOUT_MS,D as GoogleInvalidGrantError,q as SessionGenerationUnavailableError,L as TokenRefreshError,ee as createAuthHandlers,$e as createAuthServer,oe as createAuthSessionStorage,W as createAuthenticate,J as createAuthenticateInLoader,z as createGoogleAuthenticator,Q as signOutRefusal,Z as signOutRefusalResponse};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiquants/auth-react-router",
3
- "version": "0.23.0",
3
+ "version": "0.24.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"