From 693a30f4378714a88197b699c2b0077caa7164a1 Mon Sep 17 00:00:00 2001 From: Corey Blais Date: Fri, 9 Oct 2026 20:16:22 -0400 Subject: [PATCH] Invites and fixed image caching --- backend/src/app.ts | 7 ++- backend/src/storage/photoCache.test.ts | 13 ++++++ backend/src/storage/photoCache.ts | 4 ++ frontend/src/App.tsx | 28 ++++++++++-- frontend/src/photoRefresh.ts | 36 ++++++++++++++++ frontend/src/usePhotoRefresh.ts | 50 +++++++++++++++++++++ frontend/test/photoRefresh.test.ts | 60 ++++++++++++++++++++++++++ 7 files changed, 193 insertions(+), 5 deletions(-) create mode 100644 backend/src/storage/photoCache.test.ts create mode 100644 backend/src/storage/photoCache.ts create mode 100644 frontend/src/photoRefresh.ts create mode 100644 frontend/src/usePhotoRefresh.ts create mode 100644 frontend/test/photoRefresh.test.ts diff --git a/backend/src/app.ts b/backend/src/app.ts index 51dbbcb..b6e7005 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -1,3 +1,4 @@ +import { photoCacheControl } from './storage/photoCache.js'; import { canUpdateWorkspaceSettings, subscriptionAllowsWrite } from './workspaceAccess.js'; import { buildWorkspaceInviteEmail } from './emails/workspaceInviteEmail.js'; import { exportFlock } from './repositories/flockExportRepository.js'; @@ -3496,6 +3497,8 @@ app.post( ); app.get('/api/birds/:birdId/photo', async (req: Request, res: Response, next: NextFunction) => { + // Invalid tokens, missing photos and upstream failures must never be cached. + res.setHeader('Cache-Control', 'no-store'); try { const token = typeof req.query.token === 'string' ? req.query.token : ''; const photoAccess = verifyBirdPhotoAccessToken(token); @@ -3525,9 +3528,8 @@ app.get('/api/birds/:birdId/photo', async (req: Request, res: Response, next: Ne expiresInSeconds: 5 * 60, }); - res.setHeader('Cache-Control', 'private, max-age=900'); - if (photoDeliveryMode === 'redirect') { + res.setHeader('Cache-Control', photoCacheControl('redirect', photoAccess.expiresAt)); res.redirect(302, signedUrl); return; } @@ -3543,6 +3545,7 @@ app.get('/api/birds/:birdId/photo', async (req: Request, res: Response, next: Ne const contentLength = imageResponse.headers.get('content-length'); const imageBuffer = Buffer.from(await imageResponse.arrayBuffer()); + res.setHeader('Cache-Control', photoCacheControl('proxy', photoAccess.expiresAt)); res.setHeader('Content-Type', contentType); if (contentLength) { diff --git a/backend/src/storage/photoCache.test.ts b/backend/src/storage/photoCache.test.ts new file mode 100644 index 0000000..5571bb9 --- /dev/null +++ b/backend/src/storage/photoCache.test.ts @@ -0,0 +1,13 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { photoCacheControl } from './photoCache.js'; + +test('storage redirects cannot be cached beyond the signed destination lifetime', () => { + assert.equal(photoCacheControl('redirect', 1900, 1000), 'no-store'); +}); + +test('proxy caching is bounded by the remaining app token lifetime', () => { + assert.equal(photoCacheControl('proxy', 1900, 1000), 'private, max-age=900, must-revalidate'); + assert.equal(photoCacheControl('proxy', 1050, 1000), 'private, max-age=50, must-revalidate'); + assert.equal(photoCacheControl('proxy', 999, 1000), 'private, max-age=0, must-revalidate'); +}); diff --git a/backend/src/storage/photoCache.ts b/backend/src/storage/photoCache.ts new file mode 100644 index 0000000..cfdec00 --- /dev/null +++ b/backend/src/storage/photoCache.ts @@ -0,0 +1,4 @@ +// Never cache a redirect to a signed storage URL: its lifetime is independent of +// the app token. Successful proxy responses cannot outlive the app token. +export const photoCacheControl = (mode: 'proxy' | 'redirect', expiresAt: number, now = Math.floor(Date.now() / 1000)) => + mode === 'redirect' ? 'no-store' : `private, max-age=${Math.max(0, Math.min(900, expiresAt - now))}, must-revalidate`; diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 4ab752b..67555ff 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,3 +1,4 @@ +import { usePhotoRefresh } from './usePhotoRefresh'; import { FlockSwitcher } from './FlockSwitcher'; import { combineLocationOwnerMarkers } from './birdTimeline'; import { BehaviorJournal } from './BehaviorJournal'; @@ -2284,6 +2285,27 @@ function App() { const [expandedSettingsSection, setExpandedSettingsSection] = useState(null); const flockBirds = useMemo(() => sortBirdsByName([...birds, ...memorializedBirds]), [birds, memorializedBirds]); + const handlePhotoError = usePhotoRefresh({ + apiBaseUrl, token: authToken, workspaceId: workspace?.id, publicProfileCode, + fallback: defaultBirdPhoto, + onPhotos: (photos) => { + const urls = new Map(photos.map((photo) => [photo.id, photo.photoDataUrl])); + const update = (current: Bird[]) => current.map((bird) => urls.has(bird.id) + ? { ...bird, photoDataUrl: urls.get(bird.id) ?? null } : bird); + setBirds(update); + setMemorializedBirds(update); + setPublicProfile((current) => current && urls.has(current.id) + ? { ...current, photoDataUrl: urls.get(current.id) ?? null } : current); + // Renew the editor preview only if it still matches the saved photo. + // Never replace an uploaded/cropped photo or a deliberate removal. + const editingBird = [...birds, ...memorializedBirds].find((bird) => bird.id === editingBirdId); + if (editingBird && urls.has(editingBirdId)) { + setBirdForm((current) => current.photoDataUrl === editingBird.photoDataUrl + ? { ...current, photoDataUrl: urls.get(editingBirdId) ?? '' } : current); + } + }, + }); + const selectedBird = useMemo( () => flockBirds.find((bird) => bird.id === selectedBirdId) ?? null, [flockBirds, selectedBirdId], @@ -5698,7 +5720,7 @@ function App() { if (shouldShowPublicProfilePage) { return ( -
+
FlockPal @@ -5895,7 +5917,7 @@ function App() { if (loading) { return ( -
+

Loading flock data...

@@ -6006,7 +6028,7 @@ function App() { ); return ( -
+
FlockPal diff --git a/frontend/src/photoRefresh.ts b/frontend/src/photoRefresh.ts new file mode 100644 index 0000000..f8dc9a1 --- /dev/null +++ b/frontend/src/photoRefresh.ts @@ -0,0 +1,36 @@ +export type PhotoRecord = { id: string; photoDataUrl: string | null }; +export const PHOTO_REFRESH_INTERVAL_MS = 5 * 60_000; + +// One request for all mounted photos; throttle failures without blocking later recovery. +export function createPhotoRefresher({ load, apply, now = Date.now }: { + load: (signal: AbortSignal) => Promise; + apply: (photos: PhotoRecord[]) => void; + now?: () => number; +}) { + const controller = new AbortController(); + let inFlight = false; + let lastAttempt = -Infinity; + return { + async refresh() { + if (controller.signal.aborted || inFlight || now() - lastAttempt < 30_000) return; + inFlight = true; + lastAttempt = now(); + try { + const photos = await load(controller.signal); + if (!controller.signal.aborted) apply(photos); + } catch { + // Keep existing photos on transient failures; retry on the next focus/timer/error. + } finally { + inFlight = false; + } + }, + dispose() { controller.abort(); }, + }; +} + +export function isExpiringPhotoUrl(src: string) { + try { + const url = new URL(src, window.location.href); + return /\/birds\/[^/]+\/photo$/.test(url.pathname) && url.searchParams.has('token'); + } catch { return false; } +} diff --git a/frontend/src/usePhotoRefresh.ts b/frontend/src/usePhotoRefresh.ts new file mode 100644 index 0000000..bd9033e --- /dev/null +++ b/frontend/src/usePhotoRefresh.ts @@ -0,0 +1,50 @@ +import { useEffect, useRef, type SyntheticEvent } from 'react'; +import { createPhotoRefresher, isExpiringPhotoUrl, PHOTO_REFRESH_INTERVAL_MS, type PhotoRecord } from './photoRefresh'; + +export function usePhotoRefresh({ apiBaseUrl, token, workspaceId, publicProfileCode, onPhotos, fallback }: { + apiBaseUrl: string; token: string; workspaceId?: number; publicProfileCode: string; + onPhotos: (photos: PhotoRecord[]) => void; fallback: string; +}) { + const apply = useRef(onPhotos); + apply.current = onPhotos; + const refresh = useRef<(() => Promise) | null>(null); + useEffect(() => { + if (!publicProfileCode && (!token || !workspaceId)) return; + const refresher = createPhotoRefresher({ + load: async (signal) => { + const path = publicProfileCode ? `/public/birds/${encodeURIComponent(publicProfileCode)}` : '/birds'; + const response = await fetch(`${apiBaseUrl}${path}`, { + signal, cache: 'no-store', + headers: publicProfileCode ? {} : { Authorization: `Bearer ${token}` }, + }); + if (!response.ok) throw new Error('Unable to refresh photos.'); + const data = await response.json(); + return publicProfileCode ? (data.bird ? [data.bird] : []) : [...(data.birds ?? []), ...(data.memorializedBirds ?? [])]; + }, + apply: (photos) => apply.current(photos), + }); + refresh.current = refresher.refresh; + const onResume = () => { if (document.visibilityState === 'visible') void refresher.refresh(); }; + const timer = window.setInterval(onResume, PHOTO_REFRESH_INTERVAL_MS); + window.addEventListener('focus', onResume); + window.addEventListener('online', onResume); + document.addEventListener('visibilitychange', onResume); + return () => { + refresher.dispose(); + refresh.current = null; + window.clearInterval(timer); + window.removeEventListener('focus', onResume); + window.removeEventListener('online', onResume); + document.removeEventListener('visibilitychange', onResume); + }; + }, [apiBaseUrl, token, workspaceId, publicProfileCode]); + + return (event: SyntheticEvent) => { + const image = event.target; + if (!(image instanceof Element)) return; + const attribute = image.localName === 'img' ? 'src' : image.localName === 'image' ? 'href' : null; + if (!attribute || !isExpiringPhotoUrl(image.getAttribute(attribute) ?? '')) return; + image.setAttribute(attribute, fallback); + void refresh.current?.(); + }; +} diff --git a/frontend/test/photoRefresh.test.ts b/frontend/test/photoRefresh.test.ts new file mode 100644 index 0000000..f44fb38 --- /dev/null +++ b/frontend/test/photoRefresh.test.ts @@ -0,0 +1,60 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createPhotoRefresher } from '../src/photoRefresh.ts'; + +test('simultaneous image errors share a refresh, then can renew again after cooldown', async () => { + let now = 0; + let calls = 0; + let finish!: (photos: { id: string; photoDataUrl: string }[]) => void; + const applied: unknown[] = []; + const refresher = createPhotoRefresher({ + now: () => now, + load: async () => { calls++; return new Promise((resolve) => { finish = resolve; }); }, + apply: (photos) => applied.push(photos), + }); + const first = refresher.refresh(); + await refresher.refresh(); + assert.equal(calls, 1); + finish([{ id: 'bird', photoDataUrl: 'renewed' }]); + await first; + assert.equal(applied.length, 1); + await refresher.refresh(); + assert.equal(calls, 1); + now = 30_000; + const next = refresher.refresh(); + finish([]); + await next; + assert.equal(calls, 2); +}); + +test('logout or flock switching aborts requests and discards stale photo responses', async () => { + let finish!: (photos: { id: string; photoDataUrl: string }[]) => void; + let signal!: AbortSignal; + let applied = false; + const refresher = createPhotoRefresher({ + load: async (requestSignal) => { signal = requestSignal; return new Promise((resolve) => { finish = resolve; }); }, + apply: () => { applied = true; }, + }); + const pending = refresher.refresh(); + refresher.dispose(); + finish([{ id: 'old-flock-bird', photoDataUrl: 'stale' }]); + await pending; + assert.equal(signal.aborted, true); + assert.equal(applied, false); +}); + +test('a failed refresh can recover on a later timer, focus, or reconnect', async () => { + let now = 0; + let attempts = 0; + let applied = false; + const refresher = createPhotoRefresher({ + now: () => now, + load: async () => { if (++attempts === 1) throw new Error('offline'); return []; }, + apply: () => { applied = true; }, + }); + await refresher.refresh(); + assert.equal(applied, false); + now = 30_000; + await refresher.refresh(); + assert.equal(applied, true); +});