@eminuckan/spine 0.3.9 → 0.3.11

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/CHANGELOG.md CHANGED
@@ -6,6 +6,33 @@ All notable changes to this project will be documented in this file.
6
6
 
7
7
  No unreleased changes.
8
8
 
9
+ ## [0.3.11] - 2026-08-11
10
+
11
+ ### Added
12
+
13
+ - Exposed the server-only `isOAuthRecoveryEligibleCallback` predicate so
14
+ adapters can distinguish an ordinary stale callback eligible for one fresh
15
+ root login from terminal callback failures.
16
+ - Kept exact recovery-ticket consumption as the only source of a preserved
17
+ return URL; the fresh-root fallback never exchanges the stale callback code.
18
+
19
+ ## [0.3.10] - 2026-08-09
20
+
21
+ ### Added
22
+
23
+ - Added a server-only, opaque OAuth recovery ticket contract for one atomic
24
+ retry of a stale ordinary authorization callback while preserving the
25
+ originally sanitized return URL.
26
+
27
+ ### Security
28
+
29
+ - Bound recovery consumption to the exact callback state in Redis, preserving
30
+ mismatch and race safety without trusting a client boolean, callback code,
31
+ or return URL.
32
+ - Excluded provider errors, malformed callbacks, state mismatches, storage and
33
+ configuration failures, token exchange failures, and application actions
34
+ from recovery; terminal and successful callbacks clear recovery tickets.
35
+
9
36
  ## [0.3.9] - 2026-08-09
10
37
 
11
38
  ### Added
package/README.md CHANGED
@@ -250,13 +250,27 @@ export async function loader({ request }: { request: Request }) {
250
250
 
251
251
  If the callback has a non-empty `code` and `state` but the local OAuth
252
252
  transaction is missing or expired, catch `OAuthCallbackError` and check
253
- `isRecoverableOAuthCallbackError` from a server entry point. The consuming
254
- adapter owns a signed, one-shot retry marker and may start one fresh `login`
255
- flow; do not retry state mismatches, malformed callbacks, provider errors,
256
- token-exchange failures, storage/configuration failures, or application
257
- actions. Merge `error.cleanupHeaders` with any retry response using repeated
258
- `Set-Cookie` appends (or use the lossless `cleanupSetCookies` values) so
259
- session and OAuth-state cleanup cookies are preserved.
253
+ `isRecoverableOAuthCallbackError` from a server entry point. A consuming
254
+ adapter may then call `consumeOAuthRecoveryIntent(request, error)`. Spine
255
+ atomically consumes a separate opaque, HttpOnly recovery ticket and returns
256
+ the originally sanitized `returnUrl` at most once; a null `intent` means the
257
+ ticket was omitted, mismatched, expired, replayed, or unavailable. Start one
258
+ fresh `login(request, intent.returnUrl)` only after a non-null intent. If the
259
+ intent is null, a server adapter may start one fresh root `login(request)` only
260
+ when both `isRecoverableOAuthCallbackError(error)` and
261
+ `isOAuthRecoveryEligibleCallback(request)` are true; this fallback carries no
262
+ return URL and never exchanges the stale callback code. Otherwise render a
263
+ terminal error. Never use a client boolean or callback return URL as the retry
264
+ budget/destination, and never retry state mismatches, malformed callbacks,
265
+ provider errors, token-exchange failures, storage/configuration failures, or
266
+ application actions. Append both
267
+ `error.cleanupHeaders` and `recovery.cleanupHeaders` with repeated
268
+ `Set-Cookie` appends (or use `error.cleanupSetCookies` and
269
+ `recovery.cleanupSetCookies`) before the fresh
270
+ login response so cleanup cookies precede replacement OAuth cookies.
271
+ The recovery cookie path follows the configured OIDC redirect URI; adapters
272
+ with a custom callback route should pass the actual request to any standalone
273
+ clear-header helper.
260
274
 
261
275
  ```ts
262
276
  // app/routes/auth.logout.tsx
@@ -1 +1 @@
1
- {"version":3,"file":"auth.server.d.ts","sourceRoot":"","sources":["../../src/auth/auth.server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAKH,OAAO,EAKL,cAAc,EASf,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,EAEV,gBAAgB,EAChB,QAAQ,EAGR,kBAAkB,EAClB,YAAY,EAKZ,SAAS,EACV,MAAM,SAAS,CAAC;AA6OjB,wBAAgB,8BAA8B,CAAC,UAAU,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,GAAG,CAM3F;AAyUD;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,gBAAgB,GAAG,IAAI,CAgBzE;AAED;;GAEG;AACH,wBAAgB,qBAAqB,IAAI,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cAAc,EAAE,CAAC;AAE1B;;GAEG;AACH,wBAAgB,oBAAoB,IAAI,IAAI,CAG3C"}
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Server-only recovery intent for stale OAuth callbacks.
3
+ *
4
+ * A recovery intent is an opaque, HttpOnly cookie backed by a separate Redis
5
+ * record. Consumers must atomically consume it with the typed stale callback
6
+ * error; the client never supplies a boolean budget or a return URL.
7
+ */
8
+ import { OAUTH_RECOVERY_TTL_SECONDS } from './oauth-state-config';
9
+ import type { OAuthState } from './types';
10
+ export declare const OAUTH_RECOVERY_COOKIE_NAME: string;
11
+ export { OAUTH_RECOVERY_TTL_SECONDS };
12
+ export interface OAuthRecoveryIntent {
13
+ /** The sanitized destination originally supplied to login(). */
14
+ readonly returnUrl: string;
15
+ }
16
+ export interface OAuthRecoveryConsumeResult {
17
+ /** A server-record-backed destination, or null when recovery is unavailable. */
18
+ readonly intent: OAuthRecoveryIntent | null;
19
+ /** Always clear the one-shot ticket cookie in the adapter response. */
20
+ readonly cleanupHeaders: Headers;
21
+ /** Lossless repeated Set-Cookie values for runtimes without getSetCookie(). */
22
+ readonly cleanupSetCookies: readonly string[];
23
+ }
24
+ export interface OAuthRecoveryLoginResult {
25
+ readonly ticket: string;
26
+ readonly cookie: string;
27
+ }
28
+ /**
29
+ * Resolve the callback cookie path from a configured redirect URI or the
30
+ * actual callback request. Unsafe path values fall back to `/` rather than
31
+ * being interpolated into a Set-Cookie header.
32
+ */
33
+ export declare function getOAuthRecoveryCookiePath(source: Request | URL | string): string;
34
+ /**
35
+ * Build a lossless ticket-clear header using a callback request, URL, or
36
+ * configured redirect URI as the cookie-path source.
37
+ */
38
+ export declare function clearOAuthRecoveryIntentHeaders(source: Request | URL | string): Headers;
39
+ /**
40
+ * This check is intentionally stricter than the callback error code. It
41
+ * prevents recovery for provider errors, malformed callbacks, and account
42
+ * actions even if an adapter accidentally calls the consume helper there.
43
+ */
44
+ export declare function isOAuthRecoveryEligibleCallback(request: Request): boolean;
45
+ /**
46
+ * Create the opaque ticket cookie for an ordinary login transaction.
47
+ * Application-action transactions deliberately do not receive a recovery
48
+ * ticket and therefore cannot enter the automatic recovery path.
49
+ */
50
+ export declare function createOAuthRecoveryForLogin(request: Request, state: Pick<OAuthState, 'state' | 'returnUrl'>, redirectUri: string): Promise<OAuthRecoveryLoginResult>;
51
+ /**
52
+ * Delete an unconsumed ticket during terminal/successful callback cleanup.
53
+ * The caller owns error classification and should still clear the browser
54
+ * cookie if deletion fails.
55
+ */
56
+ export declare function discardOAuthRecoveryForRequest(request: Request): Promise<Headers>;
57
+ /**
58
+ * Atomically consume a stale-flow recovery intent.
59
+ *
60
+ * The typed error and the callback shape are both checked server-side. Redis
61
+ * compares the callback state and deletes only on an exact match, so a
62
+ * mismatch cannot burn a valid ticket while a replay or concurrent loser
63
+ * cannot retry.
64
+ */
65
+ export declare function consumeOAuthRecoveryIntent(request: Request, callbackError: unknown): Promise<OAuthRecoveryConsumeResult>;
66
+ //# sourceMappingURL=oauth-recovery.server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauth-recovery.server.d.ts","sourceRoot":"","sources":["../../src/auth/oauth-recovery.server.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAYH,OAAO,EAEL,0BAA0B,EAC3B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAG1C,eAAO,MAAM,0BAA0B,QAA+C,CAAC;AACvF,OAAO,EAAE,0BAA0B,EAAE,CAAC;AAEtC,MAAM,WAAW,mBAAmB;IAClC,gEAAgE;IAChE,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,0BAA0B;IACzC,gFAAgF;IAChF,QAAQ,CAAC,MAAM,EAAE,mBAAmB,GAAG,IAAI,CAAC;IAC5C,uEAAuE;IACvE,QAAQ,CAAC,cAAc,EAAE,OAAO,CAAC;IACjC,+EAA+E;IAC/E,QAAQ,CAAC,iBAAiB,EAAE,SAAS,MAAM,EAAE,CAAC;CAC/C;AAED,MAAM,WAAW,wBAAwB;IACvC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AA6DD;;;;GAIG;AACH,wBAAgB,0BAA0B,CACxC,MAAM,EAAE,OAAO,GAAG,GAAG,GAAG,MAAM,GAC7B,MAAM,CAcR;AA0CD;;;GAGG;AACH,wBAAgB,+BAA+B,CAC7C,MAAM,EAAE,OAAO,GAAG,GAAG,GAAG,MAAM,GAC7B,OAAO,CAIT;AAMD;;;;GAIG;AACH,wBAAgB,+BAA+B,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAOzE;AAwBD;;;;GAIG;AACH,wBAAsB,2BAA2B,CAC/C,OAAO,EAAE,OAAO,EAChB,KAAK,EAAE,IAAI,CAAC,UAAU,EAAE,OAAO,GAAG,WAAW,CAAC,EAC9C,WAAW,EAAE,MAAM,GAClB,OAAO,CAAC,wBAAwB,CAAC,CAiBnC;AAED;;;;GAIG;AACH,wBAAsB,8BAA8B,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAYvF;AAED;;;;;;;GAOG;AACH,wBAAsB,0BAA0B,CAC9C,OAAO,EAAE,OAAO,EAChB,aAAa,EAAE,OAAO,GACrB,OAAO,CAAC,0BAA0B,CAAC,CA8CrC"}
@@ -4,4 +4,11 @@
4
4
  */
5
5
  export declare const OAUTH_STATE_TTL_SECONDS: number;
6
6
  export declare const OAUTH_STATE_TTL_MS: number;
7
+ /**
8
+ * Lifetime for the server-side recovery ticket. It deliberately outlives
9
+ * the primary OAuth transaction so an IdP callback that arrives after state
10
+ * expiry can still recover once, while remaining short-lived.
11
+ */
12
+ export declare const OAUTH_RECOVERY_TTL_SECONDS: number;
13
+ export declare const OAUTH_RECOVERY_TTL_MS: number;
7
14
  //# sourceMappingURL=oauth-state-config.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"oauth-state-config.d.ts","sourceRoot":"","sources":["../../src/auth/oauth-state-config.ts"],"names":[],"mappings":"AAgBA;;;GAGG;AACH,eAAO,MAAM,uBAAuB,QAGnC,CAAC;AAEF,eAAO,MAAM,kBAAkB,QAAiC,CAAC"}
1
+ {"version":3,"file":"oauth-state-config.d.ts","sourceRoot":"","sources":["../../src/auth/oauth-state-config.ts"],"names":[],"mappings":"AAiBA;;;GAGG;AACH,eAAO,MAAM,uBAAuB,QAGnC,CAAC;AAEF,eAAO,MAAM,kBAAkB,QAAiC,CAAC;AAEjE;;;;GAIG;AACH,eAAO,MAAM,0BAA0B,QAGtC,CAAC;AAEF,eAAO,MAAM,qBAAqB,QAAoC,CAAC"}
@@ -35,6 +35,24 @@ export declare function getOAuthState(stateId: string, options?: {
35
35
  readonly throwOnMalformed?: boolean;
36
36
  }): Promise<OAuthState | null>;
37
37
  export declare function deleteOAuthState(stateId: string): Promise<void>;
38
+ export interface OAuthRecoveryRecord {
39
+ state: string;
40
+ returnUrl: string;
41
+ createdAt: number;
42
+ }
43
+ /**
44
+ * Store a short-lived recovery record under a separate opaque ticket.
45
+ * The ticket is returned to the caller and is never logged or embedded with
46
+ * callback state, return URLs, or provider data.
47
+ */
48
+ export declare function createOAuthRecoveryRecord(record: OAuthRecoveryRecord): Promise<string>;
49
+ /**
50
+ * Atomically consume a recovery record. The Redis script compares the exact
51
+ * expected state before DEL, so mismatched callbacks leave the ticket intact
52
+ * and concurrent exact-state requests can receive a record at most once.
53
+ */
54
+ export declare function consumeOAuthRecoveryRecord(ticket: string, expectedState: string): Promise<OAuthRecoveryRecord | null>;
55
+ export declare function deleteOAuthRecoveryRecord(ticket: string): Promise<void>;
38
56
  export declare function cleanupExpiredOAuthStates(): Promise<number>;
39
57
  export declare function closeRedisConnection(): Promise<void>;
40
58
  //# sourceMappingURL=redis-session-storage.server.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"redis-session-storage.server.d.ts","sourceRoot":"","sources":["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GAAG,IAAI,CAAC,CAgCrC;AAED,wBAAsB,yBAAyB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAG7E;AAED,wBAAsB,yBAAyB,IAAI,OAAO,CAAC,MAAM,CAAC,CAejE;AAMD,wBAAsB,oBAAoB,IAAI,OAAO,CAAC,IAAI,CAAC,CAM1D"}
@@ -7,6 +7,8 @@
7
7
  export * from './auth.server';
8
8
  export * from './callback-errors';
9
9
  export * from './redis-session-storage.server';
10
+ export { clearOAuthRecoveryIntentHeaders, consumeOAuthRecoveryIntent, getOAuthRecoveryCookiePath, isOAuthRecoveryEligibleCallback, OAUTH_RECOVERY_COOKIE_NAME, OAUTH_RECOVERY_TTL_SECONDS, } from './oauth-recovery.server';
11
+ export type { OAuthRecoveryConsumeResult, OAuthRecoveryIntent, } from './oauth-recovery.server';
10
12
  export * from './route-protection.server';
11
13
  export * from './token-refresh.server';
12
14
  export type { ApplicationType, AuthSessionSummary, AuthClaimMapping, AuthConfig, AuthError, BackChannelLogoutResult, FrontChannelLogoutResult, LoginOptions, OAuthState, OidcClientAuthMethod, ProtectedLoaderFn, ProtectionLevel, PublicAuthorizationStateContext, SessionData, SessionFlashData, UserInfo, } from './types';
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/auth/server.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,cAAc,eAAe,CAAC;AAC9B,cAAc,mBAAmB,CAAC;AAClC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,wBAAwB,CAAC;AACvC,YAAY,EACV,eAAe,EACf,kBAAkB,EAClB,gBAAgB,EAChB,UAAU,EACV,SAAS,EACT,uBAAuB,EACvB,wBAAwB,EACxB,YAAY,EACZ,UAAU,EACV,oBAAoB,EACpB,iBAAiB,EACjB,eAAe,EACf,+BAA+B,EAC/B,WAAW,EACX,gBAAgB,EAChB,QAAQ,GACT,MAAM,SAAS,CAAC;AACjB,YAAY,EACV,kBAAkB,IAAI,sBAAsB,GAC7C,MAAM,SAAS,CAAC"}
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/auth/server.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,cAAc,eAAe,CAAC;AAC9B,cAAc,mBAAmB,CAAC;AAClC,cAAc,gCAAgC,CAAC;AAC/C,OAAO,EACL,+BAA+B,EAC/B,0BAA0B,EAC1B,0BAA0B,EAC1B,+BAA+B,EAC/B,0BAA0B,EAC1B,0BAA0B,GAC3B,MAAM,yBAAyB,CAAC;AACjC,YAAY,EACV,0BAA0B,EAC1B,mBAAmB,GACpB,MAAM,yBAAyB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,wBAAwB,CAAC;AACvC,YAAY,EACV,eAAe,EACf,kBAAkB,EAClB,gBAAgB,EAChB,UAAU,EACV,SAAS,EACT,uBAAuB,EACvB,wBAAwB,EACxB,YAAY,EACZ,UAAU,EACV,oBAAoB,EACpB,iBAAiB,EACjB,eAAe,EACf,+BAA+B,EAC/B,WAAW,EACX,gBAAgB,EAChB,QAAQ,GACT,MAAM,SAAS,CAAC;AACjB,YAAY,EACV,kBAAkB,IAAI,sBAAsB,GAC7C,MAAM,SAAS,CAAC"}
@@ -1,3 +1,3 @@
1
- import { S as updateAuthSession, _ as isSessionValid, a as createOAuthState, b as listCurrentUserAuthSessions, c as destroyAuthSessionById, d as destroyAuthSessionsBySid, f as destroyAuthSessionsForUser, g as getOAuthState, h as getCurrentAuthSessionId, i as createAuthSession, l as destroyAuthSessionsByIdentitySession, m as getAuthSessionById, n as cleanupExpiredOAuthStates, o as deleteOAuthState, p as getAuthSession, r as closeRedisConnection, s as destroyAuthSession, t as AUTH_ERROR_COOKIE_PREFIX, u as destroyAuthSessionsBySessionState, v as listAuthSessionDataForUser, x as requireAuthSession, y as listAuthSessionsForUser } from "../redis-session-storage.server-CI_IYIn8.mjs";
2
- import { A as resetAuthClaimMapping, C as handleCallback, D as logout, E as login, M as OAuthCallbackFailureCodes, N as isOAuthCallbackError, O as refreshTokens, P as isRecoverableOAuthCallbackError, S as handleBackChannelLogout, T as hasAuthError, _ as createAuthorizationResponseUrl, a as configureRouteProtection, b as getAuthError, c as protectRoute, d as resetRouteProtectionConfig, f as shouldRefreshToken, g as configureAuthClaimMapping, h as clearAuthServerCache, i as authRoute, j as OAuthCallbackError, k as requireAuth, l as protectedRoute, m as clearAuthErrorHeaders, n as isTokenExpiredResponse, o as onboardingRoute, p as subscriptionRoute, r as shouldAttemptTokenRefresh, s as policyRoute, t as attemptTokenRefresh, u as publicRoute, v as extractUserInfo, w as handleFrontChannelLogout, x as getUser, y as getAccessToken } from "../server-Cw86FdT-.mjs";
3
- export { AUTH_ERROR_COOKIE_PREFIX, OAuthCallbackError, OAuthCallbackFailureCodes, attemptTokenRefresh, authRoute, cleanupExpiredOAuthStates, clearAuthErrorHeaders, clearAuthServerCache, closeRedisConnection, configureAuthClaimMapping, configureRouteProtection, createAuthSession, createAuthorizationResponseUrl, createOAuthState, deleteOAuthState, destroyAuthSession, destroyAuthSessionById, destroyAuthSessionsByIdentitySession, destroyAuthSessionsBySessionState, destroyAuthSessionsBySid, destroyAuthSessionsForUser, extractUserInfo, getAccessToken, getAuthError, getAuthSession, getAuthSessionById, getCurrentAuthSessionId, getOAuthState, getUser, handleBackChannelLogout, handleCallback, handleFrontChannelLogout, hasAuthError, isOAuthCallbackError, isRecoverableOAuthCallbackError, isSessionValid, isTokenExpiredResponse, listAuthSessionDataForUser, listAuthSessionsForUser, listCurrentUserAuthSessions, login, logout, onboardingRoute, policyRoute, protectRoute, protectedRoute, publicRoute, refreshTokens, requireAuth, requireAuthSession, resetAuthClaimMapping, resetRouteProtectionConfig, shouldAttemptTokenRefresh, shouldRefreshToken, subscriptionRoute, updateAuthSession };
1
+ import { C as listCurrentUserAuthSessions, D as OAUTH_RECOVERY_TTL_SECONDS, S as listAuthSessionsForUser, T as updateAuthSession, _ as getAuthSessionById, a as createAuthSession, b as isSessionValid, c as deleteOAuthRecoveryRecord, d as destroyAuthSessionById, f as destroyAuthSessionsByIdentitySession, g as getAuthSession, h as destroyAuthSessionsForUser, i as consumeOAuthRecoveryRecord, l as deleteOAuthState, m as destroyAuthSessionsBySid, n as cleanupExpiredOAuthStates, o as createOAuthRecoveryRecord, p as destroyAuthSessionsBySessionState, r as closeRedisConnection, s as createOAuthState, t as AUTH_ERROR_COOKIE_PREFIX, u as destroyAuthSession, v as getCurrentAuthSessionId, w as requireAuthSession, x as listAuthSessionDataForUser, y as getOAuthState } from "../redis-session-storage.server-DLJ0B7-C.mjs";
2
+ import { A as resetAuthClaimMapping, C as handleCallback, D as logout, E as login, F as isOAuthRecoveryEligibleCallback, I as OAuthCallbackError, L as OAuthCallbackFailureCodes, M as clearOAuthRecoveryIntentHeaders, N as consumeOAuthRecoveryIntent, O as refreshTokens, P as getOAuthRecoveryCookiePath, R as isOAuthCallbackError, S as handleBackChannelLogout, T as hasAuthError, _ as createAuthorizationResponseUrl, a as configureRouteProtection, b as getAuthError, c as protectRoute, d as resetRouteProtectionConfig, f as shouldRefreshToken, g as configureAuthClaimMapping, h as clearAuthServerCache, i as authRoute, j as OAUTH_RECOVERY_COOKIE_NAME, k as requireAuth, l as protectedRoute, m as clearAuthErrorHeaders, n as isTokenExpiredResponse, o as onboardingRoute, p as subscriptionRoute, r as shouldAttemptTokenRefresh, s as policyRoute, t as attemptTokenRefresh, u as publicRoute, v as extractUserInfo, w as handleFrontChannelLogout, x as getUser, y as getAccessToken, z as isRecoverableOAuthCallbackError } from "../server-349jPF7J.mjs";
3
+ export { AUTH_ERROR_COOKIE_PREFIX, OAUTH_RECOVERY_COOKIE_NAME, OAUTH_RECOVERY_TTL_SECONDS, OAuthCallbackError, OAuthCallbackFailureCodes, attemptTokenRefresh, authRoute, cleanupExpiredOAuthStates, clearAuthErrorHeaders, clearAuthServerCache, clearOAuthRecoveryIntentHeaders, closeRedisConnection, configureAuthClaimMapping, configureRouteProtection, consumeOAuthRecoveryIntent, consumeOAuthRecoveryRecord, createAuthSession, createAuthorizationResponseUrl, createOAuthRecoveryRecord, createOAuthState, deleteOAuthRecoveryRecord, deleteOAuthState, destroyAuthSession, destroyAuthSessionById, destroyAuthSessionsByIdentitySession, destroyAuthSessionsBySessionState, destroyAuthSessionsBySid, destroyAuthSessionsForUser, extractUserInfo, getAccessToken, getAuthError, getAuthSession, getAuthSessionById, getCurrentAuthSessionId, getOAuthRecoveryCookiePath, getOAuthState, getUser, handleBackChannelLogout, handleCallback, handleFrontChannelLogout, hasAuthError, isOAuthCallbackError, isOAuthRecoveryEligibleCallback, isRecoverableOAuthCallbackError, isSessionValid, isTokenExpiredResponse, listAuthSessionDataForUser, listAuthSessionsForUser, listCurrentUserAuthSessions, login, logout, onboardingRoute, policyRoute, protectRoute, protectedRoute, publicRoute, refreshTokens, requireAuth, requireAuthSession, resetAuthClaimMapping, resetRouteProtectionConfig, shouldAttemptTokenRefresh, shouldRefreshToken, subscriptionRoute, updateAuthSession };
@@ -8,10 +8,10 @@ import { t as isApiClientError } from "../types-DqCXinAk.mjs";
8
8
  import { a as withRetry, c as handleApiError, i as isRetryableError, l as ErrorCodes, n as createRetryFetch, o as ApiError, r as fetchWithTimeout, s as ErrorHandler, t as calculateBackoffDelay } from "../api-client-CB7XZaMg.mjs";
9
9
  import { a as getIdentitySignalRClient, i as createIdentitySignalRClient, n as SignalRClient, o as initializeSignalR, r as cleanupSignalR, t as IdentitySignalRClient } from "../signalr-C-TA8nEE.mjs";
10
10
  import { i as invalidationHelpers, n as createQueryClient, r as createQueryKeyFactory, t as cachePresets } from "../query-client-_xB300gc.mjs";
11
- import { S as updateAuthSession, _ as isSessionValid, a as createOAuthState, b as listCurrentUserAuthSessions, c as destroyAuthSessionById, d as destroyAuthSessionsBySid, f as destroyAuthSessionsForUser, g as getOAuthState, h as getCurrentAuthSessionId, i as createAuthSession, l as destroyAuthSessionsByIdentitySession, m as getAuthSessionById, n as cleanupExpiredOAuthStates, o as deleteOAuthState, p as getAuthSession, r as closeRedisConnection, s as destroyAuthSession, t as AUTH_ERROR_COOKIE_PREFIX, u as destroyAuthSessionsBySessionState, v as listAuthSessionDataForUser, x as requireAuthSession, y as listAuthSessionsForUser } from "../redis-session-storage.server-CI_IYIn8.mjs";
12
- import { A as resetAuthClaimMapping, C as handleCallback, D as logout, E as login, M as OAuthCallbackFailureCodes, N as isOAuthCallbackError, O as refreshTokens, P as isRecoverableOAuthCallbackError, S as handleBackChannelLogout, T as hasAuthError, _ as createAuthorizationResponseUrl, a as configureRouteProtection, b as getAuthError, c as protectRoute, d as resetRouteProtectionConfig, f as shouldRefreshToken, g as configureAuthClaimMapping, h as clearAuthServerCache, i as authRoute, j as OAuthCallbackError, k as requireAuth, l as protectedRoute, m as clearAuthErrorHeaders, n as isTokenExpiredResponse, o as onboardingRoute, p as subscriptionRoute, r as shouldAttemptTokenRefresh, s as policyRoute, t as attemptTokenRefresh, u as publicRoute, v as extractUserInfo, w as handleFrontChannelLogout, x as getUser, y as getAccessToken } from "../server-Cw86FdT-.mjs";
11
+ import { C as listCurrentUserAuthSessions, D as OAUTH_RECOVERY_TTL_SECONDS, S as listAuthSessionsForUser, T as updateAuthSession, _ as getAuthSessionById, a as createAuthSession, b as isSessionValid, c as deleteOAuthRecoveryRecord, d as destroyAuthSessionById, f as destroyAuthSessionsByIdentitySession, g as getAuthSession, h as destroyAuthSessionsForUser, i as consumeOAuthRecoveryRecord, l as deleteOAuthState, m as destroyAuthSessionsBySid, n as cleanupExpiredOAuthStates, o as createOAuthRecoveryRecord, p as destroyAuthSessionsBySessionState, r as closeRedisConnection, s as createOAuthState, t as AUTH_ERROR_COOKIE_PREFIX, u as destroyAuthSession, v as getCurrentAuthSessionId, w as requireAuthSession, x as listAuthSessionDataForUser, y as getOAuthState } from "../redis-session-storage.server-DLJ0B7-C.mjs";
12
+ import { A as resetAuthClaimMapping, C as handleCallback, D as logout, E as login, F as isOAuthRecoveryEligibleCallback, I as OAuthCallbackError, L as OAuthCallbackFailureCodes, M as clearOAuthRecoveryIntentHeaders, N as consumeOAuthRecoveryIntent, O as refreshTokens, P as getOAuthRecoveryCookiePath, R as isOAuthCallbackError, S as handleBackChannelLogout, T as hasAuthError, _ as createAuthorizationResponseUrl, a as configureRouteProtection, b as getAuthError, c as protectRoute, d as resetRouteProtectionConfig, f as shouldRefreshToken, g as configureAuthClaimMapping, h as clearAuthServerCache, i as authRoute, j as OAUTH_RECOVERY_COOKIE_NAME, k as requireAuth, l as protectedRoute, m as clearAuthErrorHeaders, n as isTokenExpiredResponse, o as onboardingRoute, p as subscriptionRoute, r as shouldAttemptTokenRefresh, s as policyRoute, t as attemptTokenRefresh, u as publicRoute, v as extractUserInfo, w as handleFrontChannelLogout, x as getUser, y as getAccessToken, z as isRecoverableOAuthCallbackError } from "../server-349jPF7J.mjs";
13
13
  import { clearActiveTenant, clearCurrentTenant, configureIdentityContextFetcher, configureTenantCookie, configureTenantResolution, getActiveTenant, getAvailableTenants, getCurrentTenant, getTenantFromIdentityContext, initializeTenant, isTenantMember, resetTenantCookieConfig, resetTenantResolutionConfig, setActiveTenant, setCurrentTenant } from "../tenant/server.mjs";
14
14
  import { clearIdentityContextCache, configureIdentityAPIFetcher, configurePermissionFetcher, contextToUserInfo, fetchIdentityContext, fetchUserPermissions, getIdentityContext, hasContextVersionChanged, updateContextVersion } from "../identity/server.mjs";
15
15
  import { n as createFetchMiddleware, r as createAPIConfigFactory, t as createApiClient } from "../server-pnsLybIH.mjs";
16
16
  import { checkPermission, configurePermissionRouteProtection, requirePermission, resetPermissionRouteProtection, withPermission } from "../server.mjs";
17
- export { AUTH_ERROR_COOKIE_PREFIX, ApiError, ErrorCodes, ErrorHandler, IdentityContextProvider, IdentitySignalRClient, LOG_LEVEL_PRIORITY, LogLevel, Logger, OAuthCallbackError, OAuthCallbackFailureCodes, PERMISSION_MODULES, PermissionChecker, PermissionInitializer, ProtectedAction, ProtectedButton, ProtectedLink, ProtectedSection, SignalRClient, TenantProvider, attemptTokenRefresh, authRoute, cachePresets, calculateBackoffDelay, checkPermission, cleanupExpiredOAuthStates, cleanupSignalR, clearActiveTenant, clearAuthErrorHeaders, clearAuthServerCache, clearCurrentTenant, clearIdentityContextCache, closeRedisConnection, configureAuthClaimMapping, configureIdentityAPIFetcher, configureIdentityContextFetcher, configureIdentityEndpoints, configureIdentityStore, configurePermissionFetcher, configurePermissionRouteProtection, configureRouteProtection, configureTenantClient, configureTenantCookie, configureTenantEndpoints, configureTenantResolution, contextToUserInfo, createAPIConfigFactory, createApiClient, createAuthSession, createAuthorizationResponseUrl, createFetchMiddleware, createIdentitySignalRClient, createLogger, createOAuthState, createQueryClient, createQueryKeyFactory, createRetryFetch, defaultLoggerConfig, deleteOAuthState, destroyAuthSession, destroyAuthSessionById, destroyAuthSessionsByIdentitySession, destroyAuthSessionsBySessionState, destroyAuthSessionsBySid, destroyAuthSessionsForUser, evaluateAccessRequirement, extractUserInfo, fetchIdentityContext, fetchUserPermissions, fetchWithTimeout, getAccessToken, getActiveTenant, getAuthError, getAuthSession, getAuthSessionById, getAvailableTenants, getCurrentAuthSessionId, getCurrentTenant, getIdentityContext, getIdentitySignalRClient, getOAuthState, getPermissionChecker, getPermissions, getTenantCookieName, getTenantFromIdentityContext, getUser, handleApiError, handleBackChannelLogout, handleCallback, handleFrontChannelLogout, hasAuthError, hasContextVersionChanged, initialIdentityContext, initializePermissions, initializeSignalR, initializeTenant, initializeTenantStore, invalidationHelpers, isApiClientError, isOAuthCallbackError, isRecoverableOAuthCallbackError, isRetryableError, isSessionValid, isTenantMember, isTokenExpiredResponse, listAuthSessionDataForUser, listAuthSessionsForUser, listCurrentUserAuthSessions, logger, login, logout, normalizeIdentityContextPayload, normalizeIdentityPermissionsPayload, normalizeTenantDataPayload, normalizeTenantSwitchPayload, onboardingRoute, policyRoute, protectRoute, protectedRoute, publicRoute, refreshTokens, requireAuth, requireAuthSession, requirePermission, resetAuthClaimMapping, resetIdentityStoreConfig, resetPermissionRouteProtection, resetRouteProtectionConfig, resetTenantClientConfig, resetTenantCookieConfig, resetTenantResolutionConfig, setActiveTenant, setCurrentTenant, shouldAttemptTokenRefresh, shouldRefreshToken, subscriptionRoute, updateAuthSession, updateContextVersion, useAllPermissions, useCurrentOrganization, useCurrentTenant, useCurrentTenantData, useHasEntitlement, useHasModulePermission, useHasPermission, useHasPermissions, useHasSubscription, useIdentityContext, useIdentityStore, useIsOnboarded, useModulePermission, useOrganization, usePermission, usePermissionChecker, usePermissionStore, usePermissions, useTenant, useTenantData, useTenantStore, useTenantSwitcher, useUserPermissions, useUserTenants, withPermission, withRetry };
17
+ export { AUTH_ERROR_COOKIE_PREFIX, ApiError, ErrorCodes, ErrorHandler, IdentityContextProvider, IdentitySignalRClient, LOG_LEVEL_PRIORITY, LogLevel, Logger, OAUTH_RECOVERY_COOKIE_NAME, OAUTH_RECOVERY_TTL_SECONDS, OAuthCallbackError, OAuthCallbackFailureCodes, PERMISSION_MODULES, PermissionChecker, PermissionInitializer, ProtectedAction, ProtectedButton, ProtectedLink, ProtectedSection, SignalRClient, TenantProvider, attemptTokenRefresh, authRoute, cachePresets, calculateBackoffDelay, checkPermission, cleanupExpiredOAuthStates, cleanupSignalR, clearActiveTenant, clearAuthErrorHeaders, clearAuthServerCache, clearCurrentTenant, clearIdentityContextCache, clearOAuthRecoveryIntentHeaders, closeRedisConnection, configureAuthClaimMapping, configureIdentityAPIFetcher, configureIdentityContextFetcher, configureIdentityEndpoints, configureIdentityStore, configurePermissionFetcher, configurePermissionRouteProtection, configureRouteProtection, configureTenantClient, configureTenantCookie, configureTenantEndpoints, configureTenantResolution, consumeOAuthRecoveryIntent, consumeOAuthRecoveryRecord, contextToUserInfo, createAPIConfigFactory, createApiClient, createAuthSession, createAuthorizationResponseUrl, createFetchMiddleware, createIdentitySignalRClient, createLogger, createOAuthRecoveryRecord, createOAuthState, createQueryClient, createQueryKeyFactory, createRetryFetch, defaultLoggerConfig, deleteOAuthRecoveryRecord, deleteOAuthState, destroyAuthSession, destroyAuthSessionById, destroyAuthSessionsByIdentitySession, destroyAuthSessionsBySessionState, destroyAuthSessionsBySid, destroyAuthSessionsForUser, evaluateAccessRequirement, extractUserInfo, fetchIdentityContext, fetchUserPermissions, fetchWithTimeout, getAccessToken, getActiveTenant, getAuthError, getAuthSession, getAuthSessionById, getAvailableTenants, getCurrentAuthSessionId, getCurrentTenant, getIdentityContext, getIdentitySignalRClient, getOAuthRecoveryCookiePath, getOAuthState, getPermissionChecker, getPermissions, getTenantCookieName, getTenantFromIdentityContext, getUser, handleApiError, handleBackChannelLogout, handleCallback, handleFrontChannelLogout, hasAuthError, hasContextVersionChanged, initialIdentityContext, initializePermissions, initializeSignalR, initializeTenant, initializeTenantStore, invalidationHelpers, isApiClientError, isOAuthCallbackError, isOAuthRecoveryEligibleCallback, isRecoverableOAuthCallbackError, isRetryableError, isSessionValid, isTenantMember, isTokenExpiredResponse, listAuthSessionDataForUser, listAuthSessionsForUser, listCurrentUserAuthSessions, logger, login, logout, normalizeIdentityContextPayload, normalizeIdentityPermissionsPayload, normalizeTenantDataPayload, normalizeTenantSwitchPayload, onboardingRoute, policyRoute, protectRoute, protectedRoute, publicRoute, refreshTokens, requireAuth, requireAuthSession, requirePermission, resetAuthClaimMapping, resetIdentityStoreConfig, resetPermissionRouteProtection, resetRouteProtectionConfig, resetTenantClientConfig, resetTenantCookieConfig, resetTenantResolutionConfig, setActiveTenant, setCurrentTenant, shouldAttemptTokenRefresh, shouldRefreshToken, subscriptionRoute, updateAuthSession, updateContextVersion, useAllPermissions, useCurrentOrganization, useCurrentTenant, useCurrentTenantData, useHasEntitlement, useHasModulePermission, useHasPermission, useHasPermissions, useHasSubscription, useIdentityContext, useIdentityStore, useIsOnboarded, useModulePermission, useOrganization, usePermission, usePermissionChecker, usePermissionStore, usePermissions, useTenant, useTenantData, useTenantStore, useTenantSwitcher, useUserPermissions, useUserTenants, withPermission, withRetry };
@@ -3,6 +3,7 @@ import Redis from "ioredis";
3
3
  import { createCipheriv, createDecipheriv, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
4
4
  //#region src/auth/oauth-state-config.ts
5
5
  const DEFAULT_OAUTH_STATE_TTL_SECONDS = 600;
6
+ const DEFAULT_OAUTH_RECOVERY_TTL_SECONDS = 1800;
6
7
  function resolvePositiveIntegerEnv$1(name, defaultValue) {
7
8
  const value = process.env[name]?.trim();
8
9
  if (!value) return defaultValue;
@@ -16,6 +17,13 @@ function resolvePositiveIntegerEnv$1(name, defaultValue) {
16
17
  */
17
18
  const OAUTH_STATE_TTL_SECONDS = resolvePositiveIntegerEnv$1("OAUTH_STATE_TTL", DEFAULT_OAUTH_STATE_TTL_SECONDS);
18
19
  const OAUTH_STATE_TTL_MS = OAUTH_STATE_TTL_SECONDS * 1e3;
20
+ /**
21
+ * Lifetime for the server-side recovery ticket. It deliberately outlives
22
+ * the primary OAuth transaction so an IdP callback that arrives after state
23
+ * expiry can still recover once, while remaining short-lived.
24
+ */
25
+ const OAUTH_RECOVERY_TTL_SECONDS = Math.max(DEFAULT_OAUTH_RECOVERY_TTL_SECONDS, OAUTH_STATE_TTL_SECONDS + 60);
26
+ const OAUTH_RECOVERY_TTL_MS = OAUTH_RECOVERY_TTL_SECONDS * 1e3;
19
27
  //#endregion
20
28
  //#region src/auth/redis-session-storage.server.ts
21
29
  /**
@@ -41,6 +49,7 @@ function getRedis() {
41
49
  const KEY_PREFIX = process.env.REDIS_KEY_PREFIX || "";
42
50
  const REDIS_KEYS = {
43
51
  oauthState: (stateId) => `${KEY_PREFIX}oauth:state:${stateId}`,
52
+ oauthRecovery: (ticket) => `${KEY_PREFIX}oauth:recovery:${ticket}`,
44
53
  session: (sessionId) => `${KEY_PREFIX}session:${sessionId}`,
45
54
  sessionByUser: (userId) => `${KEY_PREFIX}session:index:user:${userId}`,
46
55
  sessionBySid: (sid) => `${KEY_PREFIX}session:index:sid:${sid}`,
@@ -492,6 +501,62 @@ async function deleteOAuthState(stateId) {
492
501
  await getRedis().del(key);
493
502
  logger.debug("OAuth state deleted", { hasStateId: true });
494
503
  }
504
+ const CONSUME_OAUTH_RECOVERY_RECORD_SCRIPT = `
505
+ local value = redis.call('GET', KEYS[1])
506
+ if not value then
507
+ return nil
508
+ end
509
+ local ok, record = pcall(cjson.decode, value)
510
+ if not ok or type(record) ~= 'table' or type(record.state) ~= 'string' then
511
+ redis.call('DEL', KEYS[1])
512
+ return '__invalid__'
513
+ end
514
+ if record.state ~= ARGV[1] then
515
+ return '__mismatch__'
516
+ end
517
+ redis.call('DEL', KEYS[1])
518
+ return value
519
+ `;
520
+ /**
521
+ * Store a short-lived recovery record under a separate opaque ticket.
522
+ * The ticket is returned to the caller and is never logged or embedded with
523
+ * callback state, return URLs, or provider data.
524
+ */
525
+ async function createOAuthRecoveryRecord(record) {
526
+ const ticket = randomBytes(32).toString("base64url");
527
+ const key = REDIS_KEYS.oauthRecovery(ticket);
528
+ await getRedis().setex(key, OAUTH_RECOVERY_TTL_SECONDS, JSON.stringify(record));
529
+ logger.debug("OAuth recovery record created", {
530
+ hasTicket: true,
531
+ ttl: OAUTH_RECOVERY_TTL_SECONDS
532
+ });
533
+ return ticket;
534
+ }
535
+ /**
536
+ * Atomically consume a recovery record. The Redis script compares the exact
537
+ * expected state before DEL, so mismatched callbacks leave the ticket intact
538
+ * and concurrent exact-state requests can receive a record at most once.
539
+ */
540
+ async function consumeOAuthRecoveryRecord(ticket, expectedState) {
541
+ const key = REDIS_KEYS.oauthRecovery(ticket);
542
+ const value = await getRedis().eval(CONSUME_OAUTH_RECOVERY_RECORD_SCRIPT, 1, key, expectedState);
543
+ if (value === "__mismatch__" || value === null || value === void 0) return null;
544
+ if (value === "__invalid__") {
545
+ logger.error("OAuth recovery record failed atomic validation", void 0, { errorType: "InvalidRecoveryRecord" });
546
+ throw new Error("OAuth recovery storage failure");
547
+ }
548
+ if (typeof value !== "string") throw new Error("OAuth recovery storage failure");
549
+ try {
550
+ return JSON.parse(value);
551
+ } catch (error) {
552
+ logger.error("Failed to parse OAuth recovery record", void 0, { errorType: error instanceof Error ? error.name : "UnknownError" });
553
+ throw new Error("OAuth recovery storage failure");
554
+ }
555
+ }
556
+ async function deleteOAuthRecoveryRecord(ticket) {
557
+ await getRedis().del(REDIS_KEYS.oauthRecovery(ticket));
558
+ logger.debug("OAuth recovery record deleted", { hasTicket: true });
559
+ }
495
560
  async function cleanupExpiredOAuthStates() {
496
561
  const pattern = REDIS_KEYS.oauthState("*");
497
562
  const keys = await getRedis().keys(pattern);
@@ -514,6 +579,6 @@ async function closeRedisConnection() {
514
579
  }
515
580
  }
516
581
  //#endregion
517
- export { OAUTH_STATE_TTL_MS as C, updateAuthSession as S, isSessionValid as _, createOAuthState as a, listCurrentUserAuthSessions as b, destroyAuthSessionById as c, destroyAuthSessionsBySid as d, destroyAuthSessionsForUser as f, getOAuthState as g, getCurrentAuthSessionId as h, createAuthSession as i, destroyAuthSessionsByIdentitySession as l, getAuthSessionById as m, cleanupExpiredOAuthStates as n, deleteOAuthState as o, getAuthSession as p, closeRedisConnection as r, destroyAuthSession as s, AUTH_ERROR_COOKIE_PREFIX as t, destroyAuthSessionsBySessionState as u, listAuthSessionDataForUser as v, OAUTH_STATE_TTL_SECONDS as w, requireAuthSession as x, listAuthSessionsForUser as y };
582
+ export { listCurrentUserAuthSessions as C, OAUTH_RECOVERY_TTL_SECONDS as D, OAUTH_RECOVERY_TTL_MS as E, OAUTH_STATE_TTL_MS as O, listAuthSessionsForUser as S, updateAuthSession as T, getAuthSessionById as _, createAuthSession as a, isSessionValid as b, deleteOAuthRecoveryRecord as c, destroyAuthSessionById as d, destroyAuthSessionsByIdentitySession as f, getAuthSession as g, destroyAuthSessionsForUser as h, consumeOAuthRecoveryRecord as i, OAUTH_STATE_TTL_SECONDS as k, deleteOAuthState as l, destroyAuthSessionsBySid as m, cleanupExpiredOAuthStates as n, createOAuthRecoveryRecord as o, destroyAuthSessionsBySessionState as p, closeRedisConnection as r, createOAuthState as s, AUTH_ERROR_COOKIE_PREFIX as t, destroyAuthSession as u, getCurrentAuthSessionId as v, requireAuthSession as w, listAuthSessionDataForUser as x, getOAuthState as y };
518
583
 
519
- //# sourceMappingURL=redis-session-storage.server-CI_IYIn8.mjs.map
584
+ //# sourceMappingURL=redis-session-storage.server-DLJ0B7-C.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redis-session-storage.server-DLJ0B7-C.mjs","names":["resolvePositiveIntegerEnv"],"sources":["../src/auth/oauth-state-config.ts","../src/auth/redis-session-storage.server.ts"],"sourcesContent":["const DEFAULT_OAUTH_STATE_TTL_SECONDS = 10 * 60;\nconst DEFAULT_OAUTH_RECOVERY_TTL_SECONDS = 30 * 60;\n\nfunction resolvePositiveIntegerEnv(name: string, defaultValue: number): number {\n const value = process.env[name]?.trim();\n if (!value) {\n return defaultValue;\n }\n\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new Error(`${name} must be a positive integer.`);\n }\n\n return parsed;\n}\n\n/**\n * OAuth state lifetime shared by Redis expiry and callback age validation.\n * This module is internal and is not part of a package export entry point.\n */\nexport const OAUTH_STATE_TTL_SECONDS = resolvePositiveIntegerEnv(\n 'OAUTH_STATE_TTL',\n DEFAULT_OAUTH_STATE_TTL_SECONDS,\n);\n\nexport const OAUTH_STATE_TTL_MS = OAUTH_STATE_TTL_SECONDS * 1000;\n\n/**\n * Lifetime for the server-side recovery ticket. It deliberately outlives\n * the primary OAuth transaction so an IdP callback that arrives after state\n * expiry can still recover once, while remaining short-lived.\n */\nexport const OAUTH_RECOVERY_TTL_SECONDS = Math.max(\n DEFAULT_OAUTH_RECOVERY_TTL_SECONDS,\n OAUTH_STATE_TTL_SECONDS + 60,\n);\n\nexport const OAUTH_RECOVERY_TTL_MS = OAUTH_RECOVERY_TTL_SECONDS * 1000;\n","/**\n * Redis Session Storage Server Module\n *\n * Redis-backed session storage for authentication.\n * Provides secure session management with automatic expiration,\n * without depending on a framework-specific session implementation.\n */\n\nimport Redis from 'ioredis';\nimport { createCipheriv, createDecipheriv, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';\nimport type { AuthSessionSummary, SessionData, OAuthState } from './types';\nimport {\n OAUTH_RECOVERY_TTL_SECONDS,\n OAUTH_STATE_TTL_SECONDS,\n} from './oauth-state-config';\nimport { logger } from '../logging';\n\n// ============================================================================\n// Redis Client Setup\n// ============================================================================\n\nlet redis: Redis | null = null;\n\nfunction getRedis(): Redis {\n if (!redis) {\n redis = new Redis(process.env.REDIS_URL || 'redis://localhost:6379');\n\n redis.on('error', (err) => {\n logger.error('Redis Client Error', err);\n });\n\n redis.on('connect', () => {\n logger.info('Redis connected successfully');\n });\n }\n return redis;\n}\n\n// ============================================================================\n// Redis Key Patterns\n// ============================================================================\n\nconst KEY_PREFIX = process.env.REDIS_KEY_PREFIX || '';\n\nconst REDIS_KEYS = {\n oauthState: (stateId: string) => `${KEY_PREFIX}oauth:state:${stateId}`,\n oauthRecovery: (ticket: string) => `${KEY_PREFIX}oauth:recovery:${ticket}`,\n session: (sessionId: string) => `${KEY_PREFIX}session:${sessionId}`,\n sessionByUser: (userId: string) => `${KEY_PREFIX}session:index:user:${userId}`,\n sessionBySid: (sid: string) => `${KEY_PREFIX}session:index:sid:${sid}`,\n sessionBySessionState: (sessionState: string) => `${KEY_PREFIX}session:index:session_state:${sessionState}`,\n};\n\nconst DEFAULT_SESSION_SECRET = 'default-secret-change-in-production';\nconst DEFAULT_SESSION_TTL = 60 * 60 * 24 * 7;\n\nconst SESSION_TTL = resolvePositiveIntegerEnv('SESSION_DEFAULT_TTL', resolvePositiveIntegerEnv('SESSION_TTL', DEFAULT_SESSION_TTL));\n\nconst SESSION_COOKIE_NAME = process.env.SESSION_COOKIE_NAME || '__session_id';\nconst SESSION_SECRET = resolveSessionSecret();\nconst SESSION_COOKIE_SECURE = resolveCookieSecure();\nconst SESSION_COOKIE_PATH = '/';\nconst SESSION_COOKIE_SAME_SITE = resolveCookieSameSite();\nconst SESSION_COOKIE_DOMAIN = process.env.SESSION_COOKIE_DOMAIN?.trim();\nconst SESSION_ENCRYPTION_ENABLED = resolveSessionEncryptionEnabled();\nconst SESSION_ENCRYPTION_KEY = resolveSessionEncryptionKey(SESSION_ENCRYPTION_ENABLED);\n\nexport const AUTH_ERROR_COOKIE_PREFIX = SESSION_COOKIE_NAME.replace('_session', '').replace('__', '');\n\nfunction resolveBooleanEnv(name: string, defaultValue: boolean): boolean {\n const value = process.env[name]?.trim().toLowerCase();\n if (!value) {\n return defaultValue;\n }\n\n if (['1', 'true', 'yes', 'on'].includes(value)) {\n return true;\n }\n\n if (['0', 'false', 'no', 'off'].includes(value)) {\n return false;\n }\n\n throw new Error(`${name} must be a boolean value.`);\n}\n\nfunction resolvePositiveIntegerEnv(name: string, defaultValue: number): number {\n const value = process.env[name]?.trim();\n if (!value) {\n return defaultValue;\n }\n\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new Error(`${name} must be a positive integer.`);\n }\n\n return parsed;\n}\n\nfunction resolveSessionSecret(): string {\n const secret = process.env.SESSION_SECRET?.trim();\n if (!secret || secret === DEFAULT_SESSION_SECRET) {\n if (process.env.NODE_ENV === 'production') {\n throw new Error('SESSION_SECRET must be set to a unique random value in production.');\n }\n\n return DEFAULT_SESSION_SECRET;\n }\n\n if (secret.length < 32) {\n throw new Error('SESSION_SECRET must be at least 32 characters long.');\n }\n\n return secret;\n}\n\nfunction resolveCookieSecure(): boolean {\n return resolveBooleanEnv('SESSION_COOKIE_SECURE', process.env.NODE_ENV === 'production');\n}\n\nfunction resolveCookieSameSite(): 'Lax' | 'Strict' | 'None' {\n const value = process.env.SESSION_COOKIE_SAME_SITE?.trim().toLowerCase();\n const sameSite = value === 'strict' ? 'Strict' : value === 'none' ? 'None' : 'Lax';\n\n if (sameSite === 'None' && !SESSION_COOKIE_SECURE) {\n throw new Error('SESSION_COOKIE_SAME_SITE=None requires SESSION_COOKIE_SECURE=true.');\n }\n\n return sameSite;\n}\n\nfunction resolveSessionEncryptionEnabled(): boolean {\n const enabled = resolveBooleanEnv('SESSION_ENCRYPTION', process.env.NODE_ENV === 'production');\n if (process.env.NODE_ENV === 'production' && !enabled) {\n throw new Error('SESSION_ENCRYPTION cannot be disabled in production.');\n }\n\n return enabled;\n}\n\nfunction decodeBase64Url(value: string): Buffer {\n const normalized = value.replace(/-/g, '+').replace(/_/g, '/');\n const padded = normalized.padEnd(normalized.length + ((4 - (normalized.length % 4)) % 4), '=');\n return Buffer.from(padded, 'base64');\n}\n\nfunction resolveSessionEncryptionKey(enabled: boolean): Buffer | null {\n if (!enabled) {\n return null;\n }\n\n const value = process.env.SESSION_ENCRYPTION_KEY?.trim();\n if (!value) {\n throw new Error('SESSION_ENCRYPTION_KEY is required when session encryption is enabled.');\n }\n\n const key = /^[0-9a-f]{64}$/i.test(value)\n ? Buffer.from(value, 'hex')\n : decodeBase64Url(value);\n\n if (key.length !== 32) {\n throw new Error('SESSION_ENCRYPTION_KEY must decode to exactly 32 bytes. Generate one with: openssl rand -base64 32');\n }\n\n return key;\n}\n\ntype SessionCookieOptions = {\n maxAge: number;\n};\n\nfunction parseCookieHeader(cookieHeader: string | null): Record<string, string> {\n if (!cookieHeader) {\n return {};\n }\n\n return cookieHeader\n .split(';')\n .map((part) => part.trim())\n .filter(Boolean)\n .reduce<Record<string, string>>((cookies, part) => {\n const separatorIndex = part.indexOf('=');\n if (separatorIndex <= 0) {\n return cookies;\n }\n\n const name = part.slice(0, separatorIndex).trim();\n const value = part.slice(separatorIndex + 1).trim();\n if (!name) {\n return cookies;\n }\n\n cookies[name] = value;\n return cookies;\n }, {});\n}\n\nfunction createCookieSignature(value: string, secret: string): string {\n return createHmac('sha256', secret).update(value).digest('base64url');\n}\n\nfunction safelyCompareValues(left: string, right: string): boolean {\n const leftBuffer = Buffer.from(left);\n const rightBuffer = Buffer.from(right);\n\n if (leftBuffer.length !== rightBuffer.length) {\n return false;\n }\n\n return timingSafeEqual(leftBuffer, rightBuffer);\n}\n\nfunction signSessionId(sessionId: string): string {\n const signature = createCookieSignature(sessionId, SESSION_SECRET);\n return `${sessionId}.${signature}`;\n}\n\nfunction unsignSessionId(cookieValue: string | undefined): string | null {\n if (!cookieValue) {\n return null;\n }\n\n let decodedValue: string;\n try {\n decodedValue = decodeURIComponent(cookieValue);\n } catch {\n return null;\n }\n\n const separatorIndex = decodedValue.lastIndexOf('.');\n if (separatorIndex <= 0 || separatorIndex === decodedValue.length - 1) {\n return null;\n }\n\n const sessionId = decodedValue.slice(0, separatorIndex);\n const signature = decodedValue.slice(separatorIndex + 1);\n const expectedSignature = createCookieSignature(sessionId, SESSION_SECRET);\n\n return safelyCompareValues(signature, expectedSignature) ? sessionId : null;\n}\n\nfunction serializeSessionCookieValue(sessionId: string, options: SessionCookieOptions): string {\n const signedValue = encodeURIComponent(signSessionId(sessionId));\n const segments = [\n `${SESSION_COOKIE_NAME}=${signedValue}`,\n `Max-Age=${options.maxAge}`,\n `Path=${SESSION_COOKIE_PATH}`,\n `SameSite=${SESSION_COOKIE_SAME_SITE}`,\n 'HttpOnly',\n ];\n\n if (SESSION_COOKIE_DOMAIN) {\n segments.push(`Domain=${SESSION_COOKIE_DOMAIN}`);\n }\n\n if (SESSION_COOKIE_SECURE) {\n segments.push('Secure');\n }\n\n return segments.join('; ');\n}\n\nfunction serializeExpiredSessionCookie(): string {\n const segments = [\n `${SESSION_COOKIE_NAME}=`,\n 'Max-Age=0',\n `Path=${SESSION_COOKIE_PATH}`,\n `SameSite=${SESSION_COOKIE_SAME_SITE}`,\n 'HttpOnly',\n ];\n\n if (SESSION_COOKIE_DOMAIN) {\n segments.push(`Domain=${SESSION_COOKIE_DOMAIN}`);\n }\n\n if (SESSION_COOKIE_SECURE) {\n segments.push('Secure');\n }\n\n return segments.join('; ');\n}\n\nasync function getSessionIdFromRequest(request: Request): Promise<string | null> {\n const cookies = parseCookieHeader(request.headers.get('Cookie'));\n return unsignSessionId(cookies[SESSION_COOKIE_NAME]);\n}\n\nfunction getSessionIndexKeys(data: SessionData): string[] {\n const keys = new Set<string>();\n\n if (data.userId) {\n keys.add(REDIS_KEYS.sessionByUser(data.userId));\n }\n\n if (data.sid) {\n keys.add(REDIS_KEYS.sessionBySid(data.sid));\n }\n\n if (data.sessionState) {\n keys.add(REDIS_KEYS.sessionBySessionState(data.sessionState));\n }\n\n return Array.from(keys);\n}\n\nasync function registerSessionIndexes(sessionId: string, data: SessionData): Promise<void> {\n const indexKeys = getSessionIndexKeys(data);\n if (indexKeys.length === 0) {\n return;\n }\n\n const redisClient = getRedis();\n const pipeline = redisClient.pipeline();\n\n for (const indexKey of indexKeys) {\n pipeline.sadd(indexKey, sessionId);\n pipeline.expire(indexKey, SESSION_TTL);\n }\n\n await pipeline.exec();\n}\n\nasync function unregisterSessionIndexes(sessionId: string, data: SessionData): Promise<void> {\n const indexKeys = getSessionIndexKeys(data);\n if (indexKeys.length === 0) {\n return;\n }\n\n const redisClient = getRedis();\n const pipeline = redisClient.pipeline();\n\n for (const indexKey of indexKeys) {\n pipeline.srem(indexKey, sessionId);\n }\n\n await pipeline.exec();\n}\n\nfunction parseSessionData(sessionData: string | null): SessionData | null {\n if (!sessionData) {\n return null;\n }\n\n try {\n return JSON.parse(decodeSessionData(sessionData)) as SessionData;\n } catch (error) {\n logger.error('Failed to parse session data', error instanceof Error ? error : undefined);\n return null;\n }\n}\n\nfunction encodeSessionData(data: SessionData): string {\n const plaintext = JSON.stringify(data);\n if (!SESSION_ENCRYPTION_KEY) {\n return plaintext;\n }\n\n const iv = randomBytes(12);\n const cipher = createCipheriv('aes-256-gcm', SESSION_ENCRYPTION_KEY, iv);\n const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);\n const tag = cipher.getAuthTag();\n\n return [\n 'enc:v1',\n iv.toString('base64url'),\n tag.toString('base64url'),\n ciphertext.toString('base64url'),\n ].join(':');\n}\n\nfunction decodeSessionData(value: string): string {\n if (!value.startsWith('enc:v1:')) {\n if (SESSION_ENCRYPTION_ENABLED) {\n logger.warn('Reading legacy plaintext auth session payload while session encryption is enabled.');\n }\n\n return value;\n }\n\n if (!SESSION_ENCRYPTION_KEY) {\n throw new Error('Cannot decrypt auth session payload because SESSION_ENCRYPTION_KEY is not configured.');\n }\n\n const [, version, ivValue, tagValue, ciphertextValue] = value.split(':');\n if (version !== 'v1' || !ivValue || !tagValue || !ciphertextValue) {\n throw new Error('Invalid encrypted auth session payload format.');\n }\n\n const decipher = createDecipheriv('aes-256-gcm', SESSION_ENCRYPTION_KEY, Buffer.from(ivValue, 'base64url'));\n decipher.setAuthTag(Buffer.from(tagValue, 'base64url'));\n\n return Buffer.concat([\n decipher.update(Buffer.from(ciphertextValue, 'base64url')),\n decipher.final(),\n ]).toString('utf8');\n}\n\nasync function readSessionData(sessionId: string): Promise<SessionData | null> {\n try {\n const sessionData = await getRedis().get(REDIS_KEYS.session(sessionId));\n if (!sessionData) {\n logger.debug('Session not found in Redis', { sessionId });\n return null;\n }\n\n await getRedis().expire(REDIS_KEYS.session(sessionId), SESSION_TTL);\n return parseSessionData(sessionData);\n } catch (error) {\n logger.error('Failed to read session from Redis', error instanceof Error ? error : undefined);\n return null;\n }\n}\n\nasync function writeSessionData(sessionId: string, data: SessionData): Promise<void> {\n try {\n const existingSessionData = parseSessionData(await getRedis().get(REDIS_KEYS.session(sessionId)));\n if (existingSessionData) {\n await unregisterSessionIndexes(sessionId, existingSessionData);\n }\n\n await getRedis().setex(REDIS_KEYS.session(sessionId), SESSION_TTL, encodeSessionData(data));\n await registerSessionIndexes(sessionId, data);\n logger.debug('Updated Redis session', { sessionId });\n } catch (error) {\n logger.error('Failed to update session in Redis', error instanceof Error ? error : undefined);\n throw error;\n }\n}\n\nasync function deleteSessionData(sessionId: string): Promise<void> {\n try {\n const existingSessionData = parseSessionData(await getRedis().get(REDIS_KEYS.session(sessionId)));\n if (existingSessionData) {\n await unregisterSessionIndexes(sessionId, existingSessionData);\n }\n\n await getRedis().del(REDIS_KEYS.session(sessionId));\n logger.debug('Deleted Redis session', { sessionId });\n } catch (error) {\n logger.error('Failed to delete session from Redis', error instanceof Error ? error : undefined);\n }\n}\n\nfunction mergeSessionData(existingData: SessionData, updates: Partial<SessionData>): SessionData {\n const nextData = { ...existingData } as Record<string, unknown>;\n\n Object.entries(updates).forEach(([key, value]) => {\n if (value === undefined) {\n delete nextData[key];\n return;\n }\n\n nextData[key] = value;\n });\n\n return nextData as SessionData;\n}\n\nasync function getSessionIdsFromIndex(indexKey: string): Promise<string[]> {\n const sessionIds = await getRedis().smembers(indexKey);\n const activeSessionIds: string[] = [];\n const staleSessionIds: string[] = [];\n\n for (const sessionId of sessionIds) {\n const exists = await getRedis().exists(REDIS_KEYS.session(sessionId));\n if (exists) {\n activeSessionIds.push(sessionId);\n } else {\n staleSessionIds.push(sessionId);\n }\n }\n\n if (staleSessionIds.length > 0) {\n await getRedis().srem(indexKey, ...staleSessionIds);\n }\n\n return activeSessionIds;\n}\n\nfunction toAuthSessionSummary(\n sessionId: string,\n session: SessionData,\n currentSessionId?: string | null\n): AuthSessionSummary {\n return {\n sessionId,\n userId: session.userId,\n email: session.user?.email,\n name: session.user?.name,\n issuer: session.issuer,\n sid: session.sid,\n sessionState: session.sessionState,\n clientId: session.clientId,\n ipAddress: session.ipAddress,\n userAgent: session.userAgent,\n createdAt: session.createdAt,\n lastActivity: session.lastActivity,\n expiresAt: session.expiresAt,\n isCurrent: currentSessionId ? sessionId === currentSessionId : undefined,\n };\n}\n\nasync function listSessionDataByIds(sessionIds: string[]): Promise<Array<{ sessionId: string; data: SessionData }>> {\n const sessions: Array<{ sessionId: string; data: SessionData }> = [];\n\n for (const sessionId of sessionIds) {\n const data = await readSessionData(sessionId);\n if (data) {\n sessions.push({ sessionId, data });\n }\n }\n\n return sessions;\n}\n\nfunction getRequestIpAddress(request: Request): string | undefined {\n const forwardedFor = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim();\n return (\n forwardedFor ||\n request.headers.get('cf-connecting-ip')?.trim() ||\n request.headers.get('x-real-ip')?.trim() ||\n undefined\n );\n}\n\n// ============================================================================\n// Session Helper Functions\n// ============================================================================\n\nexport async function createAuthSession(\n request: Request,\n sessionData: Partial<SessionData>\n): Promise<Headers> {\n const currentSessionId = await getSessionIdFromRequest(request);\n const nextSessionId = crypto.randomUUID();\n const nextSessionData = mergeSessionData({}, {\n ...sessionData,\n sessionId: nextSessionId,\n ipAddress: sessionData.ipAddress ?? getRequestIpAddress(request),\n userAgent: sessionData.userAgent ?? request.headers.get('user-agent') ?? undefined,\n });\n\n logger.debug('Creating auth session', { dataKeys: Object.keys(sessionData) });\n\n if (currentSessionId) {\n await deleteSessionData(currentSessionId);\n }\n\n await writeSessionData(nextSessionId, nextSessionData);\n\n return new Headers({\n 'Set-Cookie': serializeSessionCookieValue(nextSessionId, { maxAge: SESSION_TTL }),\n });\n}\n\nexport async function getAuthSession(request: Request): Promise<SessionData> {\n const sessionId = await getSessionIdFromRequest(request);\n if (!sessionId) {\n return {};\n }\n\n const session = await readSessionData(sessionId);\n if (!session) {\n return {};\n }\n\n return {\n sessionId,\n userId: session.userId,\n accessToken: session.accessToken,\n refreshToken: session.refreshToken,\n idToken: session.idToken,\n expiresAt: session.expiresAt,\n issuer: session.issuer,\n sid: session.sid,\n sessionState: session.sessionState,\n clientId: session.clientId,\n ipAddress: session.ipAddress,\n userAgent: session.userAgent,\n user: session.user,\n createdAt: session.createdAt,\n lastActivity: session.lastActivity,\n };\n}\n\nexport async function updateAuthSession(\n request: Request,\n updates: Partial<SessionData>\n): Promise<Headers> {\n const currentSessionId = await getSessionIdFromRequest(request);\n const currentSessionData = currentSessionId\n ? (await readSessionData(currentSessionId)) ?? {}\n : {};\n const nextSessionId = currentSessionId ?? crypto.randomUUID();\n const nextSessionData = mergeSessionData(currentSessionData, {\n ...updates,\n sessionId: nextSessionId,\n });\n\n await writeSessionData(nextSessionId, nextSessionData);\n\n return new Headers({\n 'Set-Cookie': serializeSessionCookieValue(nextSessionId, { maxAge: SESSION_TTL }),\n });\n}\n\nexport async function destroyAuthSession(request: Request): Promise<Headers> {\n const sessionId = await getSessionIdFromRequest(request);\n if (sessionId) {\n await deleteSessionData(sessionId);\n }\n\n return new Headers({\n 'Set-Cookie': serializeExpiredSessionCookie(),\n });\n}\n\nexport async function getCurrentAuthSessionId(request: Request): Promise<string | null> {\n return await getSessionIdFromRequest(request);\n}\n\nexport async function getAuthSessionById(sessionId: string): Promise<SessionData | null> {\n const session = await readSessionData(sessionId);\n return session ? { ...session, sessionId } : null;\n}\n\nexport async function listAuthSessionDataForUser(\n userId: string\n): Promise<Array<{ sessionId: string; data: SessionData }>> {\n const sessionIds = await getSessionIdsFromIndex(REDIS_KEYS.sessionByUser(userId));\n return await listSessionDataByIds(sessionIds);\n}\n\nexport async function listAuthSessionsForUser(\n userId: string,\n currentSessionId?: string | null\n): Promise<AuthSessionSummary[]> {\n const sessions = await listAuthSessionDataForUser(userId);\n\n return sessions\n .map(({ sessionId, data }) => toAuthSessionSummary(sessionId, data, currentSessionId))\n .sort((left, right) => (right.lastActivity ?? right.createdAt ?? 0) - (left.lastActivity ?? left.createdAt ?? 0));\n}\n\nexport async function listCurrentUserAuthSessions(request: Request): Promise<AuthSessionSummary[]> {\n const currentSession = await getAuthSession(request);\n if (!currentSession.userId) {\n return [];\n }\n\n return await listAuthSessionsForUser(currentSession.userId, currentSession.sessionId);\n}\n\nexport async function destroyAuthSessionById(sessionId: string): Promise<boolean> {\n const session = await readSessionData(sessionId);\n if (!session) {\n return false;\n }\n\n await deleteSessionData(sessionId);\n return true;\n}\n\nexport async function destroyAuthSessionsForUser(userId: string): Promise<number> {\n const sessionIds = await getSessionIdsFromIndex(REDIS_KEYS.sessionByUser(userId));\n let destroyedSessions = 0;\n\n for (const sessionId of sessionIds) {\n if (await destroyAuthSessionById(sessionId)) {\n destroyedSessions += 1;\n }\n }\n\n return destroyedSessions;\n}\n\nexport async function destroyAuthSessionsBySid(sid: string): Promise<number> {\n const sessionIds = await getSessionIdsFromIndex(REDIS_KEYS.sessionBySid(sid));\n let destroyedSessions = 0;\n\n for (const sessionId of sessionIds) {\n if (await destroyAuthSessionById(sessionId)) {\n destroyedSessions += 1;\n }\n }\n\n return destroyedSessions;\n}\n\nexport async function destroyAuthSessionsBySessionState(sessionState: string): Promise<number> {\n const sessionIds = await getSessionIdsFromIndex(REDIS_KEYS.sessionBySessionState(sessionState));\n let destroyedSessions = 0;\n\n for (const sessionId of sessionIds) {\n if (await destroyAuthSessionById(sessionId)) {\n destroyedSessions += 1;\n }\n }\n\n return destroyedSessions;\n}\n\nexport async function destroyAuthSessionsByIdentitySession(params: {\n sid?: string;\n sessionState?: string;\n userId?: string;\n}): Promise<number> {\n if (params.sid) {\n return await destroyAuthSessionsBySid(params.sid);\n }\n\n if (params.sessionState) {\n return await destroyAuthSessionsBySessionState(params.sessionState);\n }\n\n if (params.userId) {\n return await destroyAuthSessionsForUser(params.userId);\n }\n\n return 0;\n}\n\nexport async function requireAuthSession(request: Request): Promise<SessionData> {\n const sessionData = await getAuthSession(request);\n\n if (!sessionData.userId || !sessionData.user || !sessionData.accessToken || isSessionDataExpired(sessionData)) {\n throw new Response('Unauthorized', { status: 401 });\n }\n\n return sessionData;\n}\n\nfunction getJwtExpiry(accessToken: string | undefined): number | null {\n if (!accessToken) {\n return null;\n }\n\n try {\n const [, encodedPayload] = accessToken.split('.');\n if (!encodedPayload) {\n return null;\n }\n\n const payload = JSON.parse(\n Buffer.from(encodedPayload, 'base64url').toString('utf8'),\n ) as { exp?: unknown };\n\n return typeof payload.exp === 'number' && Number.isFinite(payload.exp)\n ? payload.exp * 1000\n : null;\n } catch {\n return null;\n }\n}\n\nfunction isSessionDataExpired(sessionData: SessionData): boolean {\n const now = Date.now();\n if (\n typeof sessionData.expiresAt === 'number' &&\n (!Number.isFinite(sessionData.expiresAt) || now >= sessionData.expiresAt)\n ) {\n return true;\n }\n\n const jwtExpiry = getJwtExpiry(sessionData.accessToken);\n return jwtExpiry !== null && now >= jwtExpiry;\n}\n\nexport async function isSessionValid(request: Request): Promise<boolean> {\n try {\n const sessionData = await getAuthSession(request);\n\n if (!sessionData.user || !sessionData.accessToken || isSessionDataExpired(sessionData)) {\n return false;\n }\n\n return true;\n } catch {\n return false;\n }\n}\n\n// ============================================================================\n// OAuth State Management\n// ============================================================================\n\nexport async function createOAuthState(state: OAuthState): Promise<string> {\n const stateId = crypto.randomUUID();\n const key = REDIS_KEYS.oauthState(stateId);\n\n await getRedis().setex(key, OAUTH_STATE_TTL_SECONDS, JSON.stringify(state));\n\n logger.debug('OAuth state created', { hasStateId: true, ttl: OAUTH_STATE_TTL_SECONDS });\n\n return stateId;\n}\n\nexport async function getOAuthState(\n stateId: string,\n options?: { readonly throwOnMalformed?: boolean },\n): Promise<OAuthState | null> {\n const key = REDIS_KEYS.oauthState(stateId);\n const data = await getRedis().get(key);\n\n if (!data) {\n logger.warn('OAuth state not found or expired', { hasStateId: true });\n return null;\n }\n\n try {\n return JSON.parse(data);\n } catch (error) {\n logger.error('Failed to parse OAuth state', undefined, {\n errorType: error instanceof Error ? error.name : 'UnknownError',\n });\n if (options?.throwOnMalformed) {\n throw new Error('OAuth state storage failure');\n }\n return null;\n }\n}\n\nexport async function deleteOAuthState(stateId: string): Promise<void> {\n const key = REDIS_KEYS.oauthState(stateId);\n await getRedis().del(key);\n logger.debug('OAuth state deleted', { hasStateId: true });\n}\n\nexport interface OAuthRecoveryRecord {\n state: string;\n returnUrl: string;\n createdAt: number;\n}\n\nconst CONSUME_OAUTH_RECOVERY_RECORD_SCRIPT = `\nlocal value = redis.call('GET', KEYS[1])\nif not value then\n return nil\nend\nlocal ok, record = pcall(cjson.decode, value)\nif not ok or type(record) ~= 'table' or type(record.state) ~= 'string' then\n redis.call('DEL', KEYS[1])\n return '__invalid__'\nend\nif record.state ~= ARGV[1] then\n return '__mismatch__'\nend\nredis.call('DEL', KEYS[1])\nreturn value\n`;\n\n/**\n * Store a short-lived recovery record under a separate opaque ticket.\n * The ticket is returned to the caller and is never logged or embedded with\n * callback state, return URLs, or provider data.\n */\nexport async function createOAuthRecoveryRecord(\n record: OAuthRecoveryRecord,\n): Promise<string> {\n const ticket = randomBytes(32).toString('base64url');\n const key = REDIS_KEYS.oauthRecovery(ticket);\n\n await getRedis().setex(\n key,\n OAUTH_RECOVERY_TTL_SECONDS,\n JSON.stringify(record),\n );\n\n logger.debug('OAuth recovery record created', {\n hasTicket: true,\n ttl: OAUTH_RECOVERY_TTL_SECONDS,\n });\n\n return ticket;\n}\n\n/**\n * Atomically consume a recovery record. The Redis script compares the exact\n * expected state before DEL, so mismatched callbacks leave the ticket intact\n * and concurrent exact-state requests can receive a record at most once.\n */\nexport async function consumeOAuthRecoveryRecord(\n ticket: string,\n expectedState: string,\n): Promise<OAuthRecoveryRecord | null> {\n const key = REDIS_KEYS.oauthRecovery(ticket);\n const value = await getRedis().eval(\n CONSUME_OAUTH_RECOVERY_RECORD_SCRIPT,\n 1,\n key,\n expectedState,\n );\n\n if (value === '__mismatch__' || value === null || value === undefined) {\n return null;\n }\n\n if (value === '__invalid__') {\n logger.error('OAuth recovery record failed atomic validation', undefined, {\n errorType: 'InvalidRecoveryRecord',\n });\n throw new Error('OAuth recovery storage failure');\n }\n\n if (typeof value !== 'string') {\n throw new Error('OAuth recovery storage failure');\n }\n\n try {\n return JSON.parse(value) as OAuthRecoveryRecord;\n } catch (error) {\n logger.error('Failed to parse OAuth recovery record', undefined, {\n errorType: error instanceof Error ? error.name : 'UnknownError',\n });\n throw new Error('OAuth recovery storage failure');\n }\n}\n\nexport async function deleteOAuthRecoveryRecord(ticket: string): Promise<void> {\n await getRedis().del(REDIS_KEYS.oauthRecovery(ticket));\n logger.debug('OAuth recovery record deleted', { hasTicket: true });\n}\n\nexport async function cleanupExpiredOAuthStates(): Promise<number> {\n const pattern = REDIS_KEYS.oauthState('*');\n const keys = await getRedis().keys(pattern);\n\n let cleaned = 0;\n for (const key of keys) {\n const ttl = await getRedis().ttl(key);\n if (ttl === -1) {\n await getRedis().del(key);\n cleaned++;\n }\n }\n\n logger.info('OAuth state cleanup completed', { cleaned, total: keys.length });\n return cleaned;\n}\n\n// ============================================================================\n// Cleanup\n// ============================================================================\n\nexport async function closeRedisConnection(): Promise<void> {\n if (redis) {\n await redis.quit();\n redis = null;\n logger.info('Redis connection closed');\n }\n}\n"],"mappings":";;;;AAAA,MAAM,kCAAkC;AACxC,MAAM,qCAAqC;AAE3C,SAASA,4BAA0B,MAAc,cAA8B;CAC7E,MAAM,QAAQ,QAAQ,IAAI,KAAK,EAAE,KAAK;CACtC,IAAI,CAAC,OACH,OAAO;CAGT,MAAM,SAAS,OAAO,KAAK;CAC3B,IAAI,CAAC,OAAO,cAAc,MAAM,KAAK,UAAU,GAC7C,MAAM,IAAI,MAAM,GAAG,KAAK,6BAA6B;CAGvD,OAAO;AACT;;;;;AAMA,MAAa,0BAA0BA,4BACrC,mBACA,+BACF;AAEA,MAAa,qBAAqB,0BAA0B;;;;;;AAO5D,MAAa,6BAA6B,KAAK,IAC7C,oCACA,0BAA0B,EAC5B;AAEA,MAAa,wBAAwB,6BAA6B;;;;;;;;;;ACjBlE,IAAI,QAAsB;AAE1B,SAAS,WAAkB;CACzB,IAAI,CAAC,OAAO;EACV,QAAQ,IAAI,MAAM,QAAQ,IAAI,aAAa,wBAAwB;EAEnE,MAAM,GAAG,UAAU,QAAQ;GACzB,OAAO,MAAM,sBAAsB,GAAG;EACxC,CAAC;EAED,MAAM,GAAG,iBAAiB;GACxB,OAAO,KAAK,8BAA8B;EAC5C,CAAC;CACH;CACA,OAAO;AACT;AAMA,MAAM,aAAa,QAAQ,IAAI,oBAAoB;AAEnD,MAAM,aAAa;CACjB,aAAa,YAAoB,GAAG,WAAW,cAAc;CAC7D,gBAAgB,WAAmB,GAAG,WAAW,iBAAiB;CAClE,UAAU,cAAsB,GAAG,WAAW,UAAU;CACxD,gBAAgB,WAAmB,GAAG,WAAW,qBAAqB;CACtE,eAAe,QAAgB,GAAG,WAAW,oBAAoB;CACjE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