Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 6x 6x 5x 6x 1x 1x 1x 1x 6x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x | /**
* @file useSessionTimeout.ts
* @description
* Proactive session management hook. Detects expired/invalid sessions and
* navigates the user to the dedicated logout flow.
*
* @enterprise
* - Dual strategy:
* 1) **Heartbeat**: ping a lightweight endpoint (e.g., `/api/me`) on a schedule
* and when the tab becomes visible to detect server-side session invalidation.
* 2) **Idle timeout (optional)**: if enabled, logs the user out after a period
* of user inactivity (keyboard/mouse). This is off by default; enable for
* stricter environments.
* - Cross-tab sync: leverages `storage` events to ensure logout across tabs.
* - Does not throw UI; it **navigates to `/logout`** (LogoutPage does the cleanup).
*
* @usage
* Call once inside your authenticated layout (e.g., `AppShell`) or an auth gate:
*
* ```tsx
* useSessionTimeout({
* pingEndpoint: '/api/me',
* pingIntervalMs: 60_000,
* enableIdleTimeout: false,
* idleTimeoutMs: 15 * 60_000,
* });
* ```
*/
import * as React from 'react';
import { useNavigate } from 'react-router-dom';
import httpClient from '../../../api/httpClient';
import { useAuth } from '../../../hooks/useAuth';
type UseSessionTimeoutOptions = {
/** Endpoint returning 200/OK when the session is valid (e.g., GET /api/me). */
pingEndpoint?: string;
/** How often to ping while the tab is visible. Default: 60s. */
pingIntervalMs?: number;
/** Whether to auto-logout after idle period. Default: false (off). */
enableIdleTimeout?: boolean;
/** Idle period before logout when `enableIdleTimeout` is true. Default: 15 min. */
idleTimeoutMs?: number;
};
const STORAGE_FLAG = 'ssp:forceLogout';
/**
* @description
* Proactive session management hook. Detects expired/invalid sessions and
* navigates the user to the dedicated logout flow.
*
* @enterprise
* - Dual strategy:
* 1) **Heartbeat**: ping a lightweight endpoint (e.g., `/api/me`) on a schedule
* and when the tab becomes visible to detect server-side session invalidation.
* 2) **Idle timeout (optional)**: if enabled, logs the user out after a period
* of user inactivity (keyboard/mouse). This is off by default; enable for
* stricter environments.
* - Cross-tab sync: leverages `storage` events to ensure logout across tabs.
* - Does not throw UI; it **navigates to `/logout`** (LogoutPage does the cleanup).
*
* @param options - Configuration options for session timeout behavior.
* @example
* ```tsx
* useSessionTimeout({
* pingEndpoint: '/api/me',
* pingIntervalMs: 60_000,
* enableIdleTimeout: false,
* idleTimeoutMs: 15 * 60_000,
* });
* ```
*/
export function useSessionTimeout(options: UseSessionTimeoutOptions = {}) {
const {
pingEndpoint = '/api/me',
pingIntervalMs = 60_000,
enableIdleTimeout = false,
idleTimeoutMs = 15 * 60_000,
} = options;
const navigate = useNavigate();
const { user } = useAuth(); // to reset timers on user change
// ---- Heartbeat: detect server-side invalidation ----
React.useEffect(() => {
let timer: number | null = null;
// DEMO sessions have no server cookie/token; skip heartbeat entirely
if (user?.isDemo) return;
const ping = async () => {
try {
await httpClient.get(pingEndpoint, { withCredentials: true });
// session valid -> nothing to do
} catch {
// Likely 401/403/network -> force logout route (centralized cleanup there)
forceLogoutAcrossTabs();
navigate('/logout', { replace: true });
}
};
const start = () => {
// immediate check when becoming visible
ping();
// periodic checks while visible
timer = window.setInterval(ping, pingIntervalMs);
};
const stop = () => {
if (timer) {
window.clearInterval(timer);
timer = null;
}
};
// Run heartbeat only when tab is visible (saves resources)
const handleVisibility = () => {
if (document.visibilityState === 'visible') start();
else stop();
};
document.addEventListener('visibilitychange', handleVisibility);
handleVisibility(); // initialize
return () => {
document.removeEventListener('visibilitychange', handleVisibility);
stop();
};
}, [user?.isDemo, pingEndpoint, pingIntervalMs, navigate]);
// ---- Idle timeout (optional) ----
React.useEffect(() => {
// Skip idle logic for demo too
if (!enableIdleTimeout || user?.isDemo) return;
let idleTimer: number;
const resetIdle = () => {
if (idleTimer) window.clearTimeout(idleTimer);
idleTimer = window.setTimeout(() => {
forceLogoutAcrossTabs();
navigate('/logout', { replace: true });
}, idleTimeoutMs);
};
// Monitor user activity to reset idle timer
const events = ['mousemove', 'keydown', 'wheel', 'touchstart'];
events.forEach((e) => window.addEventListener(e, resetIdle, { passive: true }));
resetIdle();
// Cleanup on unmount
return () => {
if (idleTimer) window.clearTimeout(idleTimer);
events.forEach((e) => window.removeEventListener(e, resetIdle));
};
}, [enableIdleTimeout, idleTimeoutMs, user?.isDemo, navigate]);
// ---- Cross-tab sync for logout ----
React.useEffect(() => {
const onStorage = (ev: StorageEvent) => {
if (ev.key === STORAGE_FLAG && ev.newValue === '1') {
// Another tab triggered logout; follow suit.
navigate('/logout', { replace: true });
}
};
window.addEventListener('storage', onStorage);
return () => window.removeEventListener('storage', onStorage);
}, [navigate]);
}
/**
* Signal all tabs to navigate to /logout via localStorage event.
* @private
* @enterprise
* - Uses localStorage to trigger cross-tab logout.
* - Quickly removes the flag to keep storage clean while still triggering event.
* @example
* ```typescript
* forceLogoutAcrossTabs();
* ```
*/
function forceLogoutAcrossTabs() {
try {
localStorage.setItem(STORAGE_FLAG, '1');
// clear quickly to keep storage clean while still triggering event
localStorage.removeItem(STORAGE_FLAG);
} catch {
// ignore storage failures
}
}
|