diff --git a/frontend/src/features/auth/components/SessionUnreachable.test.tsx b/frontend/src/features/auth/components/SessionUnreachable.test.tsx
new file mode 100644
index 0000000..8dde1cd
--- /dev/null
+++ b/frontend/src/features/auth/components/SessionUnreachable.test.tsx
@@ -0,0 +1,52 @@
+import { describe, expect, it } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { http, HttpResponse } from 'msw';
+import { I18nextProvider } from 'react-i18next';
+import type { ReactNode } from 'react';
+import { AuthProvider } from '@/features/auth/context/AuthProvider';
+import { useAuth } from '@/features/auth/context/auth-context';
+import { SessionUnreachable } from '@/features/auth/components/SessionUnreachable';
+import { server } from '@/mocks/server';
+import { API_BASE, makeAuthResponse } from '@/features/auth/mocks/fixtures';
+import { refreshBackoff } from '@/lib/refreshPolicy';
+import i18n from '@/i18n/config';
+
+function Probe() {
+ const { status } = useAuth();
+ return status === 'unreachable' ? :
{status}
;
+}
+
+function Wrapper({ children }: { children: ReactNode }) {
+ return (
+
+ {children}
+
+ );
+}
+
+describe('SessionUnreachable', () => {
+ it('offers a retry that signs the visitor in once the server answers again', async () => {
+ const original = [...refreshBackoff.delays];
+ refreshBackoff.delays = [5];
+ try {
+ let down = true;
+ server.use(
+ http.post(`${API_BASE}/api/v1/auth/refresh`, () =>
+ down ? HttpResponse.json({ status: 429 }, { status: 429 }) : HttpResponse.json(makeAuthResponse()),
+ ),
+ );
+ render(, { wrapper: Wrapper });
+ const retry = await screen.findByTestId('session-unreachable-retry');
+
+ await userEvent.click(retry); // still down
+ expect(await screen.findByTestId('session-unreachable-failed')).toBeInTheDocument();
+
+ down = false;
+ await userEvent.click(screen.getByTestId('session-unreachable-retry'));
+ await waitFor(() => expect(screen.getByTestId('status')).toHaveTextContent('authenticated'));
+ } finally {
+ refreshBackoff.delays = original;
+ }
+ });
+});
diff --git a/frontend/src/features/auth/components/SessionUnreachable.tsx b/frontend/src/features/auth/components/SessionUnreachable.tsx
new file mode 100644
index 0000000..054c892
--- /dev/null
+++ b/frontend/src/features/auth/components/SessionUnreachable.tsx
@@ -0,0 +1,49 @@
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Button } from '@/components/ui/button';
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
+import { useAuth } from '@/features/auth/context/auth-context';
+
+/**
+ * Shown when the start-up refresh could not get a verdict (rate limit, restart, network). The visitor is not signed
+ * out - the cookie is intact - so this offers a retry instead of the login page.
+ */
+export function SessionUnreachable() {
+ const { t } = useTranslation();
+ const { refresh } = useAuth();
+ const [busy, setBusy] = useState(false);
+ const [failedAgain, setFailedAgain] = useState(false);
+
+ const retry = async () => {
+ setBusy(true);
+ setFailedAgain(false);
+ try {
+ await refresh(); // success -> authenticated, a rejected cookie -> guest; this screen then goes away
+ } catch {
+ setFailedAgain(true);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+
+
+
+ {t('session.unreachable.title')}
+ {t('session.unreachable.description')}
+
+
+ {failedAgain && (
+
+ {t('session.unreachable.stillFailing')}
+
+ )}
+
+
+
+
+ );
+}
diff --git a/frontend/src/features/auth/context/AuthContext.test.tsx b/frontend/src/features/auth/context/AuthContext.test.tsx
index ded7fbc..cb4a346 100644
--- a/frontend/src/features/auth/context/AuthContext.test.tsx
+++ b/frontend/src/features/auth/context/AuthContext.test.tsx
@@ -113,7 +113,7 @@ describe('AuthContext', () => {
expect(calls).toBe(3);
});
- it('falls back to guest (without a verdict on the cookie) after the last retry', async () => {
+ it('ends in the unreachable state (not guest) after the last retry: no verdict on the session', async () => {
let calls = 0;
server.use(
http.post(`${API_BASE}/api/v1/auth/refresh`, () => {
@@ -124,10 +124,74 @@ describe('AuthContext', () => {
const { result } = renderHook(() => useAuth(), { wrapper });
- await waitFor(() => expect(result.current.status).toBe('guest'));
+ await waitFor(() => expect(result.current.status).toBe('unreachable'));
+ expect(result.current.isAuthenticated).toBe(false);
expect(calls).toBe(1 + refreshBackoff.delays.length);
});
+ it('respects Retry-After on a 429 (waits at least that long before the next try)', async () => {
+ const stamps: number[] = [];
+ server.use(
+ http.post(`${API_BASE}/api/v1/auth/refresh`, () => {
+ stamps.push(Date.now());
+ if (stamps.length === 1) {
+ return HttpResponse.json({ status: 429 }, { status: 429, headers: { 'Retry-After': '0.3' } });
+ }
+ return HttpResponse.json(makeAuthResponse());
+ }),
+ );
+
+ const { result } = renderHook(() => useAuth(), { wrapper });
+
+ await waitFor(() => expect(result.current.status).toBe('authenticated'), { timeout: 3000 });
+ expect(stamps[1] - stamps[0]).toBeGreaterThanOrEqual(280); // the planned backoff is only 5 ms
+ });
+
+ it('recovers from the unreachable state through refresh(), without ever having been a guest', async () => {
+ let down = true;
+ server.use(
+ http.post(`${API_BASE}/api/v1/auth/refresh`, () =>
+ down ? HttpResponse.json({ status: 503 }, { status: 503 }) : HttpResponse.json(makeAuthResponse()),
+ ),
+ );
+ const seen: string[] = [];
+ const { result } = renderHook(
+ () => {
+ const a = useAuth();
+ seen.push(a.status);
+ return a;
+ },
+ { wrapper },
+ );
+ await waitFor(() => expect(result.current.status).toBe('unreachable'));
+
+ down = false;
+ await act(async () => {
+ await result.current.refresh();
+ });
+
+ expect(result.current.status).toBe('authenticated');
+ expect(seen).not.toContain('guest');
+ });
+
+ it('a 401 verdict on the retry still ends in guest', async () => {
+ let first = true;
+ server.use(
+ http.post(`${API_BASE}/api/v1/auth/refresh`, () =>
+ first ? HttpResponse.json({ status: 503 }, { status: 503 }) : HttpResponse.json({ status: 401 }, { status: 401 }),
+ ),
+ );
+ const { result } = renderHook(() => useAuth(), { wrapper });
+ await waitFor(() => expect(result.current.status).toBe('unreachable'));
+
+ first = false;
+ await act(async () => {
+ await result.current.refresh();
+ });
+
+ expect(result.current.status).toBe('guest');
+ });
+
it('does not retry when the server rejects the cookie (401)', async () => {
let calls = 0;
server.use(
diff --git a/frontend/src/features/auth/context/AuthProvider.tsx b/frontend/src/features/auth/context/AuthProvider.tsx
index cf5370e..51aed56 100644
--- a/frontend/src/features/auth/context/AuthProvider.tsx
+++ b/frontend/src/features/auth/context/AuthProvider.tsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import type { AuthResponse } from '@/features/auth/services/types';
import { api } from '@/lib/api-client';
-import { isAuthRejection, refreshBackoff } from '@/lib/refreshPolicy';
+import { isAuthRejection, nextRetryDelay, refreshBackoff } from '@/lib/refreshPolicy';
import { changeLanguage } from '@/i18n/config';
import { AuthContext, type AuthContextValue, type AuthStatus } from '@/features/auth/context/auth-context';
@@ -113,8 +113,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// Silent refresh on app mount (BR-U1-01). This intentionally synchronizes
// React state with the external session (httpOnly cookie) on startup.
- // A transient failure (429, 502 during a restart, network) is retried a few times with a backoff; if it
- // still fails the visitor is a guest for now, and the refresh cookie is untouched so a reload can recover.
+ // A transient failure (429, 502 during a restart, network) is retried a few times with a backoff (longer when the
+ // server sends Retry-After). If it still fails there is no verdict on the session: the status becomes
+ // 'unreachable' (a retry screen), NOT 'guest', and the refresh cookie is untouched.
useEffect(() => {
let cancelled = false;
void (async () => {
@@ -123,18 +124,18 @@ export function AuthProvider({ children }: { children: ReactNode }) {
try {
await refresh();
return;
- } catch {
+ } catch (err) {
if (cancelled || attempt >= delays.length) break;
- await new Promise((resolve) => setTimeout(resolve, delays[attempt]));
+ await new Promise((resolve) => setTimeout(resolve, nextRetryDelay(err, delays[attempt])));
if (cancelled) return;
}
}
- if (!cancelled) clearSession();
+ if (!cancelled) setStatus('unreachable');
})();
return () => {
cancelled = true;
};
- }, [refresh, clearSession]);
+ }, [refresh]);
const value = useMemo(
() => ({
diff --git a/frontend/src/features/auth/context/auth-context.ts b/frontend/src/features/auth/context/auth-context.ts
index 302be65..5a031fd 100644
--- a/frontend/src/features/auth/context/auth-context.ts
+++ b/frontend/src/features/auth/context/auth-context.ts
@@ -1,7 +1,12 @@
import { createContext, useContext } from 'react';
import type { User } from '@/features/auth/services/types';
-export type AuthStatus = 'loading' | 'authenticated' | 'guest';
+/**
+ * 'unreachable': the start-up refresh could not get a verdict (rate limit, restart, network) after the quiet retries.
+ * The session is neither confirmed nor ended - the refresh cookie is untouched - so the app offers a retry
+ * instead of treating the visitor as signed out.
+ */
+export type AuthStatus = 'loading' | 'authenticated' | 'guest' | 'unreachable';
export interface AuthContextValue {
status: AuthStatus;
diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json
index 9d8df90..98db0ae 100644
--- a/frontend/src/i18n/locales/en/translation.json
+++ b/frontend/src/i18n/locales/en/translation.json
@@ -20,6 +20,14 @@
"switchToLight": "Switch to light theme",
"switchToDark": "Switch to dark theme"
},
+ "session": {
+ "unreachable": {
+ "title": "Could not check your session",
+ "description": "The server is briefly unreachable or busy. You have not been signed out. Try again in a few seconds.",
+ "retry": "Try again",
+ "stillFailing": "Still no answer. Wait a moment and try again."
+ }
+ },
"login": {
"title": "Sign in",
"subtitle": "Sign in to your SlpModularCms account",
diff --git a/frontend/src/i18n/locales/nl/translation.json b/frontend/src/i18n/locales/nl/translation.json
index a2fe6bc..fa2c9df 100644
--- a/frontend/src/i18n/locales/nl/translation.json
+++ b/frontend/src/i18n/locales/nl/translation.json
@@ -20,6 +20,14 @@
"switchToLight": "Overschakelen naar licht thema",
"switchToDark": "Overschakelen naar donker thema"
},
+ "session": {
+ "unreachable": {
+ "title": "Sessie kon niet worden gecontroleerd",
+ "description": "De server is even niet bereikbaar of te druk. Je bent niet uitgelogd. Probeer het over een paar seconden opnieuw.",
+ "retry": "Opnieuw proberen",
+ "stillFailing": "Nog steeds geen antwoord. Wacht even en probeer opnieuw."
+ }
+ },
"login": {
"title": "Inloggen",
"subtitle": "Log in op je SlpModularCms-account",
diff --git a/frontend/src/lib/api-client.ts b/frontend/src/lib/api-client.ts
index 26e0544..2522a62 100644
--- a/frontend/src/lib/api-client.ts
+++ b/frontend/src/lib/api-client.ts
@@ -22,12 +22,15 @@ export type ApiResult = { ok: true; data: T } | { ok: false; error: ProblemDe
export class ProblemDetailsError extends Error {
readonly status: number;
readonly problem: ProblemDetails;
+ /** From the Retry-After header (seconds), in milliseconds; undefined when the server did not say. */
+ readonly retryAfterMs?: number;
- constructor(status: number, problem: ProblemDetails) {
+ constructor(status: number, problem: ProblemDetails, retryAfterMs?: number) {
super(problem.title ?? problem.detail ?? `Request failed with status ${status}`);
this.name = 'ProblemDetailsError';
this.status = status;
this.problem = problem;
+ this.retryAfterMs = retryAfterMs;
}
}
@@ -155,13 +158,20 @@ export class ApiClient {
const problem: ProblemDetails = isProblemDetails(data)
? data
: { status: response.status, title: response.statusText };
- throw new ProblemDetailsError(response.status, problem);
+ throw new ProblemDetailsError(response.status, problem, parseRetryAfter(response.headers.get('Retry-After')));
}
return data as T;
}
}
+/** Retry-After as delay-seconds (the only form a rate limiter sends); anything else is ignored. */
+function parseRetryAfter(value: string | null): number | undefined {
+ if (value === null) return undefined;
+ const seconds = Number(value);
+ return Number.isFinite(seconds) && seconds >= 0 ? Math.round(seconds * 1000) : undefined;
+}
+
function safeJsonParse(text: string): unknown {
try {
return JSON.parse(text);
diff --git a/frontend/src/lib/refreshPolicy.ts b/frontend/src/lib/refreshPolicy.ts
index 95623c2..5eef708 100644
--- a/frontend/src/lib/refreshPolicy.ts
+++ b/frontend/src/lib/refreshPolicy.ts
@@ -11,3 +11,12 @@ export const refreshBackoff = { delays: [400, 1200, 2500] as number[] };
export function isAuthRejection(error: unknown): boolean {
return error instanceof ProblemDetailsError && (error.status === 400 || error.status === 401 || error.status === 403);
}
+
+/** Longest a server's Retry-After is honoured at start-up; a longer wait is left to the visitor's retry button. */
+export const maxRetryAfterMs = 15000;
+
+/** How long to wait before the next quiet start-up retry: the planned backoff, or the server's Retry-After if longer. */
+export function nextRetryDelay(error: unknown, planned: number): number {
+ const asked = error instanceof ProblemDetailsError ? error.retryAfterMs : undefined;
+ return asked === undefined ? planned : Math.max(planned, Math.min(asked, maxRetryAfterMs));
+}
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx
index a7342b4..2b37fd5 100644
--- a/frontend/src/main.tsx
+++ b/frontend/src/main.tsx
@@ -8,6 +8,7 @@ import '@theme';
import './i18n/config';
import { AuthProvider } from '@/features/auth/context/AuthProvider';
import { useAuth } from '@/features/auth/context/auth-context';
+import { SessionUnreachable } from '@/features/auth/components/SessionUnreachable';
import { Toaster } from '@/components/ui/sonner';
import { router } from '@/router';
import { getAppConfig } from '@/lib/config';
@@ -44,6 +45,9 @@ function InnerApp() {
if (auth.status === 'loading') {
return ;
}
+ if (auth.status === 'unreachable') {
+ return ;
+ }
return ;
}
diff --git a/src/SlpModularCms.Core.Tests/Hosting/RateLimitRetryAfterTests.cs b/src/SlpModularCms.Core.Tests/Hosting/RateLimitRetryAfterTests.cs
new file mode 100644
index 0000000..87dd42f
--- /dev/null
+++ b/src/SlpModularCms.Core.Tests/Hosting/RateLimitRetryAfterTests.cs
@@ -0,0 +1,52 @@
+using System.Net;
+using FluentAssertions;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.RateLimiting;
+using Microsoft.AspNetCore.TestHost;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using SlpModularCms.Core.Hosting;
+
+namespace SlpModularCms.Core.Tests.Hosting;
+
+/// A rate-limited call says how long to wait (Retry-After), so the admin app's start-up retries do not hammer the same window.
+public class RateLimitRetryAfterTests
+{
+ [Fact]
+ public async Task ARejectedCall_Is429_WithARetryAfterInWholeSeconds()
+ {
+ var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary
+ {
+ ["RateLimiting:Refresh:PermitLimit"] = "1",
+ ["RateLimiting:Refresh:WindowSeconds"] = "60"
+ }).Build();
+
+ using var host = await new HostBuilder().ConfigureWebHost(web =>
+ {
+ web.UseTestServer();
+ web.ConfigureServices(s =>
+ {
+ s.AddLogging();
+ s.AddRouting();
+ s.AddCmsRateLimiting(config);
+ });
+ web.Configure(app =>
+ {
+ app.UseRouting();
+ app.UseRateLimiter();
+ app.UseEndpoints(e => e.MapPost("/refresh", () => "ok").RequireRateLimiting("refresh"));
+ });
+ }).StartAsync();
+ var client = host.GetTestClient();
+
+ (await client.PostAsync("/refresh", null)).StatusCode.Should().Be(HttpStatusCode.OK);
+ var rejected = await client.PostAsync("/refresh", null);
+
+ rejected.StatusCode.Should().Be(HttpStatusCode.TooManyRequests);
+ rejected.Headers.RetryAfter.Should().NotBeNull();
+ rejected.Headers.RetryAfter!.Delta!.Value.TotalSeconds.Should().BeGreaterThanOrEqualTo(1).And.BeLessThanOrEqualTo(60);
+ }
+}
diff --git a/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs b/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs
index e824822..ee4b76b 100644
--- a/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs
+++ b/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs
@@ -183,6 +183,29 @@ public static class ServiceCollectionExtensions
.GetMetadata()?.PolicyName ?? "(unknown)",
context.HttpContext.Request.Path);
+ // Tells a well-behaved client (the admin app's start-up retries) how long to wait, instead of
+ // having it retry into the same window and stay limited.
+ // A sliding-window lease carries no RetryAfter, so the "refresh" policy falls back to one segment
+ // (a quarter of the window: the earliest moment a permit frees up); other policies to their window.
+ var policyName = context.HttpContext.GetEndpoint()?.Metadata.GetMetadata()?.PolicyName;
+ var section = policyName switch
+ {
+ "login" => "Login",
+ "refresh" => "Refresh",
+ _ => null
+ };
+ double? waitSeconds = null;
+ if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
+ waitSeconds = retryAfter.TotalSeconds;
+ else if (section is not null)
+ {
+ var window = configuration.GetValue($"RateLimiting:{section}:WindowSeconds", 60);
+ waitSeconds = policyName == "refresh" ? window / 4.0 : window;
+ }
+ if (waitSeconds is not null)
+ context.HttpContext.Response.Headers.RetryAfter =
+ Math.Max(1, (int)Math.Ceiling(waitSeconds.Value)).ToString(System.Globalization.CultureInfo.InvariantCulture);
+
return ValueTask.CompletedTask;
};