/* Client SDK. Credentials and session handles belong exclusively on the application's backend. */ (() => { window.SSOInternalSession = { start({ issuer, clientId, checkUrl, onChange, onUnavailable = () => {}, interval = 2000, }) { const authority = new URL(issuer); const endpoint = new URL(checkUrl, location.href); if ( endpoint.origin !== location.origin || authority.username || authority.password || (authority.protocol !== "https:" && !( authority.protocol === "http:" && ["localhost", "127.0.0.1"].includes(authority.hostname) )) ) { throw new Error("Invalid session configuration"); } let stopped = false, pending = false, previous, timer; const controller = new AbortController(); const frame = document.createElement("iframe"); frame.hidden = true; frame.title = "Session synchronization"; const broker = new URL("/internal/session/frame", authority.origin); broker.searchParams.set("client_id", clientId); broker.searchParams.set("origin", location.origin); frame.src = broker.href; async function check() { if (pending || stopped) return; pending = true; try { const response = await fetch(endpoint, { credentials: "same-origin", cache: "no-store", signal: controller.signal, }); if (!response.ok) throw new Error("Session unavailable"); const state = await response.json(); const fingerprint = JSON.stringify(state); if (fingerprint !== previous && !stopped) { previous = fingerprint; onChange(state); } } catch (error) { if (!stopped) { previous = undefined; onUnavailable(error); } } finally { pending = false; } } const message = (event) => { if ( event.origin === authority.origin && event.source === frame.contentWindow && event.data?.type === "sso:session-changed" ) check(); }; function schedule() { clearTimeout(timer); if (stopped) return; timer = setTimeout( async () => { await check(); schedule(); }, document.hidden ? 10000 : Math.max(1000, interval) ); } const focus = () => { check(); schedule(); }; const hide = (event) => { if (!event.persisted) stop(); }; function stop() { stopped = true; clearTimeout(timer); controller.abort(); frame.remove(); window.removeEventListener("message", message); window.removeEventListener("focus", focus); document.removeEventListener("visibilitychange", focus); window.removeEventListener("pagehide", hide); window.removeEventListener("pageshow", focus); } window.addEventListener("message", message); window.addEventListener("focus", focus); window.addEventListener("pagehide", hide); window.addEventListener("pageshow", focus); document.addEventListener("visibilitychange", focus); document.body.append(frame); check(); schedule(); return { check, stop }; }, }; })();