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
34 changes: 34 additions & 0 deletions server/src/albums.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { eq } from 'drizzle-orm';
import { GraphQLError } from 'graphql';

import type { Db } from './db/client.js';
import { album } from './db/schema.js';

export type AlbumRecord = {
id: number;
title: string;
releaseYear: number | null;
musicBrainzReleaseGroupId: string | null;
};

const albumColumns = {
id: album.id,
title: album.title,
releaseYear: album.releaseYear,
musicBrainzReleaseGroupId: album.musicBrainzReleaseGroupId,
};

export async function findAlbumById(db: Db, id: number): Promise<AlbumRecord | null> {
const [found] = await db
.select(albumColumns)
.from(album)
.where(eq(album.id, id))
.limit(1);
return found ?? null;
}

export async function findAlbum(db: Db, id: number): Promise<AlbumRecord> {
const found = await findAlbumById(db, id);
if (!found) throw new GraphQLError('Album not found.');
return found;
}
318 changes: 318 additions & 0 deletions server/src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,318 @@
import {
createServer,
type IncomingMessage,
type Server,
type ServerResponse,
} from 'node:http';
import { createSchema, createYoga, type Plugin } from 'graphql-yoga';
import type { Db } from './db/client.js';
import { createLoaders } from './loaders/index.js';
import { resolvers, type Context } from './resolvers.js';
import {
DEFAULT_MAX_BODY_BYTES,
DEFAULT_MAX_ALIASES,
DEFAULT_MAX_COMPLEXITY,
DEFAULT_MAX_QUERY_DEPTH,
DEFAULT_RATE_LIMIT_MAX_REQUESTS,
DEFAULT_RATE_LIMIT_WINDOW_MS,
GRAPHQL_SECURITY_HEADERS,
createCorsConfig,
createQueryLimitsRule,
createRateLimiter,
getClientIp,
noIntrospectionRule,
parseCorsOrigins,
} from './security.js';
import { parseUserId } from './userIdentity.js';

export type ServerConfig = {
db: Db;
typeDefs: string;
isProduction?: boolean;
corsOrigins?: readonly string[];
maxBodyBytes?: number;
maxQueryDepth?: number;
maxAliases?: number;
maxComplexity?: number;
rateLimitWindowMs?: number;
rateLimitMaxRequests?: number;
now?: () => number;
};

function parseOptionalInt(
raw: string | undefined,
fallback: number,
{ min }: { min: number },
): number {
if (raw === undefined || raw.trim() === '') return fallback;
const trimmed = raw.trim();
if (!/^\d+$/.test(trimmed)) return fallback;
const parsed = Number(trimmed);
return Number.isSafeInteger(parsed) && parsed >= min ? parsed : fallback;
}

export function configFromEnv(
env: Record<string, string | undefined>,
): Omit<ServerConfig, 'db' | 'typeDefs'> {
return {
isProduction: env.NODE_ENV === 'production',
corsOrigins: parseCorsOrigins(env.CORS_ORIGIN),
maxBodyBytes: parseOptionalInt(env.GRAPHQL_MAX_BODY_BYTES, DEFAULT_MAX_BODY_BYTES, {
min: 1024,
}),
maxQueryDepth: parseOptionalInt(env.GRAPHQL_MAX_DEPTH, DEFAULT_MAX_QUERY_DEPTH, {
min: 1,
}),
maxAliases: parseOptionalInt(env.GRAPHQL_MAX_ALIASES, DEFAULT_MAX_ALIASES, {
min: 1,
}),
maxComplexity: parseOptionalInt(env.GRAPHQL_MAX_COMPLEXITY, DEFAULT_MAX_COMPLEXITY, {
min: 1,
}),
rateLimitWindowMs: parseOptionalInt(
env.RATE_LIMIT_WINDOW_MS,
DEFAULT_RATE_LIMIT_WINDOW_MS,
{ min: 1000 },
),
rateLimitMaxRequests: parseOptionalInt(
env.RATE_LIMIT_MAX_REQUESTS,
DEFAULT_RATE_LIMIT_MAX_REQUESTS,
{ min: 0 },
),
};
}

function sendJsonError(
res: ServerResponse,
statusCode: number,
message: string,
extraHeaders: Record<string, string> = {},
): void {
res.writeHead(statusCode, {
'content-type': 'application/json; charset=utf-8',
...GRAPHQL_SECURITY_HEADERS,
...extraHeaders,
});
res.end(JSON.stringify({ errors: [{ message }] }));
}

function toWebHeaders(req: IncomingMessage): Headers {
const headers = new Headers();
for (const [key, value] of Object.entries(req.headers)) {
if (value === undefined) continue;
if (Array.isArray(value)) {
for (const item of value) headers.append(key, item);
} else {
headers.set(key, value);
}
}
return headers;
}

function isGraphqlPath(urlPath: string | undefined): boolean {
if (!urlPath) return false;
const pathname = urlPath.split('?', 1)[0] ?? '';
return pathname === '/graphql' || pathname === '/graphql/';
}

function readBoundedBody(req: IncomingMessage, maxBytes: number): Promise<Buffer | null> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let totalBytes = 0;
let exceeded = false;

req.on('data', (chunk: Buffer | string) => {
if (exceeded) return;
const buffer = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
totalBytes += buffer.length;
if (totalBytes > maxBytes) {
exceeded = true;
resolve(null);
return;
}
chunks.push(buffer);
});

req.on('end', () => {
if (!exceeded) resolve(Buffer.concat(chunks));
});

req.on('error', (error) => {
if (!exceeded) reject(error);
});
});
}

export function createGraphQLYoga(config: ServerConfig) {
const isProduction = config.isProduction ?? false;
const queryLimitsRule = createQueryLimitsRule({
maxDepth: config.maxQueryDepth,
maxAliases: config.maxAliases,
maxComplexity: config.maxComplexity,
});

const securityPlugin: Plugin<Context> = {
onValidate({ addValidationRule }) {
addValidationRule(queryLimitsRule);
if (isProduction) {
addValidationRule(noIntrospectionRule);
}
},
onResponse({ request, response }) {
const pathname = new URL(request.url).pathname;
if (pathname === '/graphql' || pathname === '/graphql/') {
for (const [name, value] of Object.entries(GRAPHQL_SECURITY_HEADERS)) {
response.headers.set(name, value);
}
}
},
};

return createYoga<object, Context>({
schema: createSchema<Context>({ typeDefs: config.typeDefs, resolvers }),
cors: createCorsConfig(config.corsOrigins ?? []),
graphiql: !isProduction,
landingPage: !isProduction,
plugins: [securityPlugin],
// New loaders per request, so batching never leaks between requests.
context: ({ request }) => {
const userId = parseUserId(request.headers.get('x-user-id'));
return { db: config.db, userId, loaders: createLoaders(config.db, userId) };
},
});
}

export function createAppServer(config: ServerConfig): {
server: Server;
yoga: ReturnType<typeof createGraphQLYoga>;
rateLimiter: ReturnType<typeof createRateLimiter>;
} {
const maxBodyBytes = config.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
const yoga = createGraphQLYoga(config);
const rateLimiter = createRateLimiter({
windowMs: config.rateLimitWindowMs,
maxRequests: config.rateLimitMaxRequests,
now: config.now,
});

const server = createServer(async (req, res) => {
try {
const onGraphql = isGraphqlPath(req.url);
if (onGraphql && req.method !== 'OPTIONS') {
const clientIp = getClientIp(
req.socket.remoteAddress,
req.headers['x-forwarded-for'],
);
const decision = rateLimiter.check(clientIp);
if (!decision.allowed) {
sendJsonError(res, 429, 'Too many requests. Please try again later.', {
'retry-after': String(decision.retryAfterSeconds),
});
return;
}
}

const method = (req.method ?? 'GET').toUpperCase();
const hasBody = method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS';

if (!hasBody) {
await yoga(req, res);
return;
}

const contentLengthHeader = req.headers['content-length'];
if (contentLengthHeader !== undefined) {
const declaredBytes = Number(contentLengthHeader);
if (Number.isFinite(declaredBytes) && declaredBytes > maxBodyBytes) {
sendJsonError(res, 413, 'Request body too large.', { connection: 'close' });
req.resume();
return;
}
}

const body = await readBoundedBody(req, maxBodyBytes);
if (body === null) {
res.writeHead(413, {
'content-type': 'application/json; charset=utf-8',
connection: 'close',
...GRAPHQL_SECURITY_HEADERS,
});
res.end(
JSON.stringify({ errors: [{ message: 'Request body too large.' }] }),
() => {
req.destroy();
},
);
return;
}

const host = req.headers.host ?? 'localhost';
const url = `http://${host}${req.url ?? '/'}`;
const headers = toWebHeaders(req);
const response = await yoga.fetch(url, {
method,
headers,
body: new Uint8Array(body),
});

const responseHeaders: Record<string, string> = {};
response.headers.forEach((value, key) => {
responseHeaders[key] = value;
});
if (onGraphql) {
Object.assign(responseHeaders, GRAPHQL_SECURITY_HEADERS);
}

const responseBody = Buffer.from(await response.arrayBuffer());
res.writeHead(response.status, responseHeaders);
res.end(responseBody);
} catch (error) {
console.error('Unhandled HTTP request error:', error);
if (!res.headersSent) {
sendJsonError(res, 500, 'Internal server error.');
} else {
res.end();
}
}
});

return { server, yoga, rateLimiter };
}

export function registerGracefulShutdown(
server: Server,
closePool: () => Promise<void>,
{
timeoutMs = 10_000,
onExit = (code: number) => process.exit(code),
}: { timeoutMs?: number; onExit?: (code: number) => void } = {},
) {
let shuttingDown = false;

return (signal: NodeJS.Signals) => {
if (shuttingDown) return;
shuttingDown = true;
console.log(`Received ${signal}, shutting down gracefully...`);

const forceTimer = setTimeout(() => {
console.error('Graceful shutdown timed out; forcing exit.');
onExit(1);
}, timeoutMs);
forceTimer.unref();

server.close(async (closeError) => {
if (closeError) {
console.error('Error closing HTTP server:', closeError);
}
try {
await closePool();
clearTimeout(forceTimer);
onExit(closeError ? 1 : 0);
} catch (poolError) {
console.error('Error closing PostgreSQL pool:', poolError);
clearTimeout(forceTimer);
onExit(1);
}
});
};
}
29 changes: 22 additions & 7 deletions server/src/crate.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';

import { addToCrate, removeFromCrate } from './crate.js';
import { addToCrate, decodeCrateCursor, removeFromCrate } from './crate.js';

const userId = '550e8400-e29b-41d4-a716-446655440000';

Expand All @@ -13,10 +13,25 @@ describe('crate mutation validation', () => {
await expect(removeFromCrate({} as never, null, '1')).rejects.toThrow('X-User-Id');
});

it.each(['0', '-1', 'not-an-id', '1.5'])('rejects invalid album id %s', async (id) => {
await expect(addToCrate({} as never, userId, id)).rejects.toThrow('Invalid album id');
await expect(removeFromCrate({} as never, userId, id)).rejects.toThrow(
'Invalid album id',
);
});
it.each(['', ' ', '0', '-1', 'not-an-id', '1.5', ' 1 ', '2147483648'])(
'rejects invalid album id %j',
async (id) => {
await expect(addToCrate({} as never, userId, id)).rejects.toThrow(
'Invalid album id.',
);
await expect(removeFromCrate({} as never, userId, id)).rejects.toThrow(
'Invalid album id.',
);
},
);

it.each([0, -1, 2_147_483_648])(
'rejects out-of-range int4 id %s in crate cursor',
(id) => {
const forged = Buffer.from(
JSON.stringify(['2026-01-02T10:00:00.000000Z', id]),
).toString('base64url');
expect(() => decodeCrateCursor(forged)).toThrow('Invalid crate cursor.');
},
);
});
Loading