From ca641b0f8e4c9f0aaec2a8e6687f0386b7e2b1d1 Mon Sep 17 00:00:00 2001 From: "hasan.fawzi" Date: Wed, 18 Nov 2026 01:31:01 +0100 Subject: [PATCH 1/2] docs(api): explain request handling and recipe repository --- apps/api/src/app.ts | 19 +++ .../src/features/recipes/recipeRepository.ts | 135 ++++++++++++------ 2 files changed, 109 insertions(+), 45 deletions(-) diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 335948e..19f6119 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -32,6 +32,11 @@ import { SESSION_COOKIE, } from './features/auth/sessionCookie.js'; +/** + * Wires HTTP guards, session context and GraphQL resolvers into one handler. + * Injected auth/database/storage dependencies let tests exercise the same + * request flow without sharing production sessions, tables or image files. + */ export function createApp( service: AuthService = authService, trustProxy = process.env.AUTH_TRUST_PROXY === 'true', @@ -69,8 +74,13 @@ export function createApp( limits, ), ); + // Resolvers schedule cookie changes through context.setSession; onResponse + // writes them to the matching HTTP response. Request keys keep concurrent + // login/logout responses separate without retaining completed requests. const cookies = new WeakMap(); return createYoga<{ req?: IncomingMessage }, AuthContext>({ + // The browser uses the same origin through Vite/Apache. Together with the + // custom header below, disabling CORS prevents cross-origin operation calls. cors: false, graphiql: enableGraphiql && { // POST requests without this header are rejected (CSRF check below). @@ -124,6 +134,9 @@ export function createApp( }, ), ); + // /uploads is handled before GraphQL parsing: it accepts image bytes, + // not JSON, and applies its own size, CSRF and session/access checks. + // A null response means this request belongs to the GraphQL handler. const imageResponse = await handleImageRequest( request, service, @@ -185,6 +198,7 @@ export function createApp( } }, onResponse({ request, response }) { + // Includes both new sessions and cookie expiry after logout/invalid auth. const cookie = cookies.get(request); if (cookie) response.headers.append('Set-Cookie', cookie); // GraphQL answers are per-user and never cached. Image responses @@ -195,6 +209,9 @@ export function createApp( }, ], context: async ({ request, req }) => { + // Resolve the cookie against server-side sessions for every operation. + // An invalid/expired session clears the cookie; a service error propagates + // instead, so a temporary failure does not silently log the user out. const token = readSessionCookie(request); const user = token ? await service.currentUser(token) : null; if ( @@ -210,6 +227,8 @@ export function createApp( ), user, sessionToken: user ? token : null, + // Auth resolvers call this on login/register/logout. The token stays in + // the HttpOnly cookie rather than being returned as GraphQL response data. setSession: (nextToken) => { cookies.set(request, sessionCookie(nextToken, secureCookie)); context.sessionToken = nextToken; diff --git a/apps/api/src/features/recipes/recipeRepository.ts b/apps/api/src/features/recipes/recipeRepository.ts index 018c1a6..2fc62f4 100644 --- a/apps/api/src/features/recipes/recipeRepository.ts +++ b/apps/api/src/features/recipes/recipeRepository.ts @@ -20,6 +20,12 @@ export function toSearchQuery(search: string) { return [...new Set(words)].map((word) => `${word}:*`).join(' & '); } +/** + * Builds the SQL data layer used by recipeResolvers.ts. Resolvers validate + * input and require a signed-in user for writes and Cookbook; this layer + * applies row visibility, ownership checks and transactional writes. + * An injected pool/schema lets integration tests use isolated database schemas. + */ export function createRecipeRepository( pool: Pool = db, schema = 'project2', @@ -30,12 +36,20 @@ export function createRecipeRepository( ) { if (!/^[a-z_][a-z0-9_]*$/.test(schema)) throw new Error('Invalid database schema.'); - const t = (name: string) => `"${schema}"."${name}"`; + // SQL parameters bind values, not identifiers. Validate the injected schema + // above and qualify the fixed table names below; user input stays in $n values. + const table = (name: string) => `"${schema}"."${name}"`; + // In read/list SQL, $1 is the viewer's ID (null for anonymous requests). const ownedByViewer = 'r.author_id=$1::uuid'; const publicRecipe = "r.visibility='public'"; const visibleToViewer = `(${publicRecipe} OR ${ownedByViewer})`; - const savedByViewer = `EXISTS(SELECT 1 FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid)`; + const savedByViewer = `EXISTS(SELECT 1 FROM ${table('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid)`; + /** + * Explore exposes only public recipes. Cookbook also requires membership + * (created/saved/either), but saving a recipe never grants access after its + * owner makes it private. Only the owner can read private recipes. + */ function listAccessCondition(scope: 'explore' | CookbookScope) { if (scope === 'explore') return publicRecipe; const membership: Record = { @@ -46,6 +60,7 @@ export function createRecipeRepository( return `${visibleToViewer} AND (${membership[scope]})`; } + /** Uses the same search, category and time predicates for count and page rows. */ function listFilterConditions() { // Keep filter parameters separate from access rules; shared by count and rows. // $2 is a tsquery from toSearchQuery(); search_vector has a GIN index. @@ -63,25 +78,26 @@ export function createRecipeRepository( to_char(r.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "updatedAt", json_build_object('id',u.id,'name',u.name) AS author, coalesce(r.author_id = $1::uuid,false) AS "isCreatedByCurrentUser", - 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", + EXISTS(SELECT 1 FROM ${table('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid) AS "isSaved", + (SELECT count(*)::int FROM ${table('saved_recipes')} s WHERE s.recipe_id=r.id) AS "saveCount", json_build_object('average',coalesce(round(r.rating_avg,1),0)::float,'count',r.rating_count) 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 - FROM ${t('recipes')} r JOIN ${t('users')} u ON u.id=r.author_id`; + (SELECT score FROM ${table('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 ${table('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 ${table('recipe_instructions')} i WHERE i.recipe_id=r.id),'[]') AS instructions, + coalesce((SELECT json_agg(tag ORDER BY tag) FROM ${table('recipe_tags')} WHERE recipe_id=r.id),'[]') AS tags + FROM ${table('recipes')} r JOIN ${table('users')} u ON u.id=r.author_id`; // Card lists do not aggregate ingredients or instructions or join authors. const summarySelect = `SELECT r.id, r.title, r.description, r.visibility, r.image_url AS "imageUrl", r.prep_minutes AS "prepMinutes", r.cook_minutes AS "cookMinutes", r.servings, coalesce(r.author_id=$1::uuid,false) AS "isCreatedByCurrentUser", - EXISTS(SELECT 1 FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid) AS "isSaved", - coalesce((SELECT json_agg(tag ORDER BY tag) FROM ${t('recipe_tags')} WHERE recipe_id=r.id),'[]') AS tags, + EXISTS(SELECT 1 FROM ${table('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid) AS "isSaved", + coalesce((SELECT json_agg(tag ORDER BY tag) FROM ${table('recipe_tags')} WHERE recipe_id=r.id),'[]') AS tags, json_build_object('average',coalesce(round(r.rating_avg,1),0)::float,'count',r.rating_count) AS rating - FROM ${t('recipes')} r`; + FROM ${table('recipes')} r`; + /** Runs one transaction attempt and releases its connection on success or failure. */ async function attempt(work: (client: PoolClient) => Promise) { const client = await pool.connect(); try { @@ -96,7 +112,7 @@ export function createRecipeRepository( client.release(); } } - /* + /** * The API locks a recipe before its ratings, ingredients or tags, but a * write outside the API (seed, manual SQL) locks the child row first and * the recipe in its trigger. When the two meet, PostgreSQL aborts one of @@ -119,6 +135,7 @@ export function createRecipeRepository( } } } + /** Returns full details for a visible recipe, or null for missing/inaccessible IDs. */ async function read( executor: Pick, id: string, @@ -130,14 +147,20 @@ export function createRecipeRepository( ); return result.rows[0] ?? null; } + /** Reads a mutation result in the same transaction; a missing row rolls it back. */ async function readRequired(client: PoolClient, id: string, userId: string) { const recipe = await read(client, id, userId); if (!recipe) throw new Error('Recipe could not be read after writing.'); return recipe; } - async function owned(client: PoolClient, id: string, userId: string) { + /** Locks an owned recipe for writing; missing and non-owned IDs share one error. */ + async function lockOwnedRecipe( + client: PoolClient, + id: string, + userId: string, + ) { const result = await client.query( - `SELECT id FROM ${t('recipes')} WHERE id=$1 AND author_id=$2 FOR UPDATE`, + `SELECT id FROM ${table('recipes')} WHERE id=$1 AND author_id=$2 FOR UPDATE`, [id, userId], ); if (!result.rowCount) @@ -145,11 +168,18 @@ export function createRecipeRepository( extensions: { code: 'NOT_FOUND' }, }); } - // One INSERT per child table, whatever the recipe's size: the arrays are - // unnested in order, and WITH ORDINALITY numbers the positions from 1. - async function children(client: PoolClient, id: string, input: RecipeInput) { + /** + * Inserts ingredients, instructions and tags within the caller's transaction. + * One INSERT per child table keeps query count independent of recipe size; + * WITH ORDINALITY preserves input order with positions starting at 1. + */ + async function insertRecipeChildren( + client: PoolClient, + id: string, + input: RecipeInput, + ) { await client.query( - `INSERT INTO ${t('recipe_ingredients')} (recipe_id,name,amount,unit,note,position) + `INSERT INTO ${table('recipe_ingredients')} (recipe_id,name,amount,unit,note,position) SELECT $1, i.name, i.amount, i.unit, i.note, i.position FROM unnest($2::text[], $3::numeric[], $4::text[], $5::text[]) WITH ORDINALITY AS i(name, amount, unit, note, position)`, [ @@ -161,18 +191,18 @@ export function createRecipeRepository( ], ); await client.query( - `INSERT INTO ${t('recipe_instructions')} (recipe_id,text,position) + `INSERT INTO ${table('recipe_instructions')} (recipe_id,text,position) SELECT $1, i.text, i.position FROM unnest($2::text[]) WITH ORDINALITY AS i(text, position)`, [id, input.instructions], ); if (input.tags.length) await client.query( - `INSERT INTO ${t('recipe_tags')} (recipe_id,tag) SELECT $1, unnest($2::text[])`, + `INSERT INTO ${table('recipe_tags')} (recipe_id,tag) SELECT $1, unnest($2::text[])`, [id, input.tags], ); } - /* + /** * Recipe creation quota per user. A per-user lock makes parallel creates * by the same user count one after another, so they cannot all pass the * check together. Recipes created directly in the database (seed, tests) @@ -190,7 +220,7 @@ export function createRecipeRepository( `SELECT count(*)::int AS total, count(*) FILTER (WHERE created_at > now()-interval '1 hour')::int AS recent, ceil(extract(epoch FROM min(created_at) FILTER (WHERE created_at > now()-interval '1 hour') + interval '1 hour' - now()))::int AS "retryAfter" - FROM ${t('recipes')} WHERE author_id=$1`, + FROM ${table('recipes')} WHERE author_id=$1`, [userId], ); const { total, recent, retryAfter } = usage.rows[0]!; @@ -210,7 +240,8 @@ export function createRecipeRepository( }, ); } - const values = (input: RecipeInput) => [ + /** Keeps create/update parameters in the order of their shared recipe columns. */ + const recipeColumnValues = (input: RecipeInput) => [ input.title, input.description, input.imageUrl, @@ -223,7 +254,9 @@ export function createRecipeRepository( input.servings, ]; return { + /** Reads one public or owned recipe; inaccessible IDs return null. */ get: (id: string, userId: string | null) => read(pool, id, userId), + /** Returns a filtered, sorted page of card summaries and its matching count. */ async list( input: ListInput, userId: string | null, @@ -243,16 +276,19 @@ export function createRecipeRepository( input.category ?? null, input.maxCookingMinutes ?? null, ]; - // Count and rows share a snapshot, including when another request creates/deletes recipes. + // REPEATABLE READ keeps count and rows on the same snapshot: concurrent + // creates/deletes cannot change the result set between these two queries. return transaction(async (client) => { await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ'); const count = await client.query<{ total: number }>( - `SELECT count(*)::int AS total, $1::uuid AS "viewerId" FROM ${t('recipes')} r` + + `SELECT count(*)::int AS total, $1::uuid AS "viewerId" FROM ${table('recipes')} r` + where, args, ); const totalCount = count.rows[0]!.total; const totalPages = Math.ceil(totalCount / input.pageSize); + // Filters or deletions may invalidate a bookmarked page. Clamp to the + // last available page; empty results use page 1 with totalPages = 0. const page = Math.min(input.page, Math.max(totalPages, 1)); // With no matches there is nothing to fetch. Skipping the query also // avoids a worst case: for a word that matches nothing, the planner @@ -273,19 +309,21 @@ export function createRecipeRepository( }; }); }, + /** Checks quota/image access and inserts the recipe and children atomically. */ async create(input: RecipeInput, userId: string) { return transaction(async (client) => { await checkCreateQuota(client, userId); await validateImageReference(client, schema, input.imageUrl, userId); const result = await client.query<{ id: string }>( - `INSERT INTO ${t('recipes')} (title,description,image_url,category,cuisine,difficulty,visibility,prep_minutes,cook_minutes,servings,author_id) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) RETURNING id`, - [...values(input), userId], + `INSERT INTO ${table('recipes')} (title,description,image_url,category,cuisine,difficulty,visibility,prep_minutes,cook_minutes,servings,author_id) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) RETURNING id`, + [...recipeColumnValues(input), userId], ); const id = result.rows[0]!.id; - await children(client, id, input); + await insertRecipeChildren(client, id, input); return readRequired(client, id, userId); }); }, + /** Replaces an owned recipe and children, checking the supplied version if present. */ async update( id: string, input: RecipeInput, @@ -293,12 +331,12 @@ export function createRecipeRepository( expectedUpdatedAt?: string | null, ) { return transaction(async (client) => { - await owned(client, id, userId); + await lockOwnedRecipe(client, id, userId); // Optimistic concurrency: compare with updatedAt as the API serves - // it (milliseconds, UTC), under the row lock owned() just took. + // it (milliseconds, UTC), under the row lock lockOwnedRecipe() just took. if (expectedUpdatedAt) { const current = await client.query<{ updatedAt: string }>( - `SELECT to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "updatedAt" FROM ${t('recipes')} WHERE id=$1`, + `SELECT to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "updatedAt" FROM ${table('recipes')} WHERE id=$1`, [id], ); if (current.rows[0]!.updatedAt !== expectedUpdatedAt) @@ -315,31 +353,35 @@ export function createRecipeRepository( id, ); await client.query( - `UPDATE ${t('recipes')} SET title=$1,description=$2,image_url=$3,category=$4,cuisine=$5,difficulty=$6,visibility=$7,prep_minutes=$8,cook_minutes=$9,servings=$10 WHERE id=$11`, - [...values(input), id], + `UPDATE ${table('recipes')} SET title=$1,description=$2,image_url=$3,category=$4,cuisine=$5,difficulty=$6,visibility=$7,prep_minutes=$8,cook_minutes=$9,servings=$10 WHERE id=$11`, + [...recipeColumnValues(input), id], ); for (const name of [ 'recipe_ingredients', 'recipe_instructions', 'recipe_tags', ]) - await client.query(`DELETE FROM ${t(name)} WHERE recipe_id=$1`, [id]); - await children(client, id, input); + await client.query(`DELETE FROM ${table(name)} WHERE recipe_id=$1`, [ + id, + ]); + await insertRecipeChildren(client, id, input); return readRequired(client, id, userId); }); }, + /** Deletes an owned recipe; the image lock coordinates with attachment/cleanup. */ async delete(id: string, userId: string) { return transaction(async (client) => { - await owned(client, id, userId); + await lockOwnedRecipe(client, id, userId); await lockImages(client, schema); - await client.query(`DELETE FROM ${t('recipes')} WHERE id=$1`, [id]); + await client.query(`DELETE FROM ${table('recipes')} WHERE id=$1`, [id]); return true; }); }, + /** Saves another user's public recipe idempotently, locking visibility until commit. */ async save(id: string, 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`, + `SELECT id FROM ${table('recipes')} WHERE id=$1 AND visibility='public' AND author_id<>$2 FOR SHARE`, [id, userId], ); if (!result.rowCount) @@ -348,26 +390,28 @@ export function createRecipeRepository( { extensions: { code: 'FORBIDDEN' } }, ); await client.query( - `INSERT INTO ${t('saved_recipes')} (user_id,recipe_id) VALUES ($1,$2) ON CONFLICT DO NOTHING`, + `INSERT INTO ${table('saved_recipes')} (user_id,recipe_id) VALUES ($1,$2) ON CONFLICT DO NOTHING`, [userId, id], ); return readRequired(client, id, userId); }); }, + /** Removes only this user's saved link, even if the recipe is no longer visible. */ async unsave(id: string, userId: string) { await pool.query( - `DELETE FROM ${t('saved_recipes')} WHERE user_id=$1 AND recipe_id=$2`, + `DELETE FROM ${table('saved_recipes')} WHERE user_id=$1 AND recipe_id=$2`, [userId, id], ); return true; }, + /** Inserts/replaces this user's rating on another user's public recipe. */ async rate(id: string, score: number, userId: string) { return transaction(async (client) => { const result = await client.query( // Exclusive, not FOR SHARE: the ratings trigger updates this row's // cached rating. Two raters holding a shared lock would each wait // for the other to release it before updating, a deadlock. - `SELECT id FROM ${t('recipes')} WHERE id=$1 AND visibility='public' AND author_id<>$2 FOR NO KEY UPDATE`, + `SELECT id FROM ${table('recipes')} WHERE id=$1 AND visibility='public' AND author_id<>$2 FOR NO KEY UPDATE`, [id, userId], ); if (!result.rowCount) @@ -378,23 +422,24 @@ export function createRecipeRepository( }, ); await client.query( - `INSERT INTO ${t('ratings')} (recipe_id,user_id,score) VALUES ($1,$2,$3) + `INSERT INTO ${table('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); }); }, + /** Removes only this user's rating; an already absent rating is a successful no-op. */ async removeRating(id: string, userId: string) { return transaction(async (client) => { // Lock the recipe before the rating, in the same order as rate(), so // a concurrent rate and remove by the same user cannot deadlock. await client.query( - `SELECT id FROM ${t('recipes')} WHERE id=$1 FOR NO KEY UPDATE`, + `SELECT id FROM ${table('recipes')} WHERE id=$1 FOR NO KEY UPDATE`, [id], ); await client.query( - `DELETE FROM ${t('ratings')} WHERE recipe_id=$1 AND user_id=$2`, + `DELETE FROM ${table('ratings')} WHERE recipe_id=$1 AND user_id=$2`, [id, userId], ); return true; From dbbfd69a0c4669af0430c162488c4970d71834df Mon Sep 17 00:00:00 2001 From: "hasan.fawzi" Date: Wed, 18 Nov 2026 13:03:24 +0100 Subject: [PATCH 2/2] docs(api): correct authentication and lock-order explanations --- apps/api/src/app.ts | 8 +++++--- apps/api/src/features/recipes/recipeRepository.ts | 9 +++++---- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 19f6119..808e2ce 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -45,9 +45,11 @@ export function createApp( uploadDirectory = process.env.UPLOAD_DIR ?? fileURLToPath(new URL('../../../uploads/', import.meta.url)), // GraphiQL (an in-browser query editor at /graphql) is on by default so - // reviewers can explore the API; it grants no extra access, because every - // resolver enforces authentication and ownership and POSTs need the CSRF - // header. Set API_GRAPHIQL=false to turn it off. + // reviewers can explore the API; it grants no additional privileges. + // Public queries allow anonymous access, while protected operations require + // authentication. The recipe repository enforces visibility and ownership. + // GraphQL operation requests still need the CSRF header. + // Set API_GRAPHIQL=false to turn it off. enableGraphiql = process.env.API_GRAPHIQL !== 'false', // Request, query and recipe-creation limits (apiLimits.ts); tests that // send many requests from one address raise them. diff --git a/apps/api/src/features/recipes/recipeRepository.ts b/apps/api/src/features/recipes/recipeRepository.ts index 2fc62f4..b4d8470 100644 --- a/apps/api/src/features/recipes/recipeRepository.ts +++ b/apps/api/src/features/recipes/recipeRepository.ts @@ -113,10 +113,11 @@ export function createRecipeRepository( } } /** - * The API locks a recipe before its ratings, ingredients or tags, but a - * write outside the API (seed, manual SQL) locks the child row first and - * the recipe in its trigger. When the two meet, PostgreSQL aborts one of - * them as a deadlock (40P01). Lock order cannot be forced on such writers, + * The API locks a recipe before its ratings, ingredients or tags. Direct + * SQL changes to a child table can lock the child row first, then the recipe + * through a trigger. Conflicting lock orders can cause a deadlock (40P01), + * which PostgreSQL resolves by aborting a transaction. + * Lock order cannot be forced on such external writers, * so an API transaction that loses is rolled back and run again, which * then simply waits for the other writer. Serialization failures (40001) * are retried the same way. Work functions only touch the database, so