Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
3 changes: 2 additions & 1 deletion .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ dist
coverage
playwright-report
test-results
uploads

# Git
.git
Expand All @@ -27,4 +28,4 @@ test-results

# Logs
*.log
npm-debug.log*
npm-debug.log*
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ API_PORT=3001
AUTH_TRUST_PROXY=false
# false for localhost/current HTTP VM; true when HTTPS is configured.
AUTH_COOKIE_SECURE=false
# Optional absolute directory for persisted recipe images (default: uploads/ at project root).
# UPLOAD_DIR=/var/lib/recipe-platform/uploads
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ coverage/
playwright-report/
test-results/
*.tsbuildinfo
uploads/
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,19 +112,19 @@ Frontend blir tilgjengelig på:
http://127.0.0.1:5173/project2/
```

Oppskriftsvisningen kan også kjøres med frontend alene:
Frontend-serveren kan også startes separat (API og PostgreSQL kreves for data):

```bash
npm run dev:web
```

Innlogging og registrering krever imidlertid både API-et og PostgreSQL.
Oppskriftsvisning, cookbook og innlogging krever både API-et og PostgreSQL. Se [frontend integration checklist](docs/frontend-integration.md).

Ikke legg `.env`, passord, tokens eller andre hemmeligheter i Git.

## Authentication

Registration, login and logout use GraphQL and PostgreSQL. Both the API and database must be running; recipe browsing still uses mock data. Configure DATABASE_URL in .env and run `npm run db:migrate` before starting the API. User and session creation run in one transaction, so a failed session insert rolls back the new user.
Registration, login and logout use GraphQL and PostgreSQL. Both the API and database must be running; recipe browsing and CRUD also use the API. Configure DATABASE_URL in .env and run `npm run db:migrate` before starting the API. User and session creation run in one transaction, so a failed session insert rolls back the new user.

Sessions use a host-only HttpOnly cookie (`t31_project2_session`, SameSite=Lax, Path=/, seven-day lifetime). GraphQL context resolves the user from the cookie. Tokens are not returned to frontend JavaScript or stored in localStorage. Logout revokes the server session and clears the cookie. Temporary API failures preserve the cookie for retry. Existing users must log in again after this migration.

Expand Down
15 changes: 14 additions & 1 deletion apps/api/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type { Pool } from 'pg';
import { fileURLToPath } from 'node:url';
import { handleImageRequest } from './features/recipes/imageStorage.js';
import { db } from './db/client.js';
import { createRecipeRepository } from './features/recipes/recipeRepository.js';
import { createRecipeResolvers } from './features/recipes/recipeResolvers.js';
Expand All @@ -24,6 +26,8 @@ export function createApp(
trustProxy = process.env.AUTH_TRUST_PROXY === 'true',
secureCookie = process.env.AUTH_COOKIE_SECURE === 'true',
database: { pool?: Pool; schema?: string } = {},
uploadDirectory = process.env.UPLOAD_DIR ??
fileURLToPath(new URL('../../../uploads/', import.meta.url)),
) {
const authResolvers = createAuthResolvers(service);
const recipes = createRecipeResolvers(
Expand All @@ -37,7 +41,16 @@ export function createApp(
},
plugins: [
{
onRequest({ request, fetchAPI, endResponse }) {
async onRequest({ request, fetchAPI, endResponse }) {
const imageResponse = await handleImageRequest(
request,
service,
uploadDirectory,
);
if (imageResponse) {
endResponse(imageResponse);
return;
}
if (
request.method === 'POST' &&
(request.headers.get('x-requested-with') !== 'recipe-platform' ||
Expand Down
83 changes: 83 additions & 0 deletions apps/api/src/features/recipes/imageStorage.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { mkdtemp, readdir, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { createApp } from '../../app.js';
import type { AuthService } from '../auth/authService.js';

const token = '11111111-1111-4111-8111-111111111111';
const user = { id: token, name: 'Test Cook', email: 'cook@example.com' };
const service: AuthService = {
currentUser: async (value) => (value === token ? user : null),
login: async () => ({ user, sessionToken: token }),
register: async () => ({ user, sessionToken: token }),
signOut: async () => true,
};
// A complete 1x1 PNG, also used to verify bytes survive storage unchanged.
const png = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aOioAAAAASUVORK5CYII=',
'base64',
);
let directory: string;
beforeAll(async () => {
directory = await mkdtemp(join(tmpdir(), 'recipe-images-'));
});
afterAll(async () => {
if (directory.startsWith(join(tmpdir(), 'recipe-images-')))
await rm(directory, { recursive: true, force: true });
});
function upload(body: Buffer, headers: Record<string, string> = {}) {
const app = createApp(service, false, false, {}, directory);
return app.fetch('http://localhost/uploads', {
method: 'POST',
body: new Uint8Array(body),
headers: {
'Content-Type': 'image/png',
'X-Requested-With': 'recipe-platform',
Cookie: `t31_project2_session=${token}`,
...headers,
},
});
}

describe('local image storage', () => {
it('persists an image and serves it after recreating the app', async () => {
const response = await upload(png);
expect(response.status).toBe(201);
const { imageUrl } = (await response.json()) as { imageUrl: string };
expect(imageUrl).toMatch(/^\/uploads\/[0-9a-f-]+\.png$/);
const restarted = createApp(service, false, false, {}, directory);
const image = await restarted.fetch(`http://localhost${imageUrl}`);
expect(image.status).toBe(200);
expect(image.headers.get('content-type')).toBe('image/png');
expect(image.headers.get('x-content-type-options')).toBe('nosniff');
expect(Buffer.from(await image.arrayBuffer())).toEqual(png);
});
it('requires login and the same custom request header as GraphQL', async () => {
expect((await upload(png, { Cookie: '' })).status).toBe(401);
expect((await upload(png, { 'X-Requested-With': '' })).status).toBe(403);
});
it('rejects unsupported, spoofed and oversized bodies without writing files', async () => {
const before = await readdir(directory);
expect(
(await upload(png, { 'Content-Type': 'image/svg+xml' })).status,
).toBe(415);
expect((await upload(Buffer.from('<script>bad</script>'))).status).toBe(
415,
);
expect((await upload(png, { 'Content-Type': 'image/jpeg' })).status).toBe(
415,
);
expect((await upload(Buffer.alloc(5 * 1024 * 1024 + 1))).status).toBe(413);
expect(await readdir(directory)).toEqual(before);
});
it('does not serve arbitrary filenames or missing images', async () => {
const app = createApp(service, false, false, {}, directory);
for (const path of [
'/uploads/.env',
'/uploads/%2e%2e%2f.env',
'/uploads/11111111-1111-4111-8111-111111111111.jpg',
])
expect((await app.fetch('http://localhost' + path)).status).toBe(404);
});
});
103 changes: 103 additions & 0 deletions apps/api/src/features/recipes/imageStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { randomUUID } from 'node:crypto';
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import type { AuthService } from '../auth/authService.js';
import { readSessionCookie } from '../auth/sessionCookie.js';

const MAX_BYTES = 5 * 1024 * 1024;
const filePattern =
/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}\.(jpg|png|webp)$/;
export const uploadedImagePattern =
/^\/uploads\/[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}\.(jpg|png|webp)$/;
const contentTypes: Record<string, string> = {
jpg: 'image/jpeg',
png: 'image/png',
webp: 'image/webp',
};

function imageExtension(bytes: Buffer) {
if (
bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))
)
return 'png';
if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return 'jpg';
if (
bytes.toString('ascii', 0, 4) === 'RIFF' &&
bytes.toString('ascii', 8, 12) === 'WEBP'
)
return 'webp';
return null;
}

function failure(status: number, message: string) {
return Response.json({ message }, { status });
}

// A single upload endpoint and a restricted file route; client filenames are never used.
export async function handleImageRequest(
request: Request,
service: AuthService,
directory: string,
): Promise<Response | null> {
const path = new URL(request.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 (!filePattern.test(filename)) return failure(404, 'Image not found.');
try {
const image = await readFile(join(directory, filename));
return new Response(new Uint8Array(image), {
headers: {
'Content-Type': contentTypes[filename.split('.').pop()!]!,
'X-Content-Type-Options': 'nosniff',
},
});
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT')
return failure(404, 'Image not found.');
throw error;
}
}
if (request.method !== 'POST' || path !== '/uploads')
return failure(405, 'Method not allowed.');
if (request.headers.get('x-requested-with') !== 'recipe-platform')
return failure(403, 'Request blocked.');
const token = readSessionCookie(request);
if (!token || !(await service.currentUser(token)))
return failure(401, 'Please sign in to upload an image.');
const type = request.headers.get('content-type')?.split(';')[0];
if (!type || !Object.values(contentTypes).includes(type))
return failure(415, 'Choose a JPG, PNG, or WebP image.');
if (Number(request.headers.get('content-length')) > MAX_BYTES)
return failure(413, 'Choose an image up to 5 MB.');
const reader = request.body?.getReader();
if (!reader) return failure(400, 'Choose an image.');
const chunks: Uint8Array[] = [];
let size = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
size += value.byteLength;
if (size > MAX_BYTES) {
await reader.cancel();
return failure(413, 'Choose an image up to 5 MB.');
}
chunks.push(value);
}
} finally {
reader.releaseLock();
}
const image = Buffer.concat(chunks);
const extension = imageExtension(image);
if (!extension || contentTypes[extension] !== type)
return failure(415, 'The file must contain a JPG, PNG, or WebP image.');
await mkdir(directory, { recursive: true });
const filename = `${randomUUID()}.${extension}`;
await writeFile(join(directory, filename), image, { flag: 'wx' });
return Response.json({ imageUrl: `/uploads/${filename}` }, { status: 201 });
} catch {
return failure(500, 'Unable to store the image. Please try again.');
}
}
29 changes: 29 additions & 0 deletions apps/api/src/features/recipes/recipeRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') {
EXISTS(SELECT 1 FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid) AS "isSaved",
(SELECT count(*)::int FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id) AS "saveCount",
(SELECT json_build_object('average',coalesce(round(avg(score),1),0)::float,'count',count(*)::int) FROM ${t('ratings')} WHERE recipe_id=r.id) AS rating,
(SELECT score FROM ${t('ratings')} WHERE recipe_id=r.id AND user_id=$1::uuid) AS "userRating",
coalesce((SELECT json_agg(json_build_object('id',i.id,'name',i.name,'amount',i.amount::float,'unit',i.unit,'note',i.note) ORDER BY i.position) FROM ${t('recipe_ingredients')} i WHERE i.recipe_id=r.id),'[]') AS ingredients,
coalesce((SELECT json_agg(json_build_object('step',i.position,'text',i.text) ORDER BY i.position) FROM ${t('recipe_instructions')} i WHERE i.recipe_id=r.id),'[]') AS instructions,
coalesce((SELECT json_agg(tag ORDER BY tag) FROM ${t('recipe_tags')} WHERE recipe_id=r.id),'[]') AS tags
Expand Down Expand Up @@ -224,6 +225,34 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') {
);
return true;
},
async rate(id: string, score: number, userId: string) {
return transaction(async (client) => {
const result = await client.query(
`SELECT id FROM ${t('recipes')} WHERE id=$1 AND visibility='public' AND author_id<>$2 FOR SHARE`,
[id, userId],
);
if (!result.rowCount)
throw new GraphQLError(
'Only public recipes by other users can be rated.',
{
extensions: { code: 'FORBIDDEN' },
},
);
await client.query(
`INSERT INTO ${t('ratings')} (recipe_id,user_id,score) VALUES ($1,$2,$3)
ON CONFLICT (user_id,recipe_id) DO UPDATE SET score=EXCLUDED.score, updated_at=now()`,
[id, userId, score],
);
return readRequired(client, id, userId);
});
},
async removeRating(id: string, userId: string) {
await pool.query(
`DELETE FROM ${t('ratings')} WHERE recipe_id=$1 AND user_id=$2`,
[id, userId],
);
return true;
},
};
}
export type RecipeRepository = ReturnType<typeof createRecipeRepository>;
10 changes: 10 additions & 0 deletions apps/api/src/features/recipes/recipeResolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,16 @@ export function createRecipeResolvers(repository: RecipeRepository) {
),
},
Mutation: {
rateRecipe: (_parent, args, context) => {
const userId = requireUser(context);
return repository.rate(
recipeId(args.id),
validate(z.number().int().min(1).max(5), args.score),
userId,
);
},
removeRecipeRating: (_parent, args, context) =>
repository.removeRating(recipeId(args.id), requireUser(context)),
createRecipe: (_parent, args, context) => {
const userId = requireUser(context);
return repository.create(
Expand Down
16 changes: 16 additions & 0 deletions apps/api/src/features/recipes/recipeValidation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,20 @@ describe('recipe validation', () => {
});
expect(() => validate(listInputSchema, { pageSize: 51 })).toThrow();
});
it('accepts only generated local image paths or HTTP(S) URLs', () => {
const imageUrl = '/uploads/11111111-1111-4111-8111-111111111111.jpg';
expect(validate(recipeInputSchema, { ...input, imageUrl }).imageUrl).toBe(
imageUrl,
);
for (const invalid of [
'/uploads/../.env',
'/uploads/test.svg',
'//other.example/file.jpg',
'blob:local-preview',
]) {
expect(() =>
validate(recipeInputSchema, { ...input, imageUrl: invalid }),
).toThrow();
}
});
});
7 changes: 5 additions & 2 deletions apps/api/src/features/recipes/recipeValidation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { GraphQLError } from 'graphql';
import { z } from 'zod';
import { uploadedImagePattern } from './imageStorage.js';

export const categorySchema = z.enum([
'breakfast',
Expand All @@ -18,8 +19,10 @@ export const recipeInputSchema = z.object({
title: z.string().trim().min(1).max(160),
description: z.string().trim().max(200),
imageUrl: z
.url({ protocol: /^https?$/ })
.max(2048)
.union([
z.url({ protocol: /^https?$/ }).max(2048),
z.string().regex(uploadedImagePattern),
])
.nullish()
.transform((value) => value ?? null),
category: categorySchema,
Expand Down
Loading