Files
regress/server/src/app.ts
T
ssmithx 517186ac55 Add path-prefix deployment support for migrating to podsteadr's domain
Regress needs to live at podsteadr.atobitcoin.io/regress/ since / is
already podsteadr. Two coordinated pieces:
- VITE_BASE build arg (frontend asset/script paths, %BASE_URL% in
  index.html for the nostr-provider.js script tag)
- ROUTE_PREFIX runtime env (backend routes registered under the prefix
  via Fastify's plugin-encapsulation, including /api/health)

The nginx location must forward the prefix unstripped (proxy_pass with
no trailing path) — NIP-98 login signs the exact URL it calls, so a
stripped prefix makes the backend reconstruct a different URL than what
was signed and every login fails. Caught this with a real nginx+docker
integration test locally before it could break the live migration, then
fixed a matching bug in auth.ts (it was signing the unprefixed URL while
api.ts fetched the prefixed one). New routePrefix.test.ts proves the
prefix is actually enforced, including a negative case. 40 tests passing.

Also fixes a latent bug: import.meta.env usage had no vite/client type
reference, so it only ever passed typecheck by accident in earlier local
runs — added the standard vite-env.d.ts.
2026-08-05 14:58:43 +00:00

83 lines
2.6 KiB
TypeScript

import Fastify, { type FastifyInstance } from 'fastify';
import cookie from '@fastify/cookie';
import cors from '@fastify/cors';
import fastifyStatic from '@fastify/static';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import type { Config } from './config.js';
import { openDatabase, type DB } from './db/database.js';
import nostrAuth from './plugins/nostr-auth.js';
import authRoutes from './routes/auth.js';
import placesRoutes from './routes/places.js';
import claimsRoutes from './routes/claims.js';
import linksRoutes from './routes/links.js';
import fieldsRoutes from './routes/fields.js';
import syncRoutes from './routes/sync.js';
export interface AppContext {
config: Config;
db: DB;
}
declare module 'fastify' {
interface FastifyInstance {
ctx: AppContext;
}
}
export interface BuildAppOptions {
config: Config;
dbPath?: string; // override for tests (':memory:')
logger?: boolean;
}
export async function buildApp(opts: BuildAppOptions): Promise<FastifyInstance> {
const { config } = opts;
const db = openDatabase(opts.dbPath ?? join(config.DATA_DIR, 'regress.sqlite3'));
const app = Fastify({ logger: opts.logger ?? true, bodyLimit: 1 * 1024 * 1024 });
const ctx: AppContext = { config, db };
app.decorate('ctx', ctx);
await app.register(cookie);
await app.register(cors, { origin: true, credentials: true, methods: ['GET', 'POST', 'DELETE'] });
await app.register(nostrAuth, { db, config });
// Everything below is mounted under ROUTE_PREFIX (empty by default, i.e.
// root) so a single build can be deployed either standalone or under a
// shared domain's path — see config.ts for why the prefix must be
// preserved end-to-end rather than stripped by the reverse proxy.
const prefix = config.ROUTE_PREFIX;
await app.register(
async (scoped) => {
scoped.get('/api/health', async () => ({ status: 'ok' }));
await scoped.register(authRoutes);
await scoped.register(placesRoutes);
await scoped.register(claimsRoutes);
await scoped.register(linksRoutes);
await scoped.register(fieldsRoutes);
await scoped.register(syncRoutes);
const staticDir = config.STATIC_DIR;
if (staticDir && existsSync(staticDir)) {
await scoped.register(fastifyStatic, { root: staticDir, prefix: '/' });
scoped.setNotFoundHandler((req, reply) => {
if (req.raw.url?.startsWith(`${prefix}/api/`)) {
return reply.code(404).send({ error: 'not found' });
}
return reply.sendFile('index.html');
});
}
},
{ prefix },
);
app.addHook('onClose', async () => {
db.close();
});
return app;
}