Skip to content

Modern Docker Management, Designed for Everyone

fix: stop logout from hanging on permission errors after OIDC login (#4309)

Kyle Mendell1237b9b0d4be
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index f646e0109..8fc884399 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -405,6 +405,9 @@
"auth_tagline_line2": "Designed for everyone.",
"auth_login_problem_title": "Login Problem",
"auth_failed_title": "Authentication Failed",
+ "auth_signing_out": "Signing out",
+ "auth_signing_out_description": "Ending your session…",
+ "auth_logout_revocation_unconfirmed": "You were signed out on this device, but Arcane couldn't confirm the server session was revoked.",
"auth_proxy_login_error": "Arcane couldn't complete login through the reverse proxy. Check that Arcane is reachable and that the proxy allows the authentication headers, then try again.",
"auth_no_login_methods_title": "No Login Methods Configured",
"auth_no_login_methods_description": "There are currently no login methods enabled. Please contact an administrator.",
diff --git a/frontend/src/lib/components/dialogs/image-registry-search-dialog.svelte b/frontend/src/lib/components/dialogs/image-registry-search-dialog.svelte
index 8e5584d47..cb0ed5c18 100644
--- a/frontend/src/lib/components/dialogs/image-registry-search-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/image-registry-search-dialog.svelte
@@ -88,6 +88,7 @@
const result = await imageService.pullImageStream(imageRef);
pullingImageName = null;
+ if (result.cancelled) return;
if (!result.success) {
const message = result.error || m.images_pull_failed();
toast.error(message);
diff --git a/frontend/src/lib/components/sheets/image-pull-sheet.svelte b/frontend/src/lib/components/sheets/image-pull-sheet.svelte
index 66c83e40c..627e36f4b 100644
--- a/frontend/src/lib/components/sheets/image-pull-sheet.svelte
+++ b/frontend/src/lib/components/sheets/image-pull-sheet.svelte
@@ -57,6 +57,7 @@
async function drainPullStream(fullImageName: string) {
const result = await imageService.pullImageStream(fullImageName);
+ if (result.cancelled) return;
if (!result.success) {
const message = result.error || m.images_pull_unexpected_error();
toast.error(message);
diff --git a/frontend/src/lib/components/sheets/new-environment-sheet.svelte b/frontend/src/lib/components/sheets/new-environment-sheet.svelte
index eaaf84c05..fcac18997 100644
--- a/frontend/src/lib/components/sheets/new-environment-sheet.svelte
+++ b/frontend/src/lib/components/sheets/new-environment-sheet.svelte
@@ -15,6 +15,7 @@
import { RemoteEnvironmentIcon, EdgeConnectionIcon, DownloadIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
import { queryKeys } from '#lib/query/query-keys.js';
+ import { isSessionCancelledError, withSessionSignal } from '#lib/services/api-service.js';
import { environmentManagementService } from '#lib/services/env-mgmt-service.js';
import type { CreateEnvironmentDTO, DeploymentSnippetFile } from '#lib/types/environment.js';
import { downloadTextFile } from '#lib/utils/formatting.js';
@@ -190,7 +191,7 @@
const downloadUrl = file.downloadUrl;
const operationResult2 = await tryCatch(
(async () => {
- const response = await fetch(downloadUrl, { credentials: 'include' });
+ const response = await fetch(downloadUrl, { credentials: 'include', signal: withSessionSignal() });
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
@@ -205,7 +206,7 @@
URL.revokeObjectURL(url);
})()
);
- if (operationResult2.error !== null) {
+ if (operationResult2.error !== null && !isSessionCancelledError(operationResult2.error)) {
const err = operationResult2.error;
console.error('Failed to download mTLS asset:', err);
diff --git a/frontend/src/lib/services/api-service.ts b/frontend/src/lib/services/api-service.ts
index f22f179c9..07920c0aa 100644
--- a/frontend/src/lib/services/api-service.ts
+++ b/frontend/src/lib/services/api-service.ts
@@ -28,6 +28,20 @@ export interface APIResponse<T = any> {
status: number;
}
+// Thrown for work belonging to a session that ended through logout.
+export class SessionCancelledError extends Error {
+ constructor() {
+ super('Session ended');
+ this.name = 'SessionCancelledError';
+ }
+}
+
+// Browsers may surface a logout abort as a plain AbortError instead of the abort reason.
+export function isSessionCancelledError(error: unknown): boolean {
+ if (error instanceof SessionCancelledError) return true;
+ return error instanceof Error && error.name === 'AbortError' && sessionControllerInternal.signal.aborted;
+}
+
export class APIError extends Error {
config: InternalRequestConfig & { method?: string; url?: string };
request?: { url: string };
@@ -237,6 +251,31 @@ const skipAuthPathsInternal = [
'/settings/public'
];
+// Each session owns one controller; logout aborts it and keeps it aborted until
+// the next sign-in, so protected requests fail fast in between.
+let sessionControllerInternal = new AbortController();
+
+// Requests needed to sign in again, which must work after logout.
+function isSessionFreePathInternal(path: string): boolean {
+ if (path.startsWith('/auth/refresh')) return false;
+ return (
+ skipAuthPathsInternal.some((prefix) => path.startsWith(prefix)) ||
+ ['/oidc/url', '/oidc/callback', '/oidc/status'].includes(path) ||
+ path.startsWith('/app-version') ||
+ path.endsWith('/settings/public')
+ );
+}
+
+/** Combines a caller signal with the current session, so logout cancels the request. */
+export function withSessionSignal(signal?: AbortSignal | null): AbortSignal {
+ const session = sessionControllerInternal.signal;
+ return signal ? AbortSignal.any([signal, session]) : session;
+}
+
+export function currentSessionSignal(): AbortSignal {
+ return sessionControllerInternal.signal;
+}
+
type UnauthorizedActionInternal = 'none' | 'redirect' | 'reload' | 'retry';
function isAuthPagePathInternal(pathname: string): boolean {
@@ -248,7 +287,8 @@ export async function handleUnauthorizedResponseInternal(
retry = false,
serverMsg?: string | null
): Promise<UnauthorizedActionInternal> {
- if (typeof window === 'undefined' || retry) {
+ const session = sessionControllerInternal.signal;
+ if (typeof window === 'undefined' || retry || session.aborted) {
return 'none';
}
@@ -281,6 +321,7 @@ export async function handleUnauthorizedResponseInternal(
return 'reload';
})()
);
+ if (session.aborted) return 'none';
if (operationResult.error !== null) {
const error = operationResult.error;
const isTransientRefreshFailure =
@@ -355,14 +396,17 @@ class APIClient {
method,
url
};
+ const session = isSessionFreePathInternal(getRequestPath(url, baseURL)) ? undefined : sessionControllerInternal.signal;
+ const signal = session ? withSessionSignal(config.signal) : config.signal;
const operationResult = await tryCatch(
(async () => {
- const options = buildRequestOptionsInternal(method, data, config);
+ const options = buildRequestOptionsInternal(method, data, { ...config, signal });
const response = await this.client(requestUrl, options);
const parsed =
method.toUpperCase() === 'HEAD' ? undefined : await parseResponseBody(response.clone(), config.responseType);
+ if (session?.aborted) throw new SessionCancelledError();
return {
data: parsed as T,
headers: response.headers,
@@ -373,8 +417,11 @@ class APIClient {
);
if (operationResult.error !== null) {
const error = operationResult.error;
+ if (session?.aborted) {
+ throw new SessionCancelledError();
+ }
if (error instanceof KyHTTPError) {
- return this.handleHttpError<T>(error, method, url, data, config, requestConfig, requestUrl);
+ return this.handleHttpError<T>(error, method, url, data, config, requestConfig, requestUrl, session);
}
if (error instanceof TimeoutError) {
@@ -421,10 +468,12 @@ class APIClient {
data: unknown,
config: InternalRequestConfig,
requestConfig: InternalRequestConfig & { baseURL: string; method: string; url: string },
- requestUrl: string
+ requestUrl: string,
+ session: AbortSignal | undefined
): Promise<APIResponse<T>> {
const errorResponse = error.response;
const parsed = await parseErrorResponseBody(error);
+ if (session?.aborted) throw new SessionCancelledError();
const response: APIResponse = {
data: parsed,
headers: errorResponse.headers,
@@ -438,6 +487,7 @@ class APIClient {
!!config._retry,
extractServerMessage(parsed)
);
+ if (session?.aborted) throw new SessionCancelledError();
if (action === 'retry') {
return this.performRequest<T>(method, url, data, {
...config,
@@ -507,6 +557,17 @@ abstract class BaseAPIService {
upgradeInProgressInternal = value;
}
+ /** Cancels the current session's work and blocks protected requests until beginSession. */
+ static endSession() {
+ sessionControllerInternal.abort(new SessionCancelledError());
+ }
+
+ static beginSession() {
+ if (sessionControllerInternal.signal.aborted) {
+ sessionControllerInternal = new AbortController();
+ }
+ }
+
static confirmUpgradeRestart() {
upgradeReloadPendingInternal = true;
}
diff --git a/frontend/src/lib/services/auth-service.ts b/frontend/src/lib/services/auth-service.ts
index 54dac3d52..2be8e0388 100644
--- a/frontend/src/lib/services/auth-service.ts
+++ b/frontend/src/lib/services/auth-service.ts
@@ -15,7 +15,7 @@ import { parseInstant } from '#lib/utils/formatting.js';
import { getEffectiveLandingPage } from '#lib/utils/navigation.js';
import { tryCatch } from '#lib/utils/try-catch.js';
-import BaseAPIService, { APIError } from './api-service';
+import BaseAPIService, { APIError, SessionCancelledError, currentSessionSignal } from './api-service';
const REFRESH_TOKEN_KEY = 'arcane_refresh_token';
const TOKEN_EXPIRY_KEY = 'arcane_token_expiry';
@@ -32,6 +32,7 @@ class AuthService extends BaseAPIService {
private refreshTimer: ReturnType<typeof setTimeout> | null = null;
private isRefreshing = false;
private refreshSubscribers: Array<(token: string | null, error?: Error) => void> = [];
+ private logoutRequest: Promise<boolean> | null = null;
constructor() {
super();
@@ -115,6 +116,7 @@ class AuthService extends BaseAPIService {
}
this.isRefreshing = true;
+ const session = currentSessionSignal();
const operationResult = await tryCatch(
(async () => {
@@ -124,6 +126,8 @@ class AuthService extends BaseAPIService {
expiresAt?: string;
}>(this.api.post('/auth/refresh', { refreshToken }));
+ // Logout already reset the refresh state; a later login may own it now.
+ if (session.aborted) throw new SessionCancelledError();
if (response.refreshToken && response.expiresAt) {
this.storeTokenData(response.refreshToken, response.expiresAt);
}
@@ -138,6 +142,7 @@ class AuthService extends BaseAPIService {
);
if (operationResult.error !== null) {
const error = operationResult.error;
+ if (session.aborted) throw new SessionCancelledError();
const err = error instanceof Error ? error : new Error('Token refresh failed');
console.error('Token refresh failed:', err);
// Only drop the stored refresh token when the server definitively rejects it
@@ -176,6 +181,7 @@ class AuthService extends BaseAPIService {
throw new Error('Authentication did not complete');
}
+ BaseAPIService.beginSession();
if (data.refreshToken && data.expiresAt) {
this.storeTokenData(data.refreshToken, data.expiresAt);
}
@@ -244,9 +250,24 @@ class AuthService extends BaseAPIService {
}
}
- logout(queryClient: QueryClient): void {
+ /** Ends the local session, then revokes the server session. Resolves false when revocation is unconfirmed. */
+ logout(queryClient: QueryClient): Promise<boolean> {
+ // Reuse the pending request only while it still belongs to the current session.
+ if (this.logoutRequest && currentSessionSignal().aborted) return this.logoutRequest;
+
+ BaseAPIService.endSession();
this.clearTokenData();
+ this.refreshSubscribers.forEach((callback) => callback(null, new SessionCancelledError()));
+ this.refreshSubscribers = [];
+ this.isRefreshing = false;
this.resetAuthenticatedState(queryClient);
+
+ const request: Promise<boolean> = tryCatch(this.api.post('/auth/logout', undefined, { timeout: 10_000 })).then((result) => {
+ if (this.logoutRequest === request) this.logoutRequest = null;
+ return result.error === null;
+ });
+ this.logoutRequest = request;
+ return request;
}
/**
diff --git a/frontend/src/lib/services/container-service.ts b/frontend/src/lib/services/container-service.ts
index 85cf1d330..c429e6272 100644
--- a/frontend/src/lib/services/container-service.ts
+++ b/frontend/src/lib/services/container-service.ts
@@ -17,7 +17,7 @@ import { downloadFromUrl } from '#lib/utils/browser-download.js';
import { transformPaginationParams } from '#lib/utils/tables.js';
import { tryCatch } from '#lib/utils/try-catch.js';
-import BaseAPIService, { extractServerMessage, handleUnauthorizedResponseInternal } from './api-service';
+import BaseAPIService, { extractServerMessage, handleUnauthorizedResponseInternal, withSessionSignal } from './api-service';
export type ContainersPaginatedResponse = Paginated<ContainerSummaryDto, ContainerStatusCounts> & {
groups?: ContainerSummaryGroupDto[];
@@ -171,7 +171,7 @@ class ContainerService extends BaseAPIService {
private async probeDownloadInternal(url: string, retry = false): Promise<boolean> {
const probe = new AbortController();
- const response = await fetch(url, { credentials: 'include', signal: probe.signal });
+ const response = await fetch(url, { credentials: 'include', signal: withSessionSignal(probe.signal) });
if (response.ok) {
probe.abort();
return true;
diff --git a/frontend/src/lib/services/image-service.ts b/frontend/src/lib/services/image-service.ts
index afa5733e6..24e645069 100644
--- a/frontend/src/lib/services/image-service.ts
+++ b/frontend/src/lib/services/image-service.ts
@@ -21,13 +21,15 @@ import { readNdjsonStream } from '#lib/utils/streaming.js';
import { transformPaginationParams } from '#lib/utils/tables.js';
import { tryCatch } from '#lib/utils/try-catch.js';
-import BaseAPIService from './api-service';
+import BaseAPIService, { isSessionCancelledError, withSessionSignal } from './api-service';
import { uploadService, type UploadProgressCallback } from './upload-service';
export type ImagePullResult = {
success: boolean;
imageName: string;
error?: string;
+ /** The pull was abandoned because the user signed out. */
+ cancelled?: boolean;
};
/** Image list page plus the upload limit (MB) the environment enforces; absent on older agents. */
@@ -115,7 +117,8 @@ class ImageService extends BaseAPIService {
const response = await fetch(`/api/environments/${envId}/images/pull`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ imageName })
+ body: JSON.stringify({ imageName }),
+ signal: withSessionSignal()
});
if (!response.ok || !response.body) {
@@ -151,6 +154,9 @@ class ImageService extends BaseAPIService {
);
if (operationResult.error !== null) {
const error = operationResult.error;
+ if (isSessionCancelledError(error)) {
+ return { success: false, imageName, cancelled: true };
+ }
return {
success: false,
imageName,
diff --git a/frontend/src/lib/services/project-service.ts b/frontend/src/lib/services/project-service.ts
index 6514aa038..de83746ef 100644
--- a/frontend/src/lib/services/project-service.ts
+++ b/frontend/src/lib/services/project-service.ts
@@ -14,7 +14,7 @@ import type {
import { readNdjsonStream } from '#lib/utils/streaming.js';
import { transformPaginationParams } from '#lib/utils/tables.js';
-import BaseAPIService from './api-service';
+import BaseAPIService, { withSessionSignal } from './api-service';
class ProjectService extends BaseAPIService {
private async resolveEnvironmentId(environmentId?: string): Promise<string> {
@@ -150,7 +150,8 @@ class ProjectService extends BaseAPIService {
headers: {
'Content-Type': 'application/json'
},
- body: JSON.stringify(body)
+ body: JSON.stringify(body),
+ signal: withSessionSignal()
});
if (!res.ok || !res.body) {
throw new Error(messages.startFailed(String(res.status)));
@@ -244,7 +245,7 @@ class ProjectService extends BaseAPIService {
const envId = await environmentStore.getCurrentEnvironmentId();
const url = `/api/environments/${envId}/projects/${projectId}/pull`;
- const res = await fetch(url, { method: 'POST' });
+ const res = await fetch(url, { method: 'POST', signal: withSessionSignal() });
if (!res.ok || !res.body) {
throw new Error(`Failed to start project image pull (${res.status})`);
}
diff --git a/frontend/src/lib/services/stream-service.ts b/frontend/src/lib/services/stream-service.ts
index 29bd7524c..22b4bb721 100644
--- a/frontend/src/lib/services/stream-service.ts
+++ b/frontend/src/lib/services/stream-service.ts
@@ -1,7 +1,7 @@
import { streamCacheBuster } from '#lib/utils/streaming.js';
import { tryCatch } from '#lib/utils/try-catch.js';
-import BaseAPIService, { handleUnauthorizedResponseInternal } from './api-service';
+import BaseAPIService, { handleUnauthorizedResponseInternal, withSessionSignal } from './api-service';
export const STREAM_CHANNEL_ENVIRONMENTS = 'environments';
export const STREAM_CHANNEL_DASHBOARD = 'dashboard';
@@ -26,7 +26,7 @@ class StreamService extends BaseAPIService {
const response = await fetch(this.getClientStreamUrl(channels, params), {
credentials: 'include',
headers: { Accept: 'text/event-stream' },
- signal
+ signal: withSessionSignal(signal)
});
if (response.status === 401) {
if (response.body) await tryCatch(response.body.cancel());
diff --git a/frontend/src/lib/services/swarm-service.ts b/frontend/src/lib/services/swarm-service.ts
index 94bf5ce5b..425bf7958 100644
--- a/frontend/src/lib/services/swarm-service.ts
+++ b/frontend/src/lib/services/swarm-service.ts
@@ -217,9 +217,9 @@ class SwarmService extends BaseAPIService {
return this.handleResponse(this.api.get(`/environments/${envId}/swarm/info`));
}
- async getSwarmStatus(environmentId?: string): Promise<SwarmRuntimeStatus> {
+ async getSwarmStatus(environmentId?: string, config?: APIRequestConfig): Promise<SwarmRuntimeStatus> {
const envId = environmentId ?? (await environmentStore.getCurrentEnvironmentId());
- return this.handleResponse(this.api.get(`/environments/${envId}/swarm/status`));
+ return this.handleResponse(this.api.get(`/environments/${envId}/swarm/status`, config));
}
async initSwarm(request: SwarmInitRequest): Promise<SwarmInitResponse> {
diff --git a/frontend/src/lib/stores/sse-stream.svelte.ts b/frontend/src/lib/stores/sse-stream.svelte.ts
index 5641800cf..3511659e2 100644
--- a/frontend/src/lib/stores/sse-stream.svelte.ts
+++ b/frontend/src/lib/stores/sse-stream.svelte.ts
@@ -1,5 +1,6 @@
import { browser } from '$app/env';
+import { currentSessionSignal } from '#lib/services/api-service.js';
import type { SSEEventBase, SSEStreamConfig } from '#lib/types/stream.js';
import { tryCatch } from '#lib/utils/try-catch.js';
@@ -104,7 +105,7 @@ export function createSSEStream<TEvent extends SSEEventBase>(config: SSEStreamCo
);
if (operationResult.error !== null) {
const error = operationResult.error;
- if (!controller.signal.aborted && isCurrentGeneration(generation)) {
+ if (!controller.signal.aborted && !currentSessionSignal().aborted && isCurrentGeneration(generation)) {
console.warn(`${config.label} stream disconnected:`, error);
}
} else {
@@ -116,7 +117,8 @@ export function createSSEStream<TEvent extends SSEEventBase>(config: SSEStreamCo
}
if (isCurrentGeneration(generation)) {
_streamConnected = false;
- if (!controller.signal.aborted) {
+ // After logout, the next sign-in restarts streams through their stores.
+ if (!controller.signal.aborted && !currentSessionSignal().aborted) {
scheduleReconnect(generation);
}
} else if (!controller.signal.aborted) {
diff --git a/frontend/src/lib/utils/api.ts b/frontend/src/lib/utils/api.ts
index 233027e96..a8eeb9058 100644
--- a/frontend/src/lib/utils/api.ts
+++ b/frontend/src/lib/utils/api.ts
@@ -1,7 +1,7 @@
import { error as kitError } from '@sveltejs/kit';
import { toast } from 'svelte-sonner';
-import { APIError, extractServerMessage } from '#lib/services/api-service.js';
+import { APIError, extractServerMessage, isSessionCancelledError } from '#lib/services/api-service.js';
import type { Result } from '#lib/types/result.js';
import { tryCatch } from '#lib/utils/try-catch.js';
@@ -56,6 +56,8 @@ export async function handleApiResultWithCallbacks<T>({
try {
setLoadingState(true);
+ // Work from a signed-out session is dropped without feedback.
+ if (isSessionCancelledError(result.error)) return;
if (result.error) {
console.error(`API Error: ${message}:`, result.error);
if (!(result.error instanceof APIError) || result.error.status !== 403) {
diff --git a/frontend/src/lib/utils/ws.ts b/frontend/src/lib/utils/ws.ts
index ac627e19d..f87df8855 100644
--- a/frontend/src/lib/utils/ws.ts
+++ b/frontend/src/lib/utils/ws.ts
@@ -1,4 +1,5 @@
import { m } from '#lib/paraglide/messages.js';
+import { currentSessionSignal } from '#lib/services/api-service.js';
import type {
ActorDiagnostics,
Diagnostics,
@@ -119,7 +120,7 @@ export class ReconnectingWebSocket<T = unknown> {
}
private scheduleReconnect() {
- if (this.opts.shouldReconnect && !this.opts.shouldReconnect()) {
+ if (currentSessionSignal().aborted || (this.opts.shouldReconnect && !this.opts.shouldReconnect())) {
return;
}
diff --git a/frontend/src/routes/(app)/images/builds/+page.svelte b/frontend/src/routes/(app)/images/builds/+page.svelte
index 14dc3fc7b..213a6d61b 100644
--- a/frontend/src/routes/(app)/images/builds/+page.svelte
+++ b/frontend/src/routes/(app)/images/builds/+page.svelte
@@ -13,6 +13,7 @@
import TabbedPageLayout from '#lib/layouts/tabbed-page-layout.svelte';
import { m } from '#lib/paraglide/messages.js';
import { queryKeys } from '#lib/query/query-keys.js';
+ import { isSessionCancelledError, withSessionSignal } from '#lib/services/api-service.js';
import { containerRegistryService } from '#lib/services/container-registry-service.js';
import settingsStore from '#lib/stores/config-store.svelte.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
@@ -272,7 +273,8 @@
headers: {
'Content-Type': 'application/json'
},
- body: JSON.stringify(payload)
+ body: JSON.stringify(payload),
+ signal: withSessionSignal()
});
if (!response.ok || !response.body) {
@@ -596,7 +598,7 @@
toast.success(m.build_completed());
})()
);
- if (operationResult.error !== null) {
+ if (operationResult.error !== null && !isSessionCancelledError(operationResult.error)) {
const error = operationResult.error;
const message = sanitizeLogText(error instanceof Error ? error.message : m.build_failed());
diff --git a/frontend/src/routes/(auth)/logout/+page.svelte b/frontend/src/routes/(auth)/logout/+page.svelte
new file mode 100644
index 000000000..3666dd706
--- /dev/null
+++ b/frontend/src/routes/(auth)/logout/+page.svelte
@@ -0,0 +1,21 @@
+<script lang="ts">
+ import { goto } from '$app/navigation';
+ import { useQueryClient } from '@tanstack/svelte-query';
+ import { onMount } from 'svelte';
+ import { toast } from 'svelte-sonner';
+
+ import OidcStatusPanel from '#lib/components/oidc-status-panel.svelte';
+ import { m } from '#lib/paraglide/messages.js';
+ import { authService } from '#lib/services/auth-service.js';
+
+ const queryClient = useQueryClient();
+
+ // Runs on page entry only, so preloading the logout link never signs anyone out.
+ onMount(async () => {
+ const revoked = await authService.logout(queryClient);
+ await goto('/login', { replaceState: true });
+ if (!revoked) toast.error(m.auth_logout_revocation_unconfirmed());
+ });
+</script>
+
+<OidcStatusPanel busy busyTitle={m.auth_signing_out()} busyDescription={m.auth_signing_out_description()} error="" />
diff --git a/frontend/src/routes/(auth)/logout/+page.ts b/frontend/src/routes/(auth)/logout/+page.ts
deleted file mode 100644
index 910894995..000000000
--- a/frontend/src/routes/(auth)/logout/+page.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { redirect } from '@sveltejs/kit';
-
-import { authService } from '#lib/services/auth-service.js';
-import { tryCatch } from '#lib/utils/try-catch.js';
-
-import type { PageLoad } from './$types';
-
-export const load: PageLoad = async ({ fetch, parent }) => {
- const { queryClient } = await parent();
-
- const operationResult = await tryCatch(
- (async () => {
- await fetch('/api/auth/logout', {
- method: 'POST',
- credentials: 'include'
- });
- })()
- );
- if (operationResult.error !== null) {
- const error = operationResult.error;
-
- console.error('Logout error:', error);
- }
-
- authService.logout(queryClient);
-
- throw redirect(302, '/login');
-};
diff --git a/frontend/src/routes/+layout.ts b/frontend/src/routes/+layout.ts
index b1707e964..fcc5ec44c 100644
--- a/frontend/src/routes/+layout.ts
+++ b/frontend/src/routes/+layout.ts
@@ -3,13 +3,14 @@ import { redirect } from '@sveltejs/kit';
import { QueryClient } from '@tanstack/svelte-query';
import { queryKeys } from '#lib/query/query-keys.js';
+import { isSessionCancelledError } from '#lib/services/api-service.js';
import { authService } from '#lib/services/auth-service.js';
import { environmentManagementService } from '#lib/services/env-mgmt-service.js';
import { roleService } from '#lib/services/role-service.js';
import { settingsService } from '#lib/services/settings-service.js';
import { swarmService } from '#lib/services/swarm-service.js';
import { userService } from '#lib/services/user-service.js';
-import versionService from '#lib/services/version-service.js';
+import versionService, { toAppVersionInformation } from '#lib/services/version-service.js';
import settingsStore from '#lib/stores/config-store.svelte.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { featureStore } from '#lib/stores/features.store.svelte.js';
@@ -49,11 +50,24 @@ let authenticatedUserId: string | null | undefined;
// lands on the landing page. Only an explicit rejection means the session is
// gone; anything else keeps the user we already know about.
function resolveUserAfterLoadFailureInternal(error: unknown): User | null {
- if (isAuthRejectionError(error)) return null;
+ if (isAuthRejectionError(error) || isSessionCancelledError(error)) return null;
return userStore.current;
}
export const load: LayoutLoad = async ({ url }) => {
+ // Logout must not wait on, or be triggered by, authenticated requests; preloading runs this too.
+ if (url.pathname === '/logout') {
+ return {
+ user: null,
+ settings: settingsStore.current ?? null,
+ permissionsManifest: null,
+ permissionsManifestLoadFailed: false,
+ versionInformation: versionStore.current ?? toAppVersionInformation({}),
+ queryClient,
+ swarmEnabled: undefined
+ };
+ }
+
const versionInformationRequest = versionService.getVersionInformation();
const autoLoginConfigRequest = browser
? queryClient.query({
@@ -131,10 +145,17 @@ export const load: LayoutLoad = async ({ url }) => {
result.error ? null : result.data
);
featureStore.connect(queryClient);
- const featuresRequest = featureStore.refresh(await environmentStore.getCurrentEnvironmentId());
+ const currentEnvironmentId = await environmentStore.getCurrentEnvironmentId();
+ const featuresRequest = featureStore.refresh(currentEnvironmentId);
+ // Optional discovery: skip it without swarm:read and never toast a denial.
+ const swarmStatusRequest = userHasPermission(user, 'swarm:read', currentEnvironmentId)
+ ? tryCatch(swarmService.getSwarmStatus(currentEnvironmentId, { suppressAccessDeniedToast: true })).then((result) =>
+ result.error ? null : result.data
+ )
+ : Promise.resolve(null);
const [loadedSettings, loadedSwarmStatus, loadedPermissionsManifest] = await Promise.all([
settingsRequest,
- tryCatch(swarmService.getSwarmStatus()).then((result) => (result.error ? null : result.data)),
+ swarmStatusRequest,
permissionsManifestRequest
]);
// Keep recovery/settings pages reachable while a selected agent is offline.
diff --git a/tests/spec/activities.spec.ts b/tests/spec/activities.spec.ts
index f3f7508e2..8bffe2529 100644
--- a/tests/spec/activities.spec.ts
+++ b/tests/spec/activities.spec.ts
@@ -482,19 +482,34 @@ test.describe('Activity Center', () => {
});
});
await page.context().route(/\/api\/auth\/logout$/, async (route) => {
- activeUserId = 'user-b';
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ success: true })
});
});
+ await page.context().route(/\/api\/auth\/login$/, async (route) => {
+ activeUserId = 'user-b';
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ success: true,
+ status: 'authenticated',
+ user: user(activeUserId, permissions)
+ })
+ });
+ });
await page.goto('/dashboard');
let activityCenter = await openActivityCenter(page);
await expect(activityRow(activityCenter, 'user-a-private-activity')).toBeVisible();
await page.goto('/logout');
+ await page.waitForURL(/\/login/);
+ await page.getByLabel('Username').fill('user-b');
+ await page.getByLabel('Password').fill('password');
+ await page.getByRole('button', { name: 'Sign in to Arcane', exact: true }).click();
await page.waitForURL('/dashboard');
await expect.poll(() => streamedUsers).toContain('user-b');
activityCenter = await openActivityCenter(page);