feat: Implement cross-tab authentication synchronization in AuthProvider

- Add BroadcastChannel API for real-time logout synchronization across tabs
- Implement storage event listener as fallback for older browsers
- When a user logs out in one tab, all other tabs immediately reflect the logout state
- Update tests to verify storage event and BroadcastChannel behavior
- Update Architecture.md to document cross-tab synchronization
- Update Web-Development.md with authentication state management notes

The provider now broadcasts logout messages to other tabs so they immediately
reflect the logout state without requiring a page refresh or additional API calls.
The implementation uses BroadcastChannel as the primary sync mechanism with
storage events as a fallback for older browsers.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-04-30 20:15:26 +02:00
parent ac53a56ae7
commit 69d32bfbe9
5 changed files with 169 additions and 35 deletions

View File

@@ -1083,7 +1083,29 @@ This pattern prevents **stale session flicker** — the brief moment when a user
---
## 8. Naming Conventions
### Cross-Tab Authentication Synchronization
The `AuthProvider` synchronizes authentication state across multiple browser tabs in real-time. When a user logs out in one tab, all other open tabs immediately reflect the logout state without requiring a page refresh or additional API calls.
**How it works:**
1. **BroadcastChannel API (primary):** When `logout()` is called, the provider broadcasts a logout message to all other tabs via the `BroadcastChannel` API. Other tabs listening on the same channel immediately receive the message and log out.
2. **Storage Events (fallback):** If BroadcastChannel is not supported (older browsers), the provider falls back to storage events. When `sessionStorage` is cleared in one tab, a `storage` event fires in other tabs, triggering the logout.
**Why this matters:**
- **Session-scoped storage:** `sessionStorage` is per-tab, so logging out in Tab A does not automatically clear Tab B's `sessionStorage`.
- **Immediate feedback:** Users see consistent authentication state across all tabs without delays or page refreshes.
- **Better security:** If a session is revoked (e.g., due to suspicious activity), all tabs are logged out immediately.
**Implementation details:**
- The provider registers a storage event listener during mount that responds to `STORAGE_KEY_AUTHENTICATED` changes.
- It creates a `BroadcastChannel` with the name `"bangui_auth"` to listen for logout broadcasts.
- In the `logout()` function, after clearing `sessionStorage`, a logout message is broadcast to all tabs.
- The channel cleanup and event listener removal are handled in useEffect cleanup functions.
---
| Element | Convention | Example |
|---|---|---|