Files
botfights/server/src/app.ts
T

118 lines
4.5 KiB
TypeScript
Raw Normal View History

import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { logger } from 'hono/logger'
import { botsRouter } from './routes/bots.js'
import { fightsRouter } from './routes/fights.js'
import { queueRouter } from './routes/queue.js'
import { authRouter } from './routes/auth.js'
import { docsRouter } from './routes/docs.js'
import { betsRouter } from './routes/bets.js'
import { paymentsRouter } from './routes/payments.js'
import { rateLimit } from './middleware/rate-limit.js'
import { existsSync, readFileSync } from 'fs'
import { join, dirname } from 'path'
import { fileURLToPath } from 'url'
import { cleanupOrphanedFights } from './engine/orchestrator.js'
import { recoverOrphanedPayments } from './engine/payments.js'
export const app = new Hono()
app.onError((err, c) => {
console.error('[botfights] ERROR:', err.message, err.stack)
return c.json({ error: err.message }, 500)
})
app.use('*', logger())
// CORS: lock down in production, allow all in dev
const allowedOrigin = process.env.CORS_ORIGIN || '*'
app.use('/api/*', cors({ origin: allowedOrigin }))
// Rate limit all POST endpoints (60/min per IP)
app.use('/api/*', rateLimit(60_000, 60))
app.get('/api/health', (c) => c.json({ status: 'ok', name: 'botfights' }))
app.route('/api/auth', authRouter)
app.route('/api/bots', botsRouter)
app.route('/api/fights', fightsRouter)
app.route('/api/queue', queueRouter)
app.route('/api/docs', docsRouter)
app.route('/api/bets', betsRouter)
app.route('/api/payments', paymentsRouter)
// In production, serve the frontend SPA
const __dirname = dirname(fileURLToPath(import.meta.url))
const publicDir = join(__dirname, '..', 'public')
if (process.env.NODE_ENV === 'production' && existsSync(publicDir)) {
const MIME: Record<string, string> = {
js: 'application/javascript',
css: 'text/css',
html: 'text/html',
json: 'application/json',
png: 'image/png',
jpg: 'image/jpeg',
svg: 'image/svg+xml',
ico: 'image/x-icon',
woff: 'font/woff',
woff2: 'font/woff2',
webp: 'image/webp',
webmanifest: 'application/manifest+json',
}
function serveFile(c: any, reqPath: string, cacheControl: string) {
const resolved = join(publicDir, reqPath)
// Prevent path traversal
if (!resolved.startsWith(publicDir)) return c.notFound()
if (!existsSync(resolved)) return c.notFound()
const ext = resolved.split('.').pop() || ''
c.header('Content-Type', MIME[ext] || 'application/octet-stream')
c.header('Cache-Control', cacheControl)
return c.body(readFileSync(resolved))
}
// Hashed assets — immutable cache
app.get('/assets/*', (c) => serveFile(c, c.req.path, 'public, max-age=31536000, immutable'))
// Root static files (favicon, manifest, robots, etc.)
app.get('/favicon.ico', (c) => serveFile(c, '/favicon.ico', 'public, max-age=86400'))
app.get('/robots.txt', (c) => serveFile(c, '/robots.txt', 'public, max-age=86400'))
app.get('/manifest.webmanifest', (c) => serveFile(c, '/manifest.webmanifest', 'public, max-age=86400'))
// PWA service worker + related root files
app.get('/sw.js', (c) => serveFile(c, '/sw.js', 'no-cache'))
app.get('/workbox-*.js', (c) => serveFile(c, c.req.path, 'public, max-age=31536000, immutable'))
app.get('/icon-*.png', (c) => serveFile(c, c.req.path, 'public, max-age=86400'))
app.get('/icon.svg', (c) => serveFile(c, '/icon.svg', 'public, max-age=86400'))
app.get('/apple-touch-icon.png', (c) => serveFile(c, '/apple-touch-icon.png', 'public, max-age=86400'))
// SPA fallback: only for navigation requests (not JS/CSS/asset files)
app.get('*', (c) => {
if (c.req.path.startsWith('/api/')) return c.notFound()
// Don't serve index.html for asset requests — return 404 so the browser gets a proper error
const ext = c.req.path.split('.').pop()
if (ext && ext !== c.req.path && ['js', 'css', 'map', 'json', 'png', 'jpg', 'svg', 'woff', 'woff2', 'webp', 'ico'].includes(ext)) {
return c.notFound()
}
const indexPath = join(publicDir, 'index.html')
c.header('Content-Type', 'text/html')
c.header('Cache-Control', 'no-cache')
return c.body(readFileSync(indexPath))
})
console.log('[botfights] serving frontend from', publicDir)
}
// Cleanup orphaned fights on startup
cleanupOrphanedFights().then(() => {
console.log('[botfights] orphaned fights cleaned up')
}).catch(err => {
console.error('[botfights] cleanup error:', err)
})
// Recover orphaned payments on startup
recoverOrphanedPayments().catch(err => {
console.error('[botfights] payment recovery error:', err)
})