You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@gravitino.apache.org by "LauraXia123 (via GitHub)" <gi...@apache.org> on 2026/06/15 07:44:29 UTC
[PR] [#11630] web-v2(UI): Inactivity Session Timeout and Forced Re-authentication [gravitino]
LauraXia123 opened a new pull request, #11643:
URL: https://github.com/apache/gravitino/pull/11643
### What changes were proposed in this pull request?
<img width="2942" height="1434" alt="image" src="https://github.com/user-attachments/assets/81477a44-f4ae-47fc-a098-4697a0fb1759" />
Overview
When a user is inactive for a configurable period, a warning modal appears with a countdown timer. If the user doesn't respond, they are automatically signed out. The feature works across multiple browser tabs via BroadcastChannel synchronization.
Configuration
┌──────────────────────────────────┬───────────────┬───────────────────────────────────────┐
│ Environment Variable │ Default │ Description │
├──────────────────────────────────┼───────────────┼───────────────────────────────────────┤
│ NEXT_PUBLIC_IDLE_TIMEOUT_MS │ 900000 (15 │ Total idle timeout before forced │
│ │ min) │ logout │
├──────────────────────────────────┼───────────────┼───────────────────────────────────────┤
│ NEXT_PUBLIC_IDLE_WARNING_LEAD_MS │ 60000 (60s) │ Warning countdown duration before │
│ │ │ timeout │
└──────────────────────────────────┴───────────────┴───────────────────────────────────────┘
State Machine
active → warning → expired
- active: Normal operation, idle timer running
- warning: Warning modal shown with countdown
- expired: Auto-logout triggered
Cross-Tab Broadcast
Messages are broadcast via BroadcastChannel when:
- activity: User interacts with any tab → other tabs reset idle timer
- stay_signed_in: User clicks "Stay signed in" → other tabs dismiss warning
- logout: User signs out or timeout → other tabs redirect to /login
Logout Behavior by Auth Mode
┌────────────┬──────────────────────────────────────────────────────────────────────────────┐
│ Auth Mode │ Logout Action │
├────────────┼──────────────────────────────────────────────────────────────────────────────┤
│ Simple │ Clears sessionStorage, redirects to /login │
├────────────┼──────────────────────────────────────────────────────────────────────────────┤
│ OAuth/OIDC │ Clears localStorage + OIDC user store, calls IdP signoutRedirect() with │
│ │ id_token_hint │
└────────────┴──────────────────────────────────────────────────────────────────────────────┘
Exclusions
- Login page (/login) does not show the warning modal
- Unauthenticated users are not affected
- Events fired while tab is hidden are ignored
### Why are the changes needed?
N/A
Fix: #11630
### Does this PR introduce _any_ user-facing change?
N/A
### How was this patch tested?
Manually
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11630] web-v2(UI): Inactivity Session Timeout and Forced Re-authentication [gravitino]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #11643:
URL: https://github.com/apache/gravitino/pull/11643#discussion_r3418778420
##########
web-v2/web/src/lib/store/auth/index.js:
##########
@@ -96,76 +95,75 @@ export const loginAction = createAsyncThunk('auth/loginAction', async ({ params,
return { token: access_token, expired: expires_in }
})
-export const logoutAction = createAsyncThunk('auth/logoutAction', async ({ router }, { getState, dispatch }) => {
- // Clear provider authentication data first
- if (getState().auth.authType === 'oauth') {
- try {
- const provider = await oauthProviderFactory.getProvider()
- if (provider) {
- // For OIDC providers, use signoutRedirect to end IdP session
- if (provider.getUserManager) {
- const userManager = provider.getUserManager()
- if (userManager) {
- // Read id_token before clearing — needed for id_token_hint
- const user = await userManager.getUser()
-
- // Clear OIDC user data from store
- await provider.clearAuthData()
-
- // Clear legacy auth tokens
- localStorage.removeItem('accessToken')
- localStorage.removeItem('authParams')
- localStorage.removeItem('expiredIn')
- localStorage.removeItem('isIdle')
- localStorage.removeItem('version')
-
- dispatch(clearIntervalId())
- dispatch(setAuthToken(''))
-
- // Redirect to IdP logout endpoint — browser navigates away, must be last
- await userManager.signoutRedirect({ id_token_hint: user?.id_token })
-
- return { token: null } // unreachable — browser navigates away
+export const logoutAction = createAsyncThunk(
+ 'auth/logoutAction',
+ async ({ router, reason }, { getState, dispatch }) => {
+ // Clear provider authentication data first
+ if (getState().auth.authType === 'oauth') {
+ try {
+ const provider = await oauthProviderFactory.getProvider()
+ if (provider) {
+ // For OIDC providers, use signoutRedirect to end IdP session
+ if (provider.getUserManager) {
+ const userManager = provider.getUserManager()
+ if (userManager) {
+ // Read id_token before clearing — needed for id_token_hint
+ const user = await userManager.getUser()
+
+ // Clear OIDC user data from store
+ await provider.clearAuthData()
+
+ // Clear legacy auth tokens
+ localStorage.removeItem('accessToken')
+ localStorage.removeItem('authParams')
+ localStorage.removeItem('expiredIn')
+ localStorage.removeItem('version')
+
+ dispatch(clearIntervalId())
+ dispatch(setAuthToken(''))
+
+ // Redirect to IdP logout endpoint — browser navigates away, must be last
+ await userManager.signoutRedirect({ id_token_hint: user?.id_token })
+
+ return { token: null } // unreachable — browser navigates away
+ }
}
- }
- await provider.clearAuthData()
+ await provider.clearAuthData()
+ }
+ } catch (error) {
+ console.warn('[Logout Action] Provider cleanup failed:', error)
}
- } catch (error) {
- console.warn('[Logout Action] Provider cleanup failed:', error)
+
+ // Clear legacy auth tokens
+ localStorage.removeItem('accessToken')
+ localStorage.removeItem('authParams')
+ localStorage.removeItem('expiredIn')
+ localStorage.removeItem('version')
+
+ dispatch(clearIntervalId())
+ dispatch(setAuthToken(''))
+ } else {
+ dispatch(setAuthUser(null))
}
Review Comment:
OAuth logout clears access token and interval state, but it does not clear `authUser` (and therefore leaves `sessionStorage.simpleAuthUser` populated via the `setAuthUser` reducer). This can leave UI state thinking a user is still present after logout (e.g., nav/permissions decisions based on `authUser`).
##########
web-v2/web/src/lib/provider/IdleSessionProvider.js:
##########
@@ -0,0 +1,253 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+'use client'
+
+import { useEffect, useCallback, useRef, useState } from 'react'
+import { useRouter, usePathname } from 'next/navigation'
+import { useAppDispatch, useAppSelector } from '@/lib/hooks/useStore'
+import { useIdleTimeout } from '@/lib/hooks/useIdleTimeout'
+import { useBroadcastChannel } from '@/lib/hooks/useBroadcastChannel'
+import { logoutAction } from '@/lib/store/auth'
+import IdleSessionContext from './IdleSessionContext'
+import IdleWarningModal from '@/components/IdleWarningModal'
+
+/**
+ * Default idle timeout: 15 minutes in milliseconds.
+ * Overridable via NEXT_PUBLIC_IDLE_TIMEOUT_MS environment variable.
+ */
+const DEFAULT_IDLE_TIMEOUT_MS = (() => {
+ const envVal = process.env.NEXT_PUBLIC_IDLE_TIMEOUT_MS
+ const parsed = envVal ? Number(envVal) : NaN
+
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 15 * 60 * 1000
+})()
+
+/**
+ * Default warning lead time: 60 seconds in milliseconds.
+ * Overridable via NEXT_PUBLIC_IDLE_WARNING_LEAD_MS environment variable.
+ */
+const DEFAULT_WARNING_LEAD_MS = (() => {
+ const envVal = process.env.NEXT_PUBLIC_IDLE_WARNING_LEAD_MS
+ const parsed = envVal ? Number(envVal) : NaN
+
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 60 * 1000
+})()
+
+/**
+ * Converts milliseconds to seconds, rounded up.
+ */
+function msToSeconds(ms) {
+ return Math.ceil(ms / 1000)
+}
+
+/**
+ * IdleSessionProvider manages the idle timeout state machine and cross-tab
+ * coordination (IST-REQ-001 through IST-REQ-006).
+ *
+ * State machine: active → warning → expired
+ *
+ * - ACTIVE: Normal operation, idle timer is running
+ * - WARNING: Warning lead time has elapsed, modal is shown with countdown
+ * - EXPIRED: Timeout reached, logout is triggered
+ *
+ * @param {Object} props
+ * @param {React.ReactNode} props.children
+ * @param {number} [props.idleTimeoutMs] - Idle timeout in milliseconds (default: 15 min)
+ * @param {number} [props.warningLeadMs] - Warning lead time in milliseconds (default: 60s)
+ */
+export default function IdleSessionProvider({
+ children,
+ idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS,
+ warningLeadMs = DEFAULT_WARNING_LEAD_MS
+}) {
+ const router = useRouter()
+ const pathname = usePathname()
+ const dispatch = useAppDispatch()
+ const authType = useAppSelector(state => state.auth.authType)
+ const authToken = useAppSelector(state => state.auth.authToken)
+
+ // Only enable idle timeout when the user is authenticated and not on login page
+ const isAuthenticated = authType === 'simple' ? !!sessionStorage.getItem('simpleAuthUser') : !!authToken
+ const isLoginPage = pathname === '/login'
+
+ const [state, setState] = useState('active')
+ const [warningCountdown, setWarningCountdown] = useState(msToSeconds(warningLeadMs))
+ const loggedOutRef = useRef(false)
+ const wasAuthenticatedRef = useRef(isAuthenticated)
+
+ const {
+ isIdle,
+ resetActivity: resetIdleActivity,
+ idleTimeRemaining
+ } = useIdleTimeout({
+ idleTimeoutMs: isAuthenticated ? idleTimeoutMs : Number.MAX_SAFE_INTEGER,
+
+ // Pause DOM activity detection during warning state so the modal stays
+ // visible until the user explicitly clicks "Stay signed in" or "Sign out now"
+ paused: state === 'warning'
+ })
+
+ const { sendMessage, onMessage } = useBroadcastChannel()
+
+ // Track warning threshold: when idleTimeRemaining drops below warningLeadMs, show warning
+ const warningThreshold = warningLeadMs
+
+ // State machine transitions
+ useEffect(() => {
+ if (!isAuthenticated) {
+ return
+ }
+
+ if (isIdle) {
+ // Idle time exceeded full timeout → expired
+ setState('expired')
+ } else if (idleTimeRemaining <= warningThreshold && idleTimeRemaining > 0) {
+ // Within warning window
+ if (state === 'active') {
+ setState('warning')
+ setWarningCountdown(msToSeconds(idleTimeRemaining))
+ }
+ } else if (idleTimeRemaining > warningThreshold) {
+ // Back above warning threshold (activity detected)
+ if (state !== 'active') {
+ setState('active')
+ }
+ }
+ }, [isIdle, idleTimeRemaining, warningThreshold, isAuthenticated])
+
+ // Update warning countdown based on remaining idle time
+ useEffect(() => {
+ if (state === 'warning') {
+ setWarningCountdown(msToSeconds(idleTimeRemaining))
+ }
+ }, [state, idleTimeRemaining])
+
+ // Handle logout (either from timeout or "Sign out now")
+ const handleLogout = useCallback(() => {
+ if (loggedOutRef.current) {
+ return
+ }
+
+ loggedOutRef.current = true
+ setState('expired')
+
+ // Broadcast logout with reason to other tabs
+ sendMessage({ type: 'logout', reason: 'inactive', timestamp: Date.now() })
+
+ // Dispatch logout action (handles both OAuth and simple auth)
+ // Pass reason to show inactivity message on login page
+ dispatch(logoutAction({ router, reason: 'inactive' }))
+ }, [dispatch, router, sendMessage])
+
+ // Handle "Stay signed in" action (IST-REQ-003)
+ const handleStaySignedIn = useCallback(() => {
+ setState('active')
+ resetIdleActivity()
+ setWarningCountdown(msToSeconds(warningLeadMs))
+
+ // Broadcast stay_signed_in to other tabs so they also dismiss warning and stay logged in
+ sendMessage({ type: 'stay_signed_in', timestamp: Date.now() })
+ }, [resetIdleActivity, warningLeadMs, sendMessage])
+
+ // Cross-tab message handling (IST-REQ-005)
+ useEffect(() => {
+ onMessage(message => {
+ if (message.type === 'activity') {
+ // Activity in another tab resets this tab's idle timer and dismisses warning modal
+ resetIdleActivity()
+ if (state === 'warning') {
+ setState('active')
+ setWarningCountdown(msToSeconds(warningLeadMs))
+ }
+ } else if (message.type === 'stay_signed_in') {
+ // Another tab clicked "Stay signed in" — dismiss warning and stay logged in
+ resetIdleActivity()
+ if (state === 'warning') {
+ setState('active')
+ setWarningCountdown(msToSeconds(warningLeadMs))
+ }
+ } else if (message.type === 'logout') {
+ // Another tab triggered logout — redirect without calling signOut again
+ if (!loggedOutRef.current) {
+ loggedOutRef.current = true
+ const loginUrl = message.reason ? `/login?reason=${message.reason}` : '/login'
+ router.push(loginUrl)
+ }
+ }
Review Comment:
On `logout` messages from other tabs, this code only navigates to `/login` but does not clear local auth state (Redux token / localStorage / OIDC user store). That means the tab can still be treated as authenticated and can continue making API calls until reload. Consider running the centralized `logoutAction` here to ensure state is cleared consistently across tabs.
##########
web-v2/web/src/lib/provider/IdleSessionProvider.js:
##########
@@ -0,0 +1,253 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+'use client'
+
+import { useEffect, useCallback, useRef, useState } from 'react'
+import { useRouter, usePathname } from 'next/navigation'
+import { useAppDispatch, useAppSelector } from '@/lib/hooks/useStore'
+import { useIdleTimeout } from '@/lib/hooks/useIdleTimeout'
+import { useBroadcastChannel } from '@/lib/hooks/useBroadcastChannel'
+import { logoutAction } from '@/lib/store/auth'
+import IdleSessionContext from './IdleSessionContext'
+import IdleWarningModal from '@/components/IdleWarningModal'
+
+/**
+ * Default idle timeout: 15 minutes in milliseconds.
+ * Overridable via NEXT_PUBLIC_IDLE_TIMEOUT_MS environment variable.
+ */
+const DEFAULT_IDLE_TIMEOUT_MS = (() => {
+ const envVal = process.env.NEXT_PUBLIC_IDLE_TIMEOUT_MS
+ const parsed = envVal ? Number(envVal) : NaN
+
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 15 * 60 * 1000
+})()
+
+/**
+ * Default warning lead time: 60 seconds in milliseconds.
+ * Overridable via NEXT_PUBLIC_IDLE_WARNING_LEAD_MS environment variable.
+ */
+const DEFAULT_WARNING_LEAD_MS = (() => {
+ const envVal = process.env.NEXT_PUBLIC_IDLE_WARNING_LEAD_MS
+ const parsed = envVal ? Number(envVal) : NaN
+
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 60 * 1000
+})()
+
+/**
+ * Converts milliseconds to seconds, rounded up.
+ */
+function msToSeconds(ms) {
+ return Math.ceil(ms / 1000)
+}
+
+/**
+ * IdleSessionProvider manages the idle timeout state machine and cross-tab
+ * coordination (IST-REQ-001 through IST-REQ-006).
+ *
+ * State machine: active → warning → expired
+ *
+ * - ACTIVE: Normal operation, idle timer is running
+ * - WARNING: Warning lead time has elapsed, modal is shown with countdown
+ * - EXPIRED: Timeout reached, logout is triggered
+ *
+ * @param {Object} props
+ * @param {React.ReactNode} props.children
+ * @param {number} [props.idleTimeoutMs] - Idle timeout in milliseconds (default: 15 min)
+ * @param {number} [props.warningLeadMs] - Warning lead time in milliseconds (default: 60s)
+ */
+export default function IdleSessionProvider({
+ children,
+ idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS,
+ warningLeadMs = DEFAULT_WARNING_LEAD_MS
+}) {
+ const router = useRouter()
+ const pathname = usePathname()
+ const dispatch = useAppDispatch()
+ const authType = useAppSelector(state => state.auth.authType)
+ const authToken = useAppSelector(state => state.auth.authToken)
+
+ // Only enable idle timeout when the user is authenticated and not on login page
+ const isAuthenticated = authType === 'simple' ? !!sessionStorage.getItem('simpleAuthUser') : !!authToken
+ const isLoginPage = pathname === '/login'
+
+ const [state, setState] = useState('active')
+ const [warningCountdown, setWarningCountdown] = useState(msToSeconds(warningLeadMs))
+ const loggedOutRef = useRef(false)
+ const wasAuthenticatedRef = useRef(isAuthenticated)
+
+ const {
+ isIdle,
+ resetActivity: resetIdleActivity,
+ idleTimeRemaining
+ } = useIdleTimeout({
+ idleTimeoutMs: isAuthenticated ? idleTimeoutMs : Number.MAX_SAFE_INTEGER,
+
+ // Pause DOM activity detection during warning state so the modal stays
+ // visible until the user explicitly clicks "Stay signed in" or "Sign out now"
+ paused: state === 'warning'
+ })
+
+ const { sendMessage, onMessage } = useBroadcastChannel()
+
+ // Track warning threshold: when idleTimeRemaining drops below warningLeadMs, show warning
+ const warningThreshold = warningLeadMs
+
+ // State machine transitions
+ useEffect(() => {
+ if (!isAuthenticated) {
+ return
+ }
+
+ if (isIdle) {
+ // Idle time exceeded full timeout → expired
+ setState('expired')
+ } else if (idleTimeRemaining <= warningThreshold && idleTimeRemaining > 0) {
+ // Within warning window
+ if (state === 'active') {
+ setState('warning')
+ setWarningCountdown(msToSeconds(idleTimeRemaining))
+ }
+ } else if (idleTimeRemaining > warningThreshold) {
+ // Back above warning threshold (activity detected)
+ if (state !== 'active') {
+ setState('active')
+ }
+ }
+ }, [isIdle, idleTimeRemaining, warningThreshold, isAuthenticated])
+
+ // Update warning countdown based on remaining idle time
+ useEffect(() => {
+ if (state === 'warning') {
+ setWarningCountdown(msToSeconds(idleTimeRemaining))
+ }
+ }, [state, idleTimeRemaining])
+
+ // Handle logout (either from timeout or "Sign out now")
+ const handleLogout = useCallback(() => {
+ if (loggedOutRef.current) {
+ return
+ }
+
+ loggedOutRef.current = true
+ setState('expired')
+
+ // Broadcast logout with reason to other tabs
+ sendMessage({ type: 'logout', reason: 'inactive', timestamp: Date.now() })
+
+ // Dispatch logout action (handles both OAuth and simple auth)
+ // Pass reason to show inactivity message on login page
+ dispatch(logoutAction({ router, reason: 'inactive' }))
+ }, [dispatch, router, sendMessage])
+
+ // Handle "Stay signed in" action (IST-REQ-003)
+ const handleStaySignedIn = useCallback(() => {
+ setState('active')
+ resetIdleActivity()
+ setWarningCountdown(msToSeconds(warningLeadMs))
+
+ // Broadcast stay_signed_in to other tabs so they also dismiss warning and stay logged in
+ sendMessage({ type: 'stay_signed_in', timestamp: Date.now() })
+ }, [resetIdleActivity, warningLeadMs, sendMessage])
+
+ // Cross-tab message handling (IST-REQ-005)
+ useEffect(() => {
+ onMessage(message => {
+ if (message.type === 'activity') {
+ // Activity in another tab resets this tab's idle timer and dismisses warning modal
+ resetIdleActivity()
+ if (state === 'warning') {
+ setState('active')
+ setWarningCountdown(msToSeconds(warningLeadMs))
+ }
+ } else if (message.type === 'stay_signed_in') {
+ // Another tab clicked "Stay signed in" — dismiss warning and stay logged in
+ resetIdleActivity()
+ if (state === 'warning') {
+ setState('active')
+ setWarningCountdown(msToSeconds(warningLeadMs))
+ }
+ } else if (message.type === 'logout') {
+ // Another tab triggered logout — redirect without calling signOut again
+ if (!loggedOutRef.current) {
+ loggedOutRef.current = true
+ const loginUrl = message.reason ? `/login?reason=${message.reason}` : '/login'
+ router.push(loginUrl)
+ }
+ }
+ })
+ }, [onMessage, resetIdleActivity, router, state, warningLeadMs])
+
+ // Broadcast activity to other tabs when this tab has activity (IST-REQ-005)
+ // The idle hook already resets on activity; we just need to broadcast
+ const lastBroadcastRef = useRef(0)
+ useEffect(() => {
+ if (!isAuthenticated) {
+ return
+ }
+
+ // When idleTimeRemaining is reset (activity detected), broadcast to other tabs
+ // We use a throttled approach: check if enough time has passed since last broadcast
+ const now = Date.now()
+
+ if (now - lastBroadcastRef.current >= 2000) {
+ sendMessage({ type: 'activity', timestamp: now })
+ lastBroadcastRef.current = now
+ }
+ }, [idleTimeRemaining, isAuthenticated, sendMessage])
+
+ // Auto-logout when state becomes expired (from isIdle)
+ useEffect(() => {
+ if (state === 'expired' && !loggedOutRef.current) {
+ handleLogout()
+ }
+ }, [state, handleLogout])
+
+ // Detect authenticated→unauthenticated transition (e.g., manual logout from user menu)
+ // and broadcast logout to other tabs
+ useEffect(() => {
+ if (wasAuthenticatedRef.current && !isAuthenticated && !loggedOutRef.current) {
+ loggedOutRef.current = true
+ sendMessage({ type: 'logout', timestamp: Date.now() })
+ }
+ wasAuthenticatedRef.current = isAuthenticated
+ }, [isAuthenticated, sendMessage])
Review Comment:
`loggedOutRef` is set to true on logout and is never reset when the user authenticates again. In a single-page flow (logout -> login without full reload), that will prevent future idle timeouts from triggering `handleLogout()` because the guard stays engaged. Reset the guard (and timer/state) on unauthenticated→authenticated transitions.
##########
web-v2/web/src/lib/store/auth/index.js:
##########
@@ -96,76 +95,75 @@ export const loginAction = createAsyncThunk('auth/loginAction', async ({ params,
return { token: access_token, expired: expires_in }
})
-export const logoutAction = createAsyncThunk('auth/logoutAction', async ({ router }, { getState, dispatch }) => {
- // Clear provider authentication data first
- if (getState().auth.authType === 'oauth') {
- try {
- const provider = await oauthProviderFactory.getProvider()
- if (provider) {
- // For OIDC providers, use signoutRedirect to end IdP session
- if (provider.getUserManager) {
- const userManager = provider.getUserManager()
- if (userManager) {
- // Read id_token before clearing — needed for id_token_hint
- const user = await userManager.getUser()
-
- // Clear OIDC user data from store
- await provider.clearAuthData()
-
- // Clear legacy auth tokens
- localStorage.removeItem('accessToken')
- localStorage.removeItem('authParams')
- localStorage.removeItem('expiredIn')
- localStorage.removeItem('isIdle')
- localStorage.removeItem('version')
-
- dispatch(clearIntervalId())
- dispatch(setAuthToken(''))
-
- // Redirect to IdP logout endpoint — browser navigates away, must be last
- await userManager.signoutRedirect({ id_token_hint: user?.id_token })
-
- return { token: null } // unreachable — browser navigates away
+export const logoutAction = createAsyncThunk(
+ 'auth/logoutAction',
+ async ({ router, reason }, { getState, dispatch }) => {
+ // Clear provider authentication data first
+ if (getState().auth.authType === 'oauth') {
+ try {
+ const provider = await oauthProviderFactory.getProvider()
+ if (provider) {
+ // For OIDC providers, use signoutRedirect to end IdP session
+ if (provider.getUserManager) {
+ const userManager = provider.getUserManager()
+ if (userManager) {
+ // Read id_token before clearing — needed for id_token_hint
+ const user = await userManager.getUser()
+
+ // Clear OIDC user data from store
+ await provider.clearAuthData()
+
+ // Clear legacy auth tokens
+ localStorage.removeItem('accessToken')
+ localStorage.removeItem('authParams')
+ localStorage.removeItem('expiredIn')
+ localStorage.removeItem('version')
+
+ dispatch(clearIntervalId())
+ dispatch(setAuthToken(''))
+
+ // Redirect to IdP logout endpoint — browser navigates away, must be last
+ await userManager.signoutRedirect({ id_token_hint: user?.id_token })
+
+ return { token: null } // unreachable — browser navigates away
+ }
Review Comment:
`logoutAction` always calls `signoutRedirect()` for OIDC when a `UserManager` exists. If `getUser()` returns null (common after a completed signout redirect callback), this can trigger a new signout redirect without an `id_token_hint`, potentially causing a redirect loop (/oauth/logout -> logoutAction -> signoutRedirect -> /oauth/logout ...). Guard the redirect on the presence of an `id_token` so callback flows can complete and proceed to local cleanup + /login navigation.
##########
web-v2/web/src/lib/hooks/useIdleTimeout.js:
##########
@@ -0,0 +1,159 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+'use client'
+
+import { useEffect, useRef, useCallback, useState } from 'react'
+
+/**
+ * DOM events that constitute genuine user interaction and reset the idle timer.
+ * Events fired while the document is hidden are ignored.
+ */
+const ACTIVITY_EVENTS = ['mousemove', 'mousedown', 'keydown', 'touchstart', 'scroll', 'visibilitychange']
+
+/**
+ * Sentinel value indicating the hook should be effectively disabled.
+ * When idleTimeoutMs is this value, no polling loop or event listeners are attached.
+ */
+const DISABLED_SENTINEL = Number.MAX_SAFE_INTEGER
+
+/**
+ * Default idle timeout: 15 minutes in milliseconds.
+ * Overridable via NEXT_PUBLIC_IDLE_TIMEOUT_MS environment variable.
+ */
+const DEFAULT_IDLE_TIMEOUT_MS = (() => {
+ const envVal = process.env.NEXT_PUBLIC_IDLE_TIMEOUT_MS
+ const parsed = envVal ? Number(envVal) : NaN
+
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 15 * 60 * 1000
+})()
+
+/**
+ * Custom hook for idle timeout detection using DOM event listeners and
+ * requestAnimationFrame polling. Provides full control over timer reset
+ * for "Stay signed in" and cross-tab synchronization.
+ *
+ * Performance optimizations:
+ * - Skips polling loop entirely when idleTimeoutMs is Number.MAX_SAFE_INTEGER (unauthenticated)
+ * - Throttles state updates to once per second (only when remaining seconds change)
+ *
+ * @param {Object} options
+ * @param {number} [options.idleTimeoutMs] - Idle timeout in milliseconds (default: 15 minutes).
+ * Pass Number.MAX_SAFE_INTEGER to disable the hook entirely.
+ * @param {boolean} [options.paused] - When true, DOM activity events are ignored (timer keeps running).
+ * Used to keep the warning modal visible until the user explicitly acts.
+ * Programmatic calls to resetActivity() still work when paused.
+ * @returns {{ isIdle: boolean, resetActivity: () => void, idleTimeRemaining: number }}
+ */
+export function useIdleTimeout({ idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS, paused = false } = {}) {
+ const lastActivityRef = useRef(null)
+ const rafIdRef = useRef(null)
+ const pausedRef = useRef(paused)
+ const lastReportedSecondRef = useRef(null)
+ const [isIdle, setIsIdle] = useState(false)
+ const [idleTimeRemaining, setIdleTimeRemaining] = useState(idleTimeoutMs)
+
+ // Keep pausedRef in sync with the latest paused prop
+ useEffect(() => {
+ pausedRef.current = paused
+ }, [paused])
+
+ const resetActivity = useCallback(() => {
+ lastActivityRef.current = Date.now()
+ setIsIdle(false)
+ setIdleTimeRemaining(idleTimeoutMs)
+ lastReportedSecondRef.current = null
+ }, [idleTimeoutMs])
+
+ useEffect(() => {
+ // Skip entirely when disabled (unauthenticated sentinel)
+ if (idleTimeoutMs === DISABLED_SENTINEL) {
+ return
+ }
+
+ // Initialize the last activity timestamp on mount
+ lastActivityRef.current = Date.now()
+ lastReportedSecondRef.current = null
+
+ const handleActivityEvent = event => {
+ // Ignore events fired while the tab is hidden (IST-REQ-001)
+ if (document.hidden) {
+ return
+ }
+
+ // When paused (e.g. warning modal is shown), ignore DOM activity
+ // so the modal stays visible until the user explicitly acts
+ if (pausedRef.current) {
+ return
+ }
+
+ resetActivity()
+ }
Review Comment:
`handleActivityEvent` calls `resetActivity()` on every mousemove/scroll/keydown, which triggers React state updates and re-renders at extremely high frequency. The feature requirements call for debounced listeners; adding a small throttle here avoids unnecessary work while preserving correctness.
##########
web-v2/web/src/lib/provider/IdleSessionProvider.js:
##########
@@ -0,0 +1,253 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+'use client'
+
+import { useEffect, useCallback, useRef, useState } from 'react'
+import { useRouter, usePathname } from 'next/navigation'
+import { useAppDispatch, useAppSelector } from '@/lib/hooks/useStore'
+import { useIdleTimeout } from '@/lib/hooks/useIdleTimeout'
+import { useBroadcastChannel } from '@/lib/hooks/useBroadcastChannel'
+import { logoutAction } from '@/lib/store/auth'
+import IdleSessionContext from './IdleSessionContext'
+import IdleWarningModal from '@/components/IdleWarningModal'
+
+/**
+ * Default idle timeout: 15 minutes in milliseconds.
+ * Overridable via NEXT_PUBLIC_IDLE_TIMEOUT_MS environment variable.
+ */
+const DEFAULT_IDLE_TIMEOUT_MS = (() => {
+ const envVal = process.env.NEXT_PUBLIC_IDLE_TIMEOUT_MS
+ const parsed = envVal ? Number(envVal) : NaN
+
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 15 * 60 * 1000
+})()
+
+/**
+ * Default warning lead time: 60 seconds in milliseconds.
+ * Overridable via NEXT_PUBLIC_IDLE_WARNING_LEAD_MS environment variable.
+ */
+const DEFAULT_WARNING_LEAD_MS = (() => {
+ const envVal = process.env.NEXT_PUBLIC_IDLE_WARNING_LEAD_MS
+ const parsed = envVal ? Number(envVal) : NaN
+
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 60 * 1000
+})()
+
+/**
+ * Converts milliseconds to seconds, rounded up.
+ */
+function msToSeconds(ms) {
+ return Math.ceil(ms / 1000)
+}
+
+/**
+ * IdleSessionProvider manages the idle timeout state machine and cross-tab
+ * coordination (IST-REQ-001 through IST-REQ-006).
+ *
+ * State machine: active → warning → expired
+ *
+ * - ACTIVE: Normal operation, idle timer is running
+ * - WARNING: Warning lead time has elapsed, modal is shown with countdown
+ * - EXPIRED: Timeout reached, logout is triggered
+ *
+ * @param {Object} props
+ * @param {React.ReactNode} props.children
+ * @param {number} [props.idleTimeoutMs] - Idle timeout in milliseconds (default: 15 min)
+ * @param {number} [props.warningLeadMs] - Warning lead time in milliseconds (default: 60s)
+ */
+export default function IdleSessionProvider({
+ children,
+ idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS,
+ warningLeadMs = DEFAULT_WARNING_LEAD_MS
+}) {
+ const router = useRouter()
+ const pathname = usePathname()
+ const dispatch = useAppDispatch()
+ const authType = useAppSelector(state => state.auth.authType)
+ const authToken = useAppSelector(state => state.auth.authToken)
+
+ // Only enable idle timeout when the user is authenticated and not on login page
+ const isAuthenticated = authType === 'simple' ? !!sessionStorage.getItem('simpleAuthUser') : !!authToken
+ const isLoginPage = pathname === '/login'
+
+ const [state, setState] = useState('active')
+ const [warningCountdown, setWarningCountdown] = useState(msToSeconds(warningLeadMs))
+ const loggedOutRef = useRef(false)
+ const wasAuthenticatedRef = useRef(isAuthenticated)
+
+ const {
+ isIdle,
+ resetActivity: resetIdleActivity,
+ idleTimeRemaining
+ } = useIdleTimeout({
+ idleTimeoutMs: isAuthenticated ? idleTimeoutMs : Number.MAX_SAFE_INTEGER,
+
+ // Pause DOM activity detection during warning state so the modal stays
+ // visible until the user explicitly clicks "Stay signed in" or "Sign out now"
+ paused: state === 'warning'
+ })
+
+ const { sendMessage, onMessage } = useBroadcastChannel()
Review Comment:
The new idle-timeout state machine + cross-tab sync (IdleSessionProvider/useIdleTimeout/useBroadcastChannel) introduces substantial user-facing auth behavior, but there are no unit tests validating the state transitions (active→warning→expired), countdown behavior, cross-tab message handling, and logout side-effects. The web-v2 UI already uses Vitest (e.g., auth provider tests), so these behaviors should be covered to prevent regressions.
##########
web-v2/web/src/lib/provider/IdleSessionProvider.js:
##########
@@ -0,0 +1,253 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+'use client'
+
+import { useEffect, useCallback, useRef, useState } from 'react'
+import { useRouter, usePathname } from 'next/navigation'
+import { useAppDispatch, useAppSelector } from '@/lib/hooks/useStore'
+import { useIdleTimeout } from '@/lib/hooks/useIdleTimeout'
+import { useBroadcastChannel } from '@/lib/hooks/useBroadcastChannel'
+import { logoutAction } from '@/lib/store/auth'
+import IdleSessionContext from './IdleSessionContext'
+import IdleWarningModal from '@/components/IdleWarningModal'
+
+/**
+ * Default idle timeout: 15 minutes in milliseconds.
+ * Overridable via NEXT_PUBLIC_IDLE_TIMEOUT_MS environment variable.
+ */
+const DEFAULT_IDLE_TIMEOUT_MS = (() => {
+ const envVal = process.env.NEXT_PUBLIC_IDLE_TIMEOUT_MS
+ const parsed = envVal ? Number(envVal) : NaN
+
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 15 * 60 * 1000
+})()
+
+/**
+ * Default warning lead time: 60 seconds in milliseconds.
+ * Overridable via NEXT_PUBLIC_IDLE_WARNING_LEAD_MS environment variable.
+ */
+const DEFAULT_WARNING_LEAD_MS = (() => {
+ const envVal = process.env.NEXT_PUBLIC_IDLE_WARNING_LEAD_MS
+ const parsed = envVal ? Number(envVal) : NaN
+
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 60 * 1000
+})()
+
+/**
+ * Converts milliseconds to seconds, rounded up.
+ */
+function msToSeconds(ms) {
+ return Math.ceil(ms / 1000)
+}
+
+/**
+ * IdleSessionProvider manages the idle timeout state machine and cross-tab
+ * coordination (IST-REQ-001 through IST-REQ-006).
+ *
+ * State machine: active → warning → expired
+ *
+ * - ACTIVE: Normal operation, idle timer is running
+ * - WARNING: Warning lead time has elapsed, modal is shown with countdown
+ * - EXPIRED: Timeout reached, logout is triggered
+ *
+ * @param {Object} props
+ * @param {React.ReactNode} props.children
+ * @param {number} [props.idleTimeoutMs] - Idle timeout in milliseconds (default: 15 min)
+ * @param {number} [props.warningLeadMs] - Warning lead time in milliseconds (default: 60s)
+ */
+export default function IdleSessionProvider({
+ children,
+ idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS,
+ warningLeadMs = DEFAULT_WARNING_LEAD_MS
+}) {
+ const router = useRouter()
+ const pathname = usePathname()
+ const dispatch = useAppDispatch()
+ const authType = useAppSelector(state => state.auth.authType)
+ const authToken = useAppSelector(state => state.auth.authToken)
+
+ // Only enable idle timeout when the user is authenticated and not on login page
+ const isAuthenticated = authType === 'simple' ? !!sessionStorage.getItem('simpleAuthUser') : !!authToken
+ const isLoginPage = pathname === '/login'
+
+ const [state, setState] = useState('active')
+ const [warningCountdown, setWarningCountdown] = useState(msToSeconds(warningLeadMs))
+ const loggedOutRef = useRef(false)
+ const wasAuthenticatedRef = useRef(isAuthenticated)
+
+ const {
+ isIdle,
+ resetActivity: resetIdleActivity,
+ idleTimeRemaining
+ } = useIdleTimeout({
+ idleTimeoutMs: isAuthenticated ? idleTimeoutMs : Number.MAX_SAFE_INTEGER,
+
+ // Pause DOM activity detection during warning state so the modal stays
+ // visible until the user explicitly clicks "Stay signed in" or "Sign out now"
+ paused: state === 'warning'
+ })
+
+ const { sendMessage, onMessage } = useBroadcastChannel()
+
+ // Track warning threshold: when idleTimeRemaining drops below warningLeadMs, show warning
+ const warningThreshold = warningLeadMs
+
+ // State machine transitions
+ useEffect(() => {
+ if (!isAuthenticated) {
+ return
+ }
+
+ if (isIdle) {
+ // Idle time exceeded full timeout → expired
+ setState('expired')
+ } else if (idleTimeRemaining <= warningThreshold && idleTimeRemaining > 0) {
+ // Within warning window
+ if (state === 'active') {
+ setState('warning')
+ setWarningCountdown(msToSeconds(idleTimeRemaining))
+ }
+ } else if (idleTimeRemaining > warningThreshold) {
+ // Back above warning threshold (activity detected)
+ if (state !== 'active') {
+ setState('active')
+ }
+ }
+ }, [isIdle, idleTimeRemaining, warningThreshold, isAuthenticated])
+
+ // Update warning countdown based on remaining idle time
+ useEffect(() => {
+ if (state === 'warning') {
+ setWarningCountdown(msToSeconds(idleTimeRemaining))
+ }
+ }, [state, idleTimeRemaining])
+
+ // Handle logout (either from timeout or "Sign out now")
+ const handleLogout = useCallback(() => {
+ if (loggedOutRef.current) {
+ return
+ }
+
+ loggedOutRef.current = true
+ setState('expired')
+
+ // Broadcast logout with reason to other tabs
+ sendMessage({ type: 'logout', reason: 'inactive', timestamp: Date.now() })
+
+ // Dispatch logout action (handles both OAuth and simple auth)
+ // Pass reason to show inactivity message on login page
+ dispatch(logoutAction({ router, reason: 'inactive' }))
+ }, [dispatch, router, sendMessage])
+
+ // Handle "Stay signed in" action (IST-REQ-003)
+ const handleStaySignedIn = useCallback(() => {
+ setState('active')
+ resetIdleActivity()
+ setWarningCountdown(msToSeconds(warningLeadMs))
+
+ // Broadcast stay_signed_in to other tabs so they also dismiss warning and stay logged in
+ sendMessage({ type: 'stay_signed_in', timestamp: Date.now() })
+ }, [resetIdleActivity, warningLeadMs, sendMessage])
+
+ // Cross-tab message handling (IST-REQ-005)
+ useEffect(() => {
+ onMessage(message => {
+ if (message.type === 'activity') {
+ // Activity in another tab resets this tab's idle timer and dismisses warning modal
+ resetIdleActivity()
+ if (state === 'warning') {
+ setState('active')
+ setWarningCountdown(msToSeconds(warningLeadMs))
+ }
+ } else if (message.type === 'stay_signed_in') {
+ // Another tab clicked "Stay signed in" — dismiss warning and stay logged in
+ resetIdleActivity()
+ if (state === 'warning') {
+ setState('active')
+ setWarningCountdown(msToSeconds(warningLeadMs))
+ }
+ } else if (message.type === 'logout') {
+ // Another tab triggered logout — redirect without calling signOut again
+ if (!loggedOutRef.current) {
+ loggedOutRef.current = true
+ const loginUrl = message.reason ? `/login?reason=${message.reason}` : '/login'
+ router.push(loginUrl)
+ }
+ }
+ })
+ }, [onMessage, resetIdleActivity, router, state, warningLeadMs])
+
+ // Broadcast activity to other tabs when this tab has activity (IST-REQ-005)
+ // The idle hook already resets on activity; we just need to broadcast
+ const lastBroadcastRef = useRef(0)
+ useEffect(() => {
+ if (!isAuthenticated) {
+ return
+ }
+
+ // When idleTimeRemaining is reset (activity detected), broadcast to other tabs
+ // We use a throttled approach: check if enough time has passed since last broadcast
+ const now = Date.now()
+
+ if (now - lastBroadcastRef.current >= 2000) {
+ sendMessage({ type: 'activity', timestamp: now })
+ lastBroadcastRef.current = now
+ }
+ }, [idleTimeRemaining, isAuthenticated, sendMessage])
Review Comment:
This effect broadcasts an `activity` message every ~2s because `idleTimeRemaining` changes continuously while the user is idle. That will continuously reset other tabs' timers and effectively disable the inactivity timeout across tabs. Broadcast only when the idle timer is actually reset (i.e., when remaining time jumps up).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11630] web-v2(UI): Inactivity Session Timeout and Forced Re-authentication [gravitino]
Posted by "mchades (via GitHub)" <gi...@apache.org>.
mchades merged PR #11643:
URL: https://github.com/apache/gravitino/pull/11643
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11630] web-v2(UI): Inactivity Session Timeout and Forced Re-authentication [gravitino]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #11643:
URL: https://github.com/apache/gravitino/pull/11643#discussion_r3411842892
##########
web-v2/web/src/lib/hooks/useIdleTimeout.js:
##########
@@ -0,0 +1,134 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+'use client'
+
+import { useEffect, useRef, useCallback, useState } from 'react'
+
+/**
+ * DOM events that constitute genuine user interaction and reset the idle timer.
+ * Events fired while the document is hidden are ignored.
+ */
+const ACTIVITY_EVENTS = ['mousemove', 'mousedown', 'keydown', 'touchstart', 'scroll', 'visibilitychange']
+
+/**
+ * Default idle timeout: 15 minutes in milliseconds.
+ * Overridable via NEXT_PUBLIC_IDLE_TIMEOUT_MS environment variable.
+ */
+const DEFAULT_IDLE_TIMEOUT_MS = (() => {
+ const envVal = process.env.NEXT_PUBLIC_IDLE_TIMEOUT_MS
+ const parsed = envVal ? Number(envVal) : NaN
+
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 15 * 60 * 1000
+})()
+
+/**
+ * Custom hook for idle timeout detection using DOM event listeners and
+ * requestAnimationFrame polling. Provides full control over timer reset
+ * for "Stay signed in" and cross-tab synchronization.
+ *
+ * @param {Object} options
+ * @param {number} [options.idleTimeoutMs] - Idle timeout in milliseconds (default: 15 minutes)
+ * @param {boolean} [options.paused] - When true, DOM activity events are ignored (timer keeps running).
+ * Used to keep the warning modal visible until the user explicitly acts.
+ * Programmatic calls to resetActivity() still work when paused.
+ * @returns {{ isIdle: boolean, resetActivity: () => void, idleTimeRemaining: number }}
+ */
+export function useIdleTimeout({ idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS, paused = false } = {}) {
+ const lastActivityRef = useRef(null)
+ const rafIdRef = useRef(null)
+ const pausedRef = useRef(paused)
+ const [isIdle, setIsIdle] = useState(false)
+ const [idleTimeRemaining, setIdleTimeRemaining] = useState(idleTimeoutMs)
+
+ // Keep pausedRef in sync with the latest paused prop
+ useEffect(() => {
+ pausedRef.current = paused
+ }, [paused])
+
+ const resetActivity = useCallback(() => {
+ lastActivityRef.current = Date.now()
+ setIsIdle(false)
+ setIdleTimeRemaining(idleTimeoutMs)
+ }, [idleTimeoutMs])
+
+ useEffect(() => {
+ // Initialize the last activity timestamp on mount
+ lastActivityRef.current = Date.now()
+
+ const handleActivityEvent = event => {
+ // Ignore events fired while the tab is hidden (IST-REQ-001)
+ if (document.hidden) {
+ return
+ }
+
+ // When paused (e.g. warning modal is shown), ignore DOM activity
+ // so the modal stays visible until the user explicitly acts
+ if (pausedRef.current) {
+ return
+ }
+
+ resetActivity()
+ }
+
+ // Register activity event listeners
+ ACTIVITY_EVENTS.forEach(eventName => {
+ if (eventName === 'visibilitychange') {
+ document.addEventListener(eventName, handleActivityEvent, { passive: true })
+ } else {
+ window.addEventListener(eventName, handleActivityEvent, { passive: true })
+ }
+ })
+
+ // requestAnimationFrame polling loop to check idle state
+ const checkIdle = () => {
+ const now = Date.now()
+ const elapsed = now - lastActivityRef.current
+ const remaining = Math.max(0, idleTimeoutMs - elapsed)
+
+ setIdleTimeRemaining(remaining)
+
+ if (elapsed >= idleTimeoutMs) {
+ setIsIdle(true)
+ }
+
+ rafIdRef.current = requestAnimationFrame(checkIdle)
+ }
+
+ rafIdRef.current = requestAnimationFrame(checkIdle)
+
Review Comment:
`useIdleTimeout` runs a requestAnimationFrame loop and calls `setIdleTimeRemaining()` on every frame. Since this hook is used high in the provider tree, this can trigger app-wide re-renders at ~60fps (high CPU/battery usage). Consider throttling state updates (e.g., update only when the remaining second changes) and skipping the polling loop entirely when the caller passes `Number.MAX_SAFE_INTEGER` (your unauthenticated sentinel).
##########
web-v2/web/src/lib/provider/IdleSessionProvider.js:
##########
@@ -0,0 +1,241 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+'use client'
+
+import { useEffect, useCallback, useRef, useState } from 'react'
+import { useRouter, usePathname } from 'next/navigation'
+import { useAppDispatch, useAppSelector } from '@/lib/hooks/useStore'
+import { useIdleTimeout } from '@/lib/hooks/useIdleTimeout'
+import { useBroadcastChannel } from '@/lib/hooks/useBroadcastChannel'
+import { logoutAction } from '@/lib/store/auth'
+import IdleSessionContext from './IdleSessionContext'
+import IdleWarningModal from '@/components/IdleWarningModal'
+
+/**
+ * Default idle timeout: 15 minutes in milliseconds.
+ * Overridable via NEXT_PUBLIC_IDLE_TIMEOUT_MS environment variable.
+ */
+const DEFAULT_IDLE_TIMEOUT_MS = (() => {
+ const envVal = process.env.NEXT_PUBLIC_IDLE_TIMEOUT_MS
+ const parsed = envVal ? Number(envVal) : NaN
+
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 15 * 60 * 1000
+})()
+
+/**
+ * Default warning lead time: 60 seconds in milliseconds.
+ * Overridable via NEXT_PUBLIC_IDLE_WARNING_LEAD_MS environment variable.
+ */
+const DEFAULT_WARNING_LEAD_MS = (() => {
+ const envVal = process.env.NEXT_PUBLIC_IDLE_WARNING_LEAD_MS
+ const parsed = envVal ? Number(envVal) : NaN
+
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 60 * 1000
+})()
+
+/**
+ * Converts milliseconds to seconds, rounded up.
+ */
+function msToSeconds(ms) {
+ return Math.ceil(ms / 1000)
+}
+
+/**
+ * IdleSessionProvider manages the idle timeout state machine and cross-tab
+ * coordination (IST-REQ-001 through IST-REQ-006).
+ *
+ * State machine: active → warning → expired
+ *
+ * - ACTIVE: Normal operation, idle timer is running
+ * - WARNING: Warning lead time has elapsed, modal is shown with countdown
+ * - EXPIRED: Timeout reached, logout is triggered
+ *
+ * @param {Object} props
+ * @param {React.ReactNode} props.children
+ * @param {number} [props.idleTimeoutMs] - Idle timeout in milliseconds (default: 15 min)
+ * @param {number} [props.warningLeadMs] - Warning lead time in milliseconds (default: 60s)
+ */
+export default function IdleSessionProvider({
+ children,
+ idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS,
+ warningLeadMs = DEFAULT_WARNING_LEAD_MS
+}) {
+ const router = useRouter()
+ const pathname = usePathname()
+ const dispatch = useAppDispatch()
+ const authType = useAppSelector(state => state.auth.authType)
+ const authToken = useAppSelector(state => state.auth.authToken)
+
+ // Only enable idle timeout when the user is authenticated and not on login page
+ const isAuthenticated = authType === 'simple' ? !!sessionStorage.getItem('simpleAuthUser') : !!authToken
+ const isLoginPage = pathname === '/login'
+
+ const [state, setState] = useState('active')
+ const [warningCountdown, setWarningCountdown] = useState(msToSeconds(warningLeadMs))
+ const loggedOutRef = useRef(false)
+
+ const {
+ isIdle,
+ resetActivity: resetIdleActivity,
+ idleTimeRemaining
+ } = useIdleTimeout({
+ idleTimeoutMs: isAuthenticated ? idleTimeoutMs : Number.MAX_SAFE_INTEGER,
+
+ // Pause DOM activity detection during warning state so the modal stays
+ // visible until the user explicitly clicks "Stay signed in" or "Sign out now"
+ paused: state === 'warning'
+ })
+
+ const { sendMessage, onMessage, tabId } = useBroadcastChannel()
+
+ // Track warning threshold: when idleTimeRemaining drops below warningLeadMs, show warning
+ const warningThreshold = warningLeadMs
+
+ // State machine transitions
+ useEffect(() => {
+ if (!isAuthenticated) {
+ return
+ }
+
+ if (isIdle) {
+ // Idle time exceeded full timeout → expired
+ setState('expired')
+ } else if (idleTimeRemaining <= warningThreshold && idleTimeRemaining > 0) {
+ // Within warning window
+ if (state === 'active') {
+ setState('warning')
+ setWarningCountdown(msToSeconds(idleTimeRemaining))
+ }
+ } else if (idleTimeRemaining > warningThreshold) {
+ // Back above warning threshold (activity detected)
+ if (state !== 'active') {
+ setState('active')
+ }
+ }
+ }, [isIdle, idleTimeRemaining, warningThreshold, isAuthenticated])
+
+ // Update warning countdown based on remaining idle time
+ useEffect(() => {
+ if (state === 'warning') {
+ setWarningCountdown(msToSeconds(idleTimeRemaining))
+ }
+ }, [state, idleTimeRemaining])
+
+ // Handle logout (either from timeout or "Sign out now")
+ const handleLogout = useCallback(() => {
+ if (loggedOutRef.current) {
+ return
+ }
+
+ loggedOutRef.current = true
+ setState('expired')
+
+ // Broadcast logout to other tabs
+ sendMessage({ type: 'logout', timestamp: Date.now() })
+
+ // Dispatch logout action (handles both OAuth and simple auth)
+ // Pass reason to show inactivity message on login page
+ dispatch(logoutAction({ router, reason: 'inactive' }))
+ }, [dispatch, router, sendMessage])
+
+ // Handle "Stay signed in" action (IST-REQ-003)
+ const handleStaySignedIn = useCallback(() => {
+ setState('active')
+ resetIdleActivity()
+ setWarningCountdown(msToSeconds(warningLeadMs))
+
+ // Broadcast stay_signed_in to other tabs so they also dismiss warning and stay logged in
+ sendMessage({ type: 'stay_signed_in', timestamp: Date.now() })
+ }, [resetIdleActivity, warningLeadMs, sendMessage])
+
+ // Cross-tab message handling (IST-REQ-005)
+ useEffect(() => {
+ onMessage(message => {
+ if (message.type === 'activity') {
+ // Activity in another tab resets this tab's idle timer and dismisses warning modal
+ resetIdleActivity()
+ if (state === 'warning') {
+ setState('active')
+ setWarningCountdown(msToSeconds(warningLeadMs))
+ }
+ } else if (message.type === 'stay_signed_in') {
+ // Another tab clicked "Stay signed in" — dismiss warning and stay logged in
+ resetIdleActivity()
+ if (state === 'warning') {
+ setState('active')
+ setWarningCountdown(msToSeconds(warningLeadMs))
+ }
+ } else if (message.type === 'logout') {
+ // Another tab triggered logout — redirect without calling signOut again
+ if (!loggedOutRef.current) {
+ loggedOutRef.current = true
+ router.push('/login?reason=inactive')
+ }
+ }
Review Comment:
On receiving a cross-tab `logout` message, this tab always redirects to `/login?reason=inactive`. That will incorrectly show the inactivity alert for manual logouts and doesn’t align with `logoutAction`’s optional `reason` behavior. Use an optional `message.reason` and default to plain `/login` when it’s not provided (and encode it for safety).
##########
web-v2/web/src/lib/provider/IdleSessionProvider.js:
##########
@@ -0,0 +1,241 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+'use client'
+
+import { useEffect, useCallback, useRef, useState } from 'react'
+import { useRouter, usePathname } from 'next/navigation'
+import { useAppDispatch, useAppSelector } from '@/lib/hooks/useStore'
+import { useIdleTimeout } from '@/lib/hooks/useIdleTimeout'
+import { useBroadcastChannel } from '@/lib/hooks/useBroadcastChannel'
+import { logoutAction } from '@/lib/store/auth'
+import IdleSessionContext from './IdleSessionContext'
+import IdleWarningModal from '@/components/IdleWarningModal'
+
+/**
+ * Default idle timeout: 15 minutes in milliseconds.
+ * Overridable via NEXT_PUBLIC_IDLE_TIMEOUT_MS environment variable.
+ */
+const DEFAULT_IDLE_TIMEOUT_MS = (() => {
+ const envVal = process.env.NEXT_PUBLIC_IDLE_TIMEOUT_MS
+ const parsed = envVal ? Number(envVal) : NaN
+
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 15 * 60 * 1000
+})()
+
+/**
+ * Default warning lead time: 60 seconds in milliseconds.
+ * Overridable via NEXT_PUBLIC_IDLE_WARNING_LEAD_MS environment variable.
+ */
+const DEFAULT_WARNING_LEAD_MS = (() => {
+ const envVal = process.env.NEXT_PUBLIC_IDLE_WARNING_LEAD_MS
+ const parsed = envVal ? Number(envVal) : NaN
+
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 60 * 1000
+})()
+
+/**
+ * Converts milliseconds to seconds, rounded up.
+ */
+function msToSeconds(ms) {
+ return Math.ceil(ms / 1000)
+}
+
+/**
+ * IdleSessionProvider manages the idle timeout state machine and cross-tab
+ * coordination (IST-REQ-001 through IST-REQ-006).
+ *
+ * State machine: active → warning → expired
+ *
+ * - ACTIVE: Normal operation, idle timer is running
+ * - WARNING: Warning lead time has elapsed, modal is shown with countdown
+ * - EXPIRED: Timeout reached, logout is triggered
+ *
+ * @param {Object} props
+ * @param {React.ReactNode} props.children
+ * @param {number} [props.idleTimeoutMs] - Idle timeout in milliseconds (default: 15 min)
+ * @param {number} [props.warningLeadMs] - Warning lead time in milliseconds (default: 60s)
+ */
+export default function IdleSessionProvider({
+ children,
+ idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS,
+ warningLeadMs = DEFAULT_WARNING_LEAD_MS
+}) {
+ const router = useRouter()
+ const pathname = usePathname()
+ const dispatch = useAppDispatch()
+ const authType = useAppSelector(state => state.auth.authType)
+ const authToken = useAppSelector(state => state.auth.authToken)
+
+ // Only enable idle timeout when the user is authenticated and not on login page
+ const isAuthenticated = authType === 'simple' ? !!sessionStorage.getItem('simpleAuthUser') : !!authToken
+ const isLoginPage = pathname === '/login'
+
+ const [state, setState] = useState('active')
+ const [warningCountdown, setWarningCountdown] = useState(msToSeconds(warningLeadMs))
+ const loggedOutRef = useRef(false)
+
+ const {
+ isIdle,
+ resetActivity: resetIdleActivity,
+ idleTimeRemaining
+ } = useIdleTimeout({
+ idleTimeoutMs: isAuthenticated ? idleTimeoutMs : Number.MAX_SAFE_INTEGER,
+
+ // Pause DOM activity detection during warning state so the modal stays
+ // visible until the user explicitly clicks "Stay signed in" or "Sign out now"
+ paused: state === 'warning'
+ })
+
+ const { sendMessage, onMessage, tabId } = useBroadcastChannel()
+
+ // Track warning threshold: when idleTimeRemaining drops below warningLeadMs, show warning
+ const warningThreshold = warningLeadMs
+
+ // State machine transitions
+ useEffect(() => {
+ if (!isAuthenticated) {
+ return
+ }
+
+ if (isIdle) {
+ // Idle time exceeded full timeout → expired
+ setState('expired')
+ } else if (idleTimeRemaining <= warningThreshold && idleTimeRemaining > 0) {
+ // Within warning window
+ if (state === 'active') {
+ setState('warning')
+ setWarningCountdown(msToSeconds(idleTimeRemaining))
+ }
+ } else if (idleTimeRemaining > warningThreshold) {
+ // Back above warning threshold (activity detected)
+ if (state !== 'active') {
+ setState('active')
+ }
+ }
+ }, [isIdle, idleTimeRemaining, warningThreshold, isAuthenticated])
+
+ // Update warning countdown based on remaining idle time
+ useEffect(() => {
+ if (state === 'warning') {
+ setWarningCountdown(msToSeconds(idleTimeRemaining))
+ }
+ }, [state, idleTimeRemaining])
+
+ // Handle logout (either from timeout or "Sign out now")
+ const handleLogout = useCallback(() => {
+ if (loggedOutRef.current) {
+ return
+ }
+
+ loggedOutRef.current = true
+ setState('expired')
+
+ // Broadcast logout to other tabs
+ sendMessage({ type: 'logout', timestamp: Date.now() })
+
Review Comment:
The `logout` broadcast message doesn’t include a reason, but the login page behavior depends on it. If you want the inactivity alert only for idle timeouts, include `reason: 'inactive'` in the broadcast from the idle-timeout path (and let manual logout broadcasts omit it).
##########
web-v2/web/src/components/IdleWarningModal.js:
##########
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+'use client'
+
+import { useState, useEffect } from 'react'
+import { Modal, Typography, Button, Space, Flex } from 'antd'
+import { ClockCircleOutlined } from '@ant-design/icons'
Review Comment:
`Space` is imported from `antd` but never used, which will fail linting under typical eslint rules.
##########
web-v2/web/src/lib/store/auth/index.js:
##########
@@ -96,76 +95,75 @@ export const loginAction = createAsyncThunk('auth/loginAction', async ({ params,
return { token: access_token, expired: expires_in }
})
-export const logoutAction = createAsyncThunk('auth/logoutAction', async ({ router }, { getState, dispatch }) => {
- // Clear provider authentication data first
- if (getState().auth.authType === 'oauth') {
- try {
- const provider = await oauthProviderFactory.getProvider()
- if (provider) {
- // For OIDC providers, use signoutRedirect to end IdP session
- if (provider.getUserManager) {
- const userManager = provider.getUserManager()
- if (userManager) {
- // Read id_token before clearing — needed for id_token_hint
- const user = await userManager.getUser()
-
- // Clear OIDC user data from store
- await provider.clearAuthData()
-
- // Clear legacy auth tokens
- localStorage.removeItem('accessToken')
- localStorage.removeItem('authParams')
- localStorage.removeItem('expiredIn')
- localStorage.removeItem('isIdle')
- localStorage.removeItem('version')
-
- dispatch(clearIntervalId())
- dispatch(setAuthToken(''))
-
- // Redirect to IdP logout endpoint — browser navigates away, must be last
- await userManager.signoutRedirect({ id_token_hint: user?.id_token })
-
- return { token: null } // unreachable — browser navigates away
+export const logoutAction = createAsyncThunk(
+ 'auth/logoutAction',
+ async ({ router, reason }, { getState, dispatch }) => {
+ // Clear provider authentication data first
+ if (getState().auth.authType === 'oauth') {
+ try {
+ const provider = await oauthProviderFactory.getProvider()
+ if (provider) {
+ // For OIDC providers, use signoutRedirect to end IdP session
+ if (provider.getUserManager) {
+ const userManager = provider.getUserManager()
+ if (userManager) {
+ // Read id_token before clearing — needed for id_token_hint
+ const user = await userManager.getUser()
+
+ // Clear OIDC user data from store
+ await provider.clearAuthData()
+
+ // Clear legacy auth tokens
+ localStorage.removeItem('accessToken')
+ localStorage.removeItem('authParams')
+ localStorage.removeItem('expiredIn')
+ localStorage.removeItem('version')
+
+ dispatch(clearIntervalId())
+ dispatch(setAuthToken(''))
+
+ // Redirect to IdP logout endpoint — browser navigates away, must be last
+ await userManager.signoutRedirect({ id_token_hint: user?.id_token })
+
+ return { token: null } // unreachable — browser navigates away
+ }
}
- }
- await provider.clearAuthData()
+ await provider.clearAuthData()
+ }
+ } catch (error) {
+ console.warn('[Logout Action] Provider cleanup failed:', error)
}
- } catch (error) {
- console.warn('[Logout Action] Provider cleanup failed:', error)
+
+ // Clear legacy auth tokens
+ localStorage.removeItem('accessToken')
+ localStorage.removeItem('authParams')
+ localStorage.removeItem('expiredIn')
+ localStorage.removeItem('version')
+
+ dispatch(clearIntervalId())
+ dispatch(setAuthToken(''))
+ } else {
+ dispatch(setAuthUser(null))
}
- // Clear legacy auth tokens
- localStorage.removeItem('accessToken')
- localStorage.removeItem('authParams')
- localStorage.removeItem('expiredIn')
- localStorage.removeItem('isIdle')
- localStorage.removeItem('version')
-
- dispatch(clearIntervalId())
- dispatch(setAuthToken(''))
- } else {
- dispatch(setAuthUser(null))
- }
- await router.push('/login')
+ // Reset provider factory to ensure clean state for next login
+ oauthProviderFactory.reset()
- return { token: null }
-})
+ // Build login URL with optional reason parameter
+ const loginUrl = reason ? `/login?reason=${reason}` : '/login'
+ await router.push(loginUrl)
Review Comment:
`reason` is interpolated directly into the query string (`/login?reason=${reason}`), which will break for values containing `&`, `?`, spaces, etc. Encode it before building the URL.
##########
web-v2/web/src/lib/auth/providers/factory.js:
##########
@@ -118,6 +118,15 @@ class OAuthProviderFactory {
return provider.getType()
}
+
+ /**
+ * Reset the factory state to force re-initialization on next getProvider() call.
+ * This should be called during logout to ensure clean state for next login.
+ */
+ reset() {
+ this.currentProvider = null
+ this.configPromise = null
+ }
Review Comment:
New `reset()` behavior in `OAuthProviderFactory` should be covered by the existing `factory.test.js` suite (e.g., verify `reset()` clears cached provider/configPromise and forces a fresh `/configs` fetch on the next `getProvider()` call).
##########
web-v2/web/src/components/IdleWarningModal.js:
##########
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+'use client'
+
+import { useState, useEffect } from 'react'
+import { Modal, Typography, Button, Space, Flex } from 'antd'
+import { ClockCircleOutlined } from '@ant-design/icons'
+
+const { Text } = Typography
+
+/**
+ * Warning modal displayed before idle session timeout (IST-REQ-003).
+ * Shows a live countdown and provides "Stay signed in" / "Sign out now" actions.
+ *
+ * The modal is non-dismissible by clicking the overlay or pressing Escape
+ * to prevent accidental dismissal.
+ *
+ * @param {Object} props
+ * @param {boolean} props.open - Whether the modal is visible
+ * @param {number} props.countdownSeconds - Initial countdown value in seconds
+ * @param {() => void} props.onStaySignedIn - Callback when user clicks "Stay signed in"
+ * @param {() => void} props.onSignOut - Callback when user clicks "Sign out now" or countdown reaches zero
+ */
+export default function IdleWarningModal({ open, countdownSeconds, onStaySignedIn, onSignOut }) {
+ const [remaining, setRemaining] = useState(countdownSeconds)
+
+ // Reset countdown when the modal opens or countdownSeconds changes
+ useEffect(() => {
+ if (open) {
+ setRemaining(countdownSeconds)
+ }
+ }, [open, countdownSeconds])
+
+ // Countdown timer
+ useEffect(() => {
+ if (!open || remaining <= 0) {
+ return
+ }
+
+ const timer = setInterval(() => {
+ setRemaining(prev => {
+ if (prev <= 1) {
+ clearInterval(timer)
+
+ // Auto-logout when countdown reaches zero
+ onSignOut()
+
+ return 0
+ }
+
+ return prev - 1
+ })
+ }, 1000)
+
+ return () => clearInterval(timer)
+ }, [open, remaining, onSignOut])
Review Comment:
The countdown `useEffect` depends on `remaining`, so it tears down and recreates a new interval every second. This adds unnecessary timer churn and can cause subtle drift. Since you’re already using a functional `setRemaining`, the effect can depend only on `open` and `onSignOut`.
##########
web-v2/web/src/lib/provider/IdleSessionProvider.js:
##########
@@ -0,0 +1,241 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+'use client'
+
+import { useEffect, useCallback, useRef, useState } from 'react'
+import { useRouter, usePathname } from 'next/navigation'
+import { useAppDispatch, useAppSelector } from '@/lib/hooks/useStore'
+import { useIdleTimeout } from '@/lib/hooks/useIdleTimeout'
+import { useBroadcastChannel } from '@/lib/hooks/useBroadcastChannel'
+import { logoutAction } from '@/lib/store/auth'
+import IdleSessionContext from './IdleSessionContext'
+import IdleWarningModal from '@/components/IdleWarningModal'
+
+/**
+ * Default idle timeout: 15 minutes in milliseconds.
+ * Overridable via NEXT_PUBLIC_IDLE_TIMEOUT_MS environment variable.
+ */
+const DEFAULT_IDLE_TIMEOUT_MS = (() => {
+ const envVal = process.env.NEXT_PUBLIC_IDLE_TIMEOUT_MS
+ const parsed = envVal ? Number(envVal) : NaN
+
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 15 * 60 * 1000
+})()
+
+/**
+ * Default warning lead time: 60 seconds in milliseconds.
+ * Overridable via NEXT_PUBLIC_IDLE_WARNING_LEAD_MS environment variable.
+ */
+const DEFAULT_WARNING_LEAD_MS = (() => {
+ const envVal = process.env.NEXT_PUBLIC_IDLE_WARNING_LEAD_MS
+ const parsed = envVal ? Number(envVal) : NaN
+
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 60 * 1000
+})()
+
+/**
+ * Converts milliseconds to seconds, rounded up.
+ */
+function msToSeconds(ms) {
+ return Math.ceil(ms / 1000)
+}
+
+/**
+ * IdleSessionProvider manages the idle timeout state machine and cross-tab
+ * coordination (IST-REQ-001 through IST-REQ-006).
+ *
+ * State machine: active → warning → expired
+ *
+ * - ACTIVE: Normal operation, idle timer is running
+ * - WARNING: Warning lead time has elapsed, modal is shown with countdown
+ * - EXPIRED: Timeout reached, logout is triggered
+ *
+ * @param {Object} props
+ * @param {React.ReactNode} props.children
+ * @param {number} [props.idleTimeoutMs] - Idle timeout in milliseconds (default: 15 min)
+ * @param {number} [props.warningLeadMs] - Warning lead time in milliseconds (default: 60s)
+ */
+export default function IdleSessionProvider({
+ children,
+ idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS,
+ warningLeadMs = DEFAULT_WARNING_LEAD_MS
+}) {
+ const router = useRouter()
+ const pathname = usePathname()
+ const dispatch = useAppDispatch()
+ const authType = useAppSelector(state => state.auth.authType)
+ const authToken = useAppSelector(state => state.auth.authToken)
+
+ // Only enable idle timeout when the user is authenticated and not on login page
+ const isAuthenticated = authType === 'simple' ? !!sessionStorage.getItem('simpleAuthUser') : !!authToken
+ const isLoginPage = pathname === '/login'
+
+ const [state, setState] = useState('active')
+ const [warningCountdown, setWarningCountdown] = useState(msToSeconds(warningLeadMs))
+ const loggedOutRef = useRef(false)
+
+ const {
+ isIdle,
+ resetActivity: resetIdleActivity,
+ idleTimeRemaining
+ } = useIdleTimeout({
+ idleTimeoutMs: isAuthenticated ? idleTimeoutMs : Number.MAX_SAFE_INTEGER,
+
+ // Pause DOM activity detection during warning state so the modal stays
+ // visible until the user explicitly clicks "Stay signed in" or "Sign out now"
+ paused: state === 'warning'
+ })
+
+ const { sendMessage, onMessage, tabId } = useBroadcastChannel()
+
Review Comment:
Cross-tab logout is currently only broadcast from `handleLogout()` (idle timeout / modal). Manual logout via other UI paths (e.g. user menu dispatching `logoutAction`) will not notify other tabs, which conflicts with the PR description (“User signs out … other tabs redirect to /login”). You can detect an authenticated→unauthenticated transition in this provider and broadcast a `logout` message, and also drop the unused `tabId` destructuring.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org