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:
Idle timeout —
useIdleTimeouttracks user activity and signs the user out via
Supabase Auth after 20 minutes of inactivity, with a 2-minute warning toast.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 inapp/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 │ └───────────────────────┘ └───────────────────────┘
User signs in and browses. The timer resets on
mousemove,keydown,click,scroll, andtouchstart.Every activity also writes
wyzquests_last_activeto localStorage.After 18 minutes of inactivity (20 min − 2 min warning) the
onWarningcallback
fires and the "Session expiring soon" toast appears.Any activity dismisses the toast and restarts the full 20-minute timer.
If nothing happens for 2 more minutes,
onTimeoutfires → 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) │└──────────────────────────┘ └──────────────────────────┘
On a signed-in mount,
app_last_tab_closed_atis read and immediately cleared
(single use).If
elapsed >= 2 min,handleManualSignOut(reason)runs and the effect returns
early — no channel is opened for this tab.Otherwise the tab opens the
app_active_tabs_channelBroadcastChannel, generates a
randomtabId, and seedsactiveTabswith itself.It broadcasts
TAB_OPENED. A tab already listening repliesTAB_ALIVE, which is how
a newly-opened tab discovers its pre-existing siblings.On
pagehide(close, navigate away, or enter bfcache) the tab removes itself,
broadcastsTAB_CLOSED, and — only ifactiveTabsis now empty AND more than 2
seconds have elapsed since mount — writes the closure timestamp.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
storageevent onwyzquests_last_active.Multiple tabs, closure path: closing one of two tabs leaves
activeTabsnon-empty, so
no stamp is written and the session survives.Sign-out storm: all sign-out paths funnel through
handleManualSignOut, guarded by anisChangingPageref. TheisSignedIn: true → falseinterceptor checks the same ref,
so one user-initiated sign-out cannot fire twologoutheartbeats.Duplicate presence rows: the heartbeat route suppresses a second
LOGOUTrow when the
most recent row for that user is aLOGOUTless 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
disabledprop and the provider passesdisabled: !isSignedIn.iOS Safari bfcache:
BfCacheGuardforces a hard reload whenpageshowreportsevent.persisted.
Decision Points
disabled === true→ the hook does nothing and the provider skips all channel and
heartbeat work.elapsed >= 2 minon 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 |
|---|---|---|
|
| Cleared on logout, refreshed by the 60s heartbeat. Drives "Online Right Now". |
|
| Merged (not overwritten) with the parsed OS/device on each heartbeat. |
|
|
|
Client-Side State
Key | Storage | Purpose |
|---|---|---|
| localStorage | Epoch ms of the moment the final tab closed. Written by |
| localStorage | Epoch ms of the last activity event. The |
| sessionStorage | One-shot reason string rendered as the "Session Expired" toast, then removed. |
| sessionStorage | Set by |
| BroadcastChannel | Ephemeral peer-to-peer channel carrying |
9. API ENDPOINTS
POST /api/user/heartbeat
Body:
{ "logout": boolean }, sent withkeepalive: trueso it survives page unload.Unauthenticated → 401. Suspended user → rejected via
assertNotSuspended.On
logout: false— setslast_seen_at, refreshesmetadata.last_device, and writes
aLOGINrow only when there is no prior row, the prior row is aLOGOUT, or the
prior row is older than 30 minutes.On
logout: true— nullslast_seen_atand writes aLOGOUTrow, unless the most
recent row is already aLOGOUTwithin 5 seconds, in which case it returns{ message: "Duplicate logout suppressed" }and exits early.
GET /api/user/available-roles
Called by
RoleSwitcheron mount. A401short-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()fromhooks/auth/useAuth.ts— reads the Supabase session fromSessionProvider.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 |
|---|---|
| Error logged to console; |
Heartbeat POST rejects or is blocked | Caught and ignored ( |
localStorage write fails (quota, private mode, SSR) | Silently caught — the tab still tracks itself correctly in memory. |
| The effect throws before registering |
Component unmounts while timers are pending |
|
Clock skew on reopen | The 2-minute comparison uses |
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
LOGOUTpresence 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.
useIdleTimeouttimer reset logic is untested.□
wyzquests_session_timeoutis 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) orTAB_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_timeoutkey 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
LOGOUTpresence rows trending to zero as the 5-second suppression window does its job.
18. DEPENDENCIES
This feature depends on:
Supabase Auth
signOut()(was ClerksignOut()before the Phase 4 migration).BfCacheGuardfor iOS/Safari bfcache protection.middleware.tsCache-Control: no-store, no-cache, must-revalidate, proxy-revalidateheaders.user_presence_logsandapp_userswrites viaPOST /api/user/heartbeat.The browser
BroadcastChannelandpagehideAPIs — 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
useIdleTimeouthook, 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 inRoleSwitcher.Supabase Auth migration (Phase 4): Clerk calls replaced with
supabase.auth.signOut().Current: consolidated into
IdleTimeoutProviderand mounted app-wide inapp/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