Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions apps/web/public/sw.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Offline support: the app shell and the last data seen load without network; actions need the network.
const CACHE = "snug-v3";
const CACHE = "snug-v4";
const READ_API = /^\/api\/(setup|me|home|library|series\/\d+)$/;

self.addEventListener("install", (event) => {
Expand All @@ -26,6 +26,18 @@ const networkFirst = async (request) => {
}
};

// A navigation is fetched as is, so an auth proxy's redirect to its sign-in reaches the browser, which follows it;
// only a failed network falls back to the cached app shell. The server answers index.html on every app path.
const navigation = async (request) => {
try {
const response = await fetch(request);
if (response.ok) (await caches.open(CACHE)).put("/", response.clone());
return response;
} catch {
return (await caches.match("/")) ?? Response.error();
}
};

const cacheFirst = async (request) => {
const cached = await caches.match(request);
if (cached) return cached;
Expand All @@ -45,7 +57,7 @@ self.addEventListener("fetch", (event) => {
}
if (READ_API.test(url.pathname)) return event.respondWith(networkFirst(request));
// A navigation to the API (the Export's download, a feed opened in a tab) reaches the server, not the app shell.
if (request.mode === "navigate" && !url.pathname.startsWith("/api/")) return event.respondWith(networkFirst(new Request("/")));
if (request.mode === "navigate" && !url.pathname.startsWith("/api/")) return event.respondWith(navigation(request));
});

// Web Push: { title, body, url, tag } sent by the server.
Expand Down
20 changes: 20 additions & 0 deletions apps/web/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,34 @@ export async function api<T = void>(
headers: hasBody ? { "content-type": raw ? (init.contentType ?? "text/plain") : "application/json" } : undefined,
body: raw ? init.text : hasBody ? JSON.stringify(init.body) : undefined,
credentials: "same-origin",
// Snug's API never redirects: a redirect comes from an auth proxy in front of Snug (Cloudflare Access, Authelia…) asking to sign in again.
redirect: "manual",
});
if (res.type === "opaqueredirect") {
reloadForSignIn();
throw new ApiError(0, "The sign-in in front of Snug has expired");
}
if (!res.ok) {
const data = (await res.json().catch(() => null)) as { error?: string; fields?: Record<string, string> } | null;
throw new ApiError(res.status, data?.error ?? `Request failed (${res.status})`, data?.fields);
}
return (res.status === 204 || res.status === 201 ? undefined : await res.json()) as T;
}

const SIGN_IN_RELOAD_KEY = "snug:sign-in-reload";

/** Reloads the page so the browser itself follows the auth proxy to its sign-in; at most once a minute, against a loop. */
function reloadForSignIn() {
try {
const last = Number(sessionStorage.getItem(SIGN_IN_RELOAD_KEY) ?? 0);
if (Date.now() - last < 60_000) return;
sessionStorage.setItem(SIGN_IN_RELOAD_KEY, String(Date.now()));
} catch {
// No sessionStorage: reload all the same.
}
location.reload();
}

export const queryClient = new QueryClient({
defaultOptions: {
queries: { staleTime: 30_000, retry: (n, err) => !(err instanceof ApiError && err.status < 500) && n < 2 },
Expand Down
Loading