From 4eae0c975b7ea75ecbfc967f17d0d6e9bd7679ed Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Wed, 25 Sep 2024 17:06:43 +0200 Subject: [PATCH] Another attempt at better supporting auth proxies --- common/spaces/http_space_primitives.ts | 23 +++++++++++++++++++++-- common/sw_util.ts | 13 +++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/common/spaces/http_space_primitives.ts b/common/spaces/http_space_primitives.ts index e2c686b4..ea766f59 100644 --- a/common/spaces/http_space_primitives.ts +++ b/common/spaces/http_space_primitives.ts @@ -1,6 +1,9 @@ import type { SpacePrimitives } from "./space_primitives.ts"; import type { FileMeta } from "../../plug-api/types.ts"; -import { flushCachesAndUnregisterServiceWorker } from "../sw_util.ts"; +import { + flushCachesAndUnregisterServiceWorker, + unregisterServiceWorkers, +} from "../sw_util.ts"; import { encodePageURI } from "@silverbulletmd/silverbullet/lib/page_ref"; const defaultFetchTimeout = 30000; // 30 seconds @@ -41,13 +44,29 @@ export class HttpSpacePrimitives implements SpacePrimitives { } const redirectHeader = result.headers.get("location"); + if (result.type === "opaqueredirect" && !redirectHeader) { + // This is a scenario where the server sent a redirect, but this redirect is not visible to the client, likely due to CORS + // The best we can do is to reload the page and hope that the server will redirect us to the correct location + alert( + "You are not authenticated, reloading to reauthenticate", + ); + console.log("Unregistering service workers", redirectHeader); + await unregisterServiceWorkers(); + location.reload(); + // Let's throw to avoid any further processing + throw Error("Not authenticated"); + } + // console.log("Got response", result.status, result.statusText, result.url); // Attempting to handle various authentication proxies if (result.status >= 300 && result.status < 400) { if (redirectHeader) { // Got a redirect - alert("Received a redirect, redirecting to URL: " + redirectHeader); + alert( + "Received an authentication redirect, redirecting to URL: " + + redirectHeader, + ); location.href = redirectHeader; throw new Error("Redirected"); } else { diff --git a/common/sw_util.ts b/common/sw_util.ts index 8e47d539..f67b856d 100644 --- a/common/sw_util.ts +++ b/common/sw_util.ts @@ -1,3 +1,16 @@ +export async function unregisterServiceWorkers() { + if (navigator.serviceWorker) { + const registrations = await navigator.serviceWorker + .getRegistrations(); + for (const registration of registrations) { + await registration.unregister(); + console.log("Service worker unregistered"); + } + } else { + console.error("No service worker found to unregister"); + } +} + export function flushCachesAndUnregisterServiceWorker() { return new Promise((resolve) => { if (!navigator.serviceWorker) {