Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Preserve saved access when startup discovery fails

pulse-triage[bot]c11aba07acec
diff --git a/frontend-modern/src/App.tsx b/frontend-modern/src/App.tsx
index 1ad8d7def3..6eced1b786 100644
--- a/frontend-modern/src/App.tsx
+++ b/frontend-modern/src/App.tsx
@@ -475,7 +475,10 @@ function App() {
});
return (
- <Show when={!runtime.isLoading()} fallback={<AppBootstrapStatus />}>
+ <Show
+ when={!runtime.isLoading() && !runtime.bootstrapFailed()}
+ fallback={<AppBootstrapStatus failed={runtime.bootstrapFailed()} />}
+ >
<Show
when={isPublicRoute()}
fallback={
diff --git a/frontend-modern/src/__tests__/App.architecture.test.ts b/frontend-modern/src/__tests__/App.architecture.test.ts
index 23e9e556aa..84436fb4b5 100644
--- a/frontend-modern/src/__tests__/App.architecture.test.ts
+++ b/frontend-modern/src/__tests__/App.architecture.test.ts
@@ -256,7 +256,10 @@ describe('App architecture', () => {
});
it('keeps first-load connection progress understandable and retryable', () => {
- expect(appSource).toContain('fallback={<AppBootstrapStatus />}');
+ expect(appSource).toContain('when={!runtime.isLoading() && !runtime.bootstrapFailed()}');
+ expect(appSource).toContain(
+ 'fallback={<AppBootstrapStatus failed={runtime.bootstrapFailed()} />}',
+ );
expect(appSource).not.toContain('<div class="text-muted">Loading...</div>');
});
diff --git a/frontend-modern/src/__tests__/useAppRuntimeState.test.ts b/frontend-modern/src/__tests__/useAppRuntimeState.test.ts
index acede750c1..d51343f37b 100644
--- a/frontend-modern/src/__tests__/useAppRuntimeState.test.ts
+++ b/frontend-modern/src/__tests__/useAppRuntimeState.test.ts
@@ -65,6 +65,7 @@ describe('useAppRuntimeState', () => {
let getOrgIDMock: ReturnType<typeof vi.fn>;
let hasStoredAuthSessionMock: ReturnType<typeof vi.fn>;
let setOrgIDMock: ReturnType<typeof vi.fn>;
+ let clearAuthMock: ReturnType<typeof vi.fn>;
let showToastMock: ReturnType<typeof vi.fn>;
let aiAvailabilitySetEnabledMock: ReturnType<typeof vi.fn>;
let aiAvailabilityRefreshMock: ReturnType<typeof vi.fn>;
@@ -84,6 +85,7 @@ describe('useAppRuntimeState', () => {
vi.resetModules();
window.history.replaceState({}, '', '/');
window.sessionStorage.clear();
+ window.localStorage.removeItem('just_logged_out');
Object.defineProperty(window, 'matchMedia', {
writable: true,
@@ -139,6 +141,11 @@ describe('useAppRuntimeState', () => {
getOrgIDMock = vi.fn().mockReturnValue('default');
hasStoredAuthSessionMock = vi.fn().mockReturnValue(true);
setOrgIDMock = vi.fn();
+ clearAuthMock = vi.fn(() => {
+ window.sessionStorage.removeItem('auth');
+ window.sessionStorage.removeItem('pulse_auth_user');
+ window.localStorage.removeItem('org_id');
+ });
showToastMock = vi.fn();
aiAvailabilitySetEnabledMock = vi.fn();
aiAvailabilityRefreshMock = vi.fn().mockResolvedValue(undefined);
@@ -209,6 +216,7 @@ describe('useAppRuntimeState', () => {
getOrgID: getOrgIDMock,
hasAuth: hasStoredAuthSessionMock,
setOrgID: setOrgIDMock,
+ clearAuth: clearAuthMock,
}));
vi.doMock('@/stores/events', () => ({
@@ -298,6 +306,8 @@ describe('useAppRuntimeState', () => {
afterEach(async () => {
vi.clearAllMocks();
+ window.localStorage.removeItem('org_id');
+ window.localStorage.removeItem('just_logged_out');
const policyModule = await import('@/stores/sessionPresentationPolicy');
policyModule.syncSessionPresentationPolicy(null);
vi.resetModules();
@@ -315,6 +325,168 @@ describe('useAppRuntimeState', () => {
return { dispose, hookState: hookState! };
};
+ it.each([
+ 'unavailable',
+ 'forbidden',
+ 'network',
+ 'invalid-json',
+ 'null',
+ 'missing-flag',
+ 'string-flag',
+ ])('retains saved access without admitting a runtime after %s discovery', async (scenario) => {
+ const fallbackFetch = apiFetchMock.getMockImplementation()!;
+ apiFetchMock.mockImplementation(async (url: string) => {
+ if (url !== '/api/security/status') return fallbackFetch(url);
+ if (scenario === 'network') throw new TypeError('Offline');
+ if (scenario === 'unavailable') return new Response('Unavailable', { status: 503 });
+ if (scenario === 'forbidden') return new Response('Forbidden', { status: 403 });
+ const bodies: Record<string, string> = {
+ 'invalid-json': '<html>Temporary gateway page</html>',
+ null: 'null',
+ 'missing-flag': '{}',
+ 'string-flag': '{"hasAuthentication":"false"}',
+ };
+ return new Response(bodies[scenario], { status: 200 });
+ });
+ window.sessionStorage.setItem('auth', 'synthetic-saved-token');
+ window.sessionStorage.setItem('pulse_auth_user', 'synthetic-operator');
+ window.localStorage.setItem('org_id', 'acme');
+ getOrgIDMock.mockReturnValue('acme');
+
+ const { hookState, dispose } = mountHook();
+ await waitFor(() => expect(hookState.isLoading()).toBe(false));
+
+ expect(hookState.bootstrapFailed()).toBe(true);
+ expect(hookState.needsAuth()).toBe(true);
+ expect(hookState.backendHealthy()).toBe(false);
+ expect(hookState.enhancedStore()).toBeNull();
+ expect(hookState.securityStatus()).toBeNull();
+ expect(hookState.activeOrgID()).toBe('acme');
+ expect(clearAuthMock).not.toHaveBeenCalled();
+ expect(window.sessionStorage.getItem('auth')).toBe('synthetic-saved-token');
+ expect(window.sessionStorage.getItem('pulse_auth_user')).toBe('synthetic-operator');
+ expect(window.localStorage.getItem('org_id')).toBe('acme');
+ expect(setOrgIDMock).not.toHaveBeenCalled();
+ expect(getRuntimeDisplayMock).not.toHaveBeenCalled();
+ expect(apiFetchMock.mock.calls.map(([url]) => url)).toEqual(['/api/security/status']);
+ dispose();
+ });
+
+ it.each([403, 429, 500, 502, 503, 'network'])(
+ 'does not treat a %s protected session check as authenticated or expired',
+ async (status) => {
+ const fallbackFetch = apiFetchMock.getMockImplementation()!;
+ apiFetchMock.mockImplementation(async (url: string) => {
+ if (url !== '/api/state/summary') return fallbackFetch(url);
+ if (status === 'network') throw new TypeError('Offline');
+ return new Response('{}', { status: status as number });
+ });
+
+ const { hookState, dispose } = mountHook();
+ await waitFor(() => expect(hookState.isLoading()).toBe(false));
+
+ expect(hookState.bootstrapFailed()).toBe(true);
+ expect(hookState.needsAuth()).toBe(true);
+ expect(hookState.backendHealthy()).toBe(false);
+ expect(hookState.enhancedStore()).toBeNull();
+ expect(clearAuthMock).not.toHaveBeenCalled();
+ expect(setOrgIDMock).not.toHaveBeenCalled();
+ expect(getRuntimeDisplayMock).not.toHaveBeenCalled();
+ expect(apiFetchMock.mock.calls.map(([url]) => url)).toEqual([
+ '/api/security/status',
+ '/api/state/summary',
+ ]);
+ dispose();
+ },
+ );
+
+ it('keeps genuine security-status 401 handling and clears rejected stored access', async () => {
+ apiFetchMock.mockResolvedValue(new Response('{}', { status: 401 }));
+ window.sessionStorage.setItem('auth', 'synthetic-rejected-token');
+
+ const { hookState, dispose } = mountHook();
+ await waitFor(() => expect(hookState.isLoading()).toBe(false));
+
+ expect(hookState.bootstrapFailed()).toBe(false);
+ expect(hookState.needsAuth()).toBe(true);
+ expect(hookState.enhancedStore()).toBeNull();
+ expect(clearAuthMock).toHaveBeenCalledOnce();
+ expect(window.sessionStorage.getItem('auth')).toBeNull();
+ dispose();
+ });
+
+ it('keeps a genuine summary 401 on the login path, not the connection-error path', async () => {
+ const fallbackFetch = apiFetchMock.getMockImplementation()!;
+ apiFetchMock.mockImplementation(async (url: string) =>
+ url === '/api/state/summary'
+ ? new Response('{}', { status: 401 })
+ : fallbackFetch(url),
+ );
+
+ const { hookState, dispose } = mountHook();
+ await waitFor(() => expect(hookState.isLoading()).toBe(false));
+
+ expect(hookState.bootstrapFailed()).toBe(false);
+ expect(hookState.needsAuth()).toBe(true);
+ expect(hookState.enhancedStore()).toBeNull();
+ expect(getRuntimeDisplayMock).not.toHaveBeenCalled();
+ dispose();
+ });
+
+ it('requires explicit no-auth discovery before first-run setup', async () => {
+ apiFetchMock.mockResolvedValue(
+ new Response('{"hasAuthentication":false}', { status: 200 }),
+ );
+
+ const { hookState, dispose } = mountHook();
+ await waitFor(() => expect(hookState.isLoading()).toBe(false));
+
+ expect(hookState.bootstrapFailed()).toBe(false);
+ expect(hookState.hasAuth()).toBe(false);
+ expect(hookState.needsAuth()).toBe(true);
+ expect(hookState.securityStatus()?.hasAuthentication).toBe(false);
+ expect(hookState.enhancedStore()).toBeNull();
+ expect(clearAuthMock).not.toHaveBeenCalled();
+ dispose();
+ });
+
+ it('retains explicit logout intent until discovery succeeds', async () => {
+ window.localStorage.setItem('just_logged_out', 'true');
+ apiFetchMock.mockResolvedValue(new Response('Unavailable', { status: 503 }));
+
+ const { hookState, dispose } = mountHook();
+ await waitFor(() => expect(hookState.isLoading()).toBe(false));
+
+ expect(hookState.bootstrapFailed()).toBe(true);
+ expect(window.localStorage.getItem('just_logged_out')).toBe('true');
+ expect(hookState.enhancedStore()).toBeNull();
+ dispose();
+ window.localStorage.removeItem('just_logged_out');
+ });
+
+ it('recovers with the saved tenant after a fresh connection attempt succeeds', async () => {
+ const fallbackFetch = apiFetchMock.getMockImplementation()!;
+ apiFetchMock.mockRejectedValue(new TypeError('Offline'));
+ getOrgIDMock.mockReturnValue('acme');
+ isMultiTenantEnabledMock.mockReturnValue(true);
+
+ const first = mountHook();
+ await waitFor(() => expect(first.hookState.bootstrapFailed()).toBe(true));
+ expect(clearAuthMock).not.toHaveBeenCalled();
+ first.dispose();
+
+ apiFetchMock.mockImplementation(fallbackFetch);
+ const second = mountHook();
+ await waitFor(() => expect(second.hookState.isLoading()).toBe(false));
+ expect(second.hookState.bootstrapFailed()).toBe(false);
+ expect(second.hookState.needsAuth()).toBe(false);
+ expect(second.hookState.activeOrgID()).toBe('acme');
+ expect(second.hookState.enhancedStore()).not.toBeNull();
+ expect(setOrgIDMock).toHaveBeenCalledWith('acme');
+ expect(clearAuthMock).not.toHaveBeenCalled();
+ second.dispose();
+ });
+
it('loads bootstrap display settings from the authenticated runtime projection', async () => {
getRuntimeDisplayMock.mockResolvedValue({
theme: 'dark',
diff --git a/frontend-modern/src/components/AppBootstrapStatus.tsx b/frontend-modern/src/components/AppBootstrapStatus.tsx
index acec800bcb..055bb34b03 100644
--- a/frontend-modern/src/components/AppBootstrapStatus.tsx
+++ b/frontend-modern/src/components/AppBootstrapStatus.tsx
@@ -5,6 +5,7 @@ import { LoadingSpinner } from '@/components/shared/LoadingSpinner';
export const APP_BOOTSTRAP_SLOW_DELAY_MS = 10_000;
interface AppBootstrapStatusProps {
+ failed?: boolean;
onRetry?: () => void;
slowDelayMs?: number;
}
@@ -34,9 +35,11 @@ export const AppBootstrapStatus: Component<AppBootstrapStatusProps> = (props) =>
aria-labelledby="app-bootstrap-title"
>
<div class="w-full max-w-md rounded-md border border-border bg-surface p-6 text-center shadow-xs sm:p-8">
- <LoadingSpinner size="xl" tone="info" class="mb-4" />
+ <Show when={!props.failed}>
+ <LoadingSpinner size="xl" tone="info" class="mb-4" />
+ </Show>
<h1 id="app-bootstrap-title" class="text-lg font-semibold tracking-tight">
- Connecting to Pulse
+ {props.failed ? 'Could not check your session' : 'Connecting to Pulse'}
</h1>
<p
class="mt-2 text-sm leading-6 text-muted"
@@ -44,15 +47,24 @@ export const AppBootstrapStatus: Component<AppBootstrapStatusProps> = (props) =>
aria-live="polite"
aria-atomic="true"
>
- <Show when={isSlow()} fallback="Checking your session and preparing the workspace.">
- Pulse is taking longer than expected to respond. The server may still be starting or
- busy.
+ <Show
+ when={props.failed}
+ fallback={
+ <Show when={isSlow()} fallback="Checking your session and preparing the workspace.">
+ Pulse is taking longer than expected to respond. The server may still be starting
+ or busy.
+ </Show>
+ }
+ >
+ Pulse could not check your session. Your saved sign-in details have not been cleared.
</Show>
</p>
- <Show when={isSlow()}>
+ <Show when={props.failed || isSlow()}>
<div class="mt-5 border-t border-border pt-5">
<p class="mb-4 text-sm leading-6 text-muted">
- You can keep waiting, or retry the connection.
+ {props.failed
+ ? 'Check that Pulse is available, then retry the connection.'
+ : 'You can keep waiting, or retry the connection.'}
</p>
<Button variant="primary" size="md" onClick={retry}>
Retry connection
diff --git a/frontend-modern/src/components/__tests__/AppBootstrapStatus.test.tsx b/frontend-modern/src/components/__tests__/AppBootstrapStatus.test.tsx
index 8e536f2af9..38eaa5865b 100644
--- a/frontend-modern/src/components/__tests__/AppBootstrapStatus.test.tsx
+++ b/frontend-modern/src/components/__tests__/AppBootstrapStatus.test.tsx
@@ -35,6 +35,22 @@ describe('AppBootstrapStatus', () => {
expect(onRetry).toHaveBeenCalledOnce();
});
+ it('announces a failed session check immediately without suggesting it is still running', () => {
+ const onRetry = vi.fn();
+ render(() => <AppBootstrapStatus failed onRetry={onRetry} />);
+
+ expect(screen.getByRole('main')).toHaveAccessibleName('Could not check your session');
+ expect(screen.getByRole('status')).toHaveTextContent(
+ 'Your saved sign-in details have not been cleared.',
+ );
+ expect(screen.queryByText(/You can keep waiting/)).toBeNull();
+ expect(screen.queryByText(/Checking your session and preparing/)).toBeNull();
+ const retry = screen.getByRole('button', { name: 'Retry connection' });
+ expect(retry).toBeVisible();
+ fireEvent.click(retry);
+ expect(onRetry).toHaveBeenCalledOnce();
+ });
+
it('cancels a completed bootstrap timer and gives a fresh attempt its full waiting period', async () => {
vi.useFakeTimers();
const first = render(() => <AppBootstrapStatus />);
diff --git a/frontend-modern/src/useAppRuntimeState.ts b/frontend-modern/src/useAppRuntimeState.ts
index 7fb1fba023..abdf257cb5 100644
--- a/frontend-modern/src/useAppRuntimeState.ts
+++ b/frontend-modern/src/useAppRuntimeState.ts
@@ -179,6 +179,7 @@ export const useAppRuntimeState = () => {
};
const [isLoading, setIsLoading] = createSignal(true);
+ const [bootstrapFailed, setBootstrapFailed] = createSignal(false);
const [needsAuth, setNeedsAuth] = createSignal(false);
const [hasAuth, setHasAuth] = createSignal(false);
const [organizations, setOrganizations] = createSignal<Organization[]>([
@@ -365,6 +366,10 @@ export const useAppRuntimeState = () => {
return false;
}
+ if (!summaryResponse.ok) {
+ throw new Error(`Session check failed with status ${summaryResponse.status}`);
+ }
+
return true;
};
@@ -705,19 +710,6 @@ export const useAppRuntimeState = () => {
return;
}
- if (justLoggedOut) {
- localStorage.removeItem('just_logged_out');
- logger.debug('[App] User logged out, showing login page');
- if (securityResponse.ok) {
- const securityData = (await securityResponse.json()) as SecurityStatus;
- applySecurityStatus(securityData);
- }
- setHasAuth(true);
- setNeedsAuth(true);
- setIsLoading(false);
- return;
- }
-
if (!securityResponse.ok) {
throw new Error(`Security status request failed with status ${securityResponse.status}`);
}
@@ -732,10 +724,21 @@ export const useAppRuntimeState = () => {
ssoSessionDisplayName?: string;
ssoLogoutURL?: string;
};
+ if (!isRecord(securityData) || typeof securityData.hasAuthentication !== 'boolean') {
+ throw new Error('Authentication discovery is incomplete');
+ }
logger.debug('[App] Security status fetched', securityData);
applySecurityStatus(securityData);
- const authConfigured = securityData.hasAuthentication || false;
+ if (justLoggedOut) {
+ localStorage.removeItem('just_logged_out');
+ logger.debug('[App] User logged out, showing login page');
+ setHasAuth(true);
+ setNeedsAuth(true);
+ return;
+ }
+
+ const authConfigured = securityData.hasAuthentication;
setHasAuth(authConfigured);
if (securityData.hasProxyAuth && securityData.proxyAuthUsername) {
@@ -793,12 +796,10 @@ export const useAppRuntimeState = () => {
await beginAuthenticatedRuntime();
} catch (error) {
logger.error('Auth check error', error);
- try {
- const { clearAuth } = await import('@/utils/apiClient');
- clearAuth();
- } catch (clearError) {
- logger.warn('[App] Failed to clear stored auth after auth check error', clearError);
- }
+ // A transport, discovery or permission failure is not an expired session.
+ // Keep the saved credentials and tenant for an explicit connection retry,
+ // but admit neither the authenticated shell nor first-run setup.
+ setBootstrapFailed(true);
aiAvailabilityStore.setEnabled(false);
setHasAuth(false);
setNeedsAuth(true);
@@ -859,6 +860,7 @@ export const useAppRuntimeState = () => {
return {
isLoading,
+ bootstrapFailed,
needsAuth,
hasAuth,
organizations,