@aiquants/auth-react-router 0.23.0 → 0.25.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,40 @@ 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
+ Scopes for one sign-in on top of `google.scopes` (a wider permission a reader is asked to grant on a dedicated sign-in path,
71
+ for example), read from the sign-in request when the authorization redirect is built:
72
+
73
+ ```ts
74
+ createAuthServer({
75
+ google: {
76
+ ...,
77
+ // Synchronous. Map the request to a fixed set of scopes; never copy a scope from the request itself
78
+ additionalScopes: (request) => (new URL(request.url).searchParams.get("grant") === "edit" ? ["https://www.googleapis.com/auth/drive"] : []),
79
+ },
80
+ ...
81
+ })
82
+ ```
83
+
84
+ The scope sent is `google.scopes` followed by the additional ones, each once. A scope that is empty or holds white space
85
+ throws `RangeError` when the redirect is built. With `includeGrantedScopes` (the default), a scope granted once stays
86
+ with the later sign-ins too.
87
+
88
+ A sign-in written outside `googleCallbackLoader` (a test fixture that needs a signed-in cookie, say) goes through the
89
+ same write path, so it carries a valid stamp:
90
+
91
+ ```ts
92
+ const setCookie = await authServer.storage.saveSignedInSession(new Request("http://localhost/"), profile)
93
+ ```
94
+
64
95
  A host that writes its own sign-out route (to add headers to the answer, say) applies the same request rule as
65
96
  `logoutLoader` before signing out:
66
97
 
@@ -303,8 +334,10 @@ this package imports it **directly** — `src/admin/labels.ts` resolves the UI l
303
334
  `resolveVirtualScrollLocale`, so `dist/admin.mjs` carries its specifier. The pickers use the `locale` / `labels` props
304
335
  of `@aiquants/select-box` and its 0.11 render and typing contract (`RenderOptionContext.highlight`, and `value` /
305
336
  `onChange` typed by the option type), plus the locale resolution of `@aiquants/virtualscroll` 3.7.0. The published manifest carries the versions the release
306
- was built and tested with — select-box `^0.16.0`, fuzzy-search `^3.0.0`, virtualscroll `^3.11.1` — so a host installs at
307
- least those (a 0.x minor is outside the caret range: a host on select-box 0.15 bumps it explicitly).
337
+ was built and tested with (its `peerDependencies`), so a host installs at least those (a 0.x minor is outside the caret
338
+ range: a host on select-box 0.15 bumps it explicitly). The select-box version that range resolves to names its own
339
+ floors for fuzzy-search and virtualscroll, which can be higher than this package's: install the ranges the resolved
340
+ select-box's manifest names.
308
341
 
309
342
  All three are **required** peers, not optional. `src/admin/views.tsx` imports `@aiquants/select-box` and
310
343
  `src/admin/labels.ts` imports `@aiquants/virtualscroll` at the top level, and `./admin` re-exports both modules, so the
@@ -316,13 +349,17 @@ package's own `react: ">=18"`; a host that mounts `/admin` must satisfy the stri
316
349
 
317
350
  ## Behavior Contract
318
351
 
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.
352
+ - **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.
353
+ With the check enabled a cookie without a valid `"generation"` is rejected, so every user signs in once after a host
354
+ turns it on. Changing the cookie name, the `"user"` key or the profile shape invalidates all live 30-day sessions.
355
+ `session.sessionKey` must not be `"generation"` (`RangeError` when the server is built).
320
356
  - **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
357
  - **Token refresh**: expiry check → Google `oauth2/v4/token` rotate → session update; `invalid_grant` destroys the session and redirects to login with `Set-Cookie`.
322
358
  - **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
359
  - **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.
360
+ - **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
361
  - Photo lookups are cached with in-flight dedup per factory instance.
362
+ - **The test backdoor's tokens are the port's**: when `mockUser.enabled(request)` holds, `authenticate` (and so `authenticateInLoader`) returns the `accessToken`, `refreshToken` and `expirationDateMs` of the profile `mockUser.resolve(request)` builds, never a fixed value, so a host can sign the backdoor's user in with a token its API accepts. The backdoor's tokens are not refreshed.
326
363
  - **Profiles handed to route code carry no refresh token**: `authenticateInLoader` returns `user: LoaderUser`
327
364
  (`Omit<MyGoogleProfile, "refreshToken">`) and `getSessionUser` / `requireUser` / `requireAdminUser` return `SessionUser`
328
365
  (`Omit<SessionProfile, "refreshToken">`); the key is absent at runtime as well, for the `mockUser` backdoor's user and for
@@ -337,8 +374,11 @@ package's own `react: ">=18"`; a host that mounts `/admin` must satisfy the stri
337
374
  `createAuthenticate`): the `{ accessToken, refreshToken, expirationDateMs }` they return.
338
375
  - `authenticator` (from `createGoogleAuthenticator`): the `MyGoogleProfile` its `authenticate("google", request)`
339
376
  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.
377
+ - `storage.resolveSession` (the guards' internal resolver, exposed for tests): the `session` of its `signed-in` and
378
+ `revoked` results is the raw session.
379
+ - The `Set-Cookie` values of `saveSession` / `commitSession` / `storage.saveSignedInSession` and the `cookie` of
380
+ `authenticateInLoader`: the session cookie is signed, not encrypted, so the token can be read out of it. Put them
381
+ in a `Set-Cookie` header only.
342
382
  - **`loginAction` never hands out the signed-in profile**: for `_action === "Sign In with Google"` it always ends by
343
383
  throwing a redirect. The strategy normally throws the redirect to Google's authorization endpoint. When the POST's URL
344
384
  carries `code` and the `state` of the user's state cookie, remix-auth exchanges the code inside the action and returns
@@ -357,10 +397,67 @@ package's own `react: ">=18"`; a host that mounts `/admin` must satisfy the stri
357
397
  token refresh (within about an hour), and a service sharing the OAuth client loses the grant as well.
358
398
  - Revocation alone does not close one race: a token refresh that reached Google before the revocation can still set a
359
399
  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.
400
+ Google while it is. The sign-out generation (next item) closes the race: that cookie still carries the stamp of its
401
+ sign-in, and the sign-out has advanced the generation past it. With `sessionGeneration: false` the race stays open:
402
+ `authenticateInLoader` accepts that cookie until the token expires (about an hour), and the session getters
403
+ (`getSessionUser` / `requireUser` / `requireAdminUser`), which never look at the expiry, accept it until the first
404
+ `authenticateInLoader` after the expiry fails to refresh (`invalid_grant`) and deletes it.
405
+ - **Sign-out session generation** (`sessionGeneration: { store, cacheTtlMs?, timeoutMs? } | false`, required): every
406
+ identity (`provider` + the provider's stable user id, the session profile's `id`) has a generation in a store all
407
+ processes share, starting at 0 and raised past the signed-out session's stamp at each sign-out.
408
+ - **Sign-in** (`googleCallbackLoader`, through `storage.saveSignedInSession`) reads the identity's generation afresh
409
+ (never from the cache) and stamps it into the session beside the profile, overwriting any older stamp. A store that
410
+ cannot be read fails the sign-in: it is logged (`Authentication error:`) and redirected to `loginPath`, and no session
411
+ cookie is set. A token refresh (`saveSession`) keeps the stamp of the sign-in.
412
+ - **Every guard checks the stamp**: `getSessionUser` / `requireUser` / `requireAdminUser`, `authenticateInLoader` and
413
+ `authenticate`. A stamp older than the identity's generation, or a missing or invalid one, means the session was
414
+ signed out: `getSessionUser` returns `undefined`; `requireUser` / `requireAdminUser` redirect to `loginPath` with the
415
+ cookie's deletion; `authenticateInLoader` returns the deletion as `cookie` (`null` mode) or throws the redirect
416
+ carrying it; `authenticate` destroys the session (`AuthRequiredError` with `setCookie`, or the redirect with
417
+ `Set-Cookie`). The deletion wins over an `isUserActive` that also answers `false` (that alone keeps the cookie).
418
+ `loginLoader` only reads, so it shows the login page and the next sign-in overwrites the cookie. The `mockUser`
419
+ backdoor is never checked.
420
+ - **Sign-out** (`logout`, and so `logoutAndRedirect` / `logoutLoader`) advances the generation past the session's
421
+ stamp (`store.advance(identity, stamp)` raises it to at least `stamp + 1`) concurrently with the grant revocation,
422
+ and answers once both have settled, so it waits at most
423
+ `max(google.revocationTimeoutMs, sessionGeneration.timeoutMs)`. Raising past the stamp rather than by one means a
424
+ second sign-out with the same cookie, or a replay of a cookie the guards already reject, leaves the generation — and
425
+ every session signed in since — as it is. An advance that fails, times out or is answered with less than
426
+ `stamp + 1` is logged with `logger.error` (the store's error and the user id, never a token) and the session is
427
+ destroyed anyway; a cookie refreshed before that sign-out then stays valid until a later sign-out advances the
428
+ generation or the cookie expires. A session without a usable stamp (every guard already rejects it) advances
429
+ nothing and is logged with `logger.info`. A refused sign-out (`signOutRefusal`) and a request without a session
430
+ advance nothing.
431
+ - **Bound**: after a sign-out, the next request carrying an older cookie is rejected immediately on the process that
432
+ ran the sign-out, and within `cacheTtlMs` (default `DEFAULT_SESSION_GENERATION_CACHE_TTL_MS`, 15000 ms) on any other
433
+ process, which reuses a generation it read, and joins a read in flight, only while that read started less than
434
+ `cacheTtlMs` ago. On the process that ran the sign-out, a store call of that identity that started before the
435
+ sign-out's advance answered never brings the older generation back into the reused value, however late it answers.
436
+ The bound holds while the store answers that identity's calls in time; another identity's outage does not suspend
437
+ it (next item). Times are measured on the monotonic clock (`performance.now()`), so a step of the wall clock does
438
+ not stretch the bound. A server-sent-event stream or any other response opened before the sign-out keeps running
439
+ until it ends: a guard checks a request once, when it arrives.
440
+ - **Unreachable store**: every store call is bounded by `timeoutMs` (default `DEFAULT_SESSION_GENERATION_TIMEOUT_MS`,
441
+ 3000 ms). When the store cannot be reached for an identity (a call rejects with `SessionGenerationUnavailableError`,
442
+ or does not answer in time) the check is skipped and the cookie accepted, with a `logger.warn` at most once a minute
443
+ for the whole server, whichever identity it concerns. For `cacheTtlMs` afterwards, until a store call for that
444
+ identity answers in time again, every check of that identity that would need the store is skipped without calling
445
+ it (the identity's outage window), while a stamp a fresh cached generation decides (equal to it or older) is still
446
+ decided by it. Other identities are checked as usual, so a slow or locked row for one identity does not switch the
447
+ check off for everyone; during a real outage each identity costs at most one `timeoutMs` wait per `cacheTtlMs`. The process
448
+ that ran a sign-out therefore keeps rejecting the signed-out cookie through any other identity's outage window, and
449
+ through that identity's own window while its record of the advance is fresh (`cacheTtlMs` from the advance's
450
+ start); after that, the identity's window skips the check there as on any other process. Any other rejection, or a
451
+ value that is not an integer >= 0 (`TypeError`), is a defect and propagates: the guard rejects, the sign-in fails,
452
+ the sign-out logs it.
453
+ - **`cacheTtlMs: 0`** reuses nothing, joins no read and opens no outage window, so `authenticateInLoader` reads the
454
+ store twice per request (`resolveSession`, then `authenticate`). While the store hangs, every guarded request can
455
+ wait up to 2 × `timeoutMs` before it is let through (a store that fails fast costs two fast failures instead).
456
+ - **Settings**: anything other than `{ store, cacheTtlMs?, timeoutMs? }` (with `store.current` and `store.advance`
457
+ functions) or `false` — a missing key included — throws `TypeError` when the server is built; `cacheTtlMs` must be
458
+ an integer from 0 to 2147483647 and `timeoutMs` one from 1 to 2147483647 (`RangeError` otherwise).
459
+ - **`false`** turns all of it off: nothing is stamped or checked, sign-out advances nothing, and the race above stays
460
+ open.
364
461
  - **`logoutLoader` refuses sign-outs the user did not ask for**, judged by the request's fetch metadata
365
462
  (`signOutRefusal`). It signs out a `Sec-Fetch-Dest: document` request only when its `Sec-Fetch-Site` is `none` (a typed
366
463
  address or a bookmark), `same-origin` or `same-site`, and a `Sec-Fetch-Dest: empty` request only when it is
@@ -395,6 +492,18 @@ package's own `react: ">=18"`; a host that mounts `/admin` must satisfy the stri
395
492
 
396
493
  `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
494
 
495
+ `sessionGeneration.store` (`SessionGenerationStore`) is `{ current(identity), advance(identity, from) }` over storage
496
+ every process shares (a database table keyed by `identity.provider` + `identity.id`, for example;
497
+ `SessionGenerationIdentity` is `{ provider, id }`). `current` resolves to the identity's generation, `0` until its first
498
+ sign-out. `advance` receives `from`, the stamp of the session being signed out (an integer >= 0), raises the stored
499
+ generation to at least `from + 1` — a greater stored value is left as it is, and an identity with no stored generation
500
+ gets `from + 1` (in SQL, an upsert that keeps the greater of the stored value and `from + 1`) — and resolves to the
501
+ stored generation afterwards. An answer below `from + 1` is a defect: the sign-out logs it as a failed advance. A
502
+ generation never decreases. Reject with `SessionGenerationUnavailableError` (an `Error` that takes `{ cause }`)
503
+ **only** when the store cannot be reached — the check of that identity is then skipped — and let every other error
504
+ propagate, so a missing table or a refused login is loud rather than silently skipped. Pass `sessionGeneration: false`
505
+ to run without the check (the sign-out race stays open).
506
+
398
507
  > ⚠️ `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
508
 
400
509
  ## Intentional Changes vs Original (§8, approved)
package/dist/server.d.mts CHANGED
@@ -14,6 +14,7 @@ type GoogleOAuthConfig = {
14
14
  accessType?: "online" | "offline";
15
15
  includeGrantedScopes?: boolean;
16
16
  prompt?: "none" | "consent" | "select_account";
17
+ additionalScopes?: (request: Request) => readonly string[];
17
18
  revocationTimeoutMs?: number;
18
19
  };
19
20
  type FetchPort = (url: string, init: RequestInit) => Promise<Response>;
@@ -39,11 +40,25 @@ type LoggerPort = {
39
40
  warn: (...args: unknown[]) => void;
40
41
  error: (...args: unknown[]) => void;
41
42
  };
43
+ type SessionGenerationIdentity = {
44
+ readonly provider: string;
45
+ readonly id: string;
46
+ };
47
+ type SessionGenerationStore = {
48
+ current: (identity: SessionGenerationIdentity) => Promise<number>;
49
+ advance: (identity: SessionGenerationIdentity, from: number) => Promise<number>;
50
+ };
51
+ type SessionGenerationConfig = {
52
+ readonly store: SessionGenerationStore;
53
+ readonly cacheTtlMs?: number;
54
+ readonly timeoutMs?: number;
55
+ };
42
56
  type AuthServerConfig = {
43
57
  google: GoogleOAuthConfig;
44
58
  session: SessionConfig;
45
59
  isEmailAllowed: (email: string | null | undefined) => boolean | Promise<boolean>;
46
60
  isUserActive?: (profile: GoogleProfileBase) => boolean | Promise<boolean>;
61
+ sessionGeneration: SessionGenerationConfig | false;
47
62
  backendAuth?: BackendAuthPort;
48
63
  getUserPhoto?: UserPhotoPort;
49
64
  warmup?: WarmupPort;
@@ -55,6 +70,62 @@ type AuthServerConfig = {
55
70
  logger?: LoggerPort;
56
71
  fetch?: FetchPort;
57
72
  };
73
+ declare const DEFAULT_SESSION_GENERATION_CACHE_TTL_MS = 15000;
74
+ declare const DEFAULT_SESSION_GENERATION_TIMEOUT_MS = 3000;
75
+ declare class SessionGenerationUnavailableError extends Error {
76
+ constructor(message: string, options?: ErrorOptions);
77
+ }
78
+ type SessionGenerationVerdict = "current" | "stale" | "unavailable";
79
+ type AdvanceOutcome = {
80
+ readonly kind: "advanced";
81
+ readonly generation: number;
82
+ } | {
83
+ readonly kind: "unavailable";
84
+ readonly error: unknown;
85
+ } | {
86
+ readonly kind: "failed";
87
+ readonly error: unknown;
88
+ };
89
+ type SessionGenerationGate = {
90
+ readonly check: (identity: SessionGenerationIdentity, stamped: unknown) => Promise<SessionGenerationVerdict>;
91
+ readonly stamp: (identity: SessionGenerationIdentity) => Promise<number>;
92
+ readonly advance: (identity: SessionGenerationIdentity, from: number) => Promise<AdvanceOutcome>;
93
+ };
94
+ type AuthSessionStorage = ReturnType<typeof createAuthSessionStorage>;
95
+ type AuthSessionStorageOptions = {
96
+ readonly sessionGeneration: SessionGenerationConfig | false;
97
+ readonly logger?: LoggerPort;
98
+ readonly mockUser?: MockUserPort;
99
+ readonly loginPath?: string;
100
+ readonly postLoginRedirect?: string;
101
+ readonly isUserActive?: (profile: GoogleProfileBase) => boolean | Promise<boolean>;
102
+ };
103
+ type SessionResolution = {
104
+ readonly kind: "signed-in";
105
+ readonly user: SessionUser;
106
+ readonly session: Session;
107
+ } | {
108
+ readonly kind: "signed-out";
109
+ } | {
110
+ readonly kind: "inactive";
111
+ } | {
112
+ readonly kind: "revoked";
113
+ readonly session: Session;
114
+ };
115
+ declare const createAuthSessionStorage: (config: SessionConfig, options: AuthSessionStorageOptions) => {
116
+ sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
117
+ sessionKey: string;
118
+ sessionGenerationGate: SessionGenerationGate | null;
119
+ getSession: (request: Request) => Promise<Session<react_router.SessionData, react_router.SessionData>>;
120
+ resolveSession: (request: Request) => Promise<SessionResolution>;
121
+ getSessionUser: (request: Request) => Promise<SessionUser | undefined>;
122
+ saveSession: (request: Request, user: SessionProfile) => Promise<string>;
123
+ saveSignedInSession: (request: Request, profile: SessionProfile) => Promise<string>;
124
+ requireUser: (request: Request) => Promise<SessionUser>;
125
+ requireAdminUser: (request: Request) => Promise<SessionUser>;
126
+ commitSession: (session: Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
127
+ destroySession: (session: Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
128
+ };
58
129
  type AuthServer = ReturnType<typeof createAuthServer>;
59
130
  declare const createAuthServer: (config: AuthServerConfig) => {
60
131
  loginLoader: ({ request }: {
@@ -77,9 +148,12 @@ declare const createAuthServer: (config: AuthServerConfig) => {
77
148
  storage: {
78
149
  sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
79
150
  sessionKey: string;
151
+ sessionGenerationGate: SessionGenerationGate | null;
80
152
  getSession: (request: Request) => Promise<react_router.Session<react_router.SessionData, react_router.SessionData>>;
153
+ resolveSession: (request: Request) => Promise<SessionResolution>;
81
154
  getSessionUser: (request: Request) => Promise<SessionUser | undefined>;
82
155
  saveSession: (request: Request, user: _aiquants_auth_core.SessionProfile) => Promise<string>;
156
+ saveSignedInSession: (request: Request, profile: _aiquants_auth_core.SessionProfile) => Promise<string>;
83
157
  requireUser: (request: Request) => Promise<SessionUser>;
84
158
  requireAdminUser: (request: Request) => Promise<SessionUser>;
85
159
  commitSession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
@@ -134,23 +208,6 @@ declare const createAuthServer: (config: AuthServerConfig) => {
134
208
  }>;
135
209
  };
136
210
  };
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
211
  declare class TokenRefreshError extends Error {
155
212
  constructor(message: string);
156
213
  }
@@ -212,4 +269,4 @@ declare const createAuthHandlers: (config: AuthServerConfig, storage: AuthSessio
212
269
  };
213
270
  declare const signOutRefusal: (request: Request) => string | undefined;
214
271
  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 };
272
+ export { AuthRequiredError, type AuthServer, type AuthServerConfig, type AuthSessionStorage, type BackendAuthPort, DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS, DEFAULT_SESSION_GENERATION_CACHE_TTL_MS, DEFAULT_SESSION_GENERATION_TIMEOUT_MS, type FetchPort, GoogleInvalidGrantError, type GoogleOAuthConfig, type LoaderUser, type LoggerPort, type MockUserPort, type SessionConfig, type SessionGenerationConfig, type SessionGenerationIdentity, type SessionGenerationStore, SessionGenerationUnavailableError, type SessionUser, TokenRefreshError, type UserPhotoPort, type WarmupPort, createAuthHandlers, createAuthServer, createAuthSessionStorage, createAuthenticate, createAuthenticateInLoader, createGoogleAuthenticator, signOutRefusal, signOutRefusalResponse };
package/dist/server.d.ts CHANGED
@@ -14,6 +14,7 @@ type GoogleOAuthConfig = {
14
14
  accessType?: "online" | "offline";
15
15
  includeGrantedScopes?: boolean;
16
16
  prompt?: "none" | "consent" | "select_account";
17
+ additionalScopes?: (request: Request) => readonly string[];
17
18
  revocationTimeoutMs?: number;
18
19
  };
19
20
  type FetchPort = (url: string, init: RequestInit) => Promise<Response>;
@@ -39,11 +40,25 @@ type LoggerPort = {
39
40
  warn: (...args: unknown[]) => void;
40
41
  error: (...args: unknown[]) => void;
41
42
  };
43
+ type SessionGenerationIdentity = {
44
+ readonly provider: string;
45
+ readonly id: string;
46
+ };
47
+ type SessionGenerationStore = {
48
+ current: (identity: SessionGenerationIdentity) => Promise<number>;
49
+ advance: (identity: SessionGenerationIdentity, from: number) => Promise<number>;
50
+ };
51
+ type SessionGenerationConfig = {
52
+ readonly store: SessionGenerationStore;
53
+ readonly cacheTtlMs?: number;
54
+ readonly timeoutMs?: number;
55
+ };
42
56
  type AuthServerConfig = {
43
57
  google: GoogleOAuthConfig;
44
58
  session: SessionConfig;
45
59
  isEmailAllowed: (email: string | null | undefined) => boolean | Promise<boolean>;
46
60
  isUserActive?: (profile: GoogleProfileBase) => boolean | Promise<boolean>;
61
+ sessionGeneration: SessionGenerationConfig | false;
47
62
  backendAuth?: BackendAuthPort;
48
63
  getUserPhoto?: UserPhotoPort;
49
64
  warmup?: WarmupPort;
@@ -55,6 +70,62 @@ type AuthServerConfig = {
55
70
  logger?: LoggerPort;
56
71
  fetch?: FetchPort;
57
72
  };
73
+ declare const DEFAULT_SESSION_GENERATION_CACHE_TTL_MS = 15000;
74
+ declare const DEFAULT_SESSION_GENERATION_TIMEOUT_MS = 3000;
75
+ declare class SessionGenerationUnavailableError extends Error {
76
+ constructor(message: string, options?: ErrorOptions);
77
+ }
78
+ type SessionGenerationVerdict = "current" | "stale" | "unavailable";
79
+ type AdvanceOutcome = {
80
+ readonly kind: "advanced";
81
+ readonly generation: number;
82
+ } | {
83
+ readonly kind: "unavailable";
84
+ readonly error: unknown;
85
+ } | {
86
+ readonly kind: "failed";
87
+ readonly error: unknown;
88
+ };
89
+ type SessionGenerationGate = {
90
+ readonly check: (identity: SessionGenerationIdentity, stamped: unknown) => Promise<SessionGenerationVerdict>;
91
+ readonly stamp: (identity: SessionGenerationIdentity) => Promise<number>;
92
+ readonly advance: (identity: SessionGenerationIdentity, from: number) => Promise<AdvanceOutcome>;
93
+ };
94
+ type AuthSessionStorage = ReturnType<typeof createAuthSessionStorage>;
95
+ type AuthSessionStorageOptions = {
96
+ readonly sessionGeneration: SessionGenerationConfig | false;
97
+ readonly logger?: LoggerPort;
98
+ readonly mockUser?: MockUserPort;
99
+ readonly loginPath?: string;
100
+ readonly postLoginRedirect?: string;
101
+ readonly isUserActive?: (profile: GoogleProfileBase) => boolean | Promise<boolean>;
102
+ };
103
+ type SessionResolution = {
104
+ readonly kind: "signed-in";
105
+ readonly user: SessionUser;
106
+ readonly session: Session;
107
+ } | {
108
+ readonly kind: "signed-out";
109
+ } | {
110
+ readonly kind: "inactive";
111
+ } | {
112
+ readonly kind: "revoked";
113
+ readonly session: Session;
114
+ };
115
+ declare const createAuthSessionStorage: (config: SessionConfig, options: AuthSessionStorageOptions) => {
116
+ sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
117
+ sessionKey: string;
118
+ sessionGenerationGate: SessionGenerationGate | null;
119
+ getSession: (request: Request) => Promise<Session<react_router.SessionData, react_router.SessionData>>;
120
+ resolveSession: (request: Request) => Promise<SessionResolution>;
121
+ getSessionUser: (request: Request) => Promise<SessionUser | undefined>;
122
+ saveSession: (request: Request, user: SessionProfile) => Promise<string>;
123
+ saveSignedInSession: (request: Request, profile: SessionProfile) => Promise<string>;
124
+ requireUser: (request: Request) => Promise<SessionUser>;
125
+ requireAdminUser: (request: Request) => Promise<SessionUser>;
126
+ commitSession: (session: Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
127
+ destroySession: (session: Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
128
+ };
58
129
  type AuthServer = ReturnType<typeof createAuthServer>;
59
130
  declare const createAuthServer: (config: AuthServerConfig) => {
60
131
  loginLoader: ({ request }: {
@@ -77,9 +148,12 @@ declare const createAuthServer: (config: AuthServerConfig) => {
77
148
  storage: {
78
149
  sessionStorage: react_router.SessionStorage<react_router.SessionData, react_router.SessionData>;
79
150
  sessionKey: string;
151
+ sessionGenerationGate: SessionGenerationGate | null;
80
152
  getSession: (request: Request) => Promise<react_router.Session<react_router.SessionData, react_router.SessionData>>;
153
+ resolveSession: (request: Request) => Promise<SessionResolution>;
81
154
  getSessionUser: (request: Request) => Promise<SessionUser | undefined>;
82
155
  saveSession: (request: Request, user: _aiquants_auth_core.SessionProfile) => Promise<string>;
156
+ saveSignedInSession: (request: Request, profile: _aiquants_auth_core.SessionProfile) => Promise<string>;
83
157
  requireUser: (request: Request) => Promise<SessionUser>;
84
158
  requireAdminUser: (request: Request) => Promise<SessionUser>;
85
159
  commitSession: (session: react_router.Session<react_router.SessionData, react_router.SessionData>, options?: react_router.CookieSerializeOptions) => Promise<string>;
@@ -134,23 +208,6 @@ declare const createAuthServer: (config: AuthServerConfig) => {
134
208
  }>;
135
209
  };
136
210
  };
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
211
  declare class TokenRefreshError extends Error {
155
212
  constructor(message: string);
156
213
  }
@@ -212,4 +269,4 @@ declare const createAuthHandlers: (config: AuthServerConfig, storage: AuthSessio
212
269
  };
213
270
  declare const signOutRefusal: (request: Request) => string | undefined;
214
271
  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 };
272
+ export { AuthRequiredError, type AuthServer, type AuthServerConfig, type AuthSessionStorage, type BackendAuthPort, DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS, DEFAULT_SESSION_GENERATION_CACHE_TTL_MS, DEFAULT_SESSION_GENERATION_TIMEOUT_MS, type FetchPort, GoogleInvalidGrantError, type GoogleOAuthConfig, type LoaderUser, type LoggerPort, type MockUserPort, type SessionConfig, type SessionGenerationConfig, type SessionGenerationIdentity, type SessionGenerationStore, SessionGenerationUnavailableError, type SessionUser, TokenRefreshError, type UserPhotoPort, type WarmupPort, createAuthHandlers, createAuthServer, createAuthSessionStorage, createAuthenticate, createAuthenticateInLoader, createGoogleAuthenticator, signOutRefusal, signOutRefusalResponse };
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,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ve(t))!Ae.call(e,i)&&i!==n&&oe(e,i,{get:()=>t[i],enumerable:!(a=ke(t,i))||a.enumerable});return e};var Re=e=>Te(oe({},"__esModule",{value:!0}),e);var He={};Ge(He,{AuthRequiredError:()=>N,DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS:()=>ue,DEFAULT_SESSION_GENERATION_CACHE_TTL_MS:()=>re,DEFAULT_SESSION_GENERATION_TIMEOUT_MS:()=>se,GoogleInvalidGrantError:()=>F,SessionGenerationUnavailableError:()=>C,TokenRefreshError:()=>M,createAuthHandlers:()=>Q,createAuthServer:()=>ye,createAuthSessionStorage:()=>Z,createAuthenticate:()=>B,createAuthenticateInLoader:()=>X,createGoogleAuthenticator:()=>J,signOutRefusal:()=>W,signOutRefusalResponse:()=>z});module.exports=Re(He);var ie=require("react-router");var Pe="https://oauth2.googleapis.com/revoke",ue=5e3;var Ee="google",_e="invalid_token";var de=e=>{if(e===void 0)return 5e3;if(!Number.isInteger(e)||e<1||e>2147483647)throw new RangeError(`google.revocationTimeoutMs must be an integer from 1 to 2147483647 (milliseconds); got ${String(e)}`);return e},be=e=>{if(typeof e.refreshToken=="string"&&e.refreshToken!=="")return e.refreshToken;if(typeof e.accessToken=="string"&&e.accessToken!=="")return e.accessToken},Ie=async e=>{let t=await e.json().catch(()=>{});return typeof t=="object"&&t!==null&&"error"in t&&typeof t.error=="string"?t.error:void 0},Oe=e=>e instanceof Error?e.cause instanceof Error?`${e.message} (${e.cause.message})`:e.message:String(e),xe=async(e,t,n)=>{try{let a=await t(Pe,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:e}).toString(),signal:n});if(a.ok)return await a.body?.cancel(),{outcome:"revoked"};let i=await Ie(a);return a.status===400&&i===_e?{outcome:"already-invalid"}:{outcome:"failed",reason:i===void 0?`Google answered ${a.status}`:`Google answered ${a.status} ${i}`}}catch(a){return{outcome:"failed",reason:Oe(a)}}},le=async(e,t)=>{if(e===void 0)return{outcome:"nothing-to-revoke"};let n=be(e);if(n===void 0)return{outcome:"nothing-to-revoke"};if(e.provider!==Ee)return{outcome:"failed",reason:`the session's provider "${String(e.provider)}" has no revocation endpoint`};let a=new AbortController;return await new Promise(i=>{let w=setTimeout(()=>{i({outcome:"failed",reason:`Google did not answer within ${t.timeoutMs} ms`}),a.abort()},t.timeoutMs);xe(n,t.fetch,a.signal).then(v=>{clearTimeout(w),i(v)})})};var x="generation",re=15e3,se=3e3,Ue=6e4,C=class extends Error{constructor(t,n){super(t,n),this.name="SessionGenerationUnavailableError"}},O=e=>typeof e=="string"?JSON.stringify(e):typeof e=="function"?"a function":typeof e=="object"&&e!==null?Array.isArray(e)?"an array":"an object":typeof e=="bigint"?`${e}n`:String(e),Le=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return O(e);let t="store"in e?e.store:void 0;if(typeof t!="object"||t===null)return`an object whose store is ${O(t)}`;let n="current"in t?t.current:void 0,a="advance"in t?t.advance:void 0;return`an object whose store.current is ${O(n)} and store.advance is ${O(a)}`},Ne=e=>typeof e=="object"&&e!==null&&"current"in e&&typeof e.current=="function"&&"advance"in e&&typeof e.advance=="function",fe=(e,t,n,a)=>{if(t===void 0)return a;if(typeof t!="number"||!Number.isInteger(t)||t<n||t>2147483647)throw new RangeError(`${e} must be an integer from ${n} to ${2147483647} (milliseconds); got ${O(t)}`);return t},Ce=e=>{if(e===!1)return!1;let t=e;if(typeof t!="object"||t===null||!("store"in t)||!Ne(t.store))throw new TypeError(`sessionGeneration must be { store, cacheTtlMs?, timeoutMs? } or false; got ${Le(t)}`);return{store:t.store,cacheTtlMs:fe("sessionGeneration.cacheTtlMs","cacheTtlMs"in t?t.cacheTtlMs:void 0,0,re),timeoutMs:fe("sessionGeneration.timeoutMs","timeoutMs"in t?t.timeoutMs:void 0,1,se)}},$=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,ne=e=>typeof e.provider=="string"&&e.provider!==""&&typeof e.id=="string"&&e.id!=="",pe=e=>new TypeError(`a session generation identity needs a non-empty provider and id; got provider ${O(e.provider)} and id ${O(e.id)}`),$e=e=>$(e)&&$(e+1),Fe=e=>new TypeError(`a session generation advance needs the signed-out session's stamp, an integer from 0 to ${Number.MAX_SAFE_INTEGER-1}; got ${O(e)}`),L=e=>({provider:e.provider,id:e.id}),ge=(e,t)=>{let n=Ce(e);if(n===!1)return null;let{store:a,cacheTtlMs:i,timeoutMs:w}=n,v=new Map,A=new Map,m=new Map,h=new Map,k=Number.NEGATIVE_INFINITY,f=u=>`${u.provider}\0${u.id}`,g=(u,o)=>{let l=v.get(u);if(l!==void 0){if(o-l.at<i)return l;v.delete(u)}},d=(u,o,l)=>{if(l!==void 0&&o.at<=l.answeredAt&&o.value<l.value)return;let y=g(u,performance.now());if(y===void 0){v.set(u,o);return}o.value<y.value||v.set(u,{value:o.value,at:Math.max(y.at,o.at)})},p=u=>{let o=h.get(u);if(o!==void 0)return o.count+=1,o;let l={count:1,floor:void 0};return h.set(u,l),l},S=(u,o)=>{o.count-=1,o.count===0&&h.delete(u)},P=(u,o)=>{u.floor={value:u.floor===void 0?o:Math.max(u.floor.value,o),answeredAt:performance.now()}},s=(u,o)=>{let l=m.get(u);return l===void 0?!1:o<l?!0:(m.delete(u),!1)},r=(u,o)=>{let l=performance.now();return m.set(u,l+i),l-k>=Ue&&(k=l,t.warn("Session generation store unavailable; skipping the sign-out generation check:",o)),"unavailable"},c=(u,o,l)=>new Promise((y,R)=>{let{operation:G}=u,I=u.operation==="advance"?u.from+1:0,we=performance.now(),V=p(l),U=!1,ce=setTimeout(()=>{U=!0,y({kind:"unavailable",error:new C(`sessionGeneration.store.${G} did not settle within ${w} ms`)})},w);new Promise(_=>_(u.operation==="advance"?a.advance(o,u.from):a.current(o))).then(_=>{if(clearTimeout(ce),!($(_)&&_>=I)){S(l,V),U||(U=!0,R(new TypeError(`sessionGeneration.store.${G} must resolve to an integer >= ${I}; got ${O(_)}`)));return}G==="advance"&&(P(V,_),A.delete(l)),d(l,{value:_,at:we},V.floor),S(l,V),!U&&(U=!0,m.delete(l),y({kind:"value",value:_}))},_=>{if(clearTimeout(ce),S(l,V),!U){if(U=!0,_ instanceof C){y({kind:"unavailable",error:_});return}R(_)}})}),T=(u,o,l)=>{let y=A.get(o);if(y!==void 0&&l-y.startedAt<i)return y.read;let R={read:c({operation:"current"},u,o),startedAt:l};A.set(o,R);let G=()=>{A.get(o)===R&&A.delete(o)};return R.read.then(G,G),R.read},E=async(u,o,l)=>{let y=await c({operation:"current"},u,o);return y.kind==="unavailable"?r(o,y.error):l===y.value?"current":"stale"};return{check:async(u,o)=>{if(!($(o)&&ne(u)))return"stale";let l=performance.now(),y=f(u),R=g(y,l);if(R!==void 0){if(o===R.value)return"current";if(o<R.value)return"stale"}if(s(y,l))return"unavailable";if(R!==void 0)return await E(u,y,o);let G=await T(u,y,l);return G.kind==="unavailable"?r(y,G.error):o===G.value?"current":o<G.value?"stale":await E(u,y,o)},stamp:async u=>{if(!ne(u))throw pe(u);let o=await c({operation:"current"},u,f(u));if(o.kind==="unavailable")throw o.error;return o.value},advance:async(u,o)=>{if(!ne(u))return{kind:"failed",error:pe(u)};if(!$e(o))return{kind:"failed",error:Fe(o)};try{let l=await c({operation:"advance",from:o},u,f(u));return l.kind==="value"?{kind:"advanced",generation:l.value}:{kind:"unavailable",error:l.error}}catch(l){return{kind:"failed",error:l}}}}};var M=class extends Error{constructor(t){super(t),this.name="TokenRefreshError"}},F=class extends M{constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},N=class extends Error{constructor(t){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=t}},qe=["access_token","expires_in"],B=(e,t,n)=>{let a=e.loginPath??"/auth/login",i=t.sessionKey,w=async m=>{let k=m.get(i)?.refreshToken;if(!k)throw new Error("Refresh token not found in session");try{let f="https://www.googleapis.com/oauth2/v4/token",g={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:k},p=await(e.fetch??globalThis.fetch)(f,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(g)});if(!p.ok){let c=await p.json().catch(()=>{});if(p.status===400&&typeof c=="object"&&!!c&&"error"in c&&c.error==="invalid_grant")throw new F;let E=typeof c=="object"&&c&&"error_description"in c?String(c.error_description):"Unknown error";throw new M(`Google token refresh failed: ${p.status} ${E}`)}let S=await p.json(),P=qe.filter(c=>!S?.[c]);if(P.length>0)throw n.error("Invalid token response from Google; missing or empty keys:",P.join(", ")),new Error("Invalid token response from Google");let{access_token:s,expires_in:r}=S;return{accessToken:s,refreshToken:k,expirationDateMs:Number(Date.now())+r*1e3}}catch(f){if(f instanceof M)throw f;let g=f instanceof Error?f.message:"Unknown error";throw new M(`Failed to refresh Google access token: ${g}`)}},v=async m=>{let k=m.get(i).provider;if(!k)throw new Error("Provider not found in session");if(k==="google")return await w(m);throw new Error("Provider not supported")};return{authenticate:async(m,h,k)=>{let{failureRedirect:f}=k||{},g=d=>{if(f===null)return new N(d);if(f==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let p=f??a;return d!==void 0?(0,ie.redirect)(p,{headers:{"Set-Cookie":d}}):(0,ie.redirect)(p)};try{if(e.mockUser?.enabled(m)){let{accessToken:r,refreshToken:c,expirationDateMs:T}=e.mockUser.resolve(m);return{accessToken:r,refreshToken:c,expirationDateMs:T}}let d=h.get(i),p=t.sessionGenerationGate;if(d!==void 0&&p!==null&&await p.check(L(d),h.get(x))==="stale")throw g(await t.destroySession(h));if(!(d?.accessToken&&d.expirationDateMs))throw g();let{accessToken:S,refreshToken:P,expirationDateMs:s}=d;if(s<Date.now())throw P?new Error("Expired"):g();return{accessToken:S,refreshToken:P,expirationDateMs:s}}catch(d){if(d instanceof Error&&d.message==="Expired")try{let p=await v(h),S=h.get(i);return h.set(i,{...S,...p}),p}catch(p){if(p instanceof F)n.warn("Google refresh token invalid or revoked");else{let P=p instanceof Error?p.message:"Unknown error";n.error("Failed to refresh token:",P)}let S=await t.destroySession(h);throw g(S)}throw d}},refreshedAccessToken:v}};var ae=require("react-router");var K=({refreshToken:e,...t})=>t;var X=(e,t,n,a)=>{let i=new Map,w=new Map,v=async f=>{let g=i.get(f);if(g!==void 0)return g;let d=w.get(f);if(d!==void 0)return d;let p=(async()=>{try{let S=e.getUserPhoto?await e.getUserPhoto(f):"";return i.set(f,S),S}catch(S){throw i.delete(f),S}finally{w.delete(f)}})();return w.set(f,p),p},A=new WeakMap,m=async f=>{e.warmup&&await e.warmup();let g=await t.resolveSession(f);if(g.kind==="revoked")return{kind:"unauthenticated",cookie:await t.destroySession(g.session)};if(g.kind!=="signed-in")return{kind:"unauthenticated"};let{user:d,session:p}=g,S;try{S=await n.authenticate(f,p,{failureRedirect:null})}catch(b){if(b instanceof N)return b.setCookie!==void 0?{kind:"unauthenticated",cookie:b.setCookie}:{kind:"unauthenticated"};throw a.error("Error in authenticateInLoader:",b),b}let P={accessToken:S.accessToken,refreshToken:S.refreshToken,expirationDateMs:S.expirationDateMs,provider:d.provider},s={id:d.id,displayName:d.displayName,name:d.name,emails:d.emails,...P,role:d.role},r=await v(d.id),c=K({...d,...P,photo:r}),E=S.accessToken!==d.accessToken?await t.saveSession(f,s):void 0;return E!==void 0?{kind:"authenticated",user:c,cookie:E}:{kind:"authenticated",user:c}},h=f=>{let g=A.get(f);if(g!==void 0)return g;let d=m(f);return A.set(f,d),d};async function k(f,g){let{failureRedirect:d}=g;if(d==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let p=await h(f);if(p.kind==="authenticated")return p.cookie!==void 0?{user:p.user,cookie:p.cookie}:{user:p.user};if(d===null)return p.cookie!==void 0?{cookie:p.cookie}:{};throw p.cookie!==void 0?(0,ae.redirect)(d,{headers:{"Set-Cookie":p.cookie}}):(0,ae.redirect)(d)}return k};var me=require("@aiquants/auth-core"),Y=require("react-router"),Se=require("remix-auth");var he=require("remix-auth-oauth2"),De=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],je="google",Ve="https://www.googleapis.com/oauth2/v3/userinfo",H=class extends he.OAuth2Strategy{constructor({clientId:n,clientSecret:a,redirectURI:i,scopes:w,accessType:v,includeGrantedScopes:A,prompt:m,hd:h,loginHint:k,additionalScopes:f},g){let d=w??De;super({clientId:n,clientSecret:a,redirectURI:i,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:d},g);this.name=je;this.scopes=d,this.accessType=v??"online",this.includeGrantedScopes=A??!1,this.prompt=m,this.hd=h,this.loginHint=k,this.additionalScopes=f}authorizationParams(n,a){n.set("access_type",this.accessType),n.set("include_granted_scopes",String(this.includeGrantedScopes));let i=a===void 0||this.additionalScopes===void 0?[]:this.additionalScopes(a);for(let v of i)if(v===""||/\s/u.test(v))throw new RangeError(`[auth-react-router] an additional scope must be a non-empty string without white space; got ${JSON.stringify(v)}`);let w=[...new Set([...this.scopes,...i])];return w.length>0&&n.set("scope",w.join(" ")),this.prompt&&n.set("prompt",this.prompt),this.hd&&n.set("hd",this.hd),this.loginHint&&n.set("login_hint",this.loginHint),n}static async userProfile(n){let a=await fetch(Ve,{headers:{Authorization:`Bearer ${n.accessToken()}`}});if(!a.ok)throw new Error(`Failed to fetch user profile: ${a.statusText}`);let i=await a.json();return{id:i.sub,displayName:i.name,name:{familyName:i.family_name,givenName:i.given_name},emails:[{value:i.email}],photos:[{value:i.picture}],_json:i}}};var q={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var J=e=>{let t=e.logger??q,n=(0,me.resolveAuthMessages)(e.messages),a=e.loginPath??"/auth/login",i=new H({clientId:e.google.clientId,clientSecret:e.google.clientSecret,redirectURI:e.google.redirectURI,scopes:e.google.scopes,accessType:e.google.accessType??"offline",includeGrantedScopes:e.google.includeGrantedScopes??!0,prompt:e.google.prompt??"consent",additionalScopes:e.google.additionalScopes},async({request:v,tokens:A})=>{let{access_token:m,refresh_token:h,expires_in:k,scope:f,id_token:g}=A.data,{_json:{sub:d,email:p,picture:S,hd:P,email_verified:s},photos:r,...c}=await H.userProfile(A),{id:T,displayName:E,name:{familyName:b,givenName:ee},emails:te}=c,u="google";if(m===void 0||h===void 0||k===void 0||f===void 0||T===void 0||E===void 0||d===void 0||p===void 0||s===void 0){if(s===!1){let l=encodeURIComponent(n.emailNotVerified);throw(0,Y.redirect)(`${a}?error=${l}`)}let o=encodeURIComponent(n.googleFailed);throw(0,Y.redirect)(`${a}?error=${o}`)}t.info("Authenticated on Google: ",c.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(u,m)){t.error("Backend verification returned false for user:",c.displayName);let I=encodeURIComponent(n.backendFailed);throw(0,Y.redirect)(`${a}?error=${I}`)}t.info("Authenticated on Backend: ",c.displayName)}let o=c.emails[0]?.value;if(!await e.isEmailAllowed(o)){let G=new Error("You are not allowed to access this application");throw t.error(G),G}if(e.isUserActive&&!await e.isUserActive(c)){let G=new Error("You are not allowed to access this application");throw t.error("Deactivated account attempted to sign in:",o),G}e.backendAuth&&await e.backendAuth.signup(u,m,c),t.info("Authenticated complete: ",c.displayName);let l=Date.now()+k*1e3;return{...c,...{accessToken:m,refreshToken:h,expirationDateMs:l,provider:u},photo:S}}catch(o){let l=o;typeof o=="object"&&o!==null&&"cause"in o&&(l=o.cause||o),t.error("Error during backend authentication or subsequent processing:",l);let y=n.unexpected,R=!1;if(typeof o=="object"&&o!==null&&"cause"in o){let I=o.cause;I&&typeof I=="object"&&"message"in I&&typeof I.message=="string"&&I.message.includes("getaddrinfo ENOTFOUND")&&(y=n.backendUnreachable,R=!0)}if(!R&&o instanceof Error&&o.message.includes("You are not allowed to access this application")&&(y=n.notAllowed,R=!0),!R&&o instanceof Response&&o.headers.get("Location")?.startsWith(a))throw o;let G=encodeURIComponent(y);throw(0,Y.redirect)(`${a}?error=${G}`)}}),w=new Se.Authenticator;return w.use(i),w};var D=require("react-router");var Ke=new Map([["document",new Set(["none","same-origin","same-site"])],["empty",new Set(["same-origin"])]]),W=e=>{let t=e.headers.get("Sec-Fetch-Dest");if(t!==null){let a=Ke.get(t);if(a===void 0)return`its fetch destination is "${t}"`;let i=e.headers.get("Sec-Fetch-Site");if(i===null)return`its "${t}" request states no site`;if(!a.has(i))return`its "${t}" request comes from a "${i}" page`}let n=e.headers.get("Sec-Purpose");if(n!==null)return`it is speculative ("${n}")`},z=e=>new Response(`Signing out is refused because ${e}: only a navigation that does not come from another site, or a script's request from this origin, signs out.`,{status:403,headers:{"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"}});var Q=(e,t,n,a)=>{let i=e.loginPath??"/auth/login",w=e.postLoginRedirect??"/",v=e.postLogoutRedirect??"/",A=de(e.google.revocationTimeoutMs),m=async({request:s})=>{if(await t.getSessionUser(s))throw(0,D.redirect)(w);return{error:new URL(s.url).searchParams.get("error")}},h=async({request:s})=>{if((await s.clone().formData()).get("_action")!=="Sign In with Google")return null;throw await n.authenticate("google",s),(0,D.redirect)(i)},k=(s,r)=>{switch(s.outcome){case"failed":a.error(`Sign-out could not revoke the Google grant of user ${String(r)}; the session cookie is destroyed, but the grant stays valid until it expires or is revoked elsewhere:`,s.reason);return;case"already-invalid":a.info(`Sign-out found the Google grant of user ${String(r)} already unusable`);return;case"revoked":case"nothing-to-revoke":return}},f=(s,r)=>{s.kind!=="advanced"&&a.error(`Sign-out could not advance the session generation of ${r.provider} user ${r.id}; a session cookie refreshed before this sign-out stays valid until a later sign-out advances the generation or the cookie expires:`,s.error)},g=async(s,r)=>{let c=t.sessionGenerationGate;if(c!==null){if(!$(r)){a.info(`Sign-out found no usable session generation stamp in the session of ${s.provider} user ${s.id}; every guard already rejects that cookie, so the generation is not advanced`);return}f(await c.advance(s,r),s)}},d=async s=>{let r=await t.getSession(s),c=r.get(t.sessionKey),[T]=await Promise.all([le(c,{fetch:e.fetch??globalThis.fetch,timeoutMs:A}),c===void 0?void 0:g(L(c),r.get(x))]);return k(T,c?.id),await t.destroySession(r)},p=async s=>{let r=await d(s),c=new Headers;return c.append("Set-Cookie",r),(0,D.redirect)(v,{headers:c})};return{loginLoader:m,loginAction:h,logoutLoader:async({request:s})=>{let r=W(s);throw r!==void 0?z(r):await p(s)},logout:d,logoutAndRedirect:p,googleCallbackLoader:async({request:s})=>{try{let r=await n.authenticate("google",s),E=(await t.getSession(s)).get(t.sessionKey)?.refreshToken,b={accessToken:r.accessToken,refreshToken:r.refreshToken||E,expirationDateMs:r.expirationDateMs,provider:r.provider},ee={id:r.id,displayName:r.displayName,name:r.name,emails:r.emails,...b,role:r.role},te=await t.saveSignedInSession(s,ee);throw(0,D.redirect)(w,{headers:{"Set-Cookie":te}})}catch(r){throw r instanceof Response?r:(a.error("Authentication error:",r),(0,D.redirect)(i))}}}};var j=require("react-router");var Z=(e,t)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(s=>!s))throw new Error("REMIX_SESSION_SECRET must be set");let n=e.sessionKey??"user";if(n===x)throw new RangeError(`session.sessionKey must not be ${JSON.stringify(x)}, the key the session generation is stored under; got ${JSON.stringify(n)}`);let a=e.maxAge??3600*24*30,i=t.loginPath??"/auth/login",w=t.postLoginRedirect??"/",v=t.mockUser,A=t.isUserActive,m=ge(t.sessionGeneration,t.logger??q),h=(0,j.createCookieSessionStorage)({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:e.secure??process.env.NODE_ENV==="production",maxAge:a}}),k=async s=>await h.getSession(s.headers.get("Cookie")),f=async s=>{if(v?.enabled(s))return{kind:"signed-in",user:K(v.resolve(s)),session:await k(s)};let r=await k(s),c=r.get(n);if(c===void 0)return{kind:"signed-out"};let T=K(c),[E,b]=await Promise.all([A===void 0?!0:A(T),m===null?"current":m.check(L(c),r.get(x))]);return b==="stale"?{kind:"revoked",session:r}:E?{kind:"signed-in",user:T,session:r}:{kind:"inactive"}},g=async s=>{let r=await f(s);return r.kind==="signed-in"?r.user:void 0},d=async(s,r)=>{let c=await k(s);return c.set(n,r),await h.commitSession(c)},p=async(s,r)=>{let c=m===null?void 0:await m.stamp(L(r)),T=await k(s);return T.set(n,r),c!==void 0&&T.set(x,c),await h.commitSession(T)},S=async s=>{let r=await f(s);switch(r.kind){case"signed-in":return r.user;case"revoked":throw(0,j.redirect)(i,{headers:{"Set-Cookie":await h.destroySession(r.session)}});case"signed-out":case"inactive":throw(0,j.redirect)(i)}};return{sessionStorage:h,sessionKey:n,sessionGenerationGate:m,getSession:k,resolveSession:f,getSessionUser:g,saveSession:d,saveSignedInSession:p,requireUser:S,requireAdminUser:async s=>{let r=await S(s);if(r.role!=="admin")throw(0,j.redirect)(w);return r},commitSession:h.commitSession,destroySession:h.destroySession}};var ye=e=>{let t=e.logger??q,n=Z(e.session,{sessionGeneration:e.sessionGeneration,logger:t,mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive}),a=J(e),i=B(e,n,t),w=X(e,n,i,t),v=Q(e,n,a,t);return{authenticator:a,storage:n,authFns:i,sessionStorage:n.sessionStorage,getSession:n.getSession,getSessionUser:n.getSessionUser,saveSession:n.saveSession,requireUser:n.requireUser,requireAdminUser:n.requireAdminUser,commitSession:n.commitSession,destroySession:n.destroySession,authenticate:i.authenticate,refreshedAccessToken:i.refreshedAccessToken,authenticateInLoader:w,...v}};0&&(module.exports={AuthRequiredError,DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS,DEFAULT_SESSION_GENERATION_CACHE_TTL_MS,DEFAULT_SESSION_GENERATION_TIMEOUT_MS,GoogleInvalidGrantError,SessionGenerationUnavailableError,TokenRefreshError,createAuthHandlers,createAuthServer,createAuthSessionStorage,createAuthenticate,createAuthenticateInLoader,createGoogleAuthenticator,signOutRefusal,signOutRefusalResponse});
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 w=setTimeout(()=>{u({outcome:"failed",reason:`Google did not answer within ${t.timeoutMs} ms`}),c.abort()},t.timeoutMs);ve(n,t.fetch,c.signal).then(v=>{clearTimeout(w),u(v)})})};var x="generation",ce=15e3,ue=3e3,Ge=6e4,q=class extends Error{constructor(t,n){super(t,n),this.name="SessionGenerationUnavailableError"}},O=e=>typeof e=="string"?JSON.stringify(e):typeof e=="function"?"a function":typeof e=="object"&&e!==null?Array.isArray(e)?"an array":"an object":typeof e=="bigint"?`${e}n`:String(e),Te=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return O(e);let t="store"in e?e.store:void 0;if(typeof t!="object"||t===null)return`an object whose store is ${O(t)}`;let n="current"in t?t.current:void 0,c="advance"in t?t.advance:void 0;return`an object whose store.current is ${O(n)} and store.advance is ${O(c)}`},Re=e=>typeof e=="object"&&e!==null&&"current"in e&&typeof e.current=="function"&&"advance"in e&&typeof e.advance=="function",ie=(e,t,n,c)=>{if(t===void 0)return c;if(typeof t!="number"||!Number.isInteger(t)||t<n||t>2147483647)throw new RangeError(`${e} must be an integer from ${n} to ${2147483647} (milliseconds); got ${O(t)}`);return t},Pe=e=>{if(e===!1)return!1;let t=e;if(typeof t!="object"||t===null||!("store"in t)||!Re(t.store))throw new TypeError(`sessionGeneration must be { store, cacheTtlMs?, timeoutMs? } or false; got ${Te(t)}`);return{store:t.store,cacheTtlMs:ie("sessionGeneration.cacheTtlMs","cacheTtlMs"in t?t.cacheTtlMs:void 0,0,ce),timeoutMs:ie("sessionGeneration.timeoutMs","timeoutMs"in t?t.timeoutMs:void 0,1,ue)}},N=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0,X=e=>typeof e.provider=="string"&&e.provider!==""&&typeof e.id=="string"&&e.id!=="",ae=e=>new TypeError(`a session generation identity needs a non-empty provider and id; got provider ${O(e.provider)} and id ${O(e.id)}`),Ee=e=>N(e)&&N(e+1),_e=e=>new TypeError(`a session generation advance needs the signed-out session's stamp, an integer from 0 to ${Number.MAX_SAFE_INTEGER-1}; got ${O(e)}`),U=e=>({provider:e.provider,id:e.id}),de=(e,t)=>{let n=Pe(e);if(n===!1)return null;let{store:c,cacheTtlMs:u,timeoutMs:w}=n,v=new Map,A=new Map,m=new Map,h=new Map,k=Number.NEGATIVE_INFINITY,f=a=>`${a.provider}\0${a.id}`,g=(a,o)=>{let l=v.get(a);if(l!==void 0){if(o-l.at<u)return l;v.delete(a)}},d=(a,o,l)=>{if(l!==void 0&&o.at<=l.answeredAt&&o.value<l.value)return;let y=g(a,performance.now());if(y===void 0){v.set(a,o);return}o.value<y.value||v.set(a,{value:o.value,at:Math.max(y.at,o.at)})},p=a=>{let o=h.get(a);if(o!==void 0)return o.count+=1,o;let l={count:1,floor:void 0};return h.set(a,l),l},S=(a,o)=>{o.count-=1,o.count===0&&h.delete(a)},P=(a,o)=>{a.floor={value:a.floor===void 0?o:Math.max(a.floor.value,o),answeredAt:performance.now()}},s=(a,o)=>{let l=m.get(a);return l===void 0?!1:o<l?!0:(m.delete(a),!1)},r=(a,o)=>{let l=performance.now();return m.set(a,l+u),l-k>=Ge&&(k=l,t.warn("Session generation store unavailable; skipping the sign-out generation check:",o)),"unavailable"},i=(a,o,l)=>new Promise((y,R)=>{let{operation:G}=a,I=a.operation==="advance"?a.from+1:0,pe=performance.now(),F=p(l),M=!1,ne=setTimeout(()=>{M=!0,y({kind:"unavailable",error:new q(`sessionGeneration.store.${G} did not settle within ${w} ms`)})},w);new Promise(_=>_(a.operation==="advance"?c.advance(o,a.from):c.current(o))).then(_=>{if(clearTimeout(ne),!(N(_)&&_>=I)){S(l,F),M||(M=!0,R(new TypeError(`sessionGeneration.store.${G} must resolve to an integer >= ${I}; got ${O(_)}`)));return}G==="advance"&&(P(F,_),A.delete(l)),d(l,{value:_,at:pe},F.floor),S(l,F),!M&&(M=!0,m.delete(l),y({kind:"value",value:_}))},_=>{if(clearTimeout(ne),S(l,F),!M){if(M=!0,_ instanceof q){y({kind:"unavailable",error:_});return}R(_)}})}),T=(a,o,l)=>{let y=A.get(o);if(y!==void 0&&l-y.startedAt<u)return y.read;let R={read:i({operation:"current"},a,o),startedAt:l};A.set(o,R);let G=()=>{A.get(o)===R&&A.delete(o)};return R.read.then(G,G),R.read},E=async(a,o,l)=>{let y=await i({operation:"current"},a,o);return y.kind==="unavailable"?r(o,y.error):l===y.value?"current":"stale"};return{check:async(a,o)=>{if(!(N(o)&&X(a)))return"stale";let l=performance.now(),y=f(a),R=g(y,l);if(R!==void 0){if(o===R.value)return"current";if(o<R.value)return"stale"}if(s(y,l))return"unavailable";if(R!==void 0)return await E(a,y,o);let G=await T(a,y,l);return G.kind==="unavailable"?r(y,G.error):o===G.value?"current":o<G.value?"stale":await E(a,y,o)},stamp:async a=>{if(!X(a))throw ae(a);let o=await i({operation:"current"},a,f(a));if(o.kind==="unavailable")throw o.error;return o.value},advance:async(a,o)=>{if(!X(a))return{kind:"failed",error:ae(a)};if(!Ee(o))return{kind:"failed",error:_e(o)};try{let l=await i({operation:"advance",from:o},a,f(a));return l.kind==="value"?{kind:"advanced",generation:l.value}:{kind:"unavailable",error:l.error}}catch(l){return{kind:"failed",error:l}}}}};var L=class extends Error{constructor(t){super(t),this.name="TokenRefreshError"}},D=class extends L{constructor(){super("Google refresh token invalid or revoked"),this.name="GoogleInvalidGrantError"}},C=class extends Error{constructor(t){super("Authentication required"),this.name="AuthRequiredError",this.setCookie=t}},be=["access_token","expires_in"],J=(e,t,n)=>{let c=e.loginPath??"/auth/login",u=t.sessionKey,w=async m=>{let k=m.get(u)?.refreshToken;if(!k)throw new Error("Refresh token not found in session");try{let f="https://www.googleapis.com/oauth2/v4/token",g={client_id:e.google.clientId,client_secret:e.google.clientSecret,grant_type:"refresh_token",refresh_token:k},p=await(e.fetch??globalThis.fetch)(f,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(g)});if(!p.ok){let i=await p.json().catch(()=>{});if(p.status===400&&typeof i=="object"&&!!i&&"error"in i&&i.error==="invalid_grant")throw new D;let E=typeof i=="object"&&i&&"error_description"in i?String(i.error_description):"Unknown error";throw new L(`Google token refresh failed: ${p.status} ${E}`)}let S=await p.json(),P=be.filter(i=>!S?.[i]);if(P.length>0)throw n.error("Invalid token response from Google; missing or empty keys:",P.join(", ")),new Error("Invalid token response from Google");let{access_token:s,expires_in:r}=S;return{accessToken:s,refreshToken:k,expirationDateMs:Number(Date.now())+r*1e3}}catch(f){if(f instanceof L)throw f;let g=f instanceof Error?f.message:"Unknown error";throw new L(`Failed to refresh Google access token: ${g}`)}},v=async m=>{let k=m.get(u).provider;if(!k)throw new Error("Provider not found in session");if(k==="google")return await w(m);throw new Error("Provider not supported")};return{authenticate:async(m,h,k)=>{let{failureRedirect:f}=k||{},g=d=>{if(f===null)return new C(d);if(f==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let p=f??c;return d!==void 0?le(p,{headers:{"Set-Cookie":d}}):le(p)};try{if(e.mockUser?.enabled(m)){let{accessToken:r,refreshToken:i,expirationDateMs:T}=e.mockUser.resolve(m);return{accessToken:r,refreshToken:i,expirationDateMs:T}}let d=h.get(u),p=t.sessionGenerationGate;if(d!==void 0&&p!==null&&await p.check(U(d),h.get(x))==="stale")throw g(await t.destroySession(h));if(!(d?.accessToken&&d.expirationDateMs))throw g();let{accessToken:S,refreshToken:P,expirationDateMs:s}=d;if(s<Date.now())throw P?new Error("Expired"):g();return{accessToken:S,refreshToken:P,expirationDateMs:s}}catch(d){if(d instanceof Error&&d.message==="Expired")try{let p=await v(h),S=h.get(u);return h.set(u,{...S,...p}),p}catch(p){if(p instanceof D)n.warn("Google refresh token invalid or revoked");else{let P=p instanceof Error?p.message:"Unknown error";n.error("Failed to refresh token:",P)}let S=await t.destroySession(h);throw g(S)}throw d}},refreshedAccessToken:v}};import{redirect as fe}from"react-router";var j=({refreshToken:e,...t})=>t;var W=(e,t,n,c)=>{let u=new Map,w=new Map,v=async f=>{let g=u.get(f);if(g!==void 0)return g;let d=w.get(f);if(d!==void 0)return d;let p=(async()=>{try{let S=e.getUserPhoto?await e.getUserPhoto(f):"";return u.set(f,S),S}catch(S){throw u.delete(f),S}finally{w.delete(f)}})();return w.set(f,p),p},A=new WeakMap,m=async f=>{e.warmup&&await e.warmup();let g=await t.resolveSession(f);if(g.kind==="revoked")return{kind:"unauthenticated",cookie:await t.destroySession(g.session)};if(g.kind!=="signed-in")return{kind:"unauthenticated"};let{user:d,session:p}=g,S;try{S=await n.authenticate(f,p,{failureRedirect:null})}catch(b){if(b instanceof C)return b.setCookie!==void 0?{kind:"unauthenticated",cookie:b.setCookie}:{kind:"unauthenticated"};throw c.error("Error in authenticateInLoader:",b),b}let P={accessToken:S.accessToken,refreshToken:S.refreshToken,expirationDateMs:S.expirationDateMs,provider:d.provider},s={id:d.id,displayName:d.displayName,name:d.name,emails:d.emails,...P,role:d.role},r=await v(d.id),i=j({...d,...P,photo:r}),E=S.accessToken!==d.accessToken?await t.saveSession(f,s):void 0;return E!==void 0?{kind:"authenticated",user:i,cookie:E}:{kind:"authenticated",user:i}},h=f=>{let g=A.get(f);if(g!==void 0)return g;let d=m(f);return A.set(f,d),d};async function k(f,g){let{failureRedirect:d}=g;if(d==="")throw new TypeError("failureRedirect must not be an empty string; pass null to skip redirecting");let p=await h(f);if(p.kind==="authenticated")return p.cookie!==void 0?{user:p.user,cookie:p.cookie}:{user:p.user};if(d===null)return p.cookie!==void 0?{cookie:p.cookie}:{};throw p.cookie!==void 0?fe(d,{headers:{"Set-Cookie":p.cookie}}):fe(d)}return k};import{resolveAuthMessages as Ue}from"@aiquants/auth-core";import{redirect as H}from"react-router";import{Authenticator as Le}from"remix-auth";import{OAuth2Strategy as Ie}from"remix-auth-oauth2";var Oe=["openid","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/userinfo.email"],xe="google",Me="https://www.googleapis.com/oauth2/v3/userinfo",V=class extends Ie{constructor({clientId:n,clientSecret:c,redirectURI:u,scopes:w,accessType:v,includeGrantedScopes:A,prompt:m,hd:h,loginHint:k,additionalScopes:f},g){let d=w??Oe;super({clientId:n,clientSecret:c,redirectURI:u,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",scopes:d},g);this.name=xe;this.scopes=d,this.accessType=v??"online",this.includeGrantedScopes=A??!1,this.prompt=m,this.hd=h,this.loginHint=k,this.additionalScopes=f}authorizationParams(n,c){n.set("access_type",this.accessType),n.set("include_granted_scopes",String(this.includeGrantedScopes));let u=c===void 0||this.additionalScopes===void 0?[]:this.additionalScopes(c);for(let v of u)if(v===""||/\s/u.test(v))throw new RangeError(`[auth-react-router] an additional scope must be a non-empty string without white space; got ${JSON.stringify(v)}`);let w=[...new Set([...this.scopes,...u])];return w.length>0&&n.set("scope",w.join(" ")),this.prompt&&n.set("prompt",this.prompt),this.hd&&n.set("hd",this.hd),this.loginHint&&n.set("login_hint",this.loginHint),n}static async userProfile(n){let c=await fetch(Me,{headers:{Authorization:`Bearer ${n.accessToken()}`}});if(!c.ok)throw new Error(`Failed to fetch user profile: ${c.statusText}`);let u=await c.json();return{id:u.sub,displayName:u.name,name:{familyName:u.family_name,givenName:u.given_name},emails:[{value:u.email}],photos:[{value:u.picture}],_json:u}}};var $={info:(...e)=>console.info("[Auth]",...e),warn:(...e)=>console.warn("[Auth]",...e),error:(...e)=>console.error("[Auth]",...e)};var z=e=>{let t=e.logger??$,n=Ue(e.messages),c=e.loginPath??"/auth/login",u=new V({clientId:e.google.clientId,clientSecret:e.google.clientSecret,redirectURI:e.google.redirectURI,scopes:e.google.scopes,accessType:e.google.accessType??"offline",includeGrantedScopes:e.google.includeGrantedScopes??!0,prompt:e.google.prompt??"consent",additionalScopes:e.google.additionalScopes},async({request:v,tokens:A})=>{let{access_token:m,refresh_token:h,expires_in:k,scope:f,id_token:g}=A.data,{_json:{sub:d,email:p,picture:S,hd:P,email_verified:s},photos:r,...i}=await V.userProfile(A),{id:T,displayName:E,name:{familyName:b,givenName:Y},emails:B}=i,a="google";if(m===void 0||h===void 0||k===void 0||f===void 0||T===void 0||E===void 0||d===void 0||p===void 0||s===void 0){if(s===!1){let l=encodeURIComponent(n.emailNotVerified);throw H(`${c}?error=${l}`)}let o=encodeURIComponent(n.googleFailed);throw H(`${c}?error=${o}`)}t.info("Authenticated on Google: ",i.displayName);try{if(e.backendAuth){if(!await e.backendAuth.verify(a,m)){t.error("Backend verification returned false for user:",i.displayName);let I=encodeURIComponent(n.backendFailed);throw H(`${c}?error=${I}`)}t.info("Authenticated on Backend: ",i.displayName)}let o=i.emails[0]?.value;if(!await e.isEmailAllowed(o)){let G=new Error("You are not allowed to access this application");throw t.error(G),G}if(e.isUserActive&&!await e.isUserActive(i)){let G=new Error("You are not allowed to access this application");throw t.error("Deactivated account attempted to sign in:",o),G}e.backendAuth&&await e.backendAuth.signup(a,m,i),t.info("Authenticated complete: ",i.displayName);let l=Date.now()+k*1e3;return{...i,...{accessToken:m,refreshToken:h,expirationDateMs:l,provider:a},photo:S}}catch(o){let l=o;typeof o=="object"&&o!==null&&"cause"in o&&(l=o.cause||o),t.error("Error during backend authentication or subsequent processing:",l);let y=n.unexpected,R=!1;if(typeof o=="object"&&o!==null&&"cause"in o){let I=o.cause;I&&typeof I=="object"&&"message"in I&&typeof I.message=="string"&&I.message.includes("getaddrinfo ENOTFOUND")&&(y=n.backendUnreachable,R=!0)}if(!R&&o instanceof Error&&o.message.includes("You are not allowed to access this application")&&(y=n.notAllowed,R=!0),!R&&o instanceof Response&&o.headers.get("Location")?.startsWith(c))throw o;let G=encodeURIComponent(y);throw H(`${c}?error=${G}`)}}),w=new Le;return w.use(u),w};import{redirect as K}from"react-router";var Ne=new Map([["document",new Set(["none","same-origin","same-site"])],["empty",new Set(["same-origin"])]]),Q=e=>{let t=e.headers.get("Sec-Fetch-Dest");if(t!==null){let c=Ne.get(t);if(c===void 0)return`its fetch destination is "${t}"`;let u=e.headers.get("Sec-Fetch-Site");if(u===null)return`its "${t}" request states no site`;if(!c.has(u))return`its "${t}" request comes from a "${u}" page`}let n=e.headers.get("Sec-Purpose");if(n!==null)return`it is speculative ("${n}")`},Z=e=>new Response(`Signing out is refused because ${e}: only a navigation that does not come from another site, or a script's request from this origin, signs out.`,{status:403,headers:{"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"}});var ee=(e,t,n,c)=>{let u=e.loginPath??"/auth/login",w=e.postLoginRedirect??"/",v=e.postLogoutRedirect??"/",A=re(e.google.revocationTimeoutMs),m=async({request:s})=>{if(await t.getSessionUser(s))throw K(w);return{error:new URL(s.url).searchParams.get("error")}},h=async({request:s})=>{if((await s.clone().formData()).get("_action")!=="Sign In with Google")return null;throw await n.authenticate("google",s),K(u)},k=(s,r)=>{switch(s.outcome){case"failed":c.error(`Sign-out could not revoke the Google grant of user ${String(r)}; the session cookie is destroyed, but the grant stays valid until it expires or is revoked elsewhere:`,s.reason);return;case"already-invalid":c.info(`Sign-out found the Google grant of user ${String(r)} already unusable`);return;case"revoked":case"nothing-to-revoke":return}},f=(s,r)=>{s.kind!=="advanced"&&c.error(`Sign-out could not advance the session generation of ${r.provider} user ${r.id}; a session cookie refreshed before this sign-out stays valid until a later sign-out advances the generation or the cookie expires:`,s.error)},g=async(s,r)=>{let i=t.sessionGenerationGate;if(i!==null){if(!N(r)){c.info(`Sign-out found no usable session generation stamp in the session of ${s.provider} user ${s.id}; every guard already rejects that cookie, so the generation is not advanced`);return}f(await i.advance(s,r),s)}},d=async s=>{let r=await t.getSession(s),i=r.get(t.sessionKey),[T]=await Promise.all([se(i,{fetch:e.fetch??globalThis.fetch,timeoutMs:A}),i===void 0?void 0:g(U(i),r.get(x))]);return k(T,i?.id),await t.destroySession(r)},p=async s=>{let r=await d(s),i=new Headers;return i.append("Set-Cookie",r),K(v,{headers:i})};return{loginLoader:m,loginAction:h,logoutLoader:async({request:s})=>{let r=Q(s);throw r!==void 0?Z(r):await p(s)},logout:d,logoutAndRedirect:p,googleCallbackLoader:async({request:s})=>{try{let r=await n.authenticate("google",s),E=(await t.getSession(s)).get(t.sessionKey)?.refreshToken,b={accessToken:r.accessToken,refreshToken:r.refreshToken||E,expirationDateMs:r.expirationDateMs,provider:r.provider},Y={id:r.id,displayName:r.displayName,name:r.name,emails:r.emails,...b,role:r.role},B=await t.saveSignedInSession(s,Y);throw K(w,{headers:{"Set-Cookie":B}})}catch(r){throw r instanceof Response?r:(c.error("Authentication error:",r),K(u))}}}};import{createCookieSessionStorage as Ce,redirect as te}from"react-router";var oe=(e,t)=>{if(!e.secrets||e.secrets.length===0||e.secrets.some(s=>!s))throw new Error("REMIX_SESSION_SECRET must be set");let n=e.sessionKey??"user";if(n===x)throw new RangeError(`session.sessionKey must not be ${JSON.stringify(x)}, the key the session generation is stored under; got ${JSON.stringify(n)}`);let c=e.maxAge??3600*24*30,u=t.loginPath??"/auth/login",w=t.postLoginRedirect??"/",v=t.mockUser,A=t.isUserActive,m=de(t.sessionGeneration,t.logger??$),h=Ce({cookie:{name:e.cookieName??"__session",httpOnly:!0,path:"/",sameSite:"lax",secrets:e.secrets,secure:e.secure??process.env.NODE_ENV==="production",maxAge:c}}),k=async s=>await h.getSession(s.headers.get("Cookie")),f=async s=>{if(v?.enabled(s))return{kind:"signed-in",user:j(v.resolve(s)),session:await k(s)};let r=await k(s),i=r.get(n);if(i===void 0)return{kind:"signed-out"};let T=j(i),[E,b]=await Promise.all([A===void 0?!0:A(T),m===null?"current":m.check(U(i),r.get(x))]);return b==="stale"?{kind:"revoked",session:r}:E?{kind:"signed-in",user:T,session:r}:{kind:"inactive"}},g=async s=>{let r=await f(s);return r.kind==="signed-in"?r.user:void 0},d=async(s,r)=>{let i=await k(s);return i.set(n,r),await h.commitSession(i)},p=async(s,r)=>{let i=m===null?void 0:await m.stamp(U(r)),T=await k(s);return T.set(n,r),i!==void 0&&T.set(x,i),await h.commitSession(T)},S=async s=>{let r=await f(s);switch(r.kind){case"signed-in":return r.user;case"revoked":throw te(u,{headers:{"Set-Cookie":await h.destroySession(r.session)}});case"signed-out":case"inactive":throw te(u)}};return{sessionStorage:h,sessionKey:n,sessionGenerationGate:m,getSession:k,resolveSession:f,getSessionUser:g,saveSession:d,saveSignedInSession:p,requireUser:S,requireAdminUser:async s=>{let r=await S(s);if(r.role!=="admin")throw te(w);return r},commitSession:h.commitSession,destroySession:h.destroySession}};var $e=e=>{let t=e.logger??$,n=oe(e.session,{sessionGeneration:e.sessionGeneration,logger:t,mockUser:e.mockUser,loginPath:e.loginPath,postLoginRedirect:e.postLoginRedirect,isUserActive:e.isUserActive}),c=z(e),u=J(e,n,t),w=W(e,n,u,t),v=ee(e,n,c,t);return{authenticator:c,storage:n,authFns:u,sessionStorage:n.sessionStorage,getSession:n.getSession,getSessionUser:n.getSessionUser,saveSession:n.saveSession,requireUser:n.requireUser,requireAdminUser:n.requireAdminUser,commitSession:n.commitSession,destroySession:n.destroySession,authenticate:u.authenticate,refreshedAccessToken:u.refreshedAccessToken,authenticateInLoader:w,...v}};export{C as AuthRequiredError,he as DEFAULT_GOOGLE_REVOCATION_TIMEOUT_MS,ce as DEFAULT_SESSION_GENERATION_CACHE_TTL_MS,ue as DEFAULT_SESSION_GENERATION_TIMEOUT_MS,D as GoogleInvalidGrantError,q as SessionGenerationUnavailableError,L as TokenRefreshError,ee as createAuthHandlers,$e as createAuthServer,oe as createAuthSessionStorage,J as createAuthenticate,W as createAuthenticateInLoader,z as createGoogleAuthenticator,Q as signOutRefusal,Z as signOutRefusalResponse};
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.25.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"
@@ -50,9 +50,9 @@
50
50
  },
51
51
  "devDependencies": {
52
52
  "@aiquants/auth-core": "0.6.1",
53
- "@aiquants/fuzzy-search": "3.0.0",
54
- "@aiquants/select-box": "0.16.0",
55
- "@aiquants/virtualscroll": "3.11.1",
53
+ "@aiquants/fuzzy-search": "3.2.0",
54
+ "@aiquants/select-box": "0.16.3",
55
+ "@aiquants/virtualscroll": "3.17.0",
56
56
  "@tailwindcss/cli": "^4.1.18",
57
57
  "@testing-library/react": "^16.3.2",
58
58
  "@types/node": "^25.9.1",
@@ -72,9 +72,9 @@
72
72
  },
73
73
  "peerDependencies": {
74
74
  "@aiquants/auth-core": "^0.6.1",
75
- "@aiquants/fuzzy-search": "^3.0.0",
76
- "@aiquants/select-box": "^0.16.0",
77
- "@aiquants/virtualscroll": "^3.11.1",
75
+ "@aiquants/fuzzy-search": "^3.2.0",
76
+ "@aiquants/select-box": "^0.16.3",
77
+ "@aiquants/virtualscroll": "^3.17.0",
78
78
  "react": ">=18",
79
79
  "react-dom": ">=18",
80
80
  "react-icons": ">=5",