1. Front Matter
Title: Session Timeout
Author: Sean Patrick Caintic
Reviewers: Joshua Uriel Tribiana
Updated by: clydetims (Clyde Ador)
Created: February 2026
Status: Approved
References:
• PR #709 — #26: Fix/session timeout closing tab (branch: fix/session-timeout-closing-tab)
• Supabase Auth migration (Phase 4) — docs/clerk_to_supabase_migration/
Issue: [0.2] Session Timeout #68 (tab-closure extension: #26)
Milestone: [0] Auth & Security
2. Introduction & Goals
Problem Summary:
Inactive sessions pose a security risk, especially on shared computers. The system needs to automatically terminate sessions after inactivity while providing users a warning before logout. A second exposure exists on unattended machines where the app is never actively used — the user closes every tab and walks away, then returns later to a still-valid session on a machine anyone could have used in the meantime.
Goals:
• Auto-logout after 20 minutes of inactivity
• Display warning 2 minutes before timeout
• Extend session implicitly through continued activity (single interaction, no button)
• Prevent browser back-button access to cached pages after logout
• Sign the user out when all app tabs have been closed for more than 2 minutes
• Surface a user-facing reason ("Session Expired") on the resulting redirect
Non-Goals:
• Configurable timeout per user (all thresholds are compile-time constants)
• Mobile app session management
• Server-side tab-closure detection (the whole-tab-closed signal is client-side only)
• Revoking the server-side refresh token when tabs close — only the local session is ended
Glossary:
• Inactivity: No mousemove, keydown, click, scroll, or touchstart events
• Tab-closure timeout: 2-minute threshold applied on reopen when every tab was closed
• Discovery grace period: 2-second window after mount during which closure is not recorded
• Heartbeat: 60-second client ping to POST /api/user/heartbeat that maintains "Online Right Now"
3. High-Level Architecture
System Diagram — idle timeout:
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐│ Activity │────▶│ Inactivity │────▶│ Session ││ Monitor │ │ Timer │ │ Termination │└─────────────────┘ └─────────────────┘ └─────────────────┘│ │ ││ ▼ ▼│ ┌─────────────────┐ ┌─────────────────┐└─────────────▶│ Warning Toast │ │ Hard redirect ││ (2-min notice) │ │ to /sign-in │└─────────────────┘ └─────────────────┘
System Diagram — tab-closure timeout (added in PR #709):
┌──────────────────┐ pagehide ┌──────────────────────┐│ Last tab closes │──────────────▶│ BroadcastChannel ││ │ TAB_CLOSED │ peer tab registry │└──────────────────┘ └──────────────────────┘ │ │ activeTabs.size === 0 │ (no peers left) │ AND past 2s grace period ▼ ▼┌──────────────────┐ localStorage│ localStorage │ app_last_tab_closed_at = now│ app_last_tab_... │└──────────────────┘ │ │ app reopened while signed in ▼┌──────────────────┐ elapsed >= 2 min ┌──────────────────────┐│ Elapsed-time │─────────────────────▶│ signOut() + redirect ││ check on mount │ │ + "Session Expired" │└──────────────────┘ └──────────────────────┘
Technologies Used:
• React Hooks / Effects — activity monitoring, timer logic, cross-tab coordination
• BroadcastChannel — in-memory registry of live tabs, same origin
• localStorage — closure timestamp (survives all tabs being closed) and last-activity sync
• sessionStorage — one-shot toast reason that survives the sign-out redirect
• pagehide — reliable last-gasp tab-close signal (fires where beforeunload is unreliable)
• Supabase Auth — session termination (supabase.auth.signOut()); was Clerk signOut() at the time of PR #709
• Sonner (toast) — warning and post-logout messaging (no modal)
4. Detailed Design & Implementation
Data Model / Schema:
No new tables. Timeout state is client-side only; the only server-side footprint is the pre-existing presence log.
Storage | Key / Field | Purpose |
|---|---|---|
localStorage | app_last_tab_closed_at | Epoch ms of the moment the final tab closed. Written by pagehide, consumed and cleared on next mount. |
localStorage | wyzquests_last_active | Epoch ms of the last activity event; the storage event drives cross-tab idle-timer resets. |
sessionStorage | app_session_toast_message | Reason string to surface as a toast on the signed-out page. Read once, then removed. |
sessionStorage | wyzquests_session_timeout | Set by useIdleTimeout when the idle timer fires. Currently write-only (see Known Limitations). |
BroadcastChannel | app_active_tabs_channel | Ephemeral peer-to-peer channel carrying TAB_OPENED / TAB_ALIVE / TAB_CLOSED. |
DB | user_presence_logs | Existing LOGIN / LOGOUT rows written by the heartbeat endpoint. |
API Specification:
• POST /api/user/heartbeat — body { "logout": boolean }. Clears or sets app_users.last_seen_at and records a LOGIN / LOGOUT presence row.
Suppresses a duplicate LOGOUT row when the most recent presence row for the same user is a LOGOUT less than 5 seconds old (added in PR #709 to stop the multi-tab sign-out storm from producing duplicate rows). A suppressed duplicate returns 200 with { message: "Duplicate logout suppressed" }.
• GET /api/user/available-roles — called by RoleSwitcher on mount. A 401 now short-circuits silently (clear the spinner, no error state) instead of throwing, because an expired session legitimately races this fetch.
• No custom endpoint was added for tab-closure detection.
Logic & Workflows:
Timeout Configuration:
Constant | Value | Location |
|---|---|---|
DEFAULT_TIMEOUT_MS | 20 minutes | hooks/quest/useIdleTimeout.ts |
WARNING_BEFORE_MS | 2 minutes | hooks/quest/useIdleTimeout.ts |
TAB_TIMEOUT_MS | 2 minutes | components/IdleTimeoutProvider.tsx |
discoveryGracePeriod | 2 seconds | components/IdleTimeoutProvider.tsx |
Heartbeat interval | 60 seconds | components/IdleTimeoutProvider.tsx |
RECENT_LOGOUT_THRESHOLD_MS | 5 seconds | app/api/user/heartbeat/route.ts |
SESSION_TIMEOUT_MS (login row refresh) | 30 minutes | app/api/user/heartbeat/route.ts |
Monitored Events:
• mousemove
• keydown
• click
• scroll
• touchstart
Idle Timeout Flow:
Timer starts on page load (skipped while !isSignedIn).
Any user activity resets the timer to 20 min and writes wyzquests_last_active.
A storage event from another tab writing wyzquests_last_active resets this tab's timer too, keeping the idle clock consistent across tabs.
At 18 min inactivity → warning toast "Session expiring soon", dismissible, auto-expiring with the countdown.
Any activity dismisses the warning and restarts the full timer.
At 20 min → handleManualSignOut(), then a hard navigation to /sign-in.
Tab-Closure Flow (PR #709):
On mount, if signed in, read app_last_tab_closed_at.
If present, clear it immediately (it is single-use) and compute elapsed time.
If elapsed >= 2 min → handleManualSignOut(reason): stamp the reason into app_session_toast_message, POST a logout heartbeat with keepalive: true, then sign out and redirect. The provider returns early, so no tab channel is opened.
Otherwise the tab opens a BroadcastChannel, generates a random tabId, and seeds activeTabs with just itself.
It broadcasts TAB_OPENED. A tab already listening replies TAB_ALIVE, which is how a newly-opened tab discovers pre-existing siblings.
On pagehide (close, navigate away, or enter bfcache) the tab removes itself, broadcasts TAB_CLOSED, and — only if activeTabs is now empty and more than 2 seconds have elapsed since mount — writes the closure timestamp.
On the next signed-in mount, steps 2–3 evaluate the elapsed time and decide whether the session survives.
Sign-Out Race Handling:
All sign-out paths funnel through handleManualSignOut, which is guarded by an isChangingPage ref. The isSignedIn: true → false interceptor that catches sign-outs initiated elsewhere (e.g. a user button) checks the same ref before firing its final logout heartbeat. Without this guard, one tab-closure sign-out produced two logout heartbeats and two presence rows.
Post-Logout Toast:
After the redirect, the provider is mounted but unauthenticated. The !isSignedIn effect pops app_session_toast_message from sessionStorage, renders it as toast.error("Session Expired", { description }) for 10 seconds, and removes the key so the message shows exactly once. sessionStorage is per-tab, which is correct here because the message is always consumed by the same tab that initiated the sign-out.
Cache Prevention:
Authenticated pages carry Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate plus Pragma: no-cache from middleware.ts. Sign-out uses a hard navigation (window.location.assign("/sign-in")) rather than the client Router so the in-memory Router Cache cannot restore an authenticated page shell (next.config.ts enables a 30-second dynamic stale time).
Key Files:
• components/IdleTimeoutProvider.tsx — orchestrator mounted in app/layout.tsx; owns tab tracking, heartbeats, sign-out, and toasts
• hooks/quest/useIdleTimeout.ts — inactivity timer and activity detection
• app/api/user/heartbeat/route.ts — presence tracking, duplicate-logout suppression
• components/ui/RoleSwitcher.tsx — 401 handling for expired sessions
• middleware.ts — no-cache headers
5. Infrastructure & Operations
Dependencies:
• Supabase Auth — session termination
• @supabase/supabase-js — BroadcastChannel is a browser primitive, no dependency added
Monitoring & Alerting:
No server-side monitoring for timeouts. Client-side only, with one observability signal: user_presence_logs shows LOGIN / LOGOUT transitions per device, and a burst of near-simultaneous LOGOUT rows is the trace of a multi-tab sign-out.
Deployment Plan:
No database migrations and no new environment variables. All state is client-side (localStorage / sessionStorage) and self-migrating — keys are read defensively and ignored when absent, so users can roll out and roll back freely.
A stale app_last_tab_closed_at from an older build is harmless: worst case the next mount signs the user out once.
6. Testing & Quality Assurance
Test Strategy:
• Manual: Idle timeout and warning toast; tab-closure matrix below
• Manual — tab closure: close all tabs, reopen within 2 min (session survives); close all tabs, wait over 2 min, reopen (signed out + "Session Expired" toast); two tabs open, close one (no stamp); close both (stamp written); reopen a tab and close it again within 2 s (no stamp — discovery grace period)
• Manual — races: sign out from two tabs at once (single LOGOUT presence row); sign out from the user button while the idle warning toast is visible
• Manual — cache: after sign-out, press Back (no authenticated shell renders)
• Unit: None. useIdleTimeout timer reset logic is currently untested.
Known Limitations:
• Fixed thresholds — none of the constants are configurable at runtime
• BroadcastChannel is required; browsers without it (or with storage blocked) break the closure stamp, silently disabling the tab-closure timeout
• The 2-second discovery grace period means closing every tab immediately after opening never triggers a sign-out
• app_last_tab_closed_at is origin-wide, so a second browser window opening the app in the same 2-minute window consumes and clears the stamp that the first window would have needed
• A suppressed duplicate logout returns early and therefore does not clear last_seen_at
• wyzquests_session_timeout is written by useIdleTimeout but never read, so an idle-timeout sign-out shows no "Session Expired" toast; only the tab-closure path populates app_session_toast_message
• The timer resets on any activity, including incidental mouse movement
• Tab detection is same-origin and same-browser-profile only; a second device is invisible to it
7. Maintenance & Support
Troubleshooting:
• Warning toast not showing → Check IdleTimeoutProvider is mounted in app/layout.tsx inside SessionProvider
• No "Session Expired" toast → Confirm app_session_toast_message was written before the redirect; the reader only runs while !isSignedIn
• Users signed out unexpectedly on open → Inspect localStorage.app_last_tab_closed_at; a stale or spoofed value older than 2 minutes forces the sign-out
• Duplicate LOGOUT rows still appearing → The 5-second window is the suppression threshold; widen RECENT_LOGOUT_THRESHOLD_MS if the tabs are further apart than that
• Immediate logout on open → Verify system clock accuracy; the elapsed-time comparison uses Date.now()
• Tab closure never triggers → Verify BroadcastChannel availability and that pagehide fires (it does not in some in-app webview environments)
Changelog:
• 1.0 (Feb 2026): Initial implementation — 20-minute idle timeout, warning alert, cache-prevention headers
• 1.1 (Jul 2026): PR #709 — 2-minute all-tabs-closed timeout with BroadcastChannel tab tracking, localStorage closure timestamp, 5-second duplicate-logout suppression in the heartbeat route, "Session Expired" toast, and 401 handling in RoleSwitcher. Auth provider since migrated from Clerk to Supabase Auth.
Document Version
Version | Description | Date |
|---|---|---|
1.0 | Initial version | 2026-04-24 07:46 UTC |
1.0.1 | Minor revisions | 2026-04-24 07:46 UTC |
1.0.2 | Minor revisions | 2026-04-24 08:04 UTC |
1.0.3 | Minor revisions | 2026-04-24 08:05 UTC |
1.0.4 | Minor revisions | 2026-04-24 08:07 UTC |
1.0.5 | Minor revisions | 2026-06-29 08:38 UTC |
1.0.6 | Minor revisions | 2026-06-29 07:43 UTC |
1.0.7 | Minor revisions | 2026-06-29 07:48 UTC |
1.0.8 | Minor revisions | 2026-06-29 09:02 UTC |
1.1 | PR #709 tab-closure timeout | 2026-10-05 11:30 UTC |