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
1 change: 1 addition & 0 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
5 changes: 4 additions & 1 deletion apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
},
},
],
Expand Down
87 changes: 74 additions & 13 deletions apps/api/src/features/recipes/imageStorage.test.ts
Original file line number Diff line number Diff line change
@@ -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' };
Expand All @@ -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<ImageStore['authorize']>(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<string, string> = {}) {
return handleImageRequest(
new Request(`http://localhost/uploads/${token}.png${query}`, { headers }),
service,
store,
);
}
beforeEach(() => vi.clearAllMocks());
function upload(body = png, headers: Record<string, string> = {}) {
return handleImageRequest(
Expand All @@ -40,7 +50,7 @@ function upload(body = png, headers: Record<string, string> = {}) {
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);
Expand All @@ -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(
Expand All @@ -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);
});
});
63 changes: 56 additions & 7 deletions apps/api/src/features/recipes/imageStorage.ts
Original file line number Diff line number Diff line change
@@ -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<string, string> = {
Expand Down Expand Up @@ -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<Response | null> {
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) {
Expand Down Expand Up @@ -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)
Expand Down
57 changes: 57 additions & 0 deletions apps/api/src/features/recipes/imageStore.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof createImageStore>;
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);
});
});
Loading