Skip to content

Lightweight server monitoring with historical data, docker stats, and alerts.

fix(ui): finish automatic authentication before showing login (#2810)

Marko Mihovilić701872e8cb99
diff --git a/internal/site/src/components/login/auth-form.tsx b/internal/site/src/components/login/auth-form.tsx
index 7980671aa..7e7f8b82e 100644
--- a/internal/site/src/components/login/auth-form.tsx
+++ b/internal/site/src/components/login/auth-form.tsx
@@ -196,7 +196,7 @@ export function UserAuthForm({
if (code) {
const state = params.get("state")
const provider: AuthProviderInfo = JSON.parse(localStorage.getItem("provider") ?? "{}")
- localStorage.removeItem("provider")
+ localStorage.removeItem("provider")
window.history.replaceState({}, "", window.location.pathname)
if (!state || provider.state !== state) {
showLoginFaliedToast()
@@ -216,14 +216,6 @@ export function UserAuthForm({
setTimeout(() => loginWithOauth(authProviders[0], false), 300)
return
}
-
- // refresh auth if not in above states (required for trusted auth header)
- pb.collection("users")
- .authRefresh()
- .then((res) => {
- pb.authStore.save(res.token, res.record)
- $authenticated.set(!!pb.authStore.isValid)
- })
}, [])
if (!authMethods) {
diff --git a/internal/site/src/components/login/load-login.ts b/internal/site/src/components/login/load-login.ts
new file mode 100644
index 000000000..bea15d0ae
--- /dev/null
+++ b/internal/site/src/components/login/load-login.ts
@@ -0,0 +1,43 @@
+import type PocketBase from "pocketbase"
+
+/** Load the login page only after automatic / trusted-header authentication has been tried. */
+export async function loadLogin(
+ pb: PocketBase,
+ { route, search, loggedOut }: { route?: string; search: string; loggedOut: boolean },
+ signal: AbortSignal
+) {
+ const [{ firstRun }, authMethods] = await Promise.all([
+ pb
+ .send<{ firstRun: boolean }>("/api/beszel/first-run", { signal, requestKey: null })
+ .catch(() => ({ firstRun: false })),
+ pb.collection("users").listAuthMethods({ signal, requestKey: null }),
+ ])
+ const result = { firstRun, authMethods, authenticated: false }
+ // These flows are handled by their existing forms, without a session probe.
+ if (
+ signal.aborted ||
+ firstRun ||
+ route === "forgot_password" ||
+ route === "request_otp" ||
+ new URLSearchParams(search).get("code") ||
+ (!authMethods.password.enabled && authMethods.oauth2.providers.length === 1 && !loggedOut)
+ ) {
+ return result
+ }
+
+ const controller = new AbortController()
+ const abort = () => controller.abort()
+ signal.addEventListener("abort", abort, { once: true })
+ // A stalled probe must not prevent access to the regular login form.
+ const timeout = setTimeout(abort, 10_000)
+ try {
+ await pb.collection("users").authRefresh({ signal: controller.signal, requestKey: null })
+ result.authenticated = pb.authStore.isValid
+ } catch {
+ // A rejected anonymous refresh is expected when automatic login is not configured.
+ } finally {
+ clearTimeout(timeout)
+ signal.removeEventListener("abort", abort)
+ }
+ return result
+}
diff --git a/internal/site/src/components/login/login.tsx b/internal/site/src/components/login/login.tsx
index 5a648011e..0642be3ff 100644
--- a/internal/site/src/components/login/login.tsx
+++ b/internal/site/src/components/login/login.tsx
@@ -1,37 +1,45 @@
import { t } from "@lingui/core/macro"
import { useStore } from "@nanostores/react"
-import type { AuthMethodsList } from "pocketbase"
import { useEffect, useMemo, useState } from "react"
import { UserAuthForm } from "@/components/login/auth-form"
import { pb } from "@/lib/api"
+import { $authenticated } from "@/lib/stores"
import { Logo } from "../logo"
import { ModeToggle } from "../mode-toggle"
import { $router } from "../router"
import { useTheme } from "../theme-provider"
import ForgotPassword from "./forgot-pass-form"
+import { loadLogin } from "./load-login"
import { OtpRequestForm } from "./otp-forms"
export default function () {
const page = useStore($router)
- const [isFirstRun, setFirstRun] = useState(false)
- const [authMethods, setAuthMethods] = useState<AuthMethodsList>()
+ const [login, setLogin] = useState<Awaited<ReturnType<typeof loadLogin>> & { route?: string }>()
+ const isFirstRun = login?.firstRun ?? false
const { resolvedTheme } = useTheme()
useEffect(() => {
- document.title = `${t`Login`} / Beszel`
-
- pb.send("/api/beszel/first-run", {}).then(({ firstRun }) => {
- setFirstRun(firstRun)
- })
- }, [])
-
- useEffect(() => {
- pb.collection("users")
- .listAuthMethods()
- .then((methods) => {
- setAuthMethods(methods)
+ const controller = new AbortController()
+ document.title = "Beszel"
+ loadLogin(
+ pb,
+ { route: page?.route, search: window.location.search, loggedOut: !!sessionStorage.getItem("lo") },
+ controller.signal
+ )
+ .then(({ firstRun, authMethods, authenticated }) => {
+ if (controller.signal.aborted) return
+ if (authenticated) {
+ $authenticated.set(true)
+ return
+ }
+ document.title = `${t`Login`} / Beszel`
+ setLogin({ firstRun, authMethods, authenticated, route: page?.route })
+ })
+ .catch((error) => {
+ if (!controller.signal.aborted) console.error(error)
})
- }, [])
+ return () => controller.abort()
+ }, [page?.route])
const subtitle = useMemo(() => {
if (isFirstRun) {
@@ -45,7 +53,7 @@ export default function () {
}
}, [isFirstRun, page])
- if (!authMethods) {
+ if (!login || login.route !== page?.route) {
return null
}
@@ -71,7 +79,7 @@ export default function () {
) : page?.route === "request_otp" ? (
<OtpRequestForm />
) : (
- <UserAuthForm isFirstRun={isFirstRun} authMethods={authMethods} />
+ <UserAuthForm isFirstRun={isFirstRun} authMethods={login.authMethods} />
)}
</div>
</div>
diff --git a/internal/site/tests/load-login.test.ts b/internal/site/tests/load-login.test.ts
new file mode 100644
index 000000000..b8b73f36b
--- /dev/null
+++ b/internal/site/tests/load-login.test.ts
@@ -0,0 +1,150 @@
+import { describe, expect, test } from "bun:test"
+import PocketBase, { type AuthMethodsList } from "pocketbase"
+import { loadLogin } from "../src/components/login/load-login"
+
+const context = { route: "home", search: "", loggedOut: false }
+const methods: AuthMethodsList = {
+ password: { enabled: true, identityFields: ["email"] },
+ oauth2: { enabled: false, providers: [] },
+ otp: { enabled: false, duration: 180 },
+ mfa: { enabled: false, duration: 180 },
+}
+const token = `test.${btoa(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 }))}.test`
+const success = () => Response.json({ token, record: { id: "test-user", collectionName: "users" } })
+
+function client({
+ firstRun = false,
+ firstRunFailed = false,
+ authMethods = methods,
+ refresh = (_signal: AbortSignal) => Promise.resolve(success()),
+} = {}) {
+ const pb = new PocketBase("http://localhost/beszel/")
+ const requests: string[] = []
+ pb.beforeSend = (url, options) => ({
+ url,
+ options: {
+ ...options,
+ fetch: () => {
+ const path = new URL(url).pathname
+ requests.push(path)
+ if (path.endsWith("/first-run")) {
+ return Promise.resolve(Response.json({ firstRun }, { status: firstRunFailed ? 500 : 200 }))
+ }
+ if (path.endsWith("/auth-methods")) return Promise.resolve(Response.json(authMethods))
+ if (path.endsWith("/auth-refresh")) return refresh(options.signal as AbortSignal)
+ throw new Error(`Unexpected request: ${path}`)
+ },
+ },
+ })
+ return { pb, requests }
+}
+
+describe("initial login authentication", () => {
+ test("waits for automatic authentication and saves the session before resolving", async () => {
+ const response = Promise.withResolvers<Response>()
+ const started = Promise.withResolvers<void>()
+ const { pb, requests } = client({
+ refresh: () => {
+ started.resolve()
+ return response.promise
+ },
+ })
+ let resolved = false
+ const loading = loadLogin(pb, context, new AbortController().signal).then((result) => {
+ resolved = true
+ return result
+ })
+ await started.promise
+ expect(resolved).toBe(false)
+ expect(pb.authStore.isValid).toBe(false)
+ response.resolve(success())
+ expect((await loading).authenticated).toBe(true)
+ expect(pb.authStore.record?.id).toBe("test-user")
+ expect(pb.authStore.isValid).toBe(true)
+ expect(requests.filter((path) => path.endsWith("/auth-refresh"))).toEqual([
+ "/beszel/api/collections/users/auth-refresh",
+ ])
+ })
+
+ for (const failure of ["rejected", "network"] as const) {
+ test(`${failure} authentication makes the password form available`, async () => {
+ const { pb } = client({
+ refresh: () => {
+ if (failure === "network") return Promise.reject(new TypeError("Failed to fetch"))
+ return Promise.resolve(Response.json({ message: "Unauthorized" }, { status: 401 }))
+ },
+ })
+ const result = await loadLogin(pb, context, new AbortController().signal)
+ expect(result.authenticated).toBe(false)
+ expect(result.authMethods.password.enabled).toBe(true)
+ })
+ }
+
+ for (const route of ["forgot_password", "request_otp"]) {
+ test(`${route} does not attempt automatic authentication`, async () => {
+ const { pb, requests } = client()
+ await loadLogin(pb, { ...context, route }, new AbortController().signal)
+ expect(requests.some((path) => path.endsWith("/auth-refresh"))).toBe(false)
+ })
+ }
+
+ test("onboarding does not probe a nonexistent account", async () => {
+ const { pb, requests } = client({ firstRun: true })
+ const result = await loadLogin(pb, context, new AbortController().signal)
+ expect(result.firstRun).toBe(true)
+ expect(result.authenticated).toBe(false)
+ expect(requests).toHaveLength(2)
+ })
+
+ test("an unavailable first-run check does not block authentication", async () => {
+ const { pb } = client({ firstRunFailed: true })
+ const result = await loadLogin(pb, context, new AbortController().signal)
+ expect(result.firstRun).toBe(false)
+ expect(result.authenticated).toBe(true)
+ })
+
+ test("OAuth callbacks retain priority over automatic authentication", async () => {
+ const { pb, requests } = client()
+ await loadLogin(pb, { ...context, search: "?code=example&state=test" }, new AbortController().signal)
+ expect(requests).toHaveLength(2)
+ })
+
+ for (const loggedOut of [false, true]) {
+ test(`single-provider OAuth preserves the logout guard (${loggedOut})`, async () => {
+ const { pb, requests } = client({
+ authMethods: {
+ ...methods,
+ password: { ...methods.password, enabled: false },
+ oauth2: { enabled: true, providers: [{ name: "oidc" } as AuthMethodsList["oauth2"]["providers"][number]] },
+ },
+ })
+ await loadLogin(pb, { ...context, loggedOut }, new AbortController().signal)
+ expect(requests.some((path) => path.endsWith("/auth-refresh"))).toBe(loggedOut)
+ })
+ }
+
+ for (const cancel of [true, false]) {
+ test(cancel
+ ? "unmount cancels a pending probe"
+ : "a stalled probe times out and releases the login form", async () => {
+ const controller = new AbortController()
+ const started = Promise.withResolvers<void>()
+ let aborted = false
+ const { pb } = client({
+ refresh: (signal) =>
+ new Promise<Response>((_resolve, reject) => {
+ signal.addEventListener("abort", () => {
+ aborted = true
+ reject(new DOMException("Aborted", "AbortError"))
+ })
+ started.resolve()
+ }),
+ })
+ const result = loadLogin(pb, context, controller.signal)
+ await started.promise
+ if (cancel) controller.abort()
+ expect((await result).authenticated).toBe(false)
+ expect(aborted).toBe(true)
+ }, 15_000)
+ }
+})