/** * Entry point for a directly served instance, instead of `node build`. * * adapter-node guesses `https` for a request that arrives without a proxy * header, and SvelteKit treats that guess as the app's own origin, so every form * POST fails the cross-site check on a plain-HTTP install. This server answers * the origin question through `PROTOCOL_HEADER`. It also refuses to start an * older build against a newer database, before the import below opens it. * * Plain JavaScript, because it runs before the built app's module graph. */ import { createServer } from 'node:http'; import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import process from 'node:process'; import { formatOverrideWarning, formatRefusal, readDbState, resolveDatabasePath } from './scripts/db-state.mjs'; import { proxyDepth, resolveClientAddress, schemeFromForwarded, schemeFromOrigin } from './scripts/forwarded.mjs'; import { bodyLimitFor } from './scripts/request-limits.mjs'; /* * The adapter reads PROTOCOL_HEADER when its module first evaluates, so this * must be set before the dynamic import below. An ES module cannot import later. */ process.env.PROTOCOL_HEADER ??= 'x-forwarded-proto'; // Leave room for multipart headers above the 100 MiB import file limit. process.env.BODY_SIZE_LIMIT ??= '101M'; /* * Trust forwarded headers only when the deployment states that every request * arrives through a proxy: a client can send these headers itself and choose * its own address and scheme. */ const trustProxy = process.env.TRUST_PROXY === '1'; /* * The address is resolved here and written back, so adapter-node and better-auth * read one value this process decided on. better-auth never sees the socket, so * without this a client chooses its own rate-limit bucket with a header. * * The depth belongs to the proxy chain, not to the adapter: read it before the * line below pins the adapter to the single address this server writes. */ const forwardedDepth = proxyDepth(process.env.XFF_DEPTH); if (trustProxy) { process.env.ADDRESS_HEADER ??= 'x-forwarded-for'; } const addressHeader = (process.env.ADDRESS_HEADER ?? '').toLowerCase(); if (addressHeader === 'x-forwarded-for') { // This server resolves the chain itself, so the adapter must read one entry // whatever depth the operator declared for the proxies behind the app. process.env.XFF_DEPTH = '1'; } const build = buildIdentity(); refuseNewerDatabase(build); const { handler } = await import('./build/handler.js'); const port = Number(process.env.PORT ?? 3000); const host = process.env.HOST ?? '0.0.0.0'; /** Omits the commit when the build cannot name one. */ function buildName() { return build.commit && build.commit !== 'unknown' ? `${build.version} (${build.commit})` : build.version; } function buildIdentity() { try { const manifest = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')); return { version: manifest.version ?? 'unknown', commit: process.env.APP_COMMIT ?? 'unknown' }; } catch { return { version: 'unknown', commit: process.env.APP_COMMIT ?? 'unknown' }; } } /** * Stops the process when the database holds a migration this build does not * ship. A database that is missing or unreadable is not a refusal: only a * positive answer is. */ function refuseNewerDatabase(identity) { const databasePath = resolveDatabasePath(process.env.DATABASE_URL); const state = readDbState({ databasePath, // Relative to this file, so the check works from any working directory. migrationsFolder: fileURLToPath(new URL('./drizzle', import.meta.url)) }); if (!state.newerThanBuild) return; const refusal = formatRefusal(state, identity); if (process.env.FABLEWRIGHT_ALLOW_NEWER_SCHEMA === '1') { console.warn(formatOverrideWarning(state, identity)); return; } console.error(refusal); process.exit(1); } /** * The scheme to advertise for a request. The operator's declaration wins; a * forwarded header counts only when `trustProxy` says every request arrives * through a proxy, or a client would choose the app's own origin. */ function schemeFor(request) { const declared = process.env.ORIGIN?.trim(); if (declared) { const scheme = schemeFromOrigin(declared); if (scheme) return scheme; console.error(`[fablewright] ORIGIN is not a valid URL: ${declared}`); } if (trustProxy) { const forwarded = schemeFromForwarded(request.headers['x-forwarded-proto']); if (forwarded) return forwarded; } return request.socket.encrypted ? 'https' : 'http'; } /** * Refuses a request whose body is over its route's allowance, before the adapter * reads a byte of it, and reports whether the request may continue. * * A declared `Content-Length` answers most requests: the HTTP parser delivers * exactly that many bytes and no more, so the header cannot understate a body. * A chunked body declares nothing, so it is counted as it arrives. */ function bodyFits(request, response) { const limit = bodyLimitFor(request.url); const declared = Number(request.headers['content-length']); if (Number.isFinite(declared)) { if (declared <= limit) return true; refuseBody(request, response, limit); return false; } // Without a declared length, no `transfer-encoding` means no body at all. if (request.headers['transfer-encoding'] == null) return true; let seen = 0; request.on('data', (chunk) => { if (seen > limit) return; seen += chunk.length; if (seen > limit) refuseBody(request, response, limit, true); }); return true; } /** * Answers 413 for a body over its route's allowance. * * A body declared over its allowance is still being sent, so the connection stays * usable: the client finishes writing, reads this answer, and the bytes nobody * wanted are discarded as they arrive rather than buffered. Ending the socket * there would fail the client's write instead of answering it, and a writer with * an oversized save would see a network error rather than the reason. * * A chunked body has already been delivered to the adapter, which is holding it * for a handler, so the only way to stop the rest is to stop the flow and close. */ function refuseBody(request, response, limit, close = false) { if (response.headersSent || response.writableEnded) return; if (close) request.pause(); const body = JSON.stringify({ message: `That request was larger than ${Math.round(limit / 1024 / 1024)} MB.` }); const headers = { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) }; if (close) { headers.connection = 'close'; response.writeHead(413, headers); // The adapter is still reading this body and will answer it once the read // fails. Closing the socket after this answer leaves it nothing to write on, // so the 413 is the only response and no failed write reaches the log. response.end(body, () => response.destroy()); return; } response.writeHead(413, headers); response.end(body); } const server = createServer((request, response) => { if (!bodyFits(request, response)) return; // PROTOCOL_HEADER names this header, so the adapter reads it. Overwriting it // means the adapter sees one scheme, and a client cannot append its own. request.headers['x-forwarded-proto'] = schemeFor(request); const address = resolveClientAddress({ trustProxy, addressHeader, depth: forwardedDepth, headers: request.headers, socket: request.socket.remoteAddress ?? '' }); // The same rule for the address: the adapter, better-auth and anything added // later all read this one value, and no client-supplied entry survives. request.headers['x-forwarded-for'] = address; if (addressHeader && addressHeader !== 'x-forwarded-for') { request.headers[addressHeader] = address; } handler(request, response); }); server.listen(port, host, () => { // The first line of the log answers the first question of a bug report. console.info(`[fablewright] ${buildName()} listening on http://${host}:${port}`); }); function shutdown(signal) { console.info(`[fablewright] ${signal} received, shutting down`); const timeout = setTimeout(() => process.exit(0), 30_000); timeout.unref(); server.close(() => { clearTimeout(timeout); process.exit(0); }); } process.on('SIGTERM', () => shutdown('SIGTERM')); process.on('SIGINT', () => shutdown('SIGINT'));