bugfix: proxy /api/* through the SvelteKit container

The compose deploy was unreachable because frontend code reads its
API base from `import.meta.env.VITE_API_BASE` at build time, but the
shipped image baked in the fallback `/api` and never picked up the
`PUBLIC_API_BASE` env var. The browser then hit
http://localhost:3000/api/...which the Node adapter doesn't serve, so
every request 404'd.

Fix the topology at the right layer: hooks.server.ts proxies /api/*
requests through to the backend container over docker's internal
network. The browser only ever talks to :3000, cookies stay
same-origin, and CORS can stay empty.

- frontend/src/hooks.server.ts: new proxy. Reads BACKEND_URL (defaults
  to http://localhost:8080 for ad-hoc node builds). Strips `host` and
  `content-length` so the backend sees the real client request and
  recomputes the length. Sets `duplex: 'half'` for streamed POST
  bodies. GET/HEAD have no body. Non-/api paths fall through to
  SvelteKit normally.
- docker-compose.yml: drop the host port mapping on the backend
  (browser doesn't reach it directly anymore — use `ports:` instead of
  `expose:` if you want curl access). Set BACKEND_URL=http://backend:8080
  on the frontend service. Drop PUBLIC_API_BASE which was unused.
- .env.example: replace PUBLIC_API_BASE with BACKEND_URL, with a note
  on what it does.
- README: explain the new topology in Quick start, update the bot
  curl examples to hit :3000 (since that's the only published port in
  the default deploy), and call out that the TLS terminator only needs
  one upstream now.

Lockstep version bump to 0.9.1.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
MechaCat02
2026-05-16 23:17:50 +02:00
parent 57364fae32
commit ea60bd97de
7 changed files with 181 additions and 19 deletions

View File

@@ -1,6 +1,6 @@
{
"name": "mangalord-frontend",
"version": "0.9.0",
"version": "0.9.1",
"private": true,
"type": "module",
"scripts": {

View File

@@ -0,0 +1,104 @@
import {
describe,
it,
expect,
vi,
beforeEach,
afterEach,
type MockInstance
} from 'vitest';
import { handle } from './hooks.server';
// `BACKEND_URL` is read at module load time, so the values used in the
// asserts below assume the test env didn't set it. `?? 'http://localhost:8080'`
// is the default.
const DEFAULT_BACKEND = 'http://localhost:8080';
function makeEvent(path: string, init?: RequestInit) {
const url = new URL(`http://app.example.com${path}`);
const request = new Request(url, init);
return { url, request } as Parameters<typeof handle>[0]['event'];
}
describe('hooks.server proxy', () => {
let fetchSpy: MockInstance<typeof globalThis.fetch>;
beforeEach(() => {
fetchSpy = vi.spyOn(globalThis, 'fetch');
});
afterEach(() => {
vi.restoreAllMocks();
});
it('forwards /api/* requests to the backend, preserving status', async () => {
fetchSpy.mockResolvedValueOnce(
new Response(JSON.stringify({ status: 'ok' }), {
status: 200,
headers: { 'content-type': 'application/json' }
})
);
const resolve = vi.fn();
const event = makeEvent('/api/v1/health');
const resp = await handle({ event, resolve });
expect(resolve).not.toHaveBeenCalled();
expect(fetchSpy).toHaveBeenCalledTimes(1);
expect(fetchSpy.mock.calls[0][0]).toBe(`${DEFAULT_BACKEND}/api/v1/health`);
expect(resp.status).toBe(200);
expect(await resp.json()).toEqual({ status: 'ok' });
});
it('passes through the query string', async () => {
fetchSpy.mockResolvedValueOnce(new Response('[]', { status: 200 }));
const resolve = vi.fn();
await handle({
event: makeEvent('/api/v1/mangas?search=narto&limit=10'),
resolve
});
expect(fetchSpy.mock.calls[0][0]).toBe(
`${DEFAULT_BACKEND}/api/v1/mangas?search=narto&limit=10`
);
});
it('strips the host header so the backend sees its own origin', async () => {
fetchSpy.mockResolvedValueOnce(new Response('[]', { status: 200 }));
const resolve = vi.fn();
await handle({
event: makeEvent('/api/v1/health', {
headers: { host: 'app.example.com', cookie: 'mangalord_session=abc' }
}),
resolve
});
const init = fetchSpy.mock.calls[0][1] as RequestInit;
const headers = init.headers as Headers;
expect(headers.get('host')).toBeNull();
// Cookies must still be forwarded — that's how the session reaches axum.
expect(headers.get('cookie')).toBe('mangalord_session=abc');
});
it('forwards request bodies on POST', async () => {
fetchSpy.mockResolvedValueOnce(new Response('{}', { status: 201 }));
const resolve = vi.fn();
await handle({
event: makeEvent('/api/v1/auth/login', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ username: 'alice', password: 'hunter2hunter2' })
}),
resolve
});
const init = fetchSpy.mock.calls[0][1] as RequestInit;
expect(init.method).toBe('POST');
expect(init.body).toBeDefined();
});
it('delegates non-/api requests to SvelteKit', async () => {
const resolve = vi.fn().mockResolvedValue(new Response('page', { status: 200 }));
await handle({ event: makeEvent('/manga/abc'), resolve });
expect(fetchSpy).not.toHaveBeenCalled();
expect(resolve).toHaveBeenCalledTimes(1);
});
});

View File

@@ -0,0 +1,45 @@
import type { Handle } from '@sveltejs/kit';
// Reverse-proxy `/api/*` requests through to the backend container.
//
// Mangalord's compose runs SvelteKit (this process) on :3000 and axum on
// :8080. The browser only ever talks to :3000, so cookies stay
// same-origin and `CORS_ALLOWED_ORIGINS` can stay empty in the default
// deploy. The backend hostname comes from `BACKEND_URL` (compose wires
// `http://backend:8080`); for `npm run dev` we fall back to the same
// localhost target the vite proxy uses, which keeps the dev story
// consistent even if someone bypasses the vite proxy.
const BACKEND_URL = process.env.BACKEND_URL ?? 'http://localhost:8080';
export const handle: Handle = async ({ event, resolve }) => {
if (event.url.pathname.startsWith('/api/')) {
const target = `${BACKEND_URL}${event.url.pathname}${event.url.search}`;
// Strip hop-by-hop headers — `host` would mislead the backend
// about the origin, and `content-length` will be recomputed.
const headers = new Headers(event.request.headers);
headers.delete('host');
headers.delete('content-length');
const init: RequestInit & { duplex?: 'half' } = {
method: event.request.method,
headers,
redirect: 'manual'
};
if (event.request.method !== 'GET' && event.request.method !== 'HEAD') {
init.body = event.request.body;
// Node's fetch requires `duplex: 'half'` when streaming a
// request body; otherwise the stream is rejected.
init.duplex = 'half';
}
const upstream = await fetch(target, init);
return new Response(upstream.body, {
status: upstream.status,
statusText: upstream.statusText,
headers: upstream.headers
});
}
return resolve(event);
};