- Add production Dockerfile with bun build --compile, multi-stage Alpine build - Add .dockerignore - Swap bcrypt -> bcryptjs (pure JS, no native addons) - Add programmatic migrations on startup via drizzle migrator - Add /v1/version endpoint with APP_VERSION baked in at build time - Add .gitea/workflows/ci.yml (lint + test with postgres/valkey services) - Add .gitea/workflows/build.yml (version bump, build, push to registry) - Update CLAUDE.md and docs/architecture.md to remove multi-tenancy - Add docs/deployment.md covering DOKS + ArgoCD architecture Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
177 lines
6.7 KiB
TypeScript
177 lines
6.7 KiB
TypeScript
import Fastify from 'fastify'
|
|
import { drizzle } from 'drizzle-orm/postgres-js'
|
|
import { migrate } from 'drizzle-orm/postgres-js/migrator'
|
|
import postgres from 'postgres'
|
|
import rateLimit from '@fastify/rate-limit'
|
|
import { databasePlugin } from './plugins/database.js'
|
|
import { redisPlugin } from './plugins/redis.js'
|
|
import { corsPlugin } from './plugins/cors.js'
|
|
import { errorHandlerPlugin } from './plugins/error-handler.js'
|
|
import { authPlugin } from './plugins/auth.js'
|
|
import { devAuthPlugin } from './plugins/dev-auth.js'
|
|
import { storagePlugin } from './plugins/storage.js'
|
|
import { healthRoutes } from './routes/v1/health.js'
|
|
import { versionRoutes } from './routes/v1/version.js'
|
|
import { authRoutes } from './routes/v1/auth.js'
|
|
import { accountRoutes } from './routes/v1/accounts.js'
|
|
import { inventoryRoutes } from './routes/v1/inventory.js'
|
|
import { productRoutes } from './routes/v1/products.js'
|
|
import { lookupRoutes } from './routes/v1/lookups.js'
|
|
import { fileRoutes } from './routes/v1/files.js'
|
|
import { rbacRoutes } from './routes/v1/rbac.js'
|
|
import { repairRoutes } from './routes/v1/repairs.js'
|
|
import { lessonRoutes } from './routes/v1/lessons.js'
|
|
import { storageRoutes } from './routes/v1/storage.js'
|
|
import { storeRoutes } from './routes/v1/store.js'
|
|
import { vaultRoutes } from './routes/v1/vault.js'
|
|
import { webdavRoutes } from './routes/webdav/index.js'
|
|
import { moduleRoutes } from './routes/v1/modules.js'
|
|
import { RbacService } from './services/rbac.service.js'
|
|
import { ModuleService } from './services/module.service.js'
|
|
|
|
export async function buildApp() {
|
|
const app = Fastify({
|
|
logger: {
|
|
level: process.env.LOG_LEVEL ?? 'info',
|
|
...(process.env.NODE_ENV === 'development'
|
|
? { transport: { target: 'pino-pretty' } }
|
|
: process.env.LOG_FILE
|
|
? {
|
|
transport: {
|
|
targets: [
|
|
{ target: 'pino/file', options: { destination: 1 } }, // stdout
|
|
{ target: 'pino/file', options: { destination: process.env.LOG_FILE, mkdir: true } },
|
|
],
|
|
},
|
|
}
|
|
: {}),
|
|
},
|
|
genReqId: () => crypto.randomUUID(),
|
|
requestTimeout: 30000, // 30 seconds
|
|
})
|
|
|
|
// Plugins
|
|
await app.register(corsPlugin)
|
|
await app.register(errorHandlerPlugin)
|
|
await app.register(databasePlugin)
|
|
await app.register(redisPlugin)
|
|
await app.register(rateLimit, { global: false })
|
|
await app.register(storagePlugin)
|
|
|
|
// Auth — JWT in production/test, dev bypass only in development without JWT_SECRET
|
|
if (process.env.JWT_SECRET) {
|
|
await app.register(authPlugin)
|
|
} else if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
|
|
app.log.warn('JWT_SECRET not set — using dev auth bypass. DO NOT USE IN PRODUCTION.')
|
|
await app.register(devAuthPlugin)
|
|
} else {
|
|
throw new Error('JWT_SECRET is required in production')
|
|
}
|
|
|
|
// Module gate middleware — returns 403 if module is disabled
|
|
function requireModule(slug: string) {
|
|
return async (_request: any, reply: any) => {
|
|
const enabled = await ModuleService.isEnabled(app.db, slug)
|
|
if (!enabled) {
|
|
reply.status(403).send({ error: { message: `Module '${slug}' is not enabled`, statusCode: 403, module: slug } })
|
|
}
|
|
}
|
|
}
|
|
|
|
// Helper: wrap a route plugin so every route in it gets a module check.
|
|
// Uses fastify-plugin (fp) pattern to inherit parent decorators while adding the hook.
|
|
function withModule(slug: string, plugin: any) {
|
|
const wrapped = async (instance: any, opts: any) => {
|
|
instance.addHook('onRequest', requireModule(slug))
|
|
await plugin(instance, opts)
|
|
}
|
|
// Copy the plugin's symbol to maintain encapsulation behavior
|
|
if (plugin[Symbol.for('skip-override')]) {
|
|
wrapped[Symbol.for('skip-override')] = true
|
|
}
|
|
// Copy plugin name for debugging
|
|
Object.defineProperty(wrapped, 'name', { value: `${plugin.name || 'anonymous'}[${slug}]` })
|
|
return wrapped
|
|
}
|
|
|
|
// Core routes — always available
|
|
await app.register(healthRoutes, { prefix: '/v1' })
|
|
await app.register(versionRoutes, { prefix: '/v1' })
|
|
await app.register(authRoutes, { prefix: '/v1' })
|
|
await app.register(accountRoutes, { prefix: '/v1' })
|
|
await app.register(rbacRoutes, { prefix: '/v1' })
|
|
await app.register(storeRoutes, { prefix: '/v1' })
|
|
await app.register(moduleRoutes, { prefix: '/v1' })
|
|
await app.register(lookupRoutes, { prefix: '/v1' })
|
|
|
|
// Module-gated routes
|
|
await app.register(withModule('inventory', inventoryRoutes), { prefix: '/v1' })
|
|
await app.register(withModule('inventory', productRoutes), { prefix: '/v1' })
|
|
await app.register(withModule('files', fileRoutes), { prefix: '/v1' })
|
|
await app.register(withModule('files', storageRoutes), { prefix: '/v1' })
|
|
await app.register(withModule('repairs', repairRoutes), { prefix: '/v1' })
|
|
await app.register(withModule('lessons', lessonRoutes), { prefix: '/v1' })
|
|
await app.register(withModule('vault', vaultRoutes), { prefix: '/v1' })
|
|
// Register WebDAV custom HTTP methods before routes
|
|
app.addHttpMethod('PROPFIND', { hasBody: true })
|
|
app.addHttpMethod('PROPPATCH', { hasBody: true })
|
|
app.addHttpMethod('MKCOL', { hasBody: true })
|
|
app.addHttpMethod('COPY')
|
|
app.addHttpMethod('MOVE')
|
|
app.addHttpMethod('LOCK', { hasBody: true })
|
|
app.addHttpMethod('UNLOCK')
|
|
await app.register(webdavRoutes, { prefix: '/webdav' })
|
|
|
|
// Auto-seed system permissions and warm module cache on startup
|
|
app.addHook('onReady', async () => {
|
|
try {
|
|
await RbacService.seedPermissions(app.db)
|
|
await RbacService.seedDefaultRoles(app.db)
|
|
app.log.info('System permissions and roles seeded')
|
|
} catch (err) {
|
|
app.log.error({ err }, 'Failed to seed permissions/roles')
|
|
}
|
|
try {
|
|
await ModuleService.refreshCache(app.db)
|
|
const enabled = await ModuleService.getEnabledSlugs(app.db)
|
|
app.log.info({ modules: [...enabled] }, 'Module cache loaded')
|
|
} catch (err) {
|
|
app.log.error({ err }, 'Failed to load module cache')
|
|
}
|
|
})
|
|
|
|
return app
|
|
}
|
|
|
|
async function runMigrations() {
|
|
const connectionString = process.env.DATABASE_URL
|
|
if (!connectionString) throw new Error('DATABASE_URL is required')
|
|
|
|
const migrationsFolder = process.env.MIGRATIONS_DIR ?? './src/db/migrations'
|
|
const sql = postgres(connectionString, { max: 1 })
|
|
const db = drizzle(sql)
|
|
|
|
await migrate(db, { migrationsFolder })
|
|
await sql.end()
|
|
}
|
|
|
|
async function start() {
|
|
await runMigrations()
|
|
const app = await buildApp()
|
|
|
|
const port = parseInt(process.env.PORT ?? '8000', 10)
|
|
const host = process.env.HOST ?? '0.0.0.0'
|
|
|
|
try {
|
|
await app.listen({ port, host })
|
|
} catch (err) {
|
|
app.log.error(err)
|
|
process.exit(1)
|
|
}
|
|
}
|
|
|
|
// Only auto-start when not imported by tests
|
|
if (process.env.NODE_ENV !== 'test') {
|
|
start()
|
|
}
|