Session Timeout

Feature Owner: scorevi (Sean Patrick Caintic)
Module: Auth & Security
Priority: P1
Sprint #12: Fully Implemented
Date: 2026-10-05

EXECUTIVE SUMMARY

What is this feature?

Two independent client-side session terminations, both owned by a single provider
(components/IdleTimeoutProvider.tsx) mounted in the root layout:

  1. Idle timeout — useIdleTimeout tracks user activity and signs the user out via
    Supabase Auth after 20 minutes of inactivity, with a 2-minute warning toast.

  2. Tab-closure timeout (PR #709) — signs the user out when every app tab has been
    closed for more than 2 minutes, using BroadcastChannel tab tracking plus a
    localStorage closure timestamp.

Both also drive presence tracking through POST /api/user/heartbeat, and both end
with a hard navigation to /sign-in so no authenticated page shell can be restored.

Why does it matter?

Without idle timeout, a user who leaves their session open on a shared/public computer
exposes their account. The tab-closure timeout covers the second half of that problem:
a user who closes every tab and walks away returns later to a still-valid session on a
machine anyone could have used in the meantime. For enterprise/edu settings with
compliance requirements, both are security gaps.

What's the current scope?

Fully implemented and app-wide. Because IdleTimeoutProvider is mounted in
app/layout.tsx inside SessionProvider, coverage is no longer limited to the learner
and creator layouts — admin, agency, and reviewer sessions are covered too. The
Clerk-specific code paths were replaced during the Supabase Auth migration (Phase 4).

1. USER PAIN POINT & SOLUTION

Current State (Without Feature)

A user signs in on a library computer, walks away, and the session remains active
indefinitely. Anyone can access their dashboard, quests, or personal data. A user who
closes all tabs and returns the next day finds the session still valid.

Pain Point

Emotional: Anxiety about leaving a session exposed.
Functional: No automatic session termination. Manual sign-out is the only protection.
Business Impact: Compliance risk (especially for education/GDPR). Potential data
breaches from unattended sessions.

Future State (With Feature)

Idle path: after 20 minutes of inactivity the user gets a warning toast; if they do
nothing for 2 more minutes they are signed out and hard-redirected to /sign-in.

Tab-closure path: after every tab has been closed for more than 2 minutes, the next
signed-in page load signs the user out and shows a "Session Expired" toast explaining
why.

Marketing Hook

"Your session is protected. Always."

2. 4D FRAMEWORK MAPPING

Diagnose

N/A — security infrastructure.

Design

N/A — security infrastructure.

Develop

N/A — security infrastructure.

Deliver

N/A — security infrastructure.

3. USER FLOWS

Entry Point

User signs in. IdleTimeoutProvider mounts app-wide, the idle timer starts tracking
activity, and a BroadcastChannel is opened to register this tab.

Success Criteria

  • Idle: 20 minutes without activity signs the user out and hard-redirects to /sign-in.

  • Tab closure: all tabs closed for more than 2 minutes signs the user out on the next
    signed-in load, with a visible reason.

Idle Timeout Flow (happy path)

┌───────────────────────┐ ┌───────────────────────┐ ┌───────────────────────┐
│ Activity Monitor │────▶│ Inactivity Timer │────▶│ Session Termination │
└───────────────────────┘ └───────────────────────┘ └───────────────────────┘
│ │ │
│ ▼ ▼
│ ┌───────────────────────┐ ┌───────────────────────┐
└──────────────────▶│ Warning Toast (2 min) │ │ Redirect to /sign-in │
└───────────────────────┘ └───────────────────────┘
  1. User signs in and browses. The timer resets on mousemove, keydown, click,
    scroll, and touchstart.

  2. Every activity also writes wyzquests_last_active to localStorage.

  3. After 18 minutes of inactivity (20 min − 2 min warning) the onWarning callback
    fires and the "Session expiring soon" toast appears.

  4. Any activity dismisses the toast and restarts the full 20-minute timer.

  5. If nothing happens for 2 more minutes, onTimeout fires → sign out + redirect.

Tab Closure Flow (PR #709)

┌──────────────────────────────┐
│ Last app tab closes │
└──────────────────────────────┘
│ pagehide + TAB_CLOSED broadcast
▼
┌──────────────────────────────┐
│ BroadcastChannel registry │
│ drops the closing tab id │
└──────────────────────────────┘
│ activeTabs.size === 0 AND past 2s grace
▼
┌──────────────────────────────┐
│ localStorage │
│ app_last_tab_closed_at = now │
└──────────────────────────────┘
│ app reopened while signed in
▼
┌──────────────────────────────┐
│ Elapsed-time check on mount │
└──────────────────────────────┘
│
┌───────────────────────┬────────────────────────────────┐
│ │
┌──────────────────────────┐ ┌──────────────────────────┐
│ signOut() + redirect │ │ Session survives │
│+ "Session Expired" toast │ │ (elapsed < 2 min) │
└──────────────────────────┘ └──────────────────────────┘
 
  1. On a signed-in mount, app_last_tab_closed_at is read and immediately cleared
    (single use).

  2. If elapsed >= 2 min, handleManualSignOut(reason) runs and the effect returns
    early — no channel is opened for this tab.

  3. Otherwise the tab opens the app_active_tabs_channel BroadcastChannel, generates a
    random tabId, and seeds activeTabs with itself.

  4. It broadcasts TAB_OPENED. A tab already listening replies TAB_ALIVE, which is how
    a newly-opened tab discovers its pre-existing siblings.

  5. 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.

  6. The 2-second discovery grace period stops a fast refresh or an immediately-closed tab
    from stamping closure before sibling tabs have had a chance to answer.

Edge Cases

  • Multiple tabs, idle path: activity in one tab resets the timer in all tabs via the
    storage event on wyzquests_last_active.

  • Multiple tabs, closure path: closing one of two tabs leaves activeTabs non-empty, so
    no stamp is written and the session survives.

  • Sign-out storm: all sign-out paths funnel through handleManualSignOut, guarded by an
    isChangingPage ref. The isSignedIn: true → false interceptor checks the same ref,
    so one user-initiated sign-out cannot fire two logout heartbeats.

  • Duplicate presence rows: the heartbeat route suppresses a second LOGOUT row when the
    most recent row for that user is a LOGOUT less than 5 seconds old.

  • SSR / storage quota: localStorage write failures are silently caught; the tab still
    works within the current tab.

  • Disabled state: the hook accepts a disabled prop and the provider passes
    disabled: !isSignedIn.

  • iOS Safari bfcache: BfCacheGuard forces a hard reload when pageshow reports
    event.persisted.

Decision Points

  • disabled === true → the hook does nothing and the provider skips all channel and
    heartbeat work.

  • elapsed >= 2 min on mount → sign out with a reason, no tab channel opened.

  • Otherwise → register the tab and continue tracking.

4. INFORMATION ARCHITECTURE

Primary Information (Always visible)

None. The feature is invisible in its normal state; the warning toast only appears
2 minutes before the idle timeout.

Secondary Information

  • "Session expiring soon" warning toast, with the remaining minutes in the description.

  • "Session Expired" error toast after a tab-closure sign-out, carrying the reason.

Actions

  • Primary CTA: any page activity dismisses the warning and extends the session.

  • Secondary actions: N/A — termination is automatic.

5. WIREFRAMES

[Excluded — no dedicated UI beyond the two toasts described above]

6. WORKFLOWS

See the two flow diagrams in section 3.

7. PROTOTYPE

[Excluded — existing implementation]

8. BACKEND SCHEMA

Database Tables

No new tables. The timeout logic is client-side; the server footprint is the
pre-existing presence log.

Table

Column

Purpose

app_users

last_seen_at

Cleared on logout, refreshed by the 60s heartbeat. Drives "Online Right Now".

app_users

metadata.last_device

Merged (not overwritten) with the parsed OS/device on each heartbeat.

user_presence_logs

action, created_at, device_info, agency_id, role

LOGIN / LOGOUT audit rows. Duplicate LOGOUT rows within 5s are suppressed.

Client-Side State

Key

Storage

Purpose

app_last_tab_closed_at

localStorage

Epoch ms of the moment the final tab closed. Written by pagehide, consumed and cleared on the next signed-in mount.

wyzquests_last_active

localStorage

Epoch ms of the last activity event. The storage event drives cross-tab idle-timer resets.

app_session_toast_message

sessionStorage

One-shot reason string rendered as the "Session Expired" toast, then removed.

wyzquests_session_timeout

sessionStorage

Set by useIdleTimeout on idle sign-out. Currently write-only — see Known Limitations.

app_active_tabs_channel

BroadcastChannel

Ephemeral peer-to-peer channel carrying TAB_OPENED / TAB_ALIVE / TAB_CLOSED.

9. API ENDPOINTS

POST /api/user/heartbeat

  • Body: { "logout": boolean }, sent with keepalive: true so it survives page unload.

  • Unauthenticated → 401. Suspended user → rejected via assertNotSuspended.

  • On logout: false — sets last_seen_at, refreshes metadata.last_device, and writes
    a LOGIN row only when there is no prior row, the prior row is a LOGOUT, or the
    prior row is older than 30 minutes.

  • On logout: true — nulls last_seen_at and writes a LOGOUT row, unless the most
    recent row is already a LOGOUT within 5 seconds, in which case it returns
    { message: "Duplicate logout suppressed" } and exits early.

GET /api/user/available-roles

  • Called by RoleSwitcher on mount. A 401 short-circuits silently (spinner cleared,
    no error state) because an expired session legitimately races this fetch.

10. DATA REQUIREMENTS

Frontend Needs

  • hooks/quest/useIdleTimeout.ts — idle timer, activity listeners, cross-tab sync (148 lines).

  • components/IdleTimeoutProvider.tsx — tab registry, heartbeats, sign-out, toasts (193 lines).

  • components/BfCacheGuard.tsx — bfcache back-button guard (35 lines).

  • useAuth() from hooks/auth/useAuth.ts — reads the Supabase session from SessionProvider.

  • useSupabase() — supabase.auth.signOut().

Caching Strategy

N/A — no caching layer involved.

11. PERFORMANCE CONSIDERATIONS

Database Optimization

N/A — presence writes are one row per login/logout transition, not per heartbeat.

API Response Time

N/A for the timeout logic itself — timer operations are O(1) and event listeners use
{ passive: true }. The 60-second heartbeat is a single small POST with no response
handling, and the sign-out heartbeat is fire-and-forget.

12. SECURITY & AUTHORIZATION

Who can access this feature?

Everyone. IdleTimeoutProvider is mounted in app/layout.tsx for all routes, so
learner, creator, admin, agency, and reviewer sessions are all covered.

Authorization Logic

N/A — this is hook behavior, not an authorization boundary. Note that the
service-role-backed heartbeat route reads clerk_id from the authenticated session
(getCurrentSupabaseUser()), never from the request body, so it is not an IDOR surface.

Data Validation

None required — the only input is a boolean logout flag.

13. ERROR HANDLING

Error

Response

supabase.auth.signOut() fails

Error logged to console; onTimeout still fires and the redirect still happens.

Heartbeat POST rejects or is blocked

Caught and ignored (.catch(() => {})). Presence data may be stale; sign-out is never blocked by it.

localStorage write fails (quota, private mode, SSR)

Silently caught — the tab still tracks itself correctly in memory.

BroadcastChannel unavailable

The effect throws before registering pagehide; the tab-closure timeout is silently disabled.

Component unmounts while timers are pending

hasSignedOut ref prevents double sign-out; the useEffect cleanup clears all timers, the pagehide listener, and closes the channel.

Clock skew on reopen

The 2-minute comparison uses Date.now(); a wrong system clock can force or skip a sign-out.

14. TESTING CHECKLIST

Happy Path

  • □ After 20 min inactivity, the user is signed out and hard-redirected to /sign-in.

  • □ Warning toast fires at 18 min (2 min before timeout).

  • □ Any activity (mouse, keyboard, click, scroll, touch) resets the timer.

  • □ Activity in Tab A resets the timer in Tab B (cross-tab sync).

Tab Closure

  • □ Close all tabs, reopen within 2 min → session survives, no toast.

  • □ Close all tabs, wait over 2 min, reopen → signed out + "Session Expired" toast.

  • □ Two tabs open, close one → no closure stamp, no forced sign-out.

  • □ Reopen a tab and close it again within 2 s → no stamp (discovery grace period).

  • □ Sign out from two tabs at once → a single LOGOUT presence row.

Races & Cache

  • □ Sign out from the user button while the idle warning toast is visible → one heartbeat, one toast dismissal.

  • □ After sign-out, pressing Back renders no authenticated page shell.

  • □ iOS Safari bfcache restore after sign-out → forced reload.

Known Gaps

  • □ No automated tests. useIdleTimeout timer reset logic is untested.

  • □ wyzquests_session_timeout is written but never read, so idle sign-outs show no reason toast. Worth a follow-up ticket.

15. OPEN QUESTIONS

  • Should DEFAULT_TIMEOUT_MS (20 min) or TAB_TIMEOUT_MS (2 min) be configurable per role or agency?

  • Should the tab-closure timeout be surfaced anywhere (a countdown the user can see), or is a silent 2-minute grace enough?

  • Should the write-only wyzquests_session_timeout key be wired up so idle sign-outs also show a reason toast?

  • Should the discovery grace period (2 s) be tuned, or should tabs broadcast a presence sweep instead of relying on a timer?

  • What happens when a user has the app open in two browsers? The closure stamp is per-origin and cannot see the second device.

16. OUT OF SCOPE

  • Server-side session expiration enforcement (both timeouts are client-side).

  • Force logout from the admin panel (remote session termination).

  • Configurable timeout per agency/role.

  • Revoking the server-side refresh token when tabs close — only the local session ends.

17. SUCCESS METRICS

  • 100% of sessions auto-terminate after the idle timeout, app-wide.

  • 0 false timeouts from legitimate cross-tab activity (cross-tab sync prevents this).

  • 0 sessions surviving a full tab closure longer than 2 minutes.

  • Duplicate LOGOUT presence rows trending to zero as the 5-second suppression window does its job.

18. DEPENDENCIES

This feature depends on:

  • Supabase Auth signOut() (was Clerk signOut() before the Phase 4 migration).

  • BfCacheGuard for iOS/Safari bfcache protection.

  • middleware.ts Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate headers.

  • user_presence_logs and app_users writes via POST /api/user/heartbeat.

  • The browser BroadcastChannel and pagehide APIs — no library dependency.

These features depend on it:

  • Presence dashboards ("Online Right Now") and the login/logout audit log.

  • Any compliance or session-audit reporting built on user_presence_logs.

19. TIMELINE & OWNERSHIP

Status: fully implemented.

  • Sprint #12: initial useIdleTimeout hook, learner and creator layouts only.

  • PR #709 (branch fix/session-timeout-closing-tab): 2-minute tab-closure timeout,
    BroadcastChannel tab tracking, duplicate-logout suppression, "Session Expired" toast,
    and 401 handling in RoleSwitcher.

  • Supabase Auth migration (Phase 4): Clerk calls replaced with supabase.auth.signOut().

  • Current: consolidated into IdleTimeoutProvider and mounted app-wide in
    app/layout.tsx, so the former Admin/Agency/Reviewer layout gap is closed.

Owner: scorevi (Sean Patrick Caintic)

Document Version

1.0 - Initial version - 2026-06-29 08:03 UTC

1.1 - Added Document Version section and update author to have full name - 2026-06-29 08:37 UTC

1.2 (Current Version) - Updated for PR #709 tab-closure timeout, Supabase Auth
migration, and app-wide provider mount; added idle and tab-closure flow diagrams -
2026-10-05 11:30 UTC


Was this article helpful?