feat(session): preserve intended URL across session timeout and add expiry warning dialog

When a session expires, the user's current URL is now captured and restored
after re-authentication (via remember-me cookie or manual login), instead of
always redirecting to the dashboard. A JavaScript session warning dialog
appears ~2 minutes before idle timeout, allowing users to extend their session
with a single click. Includes open-redirect prevention via URL validation,
Microsoft SSO callback support, and 33 unit tests.

Refs: SESSION-REDIRECT-PRESERVE-001

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-13 14:28:49 +01:00
parent a3045fa95e
commit 04995e3712
18 changed files with 1333 additions and 7 deletions

View File

@@ -8,6 +8,7 @@ use MintyPHP\Http\ApiSystemAuditReporter;
use MintyPHP\Http\CookieStore;
use MintyPHP\Http\CookieStoreInterface;
use MintyPHP\Http\Input\RequestInputFactory;
use MintyPHP\Http\IntendedUrlService;
use MintyPHP\Http\RequestRuntime;
use MintyPHP\Http\RequestRuntimeInterface;
use MintyPHP\Http\SessionStore;
@@ -82,6 +83,7 @@ final class AppServicesRegistrar implements ContainerRegistrar
$c->get(UserReadRepository::class)
));
$container->set(GridUserCountEnricher::class, static fn (): GridUserCountEnricher => new GridUserCountEnricher());
$container->set(IntendedUrlService::class, static fn (): IntendedUrlService => new IntendedUrlService());
$container->set(RequestInputFactory::class, static fn (): RequestInputFactory => new RequestInputFactory());
$container->set(SessionStore::class, static fn (): SessionStore => new SessionStore());
$container->set(SessionStoreInterface::class, static fn (AppContainer $c): SessionStoreInterface => $c->get(SessionStore::class));

View File

@@ -58,6 +58,12 @@ class AccessControl
*
* @return bool True if access is allowed, false if redirected
*/
/**
* Redirect to login if the path requires authentication and user is not logged in.
* Appends ?return_to= so the user is redirected back after login.
*
* @return bool True if access is allowed, false if redirected
*/
public function requireAuthOrRedirect(string $path, bool $isLoggedIn): bool
{
if ($this->isPublicPath($path) || $isLoggedIn) {
@@ -65,7 +71,13 @@ class AccessControl
}
$locale = I18n::$locale ?? I18n::$defaultLocale;
Router::redirect(Request::withLocale('login', $locale));
$loginPath = Request::withLocale('login', $locale);
$requestUri = $_SERVER['REQUEST_URI'] ?? '';
$intendedUrlService = app(IntendedUrlService::class);
$loginTarget = $intendedUrlService->buildLoginRedirect($loginPath, $requestUri);
Router::redirect($loginTarget);
return false;
}

View File

@@ -0,0 +1,124 @@
<?php
namespace MintyPHP\Http;
/**
* Stores and retrieves the URL the user intended to visit before
* being redirected to the login page (session timeout, auth guard).
*
* URLs are validated to prevent open-redirect attacks.
*/
class IntendedUrlService
{
private const SESSION_KEY = 'intended_url';
private const MAX_LENGTH = 2048;
private const FALLBACK = 'admin';
/** Prefixes that must never be restored (would cause redirect loops or security issues). */
private const BLOCKED_PREFIXES = [
'auth/',
'api/',
'login',
'logout',
'flash/',
'branding/',
];
/**
* Store the intended URL in the session.
*/
public function store(string $url, SessionStoreInterface $session): void
{
$sanitized = $this->sanitize($url);
if ($sanitized !== '') {
$session->set(self::SESSION_KEY, $sanitized);
}
}
/**
* Retrieve the intended URL without removing it.
*/
public function retrieve(SessionStoreInterface $session): ?string
{
$value = $session->get(self::SESSION_KEY);
return is_string($value) && $value !== '' ? $value : null;
}
/**
* Retrieve the intended URL and remove it from the session.
* Returns the fallback ('admin') if no valid URL is stored.
*/
public function retrieveAndForget(SessionStoreInterface $session): string
{
$value = $this->retrieve($session);
$session->remove(self::SESSION_KEY);
return $value ?? self::FALLBACK;
}
/**
* Build a login redirect URL with the return_to query parameter.
*/
public function buildLoginRedirect(string $loginPath, string $returnTo): string
{
$sanitized = $this->sanitize($returnTo);
if ($sanitized === '') {
return $loginPath;
}
$separator = str_contains($loginPath, '?') ? '&' : '?';
return $loginPath . $separator . 'return_to=' . rawurlencode($sanitized);
}
/**
* Sanitize and validate a URL for safe redirect.
* Returns empty string if the URL is not safe.
*/
public function sanitize(string $url): string
{
$url = trim($url);
if ($url === '' || mb_strlen($url) > self::MAX_LENGTH) {
return '';
}
// Must be a relative path (starts with /)
if (!str_starts_with($url, '/')) {
return '';
}
// Must not contain protocol indicators (prevent //evil.com or javascript:)
if (str_contains($url, '://') || str_starts_with($url, '//')) {
return '';
}
// Strip the path to check against blocked prefixes.
// URL might be /en/admin/users or /admin/users — strip locale prefix.
$path = $this->extractPathWithoutLocale($url);
foreach (self::BLOCKED_PREFIXES as $prefix) {
if (str_starts_with($path, $prefix) || $path === rtrim($prefix, '/')) {
return '';
}
}
return $url;
}
/**
* Extract the path portion without query string and without locale prefix.
*/
private function extractPathWithoutLocale(string $url): string
{
// Remove query string and fragment
$path = strtok($url, '?#') ?: $url;
// Remove leading slash
$path = ltrim($path, '/');
// Remove locale prefix (2-letter code followed by /)
if (preg_match('#^[a-z]{2}/#', $path)) {
$path = substr($path, 3);
}
return $path;
}
}