@aiquants/auth-react-router 0.24.0 → 0.26.0

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