diff --git a/packages/server/src/html.ts b/packages/server/src/html.ts index cd86043c..543a061c 100644 --- a/packages/server/src/html.ts +++ b/packages/server/src/html.ts @@ -89,12 +89,16 @@ const RELOAD_ICON = `Updated ${formatAge(now - fetchedAt)}` + '' + + '' + `

`; } /** * Keeps the sessions page current without reloading it: swaps in `/sessions/body` every minute while the tab * is visible, and from GitHub rather than the server's cache when the reload button asks. Needs SECTIONS_SCRIPT. + * + * An expired IAP sign-in answers with a redirect to Google, which a fetch cannot follow; only reloading the page + * signs in again. That happens on its own unless the reader is typing or away, and at most once per page load. */ export const SESSIONS_SCRIPT = `(() => { const AUTO_MS = 60000; @@ -102,10 +106,28 @@ export const SESSIONS_SCRIPT = `(() => { const age = document.getElementById('sessions-age'); const error = document.getElementById('sessions-error'); const reload = document.getElementById('sessions-reload'); - if (!container || !age || !error || !reload) return; + const signedOutNote = document.getElementById('sessions-signed-out'); + if (!container || !age || !error || !reload || !signedOutNote) return; let loadedAt = Date.now(); let inFlight = false; let failed = false; + let signedOut = false; + let reloaded = false; + + const typing = () => { + const active = document.activeElement; + return !!active && (active.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(active.tagName)); + }; + const signOut = () => { + signedOut = true; + if (!reloaded && document.visibilityState === 'visible' && !typing()) { + reloaded = true; + location.reload(); + return; + } + age.hidden = true; + signedOutNote.hidden = false; + }; const formatAge = ${formatAge.toString()}; const tick = () => { @@ -114,13 +136,17 @@ export const SESSIONS_SCRIPT = `(() => { }; const refresh = async fresh => { - if (inFlight) return; + if (inFlight || signedOut) return; // Swapping the content would take focus from the control a keyboard user is on; the next tick tries again. if (!fresh && container.contains(document.activeElement)) return; inFlight = true; reload.setAttribute('aria-busy', 'true'); try { - const res = await fetch('/sessions/body' + (fresh ? '?fresh=1' : ''), { credentials: 'same-origin', cache: 'no-store' }); + const res = await fetch('/sessions/body' + (fresh ? '?fresh=1' : ''), { credentials: 'same-origin', cache: 'no-store', redirect: 'manual' }); + if (res.type === 'opaqueredirect' || res.status === 401) { + signOut(); + return; + } if (!res.ok) throw new Error('HTTP ' + res.status); const template = document.createElement('template'); template.innerHTML = await res.text(); @@ -135,19 +161,24 @@ export const SESSIONS_SCRIPT = `(() => { } finally { inFlight = false; reload.removeAttribute('aria-busy'); - error.hidden = !failed; + error.hidden = !failed || signedOut; tick(); } }; const due = () => failed || Date.now() - loadedAt >= AUTO_MS; - reload.addEventListener('click', () => refresh(true)); + reload.addEventListener('click', () => { + if (signedOut) location.reload(); + else refresh(true); + }); setInterval(() => { tick(); if (document.visibilityState === 'visible' && due()) refresh(false); }, 15000); document.addEventListener('visibilitychange', () => { - if (document.visibilityState === 'visible' && due()) refresh(false); + if (document.visibilityState !== 'visible') return; + if (signedOut) signOut(); + else if (due()) refresh(false); }); })(); `; diff --git a/packages/server/tests/http.test.ts b/packages/server/tests/http.test.ts index b700051e..51614c30 100644 --- a/packages/server/tests/http.test.ts +++ b/packages/server/tests/http.test.ts @@ -469,6 +469,10 @@ describe('pull requests awaiting review', () => { expect(sessionsScript.headers.get('content-type')).toContain('javascript'); expect(sessionsScript.body).toContain("'/sessions/body' + (fresh ? '?fresh=1' : '')"); expect(sessionsScript.body).toContain('applySections(template.content)'); + expect(sessionsScript.body).toContain("redirect: 'manual'"); + expect(sessionsScript.body).toContain("res.type === 'opaqueredirect' || res.status === 401"); + expect(sessionsScript.body).toContain('location.reload()'); + expect(page).toContain(''); const script = await api('/sections.js'); expect(script.headers.get('content-type')).toContain('javascript'); expect(script.body).toContain('localStorage'); diff --git a/packages/ui/src/components/layout/signed-out-banner.tsx b/packages/ui/src/components/layout/signed-out-banner.tsx new file mode 100644 index 00000000..30ab43f5 --- /dev/null +++ b/packages/ui/src/components/layout/signed-out-banner.tsx @@ -0,0 +1,41 @@ +import { useEffect, useSyncExternalStore } from 'react'; +import { isSignedOut, reloadIfSafe, subscribeSignedOut } from '../../lib/sign-in'; + +export function SignedOutBanner() { + const signedOut = useSyncExternalStore(subscribeSignedOut, isSignedOut, () => false); + + useEffect(() => { + if (!signedOut) { + return; + } + reloadIfSafe(); + const onVisibility = () => { + if (document.visibilityState === 'visible') { + reloadIfSafe(); + } + }; + document.addEventListener('visibilitychange', onVisibility); + return () => document.removeEventListener('visibilitychange', onVisibility); + }, [signedOut]); + + if (!signedOut) { + return null; + } + + return ( +
+ Your sign-in expired. Reload to sign in again. + +
+ ); +} diff --git a/packages/ui/src/hooks/use-tab-badge.ts b/packages/ui/src/hooks/use-tab-badge.ts index 1fee8226..96f9ff3e 100644 --- a/packages/ui/src/hooks/use-tab-badge.ts +++ b/packages/ui/src/hooks/use-tab-badge.ts @@ -1,5 +1,6 @@ import { useEffect, useRef } from 'react'; import { addBadge, titleWithCount, toHref } from '../lib/favicon-badge'; +import { apiRequest } from '../lib/request'; /** Marks the browser tab and its title while `count` answers wait unseen. */ export function useTabBadge(count: number): void { @@ -37,7 +38,7 @@ export function useTabBadge(count: number): void { if (plainSvg.current !== null) { badge(plainSvg.current); } else { - void fetch(href) + void apiRequest(href) .then(res => (res.ok ? res.text() : Promise.reject(new Error(res.statusText)))) .then(svg => { plainSvg.current = svg; diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts index f9a8e8f3..cee92083 100644 --- a/packages/ui/src/lib/api.ts +++ b/packages/ui/src/lib/api.ts @@ -17,6 +17,7 @@ import type { Tour, } from '@diffity/api'; import { apiPath } from './base'; +import { apiRequest } from './request'; export type { GitHubDetails, @@ -29,7 +30,7 @@ export type { } from '@diffity/api'; async function apiFetch(url: string, init?: RequestInit): Promise { - const res = await fetch(apiPath(url), init); + const res = await apiRequest(apiPath(url), init); if (!res.ok) { throw new Error(await errorMessage(res)); } @@ -37,7 +38,7 @@ async function apiFetch(url: string, init?: RequestInit): Promise { } async function apiVoid(url: string, init?: RequestInit): Promise { - const res = await fetch(apiPath(url), init); + const res = await apiRequest(apiPath(url), init); if (!res.ok) { throw new Error(await errorMessage(res)); } @@ -71,7 +72,7 @@ export function fetchRepoInfo(): Promise { } export async function fetchThreads(sessionId: string, status?: ThreadStatus): Promise { - const res = await fetch(apiPath(buildUrl('/api/threads', { session: sessionId, status }))); + const res = await apiRequest(apiPath(buildUrl('/api/threads', { session: sessionId, status }))); if (!res.ok) { return []; } @@ -135,7 +136,7 @@ export async function fetchFileContent(filePath: string): Promise { } export async function fetchGitHubDetails(): Promise { - const res = await fetch(apiPath('/api/github/details')); + const res = await apiRequest(apiPath('/api/github/details')); if (!res.ok) { return null; } diff --git a/packages/ui/src/lib/request.ts b/packages/ui/src/lib/request.ts new file mode 100644 index 00000000..874ac62f --- /dev/null +++ b/packages/ui/src/lib/request.ts @@ -0,0 +1,25 @@ +import { markSignedOut, writeSettled, writeStarted } from './sign-in'; + +/** + * The server never redirects these requests; a redirect is IAP sending an expired sign-in to Google, which + * a fetch cannot follow. A 401 is diffity's own sign-in gone. A write may hold the reader's only copy of their + * text, so while one is under way, or after one failed this way, the page must not reload on its own. + */ +export async function apiRequest(url: string, init?: RequestInit): Promise { + const write = (init?.method ?? 'GET').toUpperCase() !== 'GET'; + if (write) { + writeStarted(); + } + try { + const res = await fetch(url, { ...init, redirect: 'manual' }); + if (res.type === 'opaqueredirect' || res.status === 401) { + markSignedOut({ lostWrite: write }); + throw new Error('Signed out'); + } + return res; + } finally { + if (write) { + writeSettled(); + } + } +} diff --git a/packages/ui/src/lib/sign-in.ts b/packages/ui/src/lib/sign-in.ts new file mode 100644 index 00000000..4002bebf --- /dev/null +++ b/packages/ui/src/lib/sign-in.ts @@ -0,0 +1,87 @@ +let signedOut = false; +let reloaded = false; +let lostWrite = false; +let writesInFlight = 0; +const listeners = new Set<() => void>(); + +export function isSignedOut(): boolean { + return signedOut; +} + +export function markSignedOut(cause: { lostWrite?: boolean } = {}): void { + lostWrite ||= !!cause.lostWrite; + if (signedOut) { + return; + } + signedOut = true; + for (const listener of listeners) { + listener(); + } +} + +export function writeStarted(): void { + writesInFlight++; +} + +export function writeSettled(): void { + writesInFlight--; +} + +export function subscribeSignedOut(listener: () => void): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +export interface PageState { + visible: boolean; + /** Something the reader typed that a reload would throw away. */ + hasDraft: boolean; + editing: boolean; + /** A save is under way, or failed on the expired sign-in; its text may live only in memory. */ + unsavedWrite: boolean; +} + +export function shouldAutoReload(state: PageState, alreadyReloaded: boolean): boolean { + return !alreadyReloaded && !state.unsavedWrite && state.visible && !state.hasDraft && !state.editing; +} + +const TEXT_INPUT_TYPES = new Set(['', 'text', 'search', 'email', 'url', 'tel', 'password', 'number']); + +export function readPageState(doc: Document = document): PageState { + const fields = [ + ...doc.querySelectorAll('textarea'), + ...[...doc.querySelectorAll('input')].filter(input => TEXT_INPUT_TYPES.has(input.getAttribute('type')?.toLowerCase() ?? '')), + ]; + const active = doc.activeElement; + const editing = active instanceof HTMLElement + && (active.isContentEditable || active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement || active instanceof HTMLSelectElement); + return { + visible: doc.visibilityState === 'visible', + hasDraft: fields.some(field => field.value.trim() !== ''), + editing, + unsavedWrite: lostWrite || writesInFlight > 0, + }; +} + +/** + * An expired IAP sign-in can only be renewed by loading the page again. Does that once per page load, and + * only when nothing the reader is in the middle of would be lost. + */ +export function reloadIfSafe(reload: () => void = () => window.location.reload(), state: PageState = readPageState()): boolean { + if (!shouldAutoReload(state, reloaded)) { + return false; + } + reloaded = true; + reload(); + return true; +} + +export function resetSignInForTests(): void { + signedOut = false; + reloaded = false; + lostWrite = false; + writesInFlight = 0; + listeners.clear(); +} diff --git a/packages/ui/src/root.tsx b/packages/ui/src/root.tsx index 806c23c7..0a24ff27 100644 --- a/packages/ui/src/root.tsx +++ b/packages/ui/src/root.tsx @@ -5,6 +5,7 @@ import { Toaster } from "sonner"; import NProgress from "nprogress"; import { queryClient } from "./lib/query-client"; import { ErrorPage } from "./components/error-page"; +import { SignedOutBanner } from "./components/layout/signed-out-banner"; import { pagePath } from "./lib/base"; import "nprogress/nprogress.css"; import "./styles/app.css"; @@ -57,6 +58,7 @@ export default function App() { + { + resetSignInForTests(); +}); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + document.body.replaceChildren(); +}); + +const CLEAN = { visible: true, hasDraft: false, editing: false, unsavedWrite: false }; + +describe('the request helper', () => { + it('asks not to follow redirects and passes a normal response through', async () => { + const response = new Response('{}', { status: 200 }); + const fetchMock = vi.fn().mockResolvedValue(response); + vi.stubGlobal('fetch', fetchMock); + + expect(await apiRequest('/api/info', { method: 'POST' })).toBe(response); + expect(fetchMock).toHaveBeenCalledWith('/api/info', { method: 'POST', redirect: 'manual' }); + expect(isSignedOut()).toBe(false); + }); + + it('passes an error response through for the caller to handle', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('', { status: 500 }))); + + expect((await apiRequest('/api/info')).status).toBe(500); + expect(isSignedOut()).toBe(false); + }); + + it('marks the page signed out and rejects on a redirect', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ type: 'opaqueredirect', status: 0, ok: false } as Response)); + + await expect(apiRequest('/api/info')).rejects.toThrow('Signed out'); + expect(isSignedOut()).toBe(true); + expect(readPageState().unsavedWrite).toBe(false); + }); + + it('marks the page signed out on a 401, and never reloads it on its own after a failed write', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('', { status: 401 }))); + + await expect(apiRequest('/api/threads/1', { method: 'PATCH' })).rejects.toThrow('Signed out'); + expect(isSignedOut()).toBe(true); + expect(readPageState().unsavedWrite).toBe(true); + expect(reloadIfSafe(vi.fn())).toBe(false); + }); + + it('does not reload on its own while a write is still under way', async () => { + let answer!: (res: Response) => void; + vi.stubGlobal('fetch', vi.fn().mockReturnValueOnce(new Promise(resolve => { answer = resolve; }))); + + const save = apiRequest('/api/threads/1', { method: 'PATCH' }); + expect(readPageState().unsavedWrite).toBe(true); + markSignedOut(); + expect(reloadIfSafe(vi.fn())).toBe(false); + + answer(new Response('{}', { status: 200 })); + await save; + expect(readPageState().unsavedWrite).toBe(false); + }); +}); + +describe('reloading after the sign-in expired', () => { + it('reloads a visible page with nothing typed', () => { + expect(shouldAutoReload(CLEAN, false)).toBe(true); + }); + + it('leaves a page with a draft, a focused field or a hidden tab alone', () => { + expect(shouldAutoReload({ ...CLEAN, hasDraft: true }, false)).toBe(false); + expect(shouldAutoReload({ ...CLEAN, editing: true }, false)).toBe(false); + expect(shouldAutoReload({ ...CLEAN, visible: false }, false)).toBe(false); + expect(shouldAutoReload({ ...CLEAN, unsavedWrite: true }, false)).toBe(false); + }); + + it('reloads only once', () => { + const reload = vi.fn(); + expect(reloadIfSafe(reload, CLEAN)).toBe(true); + expect(reloadIfSafe(reload, CLEAN)).toBe(false); + expect(reload).toHaveBeenCalledTimes(1); + }); + + it('counts typed text as a draft, and a focused field as editing', () => { + const textarea = document.createElement('textarea'); + const checkbox = document.createElement('input'); + checkbox.type = 'checkbox'; + document.body.append(textarea, checkbox); + expect(readPageState()).toMatchObject({ hasDraft: false, editing: false }); + + textarea.value = 'half a comment'; + expect(readPageState().hasDraft).toBe(true); + + textarea.value = ''; + textarea.focus(); + expect(readPageState().editing).toBe(true); + }); +}); + +describe('the signed-out banner', () => { + it('shows nothing while signed in', () => { + render(); + expect(screen.queryByTestId('signed-out-banner')).toBeNull(); + }); + + it('offers a reload instead of reloading over a draft', () => { + const textarea = document.createElement('textarea'); + textarea.value = 'unsent'; + document.body.append(textarea); + render(); + + act(() => markSignedOut()); + + expect(screen.getByTestId('signed-out-banner').textContent).toContain('Your sign-in expired. Reload to sign in again.'); + expect(screen.getByRole('button', { name: 'Reload' })).toBeTruthy(); + }); +});