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
27 changes: 24 additions & 3 deletions apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -40,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.
Expand All @@ -69,8 +76,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<Request, string>();
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).
Expand Down Expand Up @@ -124,6 +136,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,
Expand Down Expand Up @@ -185,6 +200,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
Expand All @@ -195,6 +211,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 (
Expand All @@ -210,6 +229,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;
Expand Down
Loading