Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
75 changes: 62 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,20 @@ 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')),
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 +49,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 +60,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 +70,53 @@ 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"`);
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"`,
});
expect(response?.status).toBe(304);
expect(await response?.text()).toBe('');
expect(store.authorize).toHaveBeenCalled();
expect(store.readOriginal).not.toHaveBeenCalled();
});

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"` });
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-w480"`);
expect(store.readVariant).toHaveBeenCalledWith(`${token}.png`, 480);
expect((await getImage('?w=123'))?.status).toBe(400);
expect(store.readVariant).toHaveBeenCalledTimes(1);
});
});
62 changes: 55 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,71 @@ 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: uploads get a new UUID filename and are never overwritten,
* so the filename (plus width) is a strong ETag. "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}${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 +143,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
Loading