Skip to content

Modern Docker Management, Designed for Everyone

fix: silently refresh token on version mismatch instead of forcing logout (#1791)

Kyle Mendell0ee962bbe900
diff --git a/frontend/src/lib/services/api-service.ts b/frontend/src/lib/services/api-service.ts
index e2c5a796c..bcad94117 100644
--- a/frontend/src/lib/services/api-service.ts
+++ b/frontend/src/lib/services/api-service.ts
@@ -71,7 +71,6 @@ abstract class BaseAPIService {
'/auth/oidc',
'/auth/oidc/login',
'/auth/oidc/callback',
- '/auth/me',
'/auth/auto-login',
'/auth/auto-login-config',
'/settings/public'
@@ -85,25 +84,27 @@ abstract class BaseAPIService {
pathname.startsWith('/oidc') ||
pathname.startsWith('/auth/oidc');
- if (!isAuthApi && !isOnAuthPage && !isVersionMismatch && BaseAPIService.tokenRefreshHandler) {
+ if (!isAuthApi && !isOnAuthPage && BaseAPIService.tokenRefreshHandler) {
try {
- const newToken = await BaseAPIService.tokenRefreshHandler();
-
- if (newToken) {
- return this.api(originalRequest);
+ // Always try to refresh first — even on version mismatch, because the refresh
+ // token is not version-tagged and will return a new access token with the
+ // current app version embedded, keeping the user logged in after an update.
+ // Auth is cookie-based, so we just need the refresh to succeed (not throw);
+ // the Set-Cookie on the refresh response is what re-authorises future requests.
+ await BaseAPIService.tokenRefreshHandler();
+ return this.api(originalRequest);
+ } catch {
+ // Refresh failed (expired, missing, or server error) — redirect to login
+ if (isVersionMismatch) {
+ toast.info('Application has been updated. Please log in again.');
}
- } catch (refreshError) {
- console.error('Token refresh failed in interceptor:', refreshError);
- }
-
- // If we reach here, refresh failed - redirect to login
- if (!isOnAuthPage) {
const redirectTo = encodeURIComponent(pathname);
window.location.replace(`/login?redirect=${redirectTo}`);
return new Promise(() => {});
}
}
+ // No refresh handler available — version mismatch must force login
if (!isAuthApi && !isOnAuthPage && isVersionMismatch) {
toast.info('Application has been updated. Please log in again.');
const redirectTo = encodeURIComponent(pathname);
diff --git a/frontend/src/lib/services/auth-service.ts b/frontend/src/lib/services/auth-service.ts
index 82ca0d58d..e58ef0ceb 100644
--- a/frontend/src/lib/services/auth-service.ts
+++ b/frontend/src/lib/services/auth-service.ts
@@ -12,7 +12,7 @@ const REFRESH_BUFFER_MS = 5 * 60 * 1000; // Refresh 5 minutes before expiry
export class AuthService extends BaseAPIService {
private refreshTimer: ReturnType<typeof setTimeout> | null = null;
private isRefreshing = false;
- private refreshSubscribers: Array<(token: string) => void> = [];
+ private refreshSubscribers: Array<(token: string | null, error?: Error) => void> = [];
constructor() {
super();
@@ -77,13 +77,14 @@ export class AuthService extends BaseAPIService {
async refreshAccessToken(): Promise<string | null> {
const refreshToken = this.getStoredRefreshToken();
if (!refreshToken) {
- return null;
+ throw new Error('No refresh token available');
}
if (this.isRefreshing) {
- return new Promise((resolve) => {
- this.refreshSubscribers.push((token: string | null) => {
- resolve(token);
+ return new Promise<string | null>((resolve, reject) => {
+ this.refreshSubscribers.push((token: string | null, error?: Error) => {
+ if (error) reject(error);
+ else resolve(token);
});
});
}
@@ -102,17 +103,19 @@ export class AuthService extends BaseAPIService {
}
const token = response.token || null;
- this.refreshSubscribers.forEach((callback) => callback(token || ''));
+ this.refreshSubscribers.forEach((callback) => callback(token));
this.refreshSubscribers = [];
this.isRefreshing = false;
return token;
} catch (error) {
- console.error('Token refresh failed:', error);
+ const err = error instanceof Error ? error : new Error('Token refresh failed');
+ console.error('Token refresh failed:', err);
this.clearTokenData();
- this.isRefreshing = false;
+ this.refreshSubscribers.forEach((callback) => callback(null, err));
this.refreshSubscribers = [];
- return null;
+ this.isRefreshing = false;
+ throw err;
}
}
diff --git a/frontend/src/routes/(auth)/login/+page.ts b/frontend/src/routes/(auth)/login/+page.ts
index 61ba0a612..98dceaf04 100644
--- a/frontend/src/routes/(auth)/login/+page.ts
+++ b/frontend/src/routes/(auth)/login/+page.ts
@@ -3,12 +3,14 @@ import { redirect } from '@sveltejs/kit';
export const load = async ({ parent, url }) => {
const data = await parent();
+ const rawRedirect = url.searchParams.get('redirect') || '/dashboard';
+ // Guard against open redirects — only allow same-origin relative paths
+ const redirectTo = rawRedirect.startsWith('/') && !rawRedirect.startsWith('//') ? rawRedirect : '/dashboard';
+
if (data.user) {
- throw redirect(302, '/dashboard');
+ throw redirect(302, redirectTo);
}
- const redirectTo = url.searchParams.get('redirect') || '/dashboard';
-
const error = url.searchParams.get('error');
const errorMessage =
url.searchParams.get('message') || url.searchParams.get('error_message') || url.searchParams.get('errorMessage');
diff --git a/tests/spec/token-refresh.spec.ts b/tests/spec/token-refresh.spec.ts
new file mode 100644
index 000000000..4b4d2f669
--- /dev/null
+++ b/tests/spec/token-refresh.spec.ts
@@ -0,0 +1,146 @@
+import { test, expect, type Page } from "@playwright/test";
+
+const REFRESH_TOKEN_KEY = "arcane_refresh_token";
+const TOKEN_EXPIRY_KEY = "arcane_token_expiry";
+
+/**
+ * Register an addInitScript that plants a fake refresh token in sessionStorage
+ * BEFORE any page JavaScript runs on every navigation. Unlike page.evaluate(),
+ * addInitScript survives page.goto() calls made later in the test.
+ */
+async function registerTokenSeeding(page: Page) {
+ await page.addInitScript(
+ ([tokenKey, expiryKey]: [string, string]) => {
+ sessionStorage.setItem(tokenKey, "playwright-test-refresh-token");
+ sessionStorage.setItem(expiryKey, new Date(Date.now() + 3_600_000).toISOString());
+ },
+ [REFRESH_TOKEN_KEY, TOKEN_EXPIRY_KEY],
+ );
+}
+
+/**
+ * Intercept the FIRST request matching urlPattern with a 401 version-mismatch
+ * body. All subsequent requests (e.g. the interceptor's automatic retry) pass
+ * through. Uses a flag rather than unroute() to avoid "Route is already handled".
+ */
+async function injectVersionMismatch401Once(page: Page, urlPattern: string | RegExp) {
+ let fired = false;
+ await page.route(urlPattern, async (route) => {
+ if (!fired) {
+ fired = true;
+ await route.fulfill({
+ status: 401,
+ contentType: "application/json",
+ body: JSON.stringify({
+ code: "UNAUTHORIZED",
+ message: "Application has been updated. Please log in again.",
+ }),
+ });
+ } else {
+ await route.continue();
+ }
+ });
+}
+
+/**
+ * Intercept every request matching urlPattern with a 401.
+ */
+async function injectExpired401Always(page: Page, urlPattern: string | RegExp) {
+ await page.route(urlPattern, async (route) => {
+ await route.fulfill({
+ status: 401,
+ contentType: "application/json",
+ body: JSON.stringify({ code: "UNAUTHORIZED", message: "Invalid or expired token" }),
+ });
+ });
+}
+
+/**
+ * Mock /auth/refresh to return a synthetic 200. Returns a getter to assert
+ * whether the endpoint was called.
+ */
+async function mockRefreshSuccess(page: Page): Promise<() => boolean> {
+ let called = false;
+ await page.route(/\/api\/auth\/refresh$/, async (route) => {
+ called = true;
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({
+ success: true,
+ data: {
+ token: "mocked-access-token",
+ refreshToken: "mocked-refresh-token",
+ expiresAt: new Date(Date.now() + 3_600_000).toISOString(),
+ },
+ }),
+ });
+ });
+ return () => called;
+}
+
+test.describe("Token refresh behaviour", () => {
+ test("version mismatch 401 on /auth/me during page load is silently recovered", async ({ page }) => {
+ await registerTokenSeeding(page);
+ const wasRefreshCalled = await mockRefreshSuccess(page);
+ await injectVersionMismatch401Once(page, /\/api\/auth\/me$/);
+
+ await page.goto("/dashboard");
+ await page.waitForLoadState("networkidle");
+
+ expect(wasRefreshCalled()).toBe(true);
+ await expect(page).toHaveURL("/dashboard");
+ await expect(page.getByRole("button", { name: "Sign in to Arcane" })).not.toBeVisible();
+ });
+
+ test("version mismatch 401 on a data endpoint mid-session is silently recovered", async ({ page }) => {
+ await registerTokenSeeding(page);
+ const wasRefreshCalled = await mockRefreshSuccess(page);
+ await injectVersionMismatch401Once(page, /\/api\/environments\/0\/containers/);
+
+ await page.goto("/containers");
+ await page.waitForLoadState("networkidle");
+
+ expect(wasRefreshCalled()).toBe(true);
+ await expect(page).toHaveURL("/containers");
+ await expect(page.getByRole("heading", { name: "Containers", level: 1 })).toBeVisible();
+ await expect(page.getByRole("button", { name: "Sign in to Arcane" })).not.toBeVisible();
+ });
+
+ test("failed token refresh redirects to /login", async ({ page }) => {
+ await registerTokenSeeding(page);
+
+ await page.route(/\/api\/auth\/refresh$/, async (route) => {
+ await route.fulfill({
+ status: 401,
+ contentType: "application/json",
+ body: JSON.stringify({ code: "UNAUTHORIZED", message: "Invalid or expired refresh token" }),
+ });
+ });
+
+ // Make /auth/me always 401 so the interceptor triggers the refresh flow on load.
+ await injectExpired401Always(page, /\/api\/auth\/me$/);
+
+ await page.goto("/dashboard");
+ await page.waitForURL(/\/login/, { timeout: 10_000 });
+ await page.waitForLoadState("networkidle");
+ await expect(page).toHaveURL(/\/login/);
+ await expect(page.getByRole("button", { name: "Sign in to Arcane", exact: true })).toBeVisible();
+ });
+
+ test("unauthenticated users are redirected to /login", async ({ page }) => {
+ await page.context().clearCookies();
+ await page.goto("/dashboard");
+ await page.waitForURL(/\/login/, { timeout: 10_000 });
+ await page.waitForLoadState("networkidle");
+ await expect(page).toHaveURL(/\/login/);
+ await expect(page.getByRole("button", { name: "Sign in to Arcane", exact: true })).toBeVisible();
+ });
+
+ test("login page honours the redirect param and returns users to their original path", async ({ page }) => {
+ await page.goto("/login?redirect=%2Fcontainers");
+ await page.waitForURL(/\/containers|\/login/, { timeout: 8_000 });
+ const url = page.url();
+ expect(url).toMatch(/\/containers|\/login\?redirect=%2Fcontainers/);
+ });
+});