diff --git a/apps/api/package.json b/apps/api/package.json index 0f04ddc..659e456 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -14,6 +14,7 @@ "graphql": "16.12.0", "graphql-yoga": "5.16.2", "pg": "8.16.3", + "sharp": "0.34.4", "zod": "4.6.7" }, "devDependencies": { diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 26232d3..505e15c 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -84,7 +84,10 @@ export function createApp( onResponse({ request, response }) { const cookie = cookies.get(request); if (cookie) response.headers.append('Set-Cookie', cookie); - response.headers.set('Cache-Control', 'no-store'); + // GraphQL answers are per-user and never cached. Image responses + // set their own policy (imageStorage.ts) and keep it. + if (!response.headers.has('Cache-Control')) + response.headers.set('Cache-Control', 'no-store'); }, }, ], diff --git a/apps/api/src/features/recipes/imageStorage.test.ts b/apps/api/src/features/recipes/imageStorage.test.ts index e91a3e0..fcf8ded 100644 --- a/apps/api/src/features/recipes/imageStorage.test.ts +++ b/apps/api/src/features/recipes/imageStorage.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { handleImageRequest } from './imageStorage.js'; import type { AuthService } from '../auth/authService.js'; -import type { ImageStore } from './imageStore.js'; +import { ImageError, type ImageStore } from './imageStore.js'; const token = '11111111-1111-4111-8111-111111111111'; const user = { id: token, name: 'Test Cook', email: 'cook@example.com' }; @@ -15,11 +15,21 @@ const png = Buffer.from( 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aOioAAAAASUVORK5CYII=', 'base64', ); -const store: ImageStore = { +const store = { upload: vi.fn(async () => `/uploads/${token}.png`), - read: vi.fn(async () => png), + authorize: vi.fn(async () => 'public'), + readOriginal: vi.fn(async () => png), + readVariant: vi.fn(async () => Buffer.from('variant')), + version: vi.fn(async () => '68-1'), cleanup: vi.fn(async () => 0), -}; +} satisfies ImageStore; +function getImage(query = '', headers: Record = {}) { + return handleImageRequest( + new Request(`http://localhost/uploads/${token}.png${query}`, { headers }), + service, + store, + ); +} beforeEach(() => vi.clearAllMocks()); function upload(body = png, headers: Record = {}) { return handleImageRequest( @@ -40,7 +50,7 @@ function upload(body = png, headers: Record = {}) { describe('image upload boundary', () => { it('validates bytes and records the authenticated owner', async () => { expect((await upload())?.status).toBe(201); - expect(store.upload).toHaveBeenCalledWith(user.id, png, 'png'); + expect(store.upload).toHaveBeenCalledWith(user.id, png); }); it('rejects anonymous, cross-origin-style and invalid uploads before storage', async () => { expect((await upload(png, { Cookie: '' }))?.status).toBe(401); @@ -51,7 +61,7 @@ describe('image upload boundary', () => { expect((await upload(Buffer.alloc(5 * 1024 * 1024 + 1)))?.status).toBe(413); expect(store.upload).not.toHaveBeenCalled(); }); - it('rejects unsafe paths before looking up files and never caches images', async () => { + it('rejects unsafe paths before looking up files', async () => { expect( ( await handleImageRequest( @@ -61,13 +71,64 @@ describe('image upload boundary', () => { ) )?.status, ).toBe(404); - expect(store.read).not.toHaveBeenCalled(); - const response = await handleImageRequest( - new Request(`http://localhost/uploads/${token}.png`), - service, - store, - ); + expect(store.authorize).not.toHaveBeenCalled(); + expect(store.readOriginal).not.toHaveBeenCalled(); + }); +}); + +describe('image caching', () => { + it('lets browsers keep public images but revalidate every time', async () => { + const response = await getImage(); + expect(response?.status).toBe(200); + expect(response?.headers.get('cache-control')).toBe('public, no-cache'); + expect(response?.headers.get('etag')).toBe(`"${token}.png-68-1"`); + expect(response?.headers.get('content-type')).toBe('image/png'); + expect(store.authorize).toHaveBeenCalledWith(`${token}.png`, null); + }); + + it('marks private images as private so shared caches never store them', async () => { + store.authorize.mockResolvedValueOnce('private'); + const response = await getImage('', { + Cookie: `t31_project2_session=${token}`, + }); + expect(response?.headers.get('cache-control')).toBe('private, no-cache'); + expect(store.authorize).toHaveBeenCalledWith(`${token}.png`, user.id); + }); + + it('answers a current cached copy with an empty 304 after the access check', async () => { + const response = await getImage('', { + 'If-None-Match': `W/"other", "${token}.png-68-1"`, + }); + expect(response?.status).toBe(304); + expect(await response?.text()).toBe(''); + expect(store.authorize).toHaveBeenCalled(); + expect(store.readOriginal).not.toHaveBeenCalled(); + }); + + it('sends the new image when the file was replaced (e.g. re-seeded)', async () => { + store.version.mockResolvedValueOnce('70-2'); + const response = await getImage('', { + 'If-None-Match': `"${token}.png-68-1"`, + }); + expect(response?.status).toBe(200); + expect(response?.headers.get('etag')).toBe(`"${token}.png-70-2"`); + }); + + it('does not answer 304 once the viewer may no longer see the image', async () => { + store.authorize.mockRejectedValueOnce(new ImageError(404, 'Not found.')); + const response = await getImage('', { + 'If-None-Match': `"${token}.png-68-1"`, + }); + expect(response?.status).toBe(404); expect(response?.headers.get('cache-control')).toBe('no-store'); - expect(store.read).toHaveBeenCalledWith(`${token}.png`, null); + }); + + it('serves resized WebP variants only for the supported widths', async () => { + const response = await getImage('?w=480'); + expect(response?.headers.get('content-type')).toBe('image/webp'); + expect(response?.headers.get('etag')).toBe(`"${token}.png-68-1-w480"`); + expect(store.readVariant).toHaveBeenCalledWith(`${token}.png`, 480); + expect((await getImage('?w=123'))?.status).toBe(400); + expect(store.readVariant).toHaveBeenCalledTimes(1); }); }); diff --git a/apps/api/src/features/recipes/imageStorage.ts b/apps/api/src/features/recipes/imageStorage.ts index e26be81..51af945 100644 --- a/apps/api/src/features/recipes/imageStorage.ts +++ b/apps/api/src/features/recipes/imageStorage.ts @@ -1,7 +1,12 @@ import type { AuthService } from '../auth/authService.js'; import { readSessionCookie } from '../auth/sessionCookie.js'; import { imageFilenamePattern } from './imagePaths.js'; -import { ImageError, type ImageStore } from './imageStore.js'; +import { + IMAGE_VARIANT_WIDTHS, + ImageError, + type ImageStore, + type ImageVariantWidth, +} from './imageStore.js'; const MAX_BYTES = 5 * 1024 * 1024; const contentTypes: Record = { @@ -31,28 +36,72 @@ function failure(status: number, message: string) { ); } +/** Parses ?w=480; null means the original image. */ +function requestedWidth(url: URL): ImageVariantWidth | null | 'invalid' { + const value = url.searchParams.get('w'); + if (value === null) return null; + const width = IMAGE_VARIANT_WIDTHS.find( + (allowed) => String(allowed) === value, + ); + return width ?? 'invalid'; +} + +/** True when the browser's cached copy (If-None-Match) is still current. */ +function isNotModified(request: Request, etag: string) { + const header = request.headers.get('if-none-match'); + if (!header) return false; + return header + .split(',') + .map((tag) => tag.trim().replace(/^W\//, '')) + .some((tag) => tag === etag || tag === '*'); +} + // A single upload endpoint and a restricted file route; client filenames are never used. export async function handleImageRequest( request: Request, service: AuthService, store: ImageStore, ): Promise { - const path = new URL(request.url).pathname; + const url = new URL(request.url); + const path = url.pathname; if (path !== '/uploads' && !path.startsWith('/uploads/')) return null; try { if (request.method === 'GET' && path.startsWith('/uploads/')) { const filename = path.slice('/uploads/'.length); if (!imageFilenamePattern.test(filename)) return failure(404, 'Image not found.'); + const width = requestedWidth(url); + if (width === 'invalid') return failure(400, 'Unsupported image width.'); try { const token = readSessionCookie(request); const user = token ? await service.currentUser(token) : null; - const image = await store.read(filename, user?.id ?? null); + const visibility = await store.authorize(filename, user?.id ?? null); + /* + * Caching: the ETag is the filename plus the original's size and + * modification time (and width), so it changes if a file is ever + * replaced, as the demo seed does. "no-cache" lets the + * browser keep a copy but ask again every time; the access check + * above runs on each request and an unchanged image is answered with + * an empty 304. A recipe made private therefore stops showing its + * image immediately, while repeat visits avoid re-downloading it. + */ + const headers = { + ETag: `"${filename}-${await store.version(filename)}${width ? `-w${width}` : ''}"`, + 'Cache-Control': + visibility === 'public' ? 'public, no-cache' : 'private, no-cache', + 'X-Content-Type-Options': 'nosniff', + }; + if (isNotModified(request, headers.ETag)) + return new Response(null, { status: 304, headers }); + const image = width + ? await store.readVariant(filename, width) + : await store.readOriginal(filename); return new Response(new Uint8Array(image), { headers: { - 'Content-Type': contentTypes[filename.split('.').pop()!]!, - 'X-Content-Type-Options': 'nosniff', - 'Cache-Control': 'no-store', + ...headers, + 'Content-Type': width + ? 'image/webp' + : contentTypes[filename.split('.').pop()!]!, }, }); } catch (error) { @@ -95,7 +144,7 @@ export async function handleImageRequest( const extension = imageExtension(image); if (!extension || contentTypes[extension] !== type) return failure(415, 'The file must contain a JPG, PNG, or WebP image.'); - const imageUrl = await store.upload(user.id, image, extension); + const imageUrl = await store.upload(user.id, image); return Response.json({ imageUrl }, { status: 201 }); } catch (error) { if (error instanceof ImageError) diff --git a/apps/api/src/features/recipes/imageStore.test.ts b/apps/api/src/features/recipes/imageStore.test.ts new file mode 100644 index 0000000..192159a --- /dev/null +++ b/apps/api/src/features/recipes/imageStore.test.ts @@ -0,0 +1,57 @@ +// @vitest-environment node +import { mkdtemp, rm, utimes, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { Pool } from 'pg'; +import sharp from 'sharp'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { createImageStore } from './imageStore.js'; + +// Variant generation reads files only; the database pool is not used here. +let directory: string; +let store: ReturnType; +const filename = '11111111-1111-4111-8111-111111111111.jpg'; + +const jpeg = (width: number, height: number, orientation?: number) => { + const image = sharp({ + create: { width, height, channels: 3, background: '#c0603a' }, + }); + return (orientation ? image.withMetadata({ orientation }) : image) + .jpeg() + .toBuffer(); +}; + +beforeEach(async () => { + directory = await mkdtemp(join(tmpdir(), 'image-store-')); + store = createImageStore({} as Pool, 'project2', directory); +}); +afterEach(() => rm(directory, { recursive: true, force: true })); + +describe('image variants', () => { + it('applies EXIF orientation, so phone photos are not shown sideways', async () => { + // Stored landscape pixels with "rotate 90°" metadata, as older uploads. + await writeFile(join(directory, filename), await jpeg(200, 100, 6)); + const variant = await sharp( + await store.readVariant(filename, 480), + ).metadata(); + expect([variant.width, variant.height]).toEqual([100, 200]); + }); + + it('rebuilds variants and changes the version when the original is replaced', async () => { + const path = join(directory, filename); + await writeFile(path, await jpeg(300, 100)); + const before = await store.version(filename); + expect( + (await sharp(await store.readVariant(filename, 480)).metadata()).height, + ).toBe(100); + + // Re-seeding writes a different image under the same name. + await writeFile(path, await jpeg(100, 300)); + const later = new Date(Date.now() + 5000); + await utimes(path, later, later); + expect(await store.version(filename)).not.toBe(before); + expect( + (await sharp(await store.readVariant(filename, 480)).metadata()).height, + ).toBe(300); + }); +}); diff --git a/apps/api/src/features/recipes/imageStore.ts b/apps/api/src/features/recipes/imageStore.ts index a76b17e..d603135 100644 --- a/apps/api/src/features/recipes/imageStore.ts +++ b/apps/api/src/features/recipes/imageStore.ts @@ -1,5 +1,6 @@ import { readdir, + rename, stat, unlink, mkdir, @@ -9,9 +10,40 @@ import { import { join } from 'node:path'; import { randomUUID } from 'node:crypto'; import type { Pool, PoolClient } from 'pg'; +import sharp from 'sharp'; import { imageFilenamePattern } from './imagePaths.js'; import { lockImages } from './imageRepository.js'; +/** + * Widths the API can serve as resized WebP variants (?w=480). A fixed list + * keeps the variant cache small and stops clients requesting arbitrary sizes. + */ +export const IMAGE_VARIANT_WIDTHS = [480, 800] as const; +export type ImageVariantWidth = (typeof IMAGE_VARIANT_WIDTHS)[number]; + +/** Public images are referenced by a public recipe; all others are private. */ +export type ImageVisibility = 'public' | 'private'; + +/** Longest side, in px, of a stored upload after server-side normalisation. */ +export const MAX_UPLOAD_EDGE = 1600; + +async function normalizeUpload(original: Buffer) { + try { + return await sharp(original) + .rotate() // Apply EXIF orientation before metadata is dropped. + .resize({ + width: MAX_UPLOAD_EDGE, + height: MAX_UPLOAD_EDGE, + fit: 'inside', + withoutEnlargement: true, + }) + .webp({ quality: 80 }) + .toBuffer(); + } catch { + throw new ImageError(415, 'The file could not be read as an image.'); + } +} + export class ImageError extends Error { constructor( public status: number, @@ -78,9 +110,107 @@ export function createImageStore( if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; } } + /* + * Resized variants live in /variants//.webp. The + * folder name does not match imageFilenamePattern, so files() lists only + * originals; variantBytes() adds the variants to the global storage total. + */ + const variantPath = (filename: string, width: number) => + join( + directory, + 'variants', + String(width), + filename.replace(/\.[a-z]+$/, '.webp'), + ); + async function variantBytes() { + let total = 0; + for (const width of IMAGE_VARIANT_WIDTHS) { + const folder = join(directory, 'variants', String(width)); + let names: string[]; + try { + names = await readdir(folder); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue; + throw error; + } + for (const name of names) { + try { + total += (await stat(join(folder, name))).size; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + } + } + } + return total; + } + /** + * A WebP copy resized to `width`, generated on first request and cached on + * disk. Callers must authorize() first. Concurrent first requests may both + * generate it; the atomic rename makes the last one win harmlessly. + */ + /** Size and modification time of the original; 404 if it is missing. */ + async function originalStat(filename: string) { + try { + return await stat(join(directory, filename)); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') + throw new ImageError(404, 'Image not found.'); + throw error; + } + } + async function readVariant(filename: string, width: ImageVariantWidth) { + const path = variantPath(filename, width); + const original = await originalStat(filename); + try { + // Reuse the cached variant unless the original was replaced after it + // was made (the demo seed rewrites its images under the same names). + if ((await stat(path)).mtimeMs >= original.mtimeMs) + return await readFile(path); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + } + const variant = await sharp(await readOriginal(filename)) + .rotate() // Older uploads were stored before EXIF auto-rotation. + .resize({ width, withoutEnlargement: true }) + .webp({ quality: 75 }) + .toBuffer(); + await mkdir(join(directory, 'variants', String(width)), { + recursive: true, + }); + const temporary = `${path}.${randomUUID()}.tmp`; + await writeFile(temporary, variant); + await rename(temporary, path); + return variant; + } + async function removeVariants(filename: string) { + for (const width of IMAGE_VARIANT_WIDTHS) { + try { + await unlink(variantPath(filename, width)); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + } + } + } + async function readOriginal(filename: string) { + try { + return await readFile(join(directory, filename)); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') + throw new ImageError(404, 'Image not found.'); + throw error; + } + } return { - async upload(userId: string, bytes: Buffer, extension: string) { - return locked(async (client) => { + /** + * Stores an uploaded image for `userId` and returns its /uploads/ URL. + * Every upload is normalised on the server, whatever the client did: + * rotated upright from its EXIF orientation, scaled to at most + * MAX_UPLOAD_EDGE px on its longest side and re-encoded as WebP. Metadata + * such as GPS position is not copied. Quotas count the stored size. + */ + async upload(userId: string, original: Buffer) { + const bytes = await normalizeUpload(original); + const imageUrl = await locked(async (client) => { const usage = await client.query<{ bytes: string; recent: number }>( `SELECT coalesce(sum(byte_size),0) AS bytes, count(*) FILTER (WHERE created_at > now()-interval '1 hour')::int AS recent FROM ${images} WHERE owner_id=$1`, [userId], @@ -95,16 +225,16 @@ export function createImageStore( const stored = await files(); if ( stored.length >= limits.totalFiles || - stored.reduce((sum, file) => sum + file.size, 0) + bytes.length > + stored.reduce((sum, file) => sum + file.size, 0) + + (await variantBytes()) + + bytes.length > limits.totalBytes ) throw new ImageError( 507, 'Image storage is full. Please try again later.', ); - const filename = `${randomUUID()}.${extension}`; - if (!imageFilenamePattern.test(filename)) - throw new ImageError(415, 'Unsupported image type.'); + const filename = `${randomUUID()}.webp`; let written = false; try { await writeFile(join(directory, filename), bytes, { flag: 'wx' }); @@ -119,22 +249,47 @@ export function createImageStore( } return `/uploads/${filename}`; }); + // Pre-build the card variants now, outside the lock, so the first + // visitor does not wait. Best effort: readVariant() retries lazily. + const filename = imageUrl.slice('/uploads/'.length); + await Promise.all( + IMAGE_VARIANT_WIDTHS.map((width) => + readVariant(filename, width).catch(() => undefined), + ), + ); + return imageUrl; }, - async read(filename: string, userId: string | null) { - const allowed = await pool.query( - `SELECT 1 FROM ${images} i WHERE i.filename=$1 AND ( + /** + * Checks that the viewer may see an image and reports whether it is + * public. Readable: images on a public recipe, images on the viewer's + * own recipes, and the viewer's own uploads not yet attached to a recipe. + * Runs on every request, including cache revalidations, so an image + * stops being served as soon as its recipe becomes private. + */ + async authorize( + filename: string, + userId: string | null, + ): Promise { + const allowed = await pool.query<{ public: boolean }>( + `SELECT EXISTS(SELECT 1 FROM ${recipes} r WHERE r.image_url='/uploads/' || i.filename AND r.visibility='public') AS public + FROM ${images} i WHERE i.filename=$1 AND ( EXISTS(SELECT 1 FROM ${recipes} r WHERE r.image_url='/uploads/' || i.filename AND (r.visibility='public' OR r.author_id=$2::uuid)) OR (i.owner_id=$2::uuid AND NOT ${reference}))`, [filename, userId], ); if (!allowed.rowCount) throw new ImageError(404, 'Image not found.'); - try { - return await readFile(join(directory, filename)); - } catch (error) { - if ((error as NodeJS.ErrnoException).code === 'ENOENT') - throw new ImageError(404, 'Image not found.'); - throw error; - } + return allowed.rows[0]!.public ? 'public' : 'private'; + }, + /** Original file bytes. Call authorize() first. */ + readOriginal, + readVariant, + /** + * Changes whenever the original file is replaced, for use in ETags, so + * browsers never keep showing an image that was overwritten (re-seed). + */ + async version(filename: string) { + const original = await originalStat(filename); + return `${original.size}-${Math.floor(original.mtimeMs)}`; }, async cleanup() { return locked(async (client) => { @@ -153,11 +308,37 @@ export function createImageStore( ); if (protectedFile.rowCount) continue; await removeFile(file.name); + await removeVariants(file.name); await client.query(`DELETE FROM ${images} WHERE filename=$1`, [ file.name, ]); removed += 1; } + // Variants (and interrupted .tmp writes) whose original no longer + // exists, e.g. removed by hand or by an earlier cleanup, would + // otherwise count against the storage limit forever. + const originals = new Set( + (await files()).map((file) => file.name.replace(/\.[a-z]+$/, '')), + ); + for (const width of IMAGE_VARIANT_WIDTHS) { + const folder = join(directory, 'variants', String(width)); + let names: string[] = []; + try { + names = await readdir(folder); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + } + for (const name of names) { + const stem = name.split('.')[0]!; + if (originals.has(stem)) continue; + try { + await unlink(join(folder, name)); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') + throw error; + } + } + } // Missing files must not leave permanent quota usage behind. await client.query( `DELETE FROM ${images} i WHERE NOT ${reference} AND created_at < now()-interval '24 hours' AND NOT (filename=ANY($1::text[]))`, diff --git a/apps/web/src/assets/recipe-fallback.webp b/apps/web/src/assets/recipe-fallback.webp index 6948b1a..a72ff1a 100644 Binary files a/apps/web/src/assets/recipe-fallback.webp and b/apps/web/src/assets/recipe-fallback.webp differ diff --git a/apps/web/src/components/recipe/RecipeCard/RecipeCard.tsx b/apps/web/src/components/recipe/RecipeCard/RecipeCard.tsx index 3c7b609..b3e60b7 100644 --- a/apps/web/src/components/recipe/RecipeCard/RecipeCard.tsx +++ b/apps/web/src/components/recipe/RecipeCard/RecipeCard.tsx @@ -24,13 +24,24 @@ export interface RecipeCardTag { type RecipeCardImageProps = | { imageSrc: string; + /** Optional resized variants (see recipeImageSrcSet). */ + imageSrcSet?: string; imageAlt: string; } | { imageSrc?: undefined; + imageSrcSet?: never; imageAlt?: never; }; +/* + * Rendered card width per layout (ExplorePage.css / CookbookPage.css): + * one column below 44rem, two up to 65rem, otherwise three columns in the + * 75rem container (about 400 px each). Lets the browser pick a variant. + */ +const CARD_IMAGE_SIZES = + '(max-width: 44rem) 100vw, (max-width: 65rem) 50vw, 400px'; + type RecipeCardBaseProps = Omit< ComponentPropsWithoutRef<'article'>, 'children' | 'title' @@ -99,6 +110,7 @@ export default function RecipeCard({ title, description, imageSrc, + imageSrcSet, imageAlt, rating, cookingTimeMinutes, @@ -191,6 +203,8 @@ export default function RecipeCard({ .filter(Boolean) .join(' ')} src={imageSrc ?? fallbackRecipeImage} + srcSet={imageSrcSet} + sizes={imageSrcSet ? CARD_IMAGE_SIZES : undefined} alt={imageSrc ? imageAlt : ''} loading="lazy" decoding="async" diff --git a/apps/web/src/components/recipe/toRecipeCardProps.ts b/apps/web/src/components/recipe/toRecipeCardProps.ts index 1492d59..f302b0d 100644 --- a/apps/web/src/components/recipe/toRecipeCardProps.ts +++ b/apps/web/src/components/recipe/toRecipeCardProps.ts @@ -1,6 +1,6 @@ import type { RecipeSummary } from '../../types/recipe'; import type { RecipeCardProps } from './RecipeCard/RecipeCard'; -import { recipeImageUrl } from '../../lib/recipeImageUrl'; +import { recipeImageSrcSet, recipeImageUrl } from '../../lib/recipeImageUrl'; function formatTagLabel(tag: string) { return tag @@ -32,6 +32,7 @@ export function toRecipeCardProps(recipe: RecipeSummary): RecipeCardProps { return { ...commonProps, imageSrc: recipeImageUrl(recipe.imageUrl), + imageSrcSet: recipeImageSrcSet(recipe.imageUrl), imageAlt: recipe.title, }; } diff --git a/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx b/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx index 384750d..2b02a01 100644 --- a/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx +++ b/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx @@ -7,7 +7,7 @@ import RecipeMeta from '../../components/recipe/RecipeMeta/RecipeMeta'; import RecipeRating from '../../components/recipe/RecipeRating/RecipeRating'; import RecipeRatingInput from '../../components/recipe/RecipeRatingInput/RecipeRatingInput'; import Dialog from '../../components/ui/Dialog/Dialog'; -import { recipeImageUrl } from '../../lib/recipeImageUrl'; +import { recipeImageSrcSet, recipeImageUrl } from '../../lib/recipeImageUrl'; import Avatar from '../../components/ui/Avatar/Avatar'; import Button from '../../components/ui/Button/Button'; import ConfirmationDialog from '../../components/ui/ConfirmationDialog/ConfirmationDialog'; @@ -273,6 +273,12 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { ? recipeImageUrl(recipe.imageUrl) : fallbackRecipeImage } + srcSet={ + recipe.imageUrl ? recipeImageSrcSet(recipe.imageUrl) : undefined + } + // Full width below 60rem; otherwise the media column of the + // two-column header (at most about 640 px in the 75rem container). + sizes="(max-width: 60rem) 100vw, 640px" alt={recipe.imageUrl ? recipe.title : ''} /> diff --git a/apps/web/src/lib/recipeImageUrl.test.ts b/apps/web/src/lib/recipeImageUrl.test.ts new file mode 100644 index 0000000..8b66745 --- /dev/null +++ b/apps/web/src/lib/recipeImageUrl.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from 'vitest'; +import { recipeImageSrcSet } from './recipeImageUrl'; + +describe('recipeImageSrcSet', () => { + it('offers the API variants and the original for uploaded images', () => { + const srcSet = recipeImageSrcSet('/uploads/abc.webp'); + expect(srcSet).toContain('/uploads/abc.webp?w=480 480w'); + expect(srcSet).toContain('/uploads/abc.webp?w=800 800w'); + expect(srcSet).toMatch(/\/uploads\/abc\.webp 1600w$/); + }); + + it('returns undefined for external images, which have no variants', () => { + expect(recipeImageSrcSet('https://example.com/soup.jpg')).toBeUndefined(); + }); +}); diff --git a/apps/web/src/lib/recipeImageUrl.ts b/apps/web/src/lib/recipeImageUrl.ts index 64e6a01..fdf0ca3 100644 --- a/apps/web/src/lib/recipeImageUrl.ts +++ b/apps/web/src/lib/recipeImageUrl.ts @@ -1,5 +1,18 @@ +/** Absolute URL for a recipe image; uploads are served by the API. */ export function recipeImageUrl(url: string) { return url.startsWith('/uploads/') && !import.meta.env.DEV ? `/project2/api${url}` : url; } + +/** + * srcset for uploaded images: the API serves resized WebP copies at 480 and + * 800 px (?w=…), so the browser downloads only the size the layout needs. + * Uploads are at most 1600 px wide, hence the descriptor for the original. + * External image URLs have no variants and return undefined. + */ +export function recipeImageSrcSet(url: string) { + if (!url.startsWith('/uploads/')) return undefined; + const source = recipeImageUrl(url); + return `${source}?w=480 480w, ${source}?w=800 800w, ${source} 1600w`; +} diff --git a/deploy/apache.conf b/deploy/apache.conf index 4b27e19..ad72ad0 100644 --- a/deploy/apache.conf +++ b/deploy/apache.conf @@ -5,4 +5,18 @@ Alias /project2/ /srv/t31-project2/current/apps/web/dist/ Require all granted FallbackResource /project2/index.html + + # index.html and other unhashed files: always ask for the latest deploy. + Header set Cache-Control "no-cache" + + + # Vite puts a content hash in every file name under assets/, so changed + # files always get a new URL. Browsers can keep these for a year without + # asking again. Location is merged after Directory, so this wins for assets. + + Header set Cache-Control "public, max-age=31536000, immutable" + + +# The API (/project2/api/) sets its own Cache-Control; nothing here changes it. +# Requires mod_headers: sudo a2enmod headers && sudo systemctl reload apache2 diff --git a/docs/performance-and-images.md b/docs/performance-and-images.md index c2eda90..9c30ae9 100644 --- a/docs/performance-and-images.md +++ b/docs/performance-and-images.md @@ -32,23 +32,56 @@ og alle testtilfellene beholdes. Endringer gjort av andre brukere kan være opptil 30 sekunder gamle når en cacheoppføring gjenbrukes. En allerede åpen side oppdateres ikke automatisk ved andre brukeres endringer. Tilgangskontroll på serveren gjelder fortsatt for alle -nye forespørsler. Bildeendepunktet bruker `Cache-Control: no-store` av hensyn til -privat/offentlig synlighet. Det caches ikke av denne resultatcachen. +nye forespørsler. Bilder caches ikke av denne resultatcachen, men av nettleseren +(se under). + +## HTTP-caching + +| Ressurs | `Cache-Control` | Effekt | +| --------------------------------------- | ------------------------------------- | -------------------------------------------------------- | +| `/project2/assets/*` (filnavn med hash) | `public, max-age=31536000, immutable` | Lastes ned én gang; ny deploy gir nye filnavn | +| `index.html` og øvrige filer i klienten | `no-cache` | Nettleseren spør alltid etter siste deploy | +| Offentlige bilder (`/uploads/…`) | `public, no-cache` + `ETag` | Uendret bilde besvares med tom `304`, ikke ny nedlasting | +| Private bilder | `private, no-cache` + `ETag` | Som over, men lagres ikke i delte mellomlagre | +| GraphQL-svar og feil | `no-store` | Persondata og tilgangsstyrte svar lagres aldri | + +`ETag`-en består av filnavnet og originalens størrelse og endringstid, så +den endres hvis en fil erstattes, for eksempel når demo-seeden kjøres på nytt. +Varianter lages da også på nytt, og de roteres etter EXIF-orientering. Tilgangskontrollen kjører ved hver forespørsel, også når +nettleseren bare spør om bildet er endret. Et bilde som blir privat, slutter +derfor å vises med en gang, samtidig som gjentatte besøk slipper å laste ned +bildet på nytt. + +Asset-reglene står i `deploy/apache.conf` og krever `mod_headers` +(`sudo a2enmod headers`). Filen må legges inn i Apache på VM-en manuelt. ## Bilder og bærekraft -- Fallback-bildet og 404-illustrasjonen er WebP på henholdsvis 173 440 og - 10 392 byte. Tidligere var de til sammen 4 290 949 byte; reduksjonen er omtrent - 96 %. Dette måler filstørrelse, ikke utslipp eller faktisk lastetid. +- **Serverside behandling:** API-et behandler alle opplastede bilder med + `sharp`, uansett hva klienten har gjort: bildet roteres riktig etter + EXIF-orientering, skaleres til maksimalt 1600 px på lengste side og lagres + som WebP (kvalitet 80). Metadata som GPS-posisjon kopieres ikke. Kvotene + regner med den lagrede størrelsen. Eksisterende bilder og URL-er endres ikke. +- **Varianter:** API-et lager WebP-varianter på 480 og 800 px (`?w=480`, + kvalitet 75) under `UPLOAD_DIR/variants/`, ved opplasting og ellers første + gang de etterspørres (eldre bilder). Oppskriftskort og detaljsiden bruker + `srcset` og `sizes`, slik at nettleseren henter størrelsen som passer + visningen. Et seed-bilde på 133 568 byte blir 18 192 byte i 480 px (−86 %). +- **Livssyklus for varianter:** hver variant går gjennom samme tilgangskontroll + som originalen ved hver forespørsel, også når et bilde blir privat. Varianter + slettes sammen med originalen ved opprydding (også varianter der originalen + allerede mangler), og den samlede lagringsgrensen regner med varianter. +- Fallback-bildet er skalert ned til 800 px: 51 232 byte (tidligere 173 440). + 404-illustrasjonen er 10 392 byte. Opprinnelig var de to til sammen + 4 290 949 byte. Dette måler filstørrelse, ikke utslipp eller faktisk lastetid. - Seed inneholder 51 lokale WebP-bilder. Disse leveres av appen fremfor å hotlinkes fra eksterne nettsider. - Oppskriftskort bruker `loading="lazy"`, slik at nettleseren kan utsette bilder utenfor den synlige delen av siden. Den nøyaktige terskelen bestemmes av nettleseren. -- Opplastingsgrensesnittet beskjærer og skalerer bilder til maksimalt 1600 px på - lengste side før opplasting. API-et kontrollerer også filtype og størrelse. -- Separate mobilvarianter og `srcset` for opplastede bilder er videre arbeid; - dagens mobilvisning kan laste samme bildefil som desktop. +- Opplastingsgrensesnittet beskjærer og skalerer bilder til maksimalt 1600 px + før opplasting, slik at mindre data sendes. API-et kontrollerer filtype og + størrelse og normaliserer bildet uansett (se over). ## Kilder og rettigheter diff --git a/docs/review-test-guide.md b/docs/review-test-guide.md index 41c191f..f126ab0 100644 --- a/docs/review-test-guide.md +++ b/docs/review-test-guide.md @@ -36,7 +36,9 @@ Use two accounts: an owner and a reader. An image is public only while at least one public recipe references it. Unattached uploads are visible only to their uploader; attached private -images are visible to the recipe owner. Responses use `Cache-Control: no-store`. +images are visible to the recipe owner. Image responses use `no-cache` with an +`ETag` (`public` or `private`), so the access check runs on every request and an +unchanged image is answered with an empty 304. ## Cleanup and limits diff --git a/e2e/smoke.spec.ts b/e2e/smoke.spec.ts index 6b2ba23..cd60a87 100644 --- a/e2e/smoke.spec.ts +++ b/e2e/smoke.spec.ts @@ -248,6 +248,22 @@ test('icons stay within their controls on desktop and mobile', async ({ } }); +test('clicking anywhere on a recipe card, including its image, opens the recipe', async ({ + page, +}) => { + // The title link's ::after overlay (RecipeCard.css) covers the whole card. + // jsdom cannot hit-test CSS, so this is checked in a real browser. + await page.goto('.'); + const image = page.locator('.recipe-card__image').first(); + await expect(image).toBeVisible(); + const box = (await image.boundingBox())!; + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await expect(page).toHaveURL(/recipes\/11111111-1111-4111-8111-111111111111/); + await expect( + page.getByRole('heading', { name: 'Creamy salmon pasta' }), + ).toBeVisible(); +}); + test('renders each core route through the shared shell', async ({ page }) => { for (const [path, title] of coreRoutes) { await page.goto(path === '/' ? '.' : path.slice(1)); diff --git a/package-lock.json b/package-lock.json index 60476a7..b3db4d9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -50,6 +50,7 @@ "graphql": "16.12.0", "graphql-yoga": "5.16.2", "pg": "8.16.3", + "sharp": "0.34.4", "zod": "4.6.7" }, "devDependencies": { @@ -558,6 +559,16 @@ "dev": true, "license": "Apache-2.0" }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@envelop/core": { "version": "5.6.1", "resolved": "https://registry.npmjs.org/@envelop/core/-/core-5.6.1.tgz", @@ -2196,6 +2207,475 @@ "url": "https://github.com/sponsors/nzakas" } }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.4.tgz", + "integrity": "sha512-sitdlPzDVyvmINUdJle3TNHl+AG9QcwiAMsXmccqsCOMZNIdW2/7S26w0LyU8euiLVzFBL3dXPwVCq/ODnf2vA==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.2.3" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.4.tgz", + "integrity": "sha512-rZheupWIoa3+SOdF/IcUe1ah4ZDpKBGWcsPX6MT0lYniH9micvIU7HQkYTfrx5Xi8u+YqwLtxC/3vl8TQN6rMg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.2.3" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.3.tgz", + "integrity": "sha512-QzWAKo7kpHxbuHqUC28DZ9pIKpSi2ts2OJnoIGI26+HMgq92ZZ4vk8iJd4XsxN+tYfNJxzH6W62X5eTcsBymHw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.3.tgz", + "integrity": "sha512-Ju+g2xn1E2AKO6YBhxjj+ACcsPQRHT0bhpglxcEf+3uyPY+/gL8veniKoo96335ZaPo03bdDXMv0t+BBFAbmRA==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.3.tgz", + "integrity": "sha512-x1uE93lyP6wEwGvgAIV0gP6zmaL/a0tGzJs/BIDDG0zeBhMnuUPm7ptxGhUbcGs4okDJrk4nxgrmxpib9g6HpA==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.3.tgz", + "integrity": "sha512-I4RxkXU90cpufazhGPyVujYwfIm9Nk1QDEmiIsaPwdnm013F7RIceaCc87kAH+oUB1ezqEvC6ga4m7MSlqsJvQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.3.tgz", + "integrity": "sha512-Y2T7IsQvJLMCBM+pmPbM3bKT/yYJvVtLJGfCs4Sp95SjvnFIjynbjzsa7dY1fRJX45FTSfDksbTp6AGWudiyCg==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.3.tgz", + "integrity": "sha512-RgWrs/gVU7f+K7P+KeHFaBAJlNkD1nIZuVXdQv6S+fNA6syCcoboNjsV2Pou7zNlVdNQoQUpQTk8SWDHUA3y/w==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.3.tgz", + "integrity": "sha512-3JU7LmR85K6bBiRzSUc/Ff9JBVIFVvq6bomKE0e63UXGeRw2HPVEjoJke1Yx+iU4rL7/7kUjES4dZ/81Qjhyxg==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.3.tgz", + "integrity": "sha512-F9q83RZ8yaCwENw1GieztSfj5msz7GGykG/BA+MOUefvER69K/ubgFHNeSyUu64amHIYKGDs4sRCMzXVj8sEyw==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.3.tgz", + "integrity": "sha512-U5PUY5jbc45ANM6tSJpsgqmBF/VsL6LnxJmIf11kB7J5DctHgqm0SkuXzVWtIY90GnJxKnC/JT251TDnk1fu/g==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.4.tgz", + "integrity": "sha512-Xyam4mlqM0KkTHYVSuc6wXRmM7LGN0P12li03jAnZ3EJWZqj83+hi8Y9UxZUbxsgsK1qOEwg7O0Bc0LjqQVtxA==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.2.3" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.4.tgz", + "integrity": "sha512-YXU1F/mN/Wu786tl72CyJjP/Ngl8mGHN1hST4BGl+hiW5jhCnV2uRVTNOcaYPs73NeT/H8Upm3y9582JVuZHrQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.2.3" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.4.tgz", + "integrity": "sha512-F4PDtF4Cy8L8hXA2p3TO6s4aDt93v+LKmpcYFLAVdkkD3hSxZzee0rh6/+94FpAynsuMpLX5h+LRsSG3rIciUQ==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.2.3" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.4.tgz", + "integrity": "sha512-qVrZKE9Bsnzy+myf7lFKvng6bQzhNUAYcVORq2P7bDlvmF6u2sCmK2KyEQEBdYk+u3T01pVsPrkj943T1aJAsw==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.2.3" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.4.tgz", + "integrity": "sha512-ZfGtcp2xS51iG79c6Vhw9CWqQC8l2Ot8dygxoDoIQPTat/Ov3qAa8qpxSrtAEAJW+UjTXc4yxCjNfxm4h6Xm2A==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.2.3" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.4.tgz", + "integrity": "sha512-8hDVvW9eu4yHWnjaOOR8kHVrew1iIX+MUgwxSuH2XyYeNRtLUe4VNioSqbNkB7ZYQJj9rUTT4PyRscyk2PXFKA==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.2.3" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.4.tgz", + "integrity": "sha512-lU0aA5L8QTlfKjpDCEFOZsTYGn3AEiO6db8W5aQDxj0nQkVrZWmN3ZP9sYKWJdtq3PWPhUNlqehWyXpYDcI9Sg==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.2.3" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.4.tgz", + "integrity": "sha512-33QL6ZO/qpRyG7woB/HUALz28WnTMI2W1jgX3Nu2bypqLIKx/QKMILLJzJjI+SIbvXdG9fUnmrxR7vbi1sTBeA==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.5.0" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.4.tgz", + "integrity": "sha512-2Q250do/5WXTwxW3zjsEuMSv5sUU4Tq9VThWKlU2EYLm4MB7ZeMwF+SFJutldYODXF6jzc6YEOC+VfX0SZQPqA==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.4.tgz", + "integrity": "sha512-3ZeLue5V82dT92CNL6rsal6I2weKw1cYu+rGKm8fOCCtJTR2gYeUfY3FqUnIJsMUPIH68oS5jmZ0NiJ508YpEw==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.4.tgz", + "integrity": "sha512-xIyj4wpYs8J18sVN3mSQjwrw7fKUqRw+Z5rnHNCy5fYTxigBz81u5mOMPmFumwjcn8+ld1ppptMBCLic1nz6ig==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.13", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", @@ -4565,9 +5045,7 @@ "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "dev": true, "license": "Apache-2.0", - "peer": true, "engines": { "node": ">=8" } @@ -8969,6 +9447,60 @@ "node": ">= 0.4" } }, + "node_modules/sharp": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.4.tgz", + "integrity": "sha512-FUH39xp3SBPnxWvd5iib1X8XY7J0K0X7d93sie9CJg2PO8/7gmg89Nve6OjItK53/MlAushNNxteBYfM6DEuoA==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.0.0", + "detect-libc": "^2.1.0", + "semver": "^7.7.2" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.34.4", + "@img/sharp-darwin-x64": "0.34.4", + "@img/sharp-libvips-darwin-arm64": "1.2.3", + "@img/sharp-libvips-darwin-x64": "1.2.3", + "@img/sharp-libvips-linux-arm": "1.2.3", + "@img/sharp-libvips-linux-arm64": "1.2.3", + "@img/sharp-libvips-linux-ppc64": "1.2.3", + "@img/sharp-libvips-linux-s390x": "1.2.3", + "@img/sharp-libvips-linux-x64": "1.2.3", + "@img/sharp-libvips-linuxmusl-arm64": "1.2.3", + "@img/sharp-libvips-linuxmusl-x64": "1.2.3", + "@img/sharp-linux-arm": "0.34.4", + "@img/sharp-linux-arm64": "0.34.4", + "@img/sharp-linux-ppc64": "0.34.4", + "@img/sharp-linux-s390x": "0.34.4", + "@img/sharp-linux-x64": "0.34.4", + "@img/sharp-linuxmusl-arm64": "0.34.4", + "@img/sharp-linuxmusl-x64": "0.34.4", + "@img/sharp-wasm32": "0.34.4", + "@img/sharp-win32-arm64": "0.34.4", + "@img/sharp-win32-ia32": "0.34.4", + "@img/sharp-win32-x64": "0.34.4" + } + }, + "node_modules/sharp/node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", diff --git a/scripts/test-recipe-api.ts b/scripts/test-recipe-api.ts index 75befa0..0ce753b 100644 --- a/scripts/test-recipe-api.ts +++ b/scripts/test-recipe-api.ts @@ -1,6 +1,13 @@ import assert from 'node:assert/strict'; import { randomUUID } from 'node:crypto'; -import { mkdtemp, readFile, rm, utimes, access } from 'node:fs/promises'; +import { + mkdtemp, + readFile, + rm, + utimes, + access, + writeFile, +} from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { @@ -9,6 +16,7 @@ import { } from '../apps/api/src/features/recipes/imageStore.js'; import { test } from 'node:test'; import { Pool } from 'pg'; +import sharp from 'sharp'; import { print } from 'graphql'; import type { TypedDocumentNode } from '@graphql-typed-document-node/core'; import { createApp } from '../apps/api/src/app.js'; @@ -255,9 +263,63 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { const uploaded = await upload(owner.cookie); assert.equal(uploaded.status, 201); const { imageUrl } = (await uploaded.json()) as { imageUrl: string }; - const image = (cookie?: string) => - api.fetch(`http://localhost${imageUrl}`, { - headers: cookie ? { Cookie: cookie } : {}, + // Every upload is re-encoded as WebP on the server. + assert.match(imageUrl, /\.webp$/); + // A large camera-sized photo is scaled down to 1600 px on the server, + // whatever the client sent. (Row removed again so the per-hour quota + // checks below start from zero.) + const photo = await sharp({ + create: { + width: 3000, + height: 2000, + channels: 3, + background: '#c0603a', + }, + }) + .jpeg() + .toBuffer(); + const large = await createImageStore( + pool, + schema, + imageDirectory, + ).upload(owner.user.id, photo); + const largeFile = join(imageDirectory, large.slice('/uploads/'.length)); + const stored = await sharp(largeFile).metadata(); + assert.deepEqual( + [stored.format, stored.width, stored.height], + ['webp', 1600, 1067], + ); + await access( + join( + imageDirectory, + 'variants', + '480', + large.slice('/uploads/'.length), + ), + ); + await pool.query( + `DELETE FROM "${schema}".uploaded_images WHERE filename=$1`, + [large.slice('/uploads/'.length)], + ); + for (const path of [ + largeFile, + ...['480', '800'].map((width) => + join( + imageDirectory, + 'variants', + width, + large.slice('/uploads/'.length), + ), + ), + ]) + await rm(path, { force: true }); + const image = ( + cookie?: string, + query = '', + headers: Record = {}, + ) => + api.fetch(`http://localhost${imageUrl}${query}`, { + headers: { ...headers, ...(cookie ? { Cookie: cookie } : {}) }, }); assert.equal((await image()).status, 404); assert.equal((await image(reader.cookie)).status, 404); @@ -287,8 +349,27 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { }, owner.cookie, ); - assert.equal((await image()).status, 200); - assert.equal((await image()).headers.get('cache-control'), 'no-store'); + const publicImage = await image(); + assert.equal(publicImage.status, 200); + // Browsers may keep public images but must revalidate each time. + assert.equal( + publicImage.headers.get('cache-control'), + 'public, no-cache', + ); + const etag = publicImage.headers.get('etag')!; + const revalidated = await image(undefined, '', { + 'If-None-Match': etag, + }); + assert.equal(revalidated.status, 304); + assert.equal((await revalidated.arrayBuffer()).byteLength, 0); + // Resized WebP variants are generated with sharp and cached on disk. + const filename = imageUrl.slice('/uploads/'.length); + const thumbnail = await image(undefined, '?w=480'); + assert.equal(thumbnail.status, 200); + assert.equal(thumbnail.headers.get('content-type'), 'image/webp'); + const variantFile = join(imageDirectory, 'variants', '480', filename); + await access(variantFile); + assert.equal((await image(undefined, '?w=999')).status, 400); await ok( UpdateRecipeDocument, { @@ -298,8 +379,16 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { owner.cookie, ); assert.equal((await image()).status, 404); + // A cached public copy is not confirmed once the recipe is private. + assert.equal( + (await image(undefined, '', { 'If-None-Match': etag })).status, + 404, + ); + assert.equal( + (await image(owner.cookie)).headers.get('cache-control'), + 'private, no-cache', + ); const store = createImageStore(pool, schema, imageDirectory); - const filename = imageUrl.slice('/uploads/'.length); const old = new Date(Date.now() - 25 * 60 * 60 * 1000); await utimes(join(imageDirectory, filename), old, old); await pool.query( @@ -318,15 +407,26 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { ); assert.equal(await store.cleanup(), 1); await assert.rejects(access(join(imageDirectory, filename))); + await assert.rejects(access(variantFile)); // Variants go with it. + // A variant whose original is already gone is removed too. + const orphan = join( + imageDirectory, + 'variants', + '800', + `${randomUUID()}.webp`, + ); + await writeFile(orphan, 'stale'); + await store.cleanup(); + await assert.rejects(access(orphan)); const restricted = createImageStore(pool, schema, imageDirectory, { userBytes: 1000, totalBytes: 2000, totalFiles: 2, perHour: 1, }); - await restricted.upload(owner.user.id, png, 'png'); + await restricted.upload(owner.user.id, png); await assert.rejects( - restricted.upload(owner.user.id, png, 'png'), + restricted.upload(owner.user.id, png), (error: unknown) => error instanceof ImageError && error.status === 429, ); @@ -337,7 +437,7 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { perHour: 20, }); await assert.rejects( - full.upload(reader.user.id, png, 'png'), + full.upload(reader.user.id, png), (error: unknown) => error instanceof ImageError && error.status === 507, ); @@ -348,13 +448,13 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { perHour: 20, }); await assert.rejects( - userFull.upload(owner.user.id, png, 'png'), + userFull.upload(owner.user.id, png), (error: unknown) => error instanceof ImageError && error.status === 413, ); const concurrent = await Promise.allSettled([ - restricted.upload(reader.user.id, png, 'png'), - restricted.upload(reader.user.id, png, 'png'), + restricted.upload(reader.user.id, png), + restricted.upload(reader.user.id, png), ]); assert.equal( concurrent.filter((result) => result.status === 'fulfilled').length,