Lightweight server monitoring with historical data, docker stats, and alerts.
fix(ui): only probe auto login when configured, load login data once
henrygdea4519014ea2
diff --git a/internal/hub/server.go b/internal/hub/server.goindex 0d55bbf57..cac40c723 100644--- a/internal/hub/server.go+++ b/internal/hub/server.go@@ -14,7 +14,10 @@ type PublicAppInfo struct {BASE_PATH stringHUB_VERSION stringHUB_URL string- OAUTH_DISABLE_POPUP bool `json:"OAUTH_DISABLE_POPUP,omitzero"`+ OAUTH_DISABLE_POPUP bool `json:",omitzero"`+ // AUTO_LOGIN is true when AUTO_LOGIN or TRUSTED_AUTH_HEADER is configured, so the+ // login page knows to try an anonymous auth refresh before showing the form.+ AUTO_LOGIN bool `json:",omitzero"`}// modifyIndexHTML injects the public app information into the index.html content@@ -64,5 +67,8 @@ func getPublicAppInfo(hub *Hub) PublicAppInfo {if val, _ := utils.GetEnv("OAUTH_DISABLE_POPUP"); val == "true" {info.OAUTH_DISABLE_POPUP = true}+ autoLogin, _ := utils.GetEnv("AUTO_LOGIN")+ trustedHeader, _ := utils.GetEnv("TRUSTED_AUTH_HEADER")+ info.AUTO_LOGIN = autoLogin != "" || trustedHeader != ""return info}diff --git a/internal/hub/server_test.go b/internal/hub/server_test.goindex 4dcbde90a..545a30f98 100644--- a/internal/hub/server_test.go+++ b/internal/hub/server_test.go@@ -57,3 +57,25 @@ func TestIsAppRoute(t *testing.T) {assert.Equal(t, tt.want, isAppRoute(tt.path, tt.basePath), "path=%q basePath=%q", tt.path, tt.basePath)}}++func TestGetPublicAppInfoAutoLogin(t *testing.T) {+ tests := []struct {+ name string+ autoLogin string+ trustedHeader string+ want bool+ }{+ {"neither configured", "", "", false},+ {"auto login", "[email protected]", "", true},+ {"trusted header", "", "X-Email", true},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ // prefixed vars take precedence, so an empty value overrides any ambient env+ t.Setenv("BESZEL_HUB_AUTO_LOGIN", tt.autoLogin)+ t.Setenv("BESZEL_HUB_TRUSTED_AUTH_HEADER", tt.trustedHeader)+ info := getPublicAppInfo(&Hub{appURL: "http://localhost:8090"})+ assert.Equal(t, tt.want, info.AUTO_LOGIN)+ })+ }+}diff --git a/internal/site/src/components/login/load-login.ts b/internal/site/src/components/login/load-login.tsindex bea15d0ae..2112003d5 100644--- a/internal/site/src/components/login/load-login.ts+++ b/internal/site/src/components/login/load-login.ts@@ -1,10 +1,22 @@import type PocketBase from "pocketbase"-/** Load the login page only after automatic / trusted-header authentication has been tried. */+interface LoginContext {+ route?: string+ search: string+ loggedOut: boolean+ /** Server has AUTO_LOGIN or TRUSTED_AUTH_HEADER configured. */+ autoLogin: boolean+}++/**+ * Load login page data. When automatic / trusted-header authentication is configured,+ * try it before resolving so the form isn't shown to users who will be logged in anyway.+ */export async function loadLogin(pb: PocketBase,- { route, search, loggedOut }: { route?: string; search: string; loggedOut: boolean },- signal: AbortSignal+ { route, search, loggedOut, autoLogin }: LoginContext,+ signal: AbortSignal,+ timeoutMs = 10_000) {const [{ firstRun }, authMethods] = await Promise.all([pb@@ -13,8 +25,10 @@ export async function loadLogin(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.+ // Only probe when the server can authenticate an anonymous request. Other flows are+ // handled by their existing forms.if (+ !autoLogin ||signal.aborted ||firstRun ||route === "forgot_password" ||@@ -29,12 +43,12 @@ export async function loadLogin(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)+ const timeout = setTimeout(abort, timeoutMs)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.+ // Rejected or timed out: fall back to the login form.} finally {clearTimeout(timeout)signal.removeEventListener("abort", abort)diff --git a/internal/site/src/components/login/login.tsx b/internal/site/src/components/login/login.tsxindex 0642be3ff..0218a1029 100644--- a/internal/site/src/components/login/login.tsx+++ b/internal/site/src/components/login/login.tsx@@ -14,32 +14,40 @@ import { OtpRequestForm } from "./otp-forms"export default function () {const page = useStore($router)- const [login, setLogin] = useState<Awaited<ReturnType<typeof loadLogin>> & { route?: string }>()+ const [login, setLogin] = useState<Awaited<ReturnType<typeof loadLogin>>>()const isFirstRun = login?.firstRun ?? falseconst { resolvedTheme } = useTheme()+ // Load once on mount; switching between login routes reuses the result.useEffect(() => {const controller = new AbortController()- document.title = "Beszel"+ const autoLogin = !!globalThis.BESZEL.AUTO_LOGIN+ // keep the title neutral while automatic authentication may still succeed+ document.title = autoLogin ? "Beszel" : `${t`Login`} / Beszel`loadLogin(pb,- { route: page?.route, search: window.location.search, loggedOut: !!sessionStorage.getItem("lo") },+ {+ route: $router.get()?.route,+ search: window.location.search,+ loggedOut: !!sessionStorage.getItem("lo"),+ autoLogin,+ },controller.signal)- .then(({ firstRun, authMethods, authenticated }) => {+ .then((result) => {if (controller.signal.aborted) return- if (authenticated) {+ if (result.authenticated) {$authenticated.set(true)return}document.title = `${t`Login`} / Beszel`- setLogin({ firstRun, authMethods, authenticated, route: page?.route })+ setLogin(result)}).catch((error) => {if (!controller.signal.aborted) console.error(error)})return () => controller.abort()- }, [page?.route])+ }, [])const subtitle = useMemo(() => {if (isFirstRun) {@@ -53,7 +61,7 @@ export default function () {}}, [isFirstRun, page])- if (!login || login.route !== page?.route) {+ if (!login) {return null}diff --git a/internal/site/src/types.d.ts b/internal/site/src/types.d.tsindex cb44d0816..9acc1a6e2 100644--- a/internal/site/src/types.d.ts+++ b/internal/site/src/types.d.ts@@ -8,6 +8,7 @@ declare global {HUB_VERSION: stringHUB_URL: stringOAUTH_DISABLE_POPUP: boolean+ AUTO_LOGIN?: boolean}}diff --git a/internal/site/tests/load-login.test.ts b/internal/site/tests/load-login.test.tsindex b8b73f36b..b0da4291d 100644--- a/internal/site/tests/load-login.test.ts+++ b/internal/site/tests/load-login.test.ts@@ -2,7 +2,7 @@ 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 context = { route: "home", search: "", loggedOut: false, autoLogin: true }const methods: AuthMethodsList = {password: { enabled: true, identityFields: ["email"] },oauth2: { enabled: false, providers: [] },@@ -80,6 +80,14 @@ describe("initial login authentication", () => {})}+ test("does not probe when automatic authentication is not configured", async () => {+ const { pb, requests } = client()+ const result = await loadLogin(pb, { ...context, autoLogin: false }, new AbortController().signal)+ expect(result.authenticated).toBe(false)+ expect(result.authMethods.password.enabled).toBe(true)+ expect(requests.some((path) => path.endsWith("/auth-refresh"))).toBe(false)+ })+for (const route of ["forgot_password", "request_otp"]) {test(`${route} does not attempt automatic authentication`, async () => {const { pb, requests } = client()@@ -124,27 +132,28 @@ describe("initial login authentication", () => {}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)+ 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, cancel ? 10_000 : 20)+ await started.promise+ if (cancel) controller.abort()+ expect((await result).authenticated).toBe(false)+ expect(aborted).toBe(true)+ }+ )}})