Skip to content

Commit efea619

Browse files
Merge pull request #129 from YvigUnderscore/feat/fastify-shell
feat(server): serve the Express app through a Fastify 5 shell
2 parents 46d9173 + c9870a7 commit efea619

16 files changed

Lines changed: 1415 additions & 25 deletions

‎THIRD-PARTY-NOTICES.md‎

Lines changed: 830 additions & 9 deletions
Large diffs are not rendered by default.

‎apps/server/package.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
"@asteasolutions/zod-to-openapi": "^8.5.0",
3636
"@aws-sdk/client-s3": "^3.700.0",
3737
"@aws-sdk/s3-request-presigner": "^3.700.0",
38+
"@fastify/express": "^4.0.14",
3839
"@prisma/adapter-pg": "^7.10.1",
3940
"@prisma/client": "^7.10.1",
4041
"@socket.io/redis-adapter": "^8.3.0",
@@ -45,6 +46,7 @@
4546
"cors": "^2.8.5",
4647
"dotenv": "^17.2.3",
4748
"express": "^5.2.1",
49+
"fastify": "^5.12.8",
4850
"fluent-ffmpeg": "^2.1.3",
4951
"gltf-import-export": "^1.0.22",
5052
"helmet": "^8.1.0",
@@ -81,6 +83,7 @@
8183
"globals": "^17.11.0",
8284
"pino-pretty": "^13.1.3",
8385
"prettier": "^3.9.4",
86+
"socket.io-client": "^4.8.2",
8487
"supertest": "^7.0.0",
8588
"tsx": "^4.19.2",
8689
"typescript": "npm:@typescript/typescript6@^6.0.2",

‎apps/server/src/app.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ vi.mock('./lib/redis.js', async (importOriginal) => ({
1313
import request from 'supertest';
1414
import { createApp } from './app.js';
1515

16-
const app = createApp({ rateLimit: false });
16+
const app = await createApp({ rateLimit: false });
1717

1818
describe('createApp', () => {
1919
it('serves the public OpenAPI document, with the security headers', async () => {
@@ -44,7 +44,7 @@ describe('createApp', () => {
4444
const previous = env.NODE_ENV;
4545
(env as { NODE_ENV: string }).NODE_ENV = 'production';
4646
try {
47-
expect(() => createApp({ rateLimit: false })).toThrow(/reserved for NODE_ENV=test/);
47+
await expect(createApp({ rateLimit: false })).rejects.toThrow(/reserved for NODE_ENV=test/);
4848
} finally {
4949
(env as { NODE_ENV: string }).NODE_ENV = previous;
5050
}

‎apps/server/src/app.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@
22
// SPDX-License-Identifier: AGPL-3.0-or-later
33

44
import './lib/bigintJson.js';
5+
import type { RequestListener } from 'node:http';
56
import express, { type Express } from 'express';
67
import cors from 'cors';
78
import helmet from 'helmet';
89
import { env } from './config/env.js';
10+
import { buildFastifyShell, shellRequestListener } from './http/fastify-shell.js';
911
import { secretEquals } from './lib/crypto.js';
1012
import { enableRedisTransport } from './lib/redis.js';
1113
import { rateLimit, identityRateKey, identityMax, __rateLimitTesting } from './middleware/rateLimit.js';
@@ -124,7 +126,15 @@ export interface CreateAppOptions {
124126
/** A counter that does not count: every hit returns the first value, so the limit is never exceeded. */
125127
const unlimitedCounter = () => ({ hit: () => Promise.resolve(1) });
126128

127-
export const createApp = (options: CreateAppOptions = {}): Express => {
129+
/**
130+
* The HTTP app every caller uses (server, integration and unit tests): the Express app below,
131+
* served through the Fastify shell. Async because the shell registers its plugins before it serves.
132+
*/
133+
export const createApp = async (options: CreateAppOptions = {}): Promise<RequestListener> =>
134+
shellRequestListener(await buildFastifyShell(buildExpressApp(options)));
135+
136+
/** The V2 Express app on its own, as mounted inside the shell (shell tests compare both). */
137+
export const buildExpressApp = (options: CreateAppOptions = {}): Express => {
128138
const limitersOff = options.rateLimit === false;
129139
if (limitersOff && env.NODE_ENV !== 'test') {
130140
throw new Error('createApp({ rateLimit: false }) is reserved for NODE_ENV=test');
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
// SPDX-FileCopyrightText: 2026 Yvig Bidon
2+
// SPDX-License-Identifier: AGPL-3.0-or-later
3+
4+
import { describe, expect, it, vi } from 'vitest';
5+
6+
// The assembled app without Redis, as in app.test.ts: every request below is answered before any
7+
// database or queue is reached.
8+
vi.mock('../lib/redis.js', async (importOriginal) => ({
9+
...(await importOriginal<typeof import('../lib/redis.js')>()),
10+
enableRedisTransport: vi.fn(),
11+
}));
12+
13+
import express, { type Express } from 'express';
14+
import request from 'supertest';
15+
import { buildExpressApp } from '../app.js';
16+
import { buildFastifyShell, shellRequestListener } from './fastify-shell.js';
17+
18+
const STREAM_BYTES = 20 * 1024 * 1024;
19+
const STREAM_CHUNK_BYTES = 64 * 1024;
20+
const BODY_LIMIT = '2mb';
21+
22+
const shelled = async (app: Express) => shellRequestListener(await buildFastifyShell(app));
23+
24+
const v2Alone = buildExpressApp({ rateLimit: false });
25+
const v2Shelled = await shelled(buildExpressApp({ rateLimit: false }));
26+
27+
/** A minimal Express app parsing bodies the way V2 does, to check what reaches a route. */
28+
function echoApp(): Express {
29+
const app = express();
30+
app.use(express.json({ limit: BODY_LIMIT }));
31+
app.use(express.urlencoded({ extended: false, limit: BODY_LIMIT }));
32+
app.post('/echo', (req, res) => {
33+
res.json({ body: req.body as unknown });
34+
});
35+
return app;
36+
}
37+
38+
describe('Fastify shell around the V2 Express app', () => {
39+
it('answers like Express alone on a public route, security headers included', async () => {
40+
const [direct, shell] = await Promise.all([
41+
request(v2Alone).get('/api/openapi.json'),
42+
request(v2Shelled).get('/api/openapi.json'),
43+
]);
44+
expect(shell.status).toBe(direct.status);
45+
expect(shell.body).toEqual(direct.body);
46+
expect(shell.headers['x-content-type-options']).toBe('nosniff');
47+
expect(shell.headers['content-security-policy']).toBe(direct.headers['content-security-policy']);
48+
});
49+
50+
it('keeps the error shape of a refused call', async () => {
51+
const [direct, shell] = await Promise.all([
52+
request(v2Alone).get('/api/projects'),
53+
request(v2Shelled).get('/api/projects'),
54+
]);
55+
expect(shell.status).toBe(401);
56+
expect(shell.body).toEqual(direct.body);
57+
});
58+
59+
it('answers a body sent to an unknown route with a 404 instead of hanging (probe finding 1)', async () => {
60+
// Express consumes the body, finds no route and hands over to Fastify, which would wait for a
61+
// body already read without the shell's pass-through parser.
62+
const res = await request(v2Shelled)
63+
.patch('/api/does-not-exist')
64+
.send({ trim: { inFrame: 1 } })
65+
.timeout(5_000);
66+
expect(res.status).toBe(404);
67+
});
68+
69+
it('answers an unknown path with a JSON 404 where Express alone sent an HTML page', async () => {
70+
// V2 has no 404 handler of its own. The status is unchanged; the body is Fastify's.
71+
const [direct, shell] = await Promise.all([
72+
request(v2Alone).get('/api/does-not-exist'),
73+
request(v2Shelled).get('/api/does-not-exist'),
74+
]);
75+
expect(direct.status).toBe(404);
76+
expect(direct.headers['content-type']).toMatch(/text\/html/);
77+
expect(shell.status).toBe(404);
78+
expect(shell.body).toMatchObject({ statusCode: 404, error: 'Not Found' });
79+
});
80+
81+
it('records what Express routes lose through the shell until step 3: ETag/304 and the request id', async () => {
82+
// Probe finding 3: the plugin swaps Express's res.send for Fastify's, skipping Express's ETag and
83+
// freshness check, and sets req.id first, so V2's logger neither generates nor echoes
84+
// x-request-id. Step 3 of the phase 2a plan restores both on the Fastify side and flips this test.
85+
const [direct, shell] = await Promise.all([
86+
request(v2Alone).get('/api/openapi.json'),
87+
request(v2Shelled).get('/api/openapi.json'),
88+
]);
89+
expect(direct.headers.etag).toBeDefined();
90+
expect(direct.headers['x-request-id']).toBeDefined();
91+
expect(shell.headers.etag).toBeUndefined();
92+
expect(shell.headers['x-request-id']).toBeUndefined();
93+
});
94+
});
95+
96+
describe('Fastify shell mechanics (minimal Express apps)', () => {
97+
it('trusts exactly the proxies Express trusts: the client IP behind nginx (probe finding 2)', async () => {
98+
const ipApp = (hops: number) => {
99+
const app = express();
100+
app.set('trust proxy', hops);
101+
app.get('/ip', (req, res) => {
102+
res.json({ ip: req.ip });
103+
});
104+
return app;
105+
};
106+
const behindProxy = await request(await shelled(ipApp(1)))
107+
.get('/ip')
108+
.set('X-Forwarded-For', '203.0.113.7');
109+
expect(behindProxy.body).toEqual({ ip: '203.0.113.7' });
110+
// TRUST_PROXY=0: a spoofed header is ignored, as with Express alone.
111+
const direct = await request(ipApp(0)).get('/ip').set('X-Forwarded-For', '203.0.113.7');
112+
const spoofed = await request(await shelled(ipApp(0)))
113+
.get('/ip')
114+
.set('X-Forwarded-For', '203.0.113.7');
115+
expect(spoofed.body).toEqual(direct.body);
116+
expect(spoofed.body).not.toEqual({ ip: '203.0.113.7' });
117+
});
118+
119+
it('lets JSON and urlencoded bodies reach the Express route', async () => {
120+
const shell = await shelled(echoApp());
121+
const json = await request(shell).post('/echo').send({ name: 'shot 010' }).timeout(5_000);
122+
const form = await request(shell).post('/echo').type('form').send('name=shot+010').timeout(5_000);
123+
expect(json.body).toEqual({ body: { name: 'shot 010' } });
124+
expect(form.body).toEqual({ body: { name: 'shot 010' } });
125+
});
126+
127+
it('refuses a body over the limit the way Express alone does', async () => {
128+
const big = { blob: 'x'.repeat(2 * 1024 * 1024 + 10) };
129+
const direct = await request(echoApp()).post('/echo').send(big).timeout(10_000);
130+
const shell = await request(await shelled(echoApp()))
131+
.post('/echo')
132+
.send(big)
133+
.timeout(10_000);
134+
expect(shell.status).toBe(direct.status);
135+
});
136+
137+
it('streams a large response and answers a Range request', async () => {
138+
const file = Buffer.alloc(STREAM_BYTES, 7);
139+
const app = express();
140+
app.get('/file', (req, res) => {
141+
const range = /bytes=(\d+)-(\d+)/.exec(req.headers.range ?? '');
142+
if (range) {
143+
const [start, end] = [Number(range[1]), Number(range[2])];
144+
res
145+
.status(206)
146+
.set('Content-Range', `bytes ${start}-${end}/${file.length}`)
147+
.end(file.subarray(start, end + 1));
148+
return;
149+
}
150+
res.set('Content-Length', String(file.length));
151+
let offset = 0;
152+
const pump = (): void => {
153+
while (offset < file.length) {
154+
const chunk = file.subarray(offset, offset + STREAM_CHUNK_BYTES);
155+
offset += chunk.length;
156+
if (!res.write(chunk)) {
157+
res.once('drain', pump);
158+
return;
159+
}
160+
}
161+
res.end();
162+
};
163+
pump();
164+
});
165+
const shell = await shelled(app);
166+
const full = await request(shell)
167+
.get('/file')
168+
.buffer(true)
169+
.parse((res, done) => {
170+
const parts: Buffer[] = [];
171+
res.on('data', (chunk: Buffer) => parts.push(chunk));
172+
res.on('end', () => {
173+
done(null, Buffer.concat(parts));
174+
});
175+
});
176+
const part = await request(shell).get('/file').set('Range', 'bytes=0-1023');
177+
expect((full.body as Buffer).length).toBe(file.length);
178+
expect(part.status).toBe(206);
179+
expect(part.headers['content-range']).toBe(`bytes 0-1023/${file.length}`);
180+
});
181+
});
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// SPDX-FileCopyrightText: 2026 Yvig Bidon
2+
// SPDX-License-Identifier: AGPL-3.0-or-later
3+
4+
/**
5+
* Fastify 5 is the HTTP front door; the whole V2 Express app is mounted inside it through
6+
* `@fastify/express`. Routes leave Express one group at a time (phase 2a pilot, then the sweep of
7+
* phases 2b–3), so both live side by side until Express is gone.
8+
*
9+
* Two fixes found by the transition probe (`probes/fastify/REPORT.md`, findings 1 and 2) are part of
10+
* the shell from day one, each pinned by a test in `fastify-shell.test.ts`.
11+
*/
12+
import type { IncomingMessage, RequestListener, ServerResponse } from 'node:http';
13+
import fastifyExpress from '@fastify/express';
14+
import type { Express } from 'express';
15+
import Fastify, { type FastifyInstance } from 'fastify';
16+
17+
/** Express's compiled `trust proxy` setting: `(address, hop) => trusted`. */
18+
type TrustProxyFn = (address: string, hop: number) => boolean;
19+
20+
export async function buildFastifyShell(expressApp: Express): Promise<FastifyInstance> {
21+
// Finding 2 (client IP behind nginx): `@fastify/express` replaces Express's `req.ip` with Fastify's,
22+
// so Fastify must trust exactly the proxies Express trusts. The same hop count is not enough
23+
// (Express `trust proxy = 1` gives the X-Forwarded-For client, Fastify `trustProxy: 1` gave the
24+
// proxy, and Fastify 5 now refuses a bare number): hand Fastify the function Express compiled from
25+
// `TRUST_PROXY`. It is hop-based like V2's, which is safe only because nginx is the one service
26+
// that publishes a port (deployment rules); the server is never reached directly.
27+
const trustProxy = expressApp.get('trust proxy fn') as TrustProxyFn;
28+
// Logging stays in Express (pino-http) while Express serves every route.
29+
const shell = Fastify({ trustProxy, logger: false });
30+
31+
// Finding 1 (hang): Express parses bodies itself. When it finds no route it hands the request back
32+
// to Fastify, whose own parser would then wait for a body already consumed, and the request never
33+
// answers. While Express owns parsing, Fastify accepts every content type without reading it.
34+
// Settled for native routes in step 4 of the phase 2a plan.
35+
shell.removeAllContentTypeParsers();
36+
shell.addContentTypeParser('*', (_request, _payload, done) => {
37+
done(null, undefined);
38+
});
39+
40+
await shell.register(fastifyExpress);
41+
shell.use(expressApp);
42+
await shell.ready();
43+
return shell;
44+
}
45+
46+
/** The shell as a plain Node request listener, for `http.createServer` and supertest. */
47+
export function shellRequestListener(shell: FastifyInstance): RequestListener {
48+
return (request: IncomingMessage, response: ServerResponse) => {
49+
shell.routing(request, response);
50+
};
51+
}

‎apps/server/src/integration/api.itest.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import { MAX_PAGE_SIZE } from '../lib/pagination.js';
1616
* studio's initial setup in it. It is still written so that it works on an already populated
1717
* database, which is what allows replaying it without a reset while debugging.
1818
*/
19-
const app = createApp({ rateLimit: false });
19+
const app = await createApp({ rateLimit: false });
2020
let token = '';
2121
let artistToken = '';
2222
let artistId = 0;

0 commit comments

Comments
 (0)