styles/source/server/index.ts

60 lines
2.0 KiB
TypeScript
Raw Normal View History

2026-07-15 07:00:55 +00:00
import 'dotenv/config';
import express from 'express';
import cookieParser from 'cookie-parser';
import path from 'path';
import { requireAuth } from './middleware/requireAuth';
import { requireAccess, STYLES_RULES } from './middleware/requireAccess';
import { publicFontsRouter, apiFontsRouter } from './routes/fonts';
const app = express();
app.set( 'trust proxy', 1 );
app.use( express.json() );
app.use( cookieParser() );
2026-07-15 15:31:27 +00:00
// CORS for public font resources — only allowed origins receive the header
const CORS_ALLOWED: Array<string | RegExp> = [
/^https?:\/\/([\w-]+\.)?rokojori\.com$/,
];
function allowFontCors( req: express.Request, res: express.Response, next: express.NextFunction ): void
{
const origin = req.headers.origin;
if ( origin && CORS_ALLOWED.some( rule => typeof rule === 'string' ? rule === origin : rule.test( origin ) ) )
{
res.set( 'Access-Control-Allow-Origin', origin );
}
next();
}
app.use( '/get-font', allowFontCors );
app.use( '/fonts', allowFontCors );
2026-07-15 07:00:55 +00:00
// Public: font CSS endpoint
app.use( publicFontsRouter );
// Public: raw font files
app.use( '/fonts', express.static( path.join( __dirname, '..', '..', 'storage', 'fonts' ) ) );
// Auth-gated: font management API
app.use( '/api/fonts', requireAuth, requireAccess( STYLES_RULES ), apiFontsRouter );
// Auth-gated: pages (served dynamically so middleware can run before sending the file)
const pagesDir = path.join( __dirname, '..', '..', 'build', 'app' );
app.get( '/list-fonts', requireAuth, requireAccess( STYLES_RULES ), ( _req, res ) =>
{
res.sendFile( path.join( pagesDir, 'list-fonts.html' ) );
} );
app.get( '/add-fonts', requireAuth, requireAccess( STYLES_RULES ), ( _req, res ) =>
{
res.sendFile( path.join( pagesDir, 'add-fonts.html' ) );
} );
// Public: static pages (index.html, assets)
app.use( express.static( pagesDir ) );
const PORT = process.env.PORT ? Number( process.env.PORT ) : 3002;
app.listen( PORT, () => console.log( `styles running on http://localhost:${PORT}` ) );