2026-04-14 20:55:42 +08:00
|
|
|
import { isGpuAvailable } from "@ashim/ai";
|
|
|
|
|
import { APP_VERSION } from "@ashim/shared";
|
2026-04-14 22:01:04 +08:00
|
|
|
import cors from "@fastify/cors";
|
|
|
|
|
import rateLimit from "@fastify/rate-limit";
|
2026-03-25 09:24:37 +08:00
|
|
|
import Fastify from "fastify";
|
|
|
|
|
import { env } from "./config.js";
|
|
|
|
|
import { db, schema } from "./db/index.js";
|
2026-03-22 02:51:57 +08:00
|
|
|
import { runMigrations } from "./db/migrate.js";
|
2026-03-22 03:09:33 +08:00
|
|
|
import { startCleanupCron } from "./lib/cleanup.js";
|
2026-03-29 17:23:41 +08:00
|
|
|
import { shutdownWorkerPool } from "./lib/worker-pool.js";
|
2026-03-28 19:00:50 +08:00
|
|
|
import { authMiddleware, authRoutes, ensureDefaultAdmin, requireAdmin } from "./plugins/auth.js";
|
2026-03-25 09:24:37 +08:00
|
|
|
import { registerStatic } from "./plugins/static.js";
|
|
|
|
|
import { registerUpload } from "./plugins/upload.js";
|
|
|
|
|
import { apiKeyRoutes } from "./routes/api-keys.js";
|
2026-03-22 04:03:38 +08:00
|
|
|
import { registerBatchRoutes } from "./routes/batch.js";
|
2026-03-25 09:35:28 +08:00
|
|
|
import { brandingRoutes } from "./routes/branding.js";
|
2026-03-27 12:28:35 +08:00
|
|
|
import { docsRoutes } from "./routes/docs.js";
|
2026-03-25 09:24:37 +08:00
|
|
|
import { fileRoutes } from "./routes/files.js";
|
2026-03-22 04:41:51 +08:00
|
|
|
import { registerPipelineRoutes } from "./routes/pipeline.js";
|
2026-03-29 17:23:41 +08:00
|
|
|
import { recoverStaleJobs, registerProgressRoutes } from "./routes/progress.js";
|
2026-03-22 19:28:57 +08:00
|
|
|
import { settingsRoutes } from "./routes/settings.js";
|
2026-03-25 09:24:37 +08:00
|
|
|
import { teamsRoutes } from "./routes/teams.js";
|
|
|
|
|
import { registerToolRoutes } from "./routes/tools/index.js";
|
2026-03-25 01:16:52 +08:00
|
|
|
import { userFileRoutes } from "./routes/user-files.js";
|
2026-03-22 02:51:57 +08:00
|
|
|
|
|
|
|
|
// Run before anything else
|
|
|
|
|
runMigrations();
|
|
|
|
|
console.log("Database initialized");
|
2026-03-22 02:46:34 +08:00
|
|
|
|
2026-03-22 02:55:10 +08:00
|
|
|
// Create default admin user if no users exist
|
|
|
|
|
await ensureDefaultAdmin();
|
|
|
|
|
|
2026-03-29 17:23:41 +08:00
|
|
|
// Mark any jobs left in processing/queued from a previous unclean shutdown
|
|
|
|
|
recoverStaleJobs();
|
|
|
|
|
|
2026-03-22 02:46:34 +08:00
|
|
|
const app = Fastify({
|
2026-04-11 14:47:30 +08:00
|
|
|
logger: { level: env.LOG_LEVEL },
|
2026-03-22 02:46:34 +08:00
|
|
|
bodyLimit: env.MAX_UPLOAD_SIZE_MB * 1024 * 1024,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Plugins
|
2026-03-23 11:46:45 +08:00
|
|
|
await app.register(cors, {
|
|
|
|
|
origin: env.CORS_ORIGIN
|
|
|
|
|
? env.CORS_ORIGIN.split(",").map((s) => s.trim())
|
2026-03-25 09:24:37 +08:00
|
|
|
: process.env.NODE_ENV !== "production",
|
2026-03-23 11:46:45 +08:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Security headers
|
|
|
|
|
app.addHook("onSend", async (_request, reply) => {
|
|
|
|
|
reply.header("X-Content-Type-Options", "nosniff");
|
|
|
|
|
reply.header("X-Frame-Options", "DENY");
|
|
|
|
|
reply.header("X-XSS-Protection", "0");
|
|
|
|
|
reply.header("Referrer-Policy", "strict-origin-when-cross-origin");
|
2026-03-24 21:38:06 +08:00
|
|
|
reply.header("Permissions-Policy", "camera=(), microphone=(), geolocation=()");
|
|
|
|
|
if (process.env.NODE_ENV === "production") {
|
|
|
|
|
reply.header("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
|
2026-03-29 23:57:08 +08:00
|
|
|
const csp = _request.url.startsWith("/api/docs")
|
|
|
|
|
? "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; connect-src 'self'; font-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'"
|
2026-04-12 08:50:19 +08:00
|
|
|
: "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data: https://tile.openstreetmap.org; connect-src 'self'; font-src 'self' data:; object-src 'none'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'";
|
2026-03-29 23:57:08 +08:00
|
|
|
reply.header("Content-Security-Policy", csp);
|
2026-03-24 21:38:06 +08:00
|
|
|
}
|
2026-03-23 11:46:45 +08:00
|
|
|
});
|
|
|
|
|
|
2026-03-22 02:46:34 +08:00
|
|
|
await app.register(rateLimit, {
|
|
|
|
|
max: env.RATE_LIMIT_PER_MIN,
|
|
|
|
|
timeWindow: "1 minute",
|
2026-04-15 18:13:23 +08:00
|
|
|
// Only rate-limit API endpoints — static files and the SPA fallback must never be throttled
|
|
|
|
|
allowList: (request) => !request.url.startsWith("/api/"),
|
2026-03-22 02:46:34 +08:00
|
|
|
});
|
|
|
|
|
|
2026-03-22 03:47:54 +08:00
|
|
|
// Multipart upload support
|
|
|
|
|
await registerUpload(app);
|
|
|
|
|
|
2026-03-22 02:55:10 +08:00
|
|
|
// Auth middleware (must be registered before routes it protects)
|
|
|
|
|
await authMiddleware(app);
|
|
|
|
|
|
|
|
|
|
// Auth routes
|
|
|
|
|
await authRoutes(app);
|
|
|
|
|
|
2026-03-22 03:47:54 +08:00
|
|
|
// File upload/download routes
|
|
|
|
|
await fileRoutes(app);
|
|
|
|
|
|
2026-03-25 01:16:52 +08:00
|
|
|
// User file library routes (persistent file management with versioning)
|
|
|
|
|
await userFileRoutes(app);
|
|
|
|
|
|
2026-03-22 03:48:11 +08:00
|
|
|
// Tool routes (generic factory-based)
|
|
|
|
|
await registerToolRoutes(app);
|
|
|
|
|
|
2026-03-22 04:03:38 +08:00
|
|
|
// Batch processing routes (must be after tool routes so the registry is populated)
|
|
|
|
|
await registerBatchRoutes(app);
|
|
|
|
|
|
2026-03-22 04:41:51 +08:00
|
|
|
// Pipeline routes (must be after tool routes so the registry is populated)
|
|
|
|
|
await registerPipelineRoutes(app);
|
|
|
|
|
|
2026-03-22 04:03:38 +08:00
|
|
|
// Progress SSE routes
|
|
|
|
|
await registerProgressRoutes(app);
|
|
|
|
|
|
2026-03-22 19:28:57 +08:00
|
|
|
// API key management routes
|
|
|
|
|
await apiKeyRoutes(app);
|
|
|
|
|
|
|
|
|
|
// Settings routes
|
|
|
|
|
await settingsRoutes(app);
|
|
|
|
|
|
2026-03-25 09:35:28 +08:00
|
|
|
// Branding routes (logo upload/serve/delete)
|
|
|
|
|
await brandingRoutes(app);
|
|
|
|
|
|
2026-03-25 09:24:37 +08:00
|
|
|
// Teams routes
|
|
|
|
|
await teamsRoutes(app);
|
|
|
|
|
|
2026-03-27 12:28:35 +08:00
|
|
|
// API docs (Scalar)
|
|
|
|
|
await docsRoutes(app);
|
|
|
|
|
|
2026-04-10 13:21:06 +08:00
|
|
|
// Public health check (checks core dependencies)
|
|
|
|
|
app.get("/api/v1/health", async (_request, reply) => {
|
|
|
|
|
let dbOk = false;
|
|
|
|
|
try {
|
|
|
|
|
db.select().from(schema.settings).limit(1).get();
|
|
|
|
|
dbOk = true;
|
|
|
|
|
} catch {
|
|
|
|
|
/* db unreachable */
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const status = dbOk ? "healthy" : "unhealthy";
|
|
|
|
|
const code = dbOk ? 200 : 503;
|
|
|
|
|
return reply.code(code).send({
|
|
|
|
|
status,
|
|
|
|
|
version: APP_VERSION,
|
|
|
|
|
});
|
|
|
|
|
});
|
2026-03-28 19:00:50 +08:00
|
|
|
|
|
|
|
|
// Admin health check (full diagnostics)
|
|
|
|
|
app.get("/api/v1/admin/health", async (request, reply) => {
|
|
|
|
|
const admin = requireAdmin(request, reply);
|
|
|
|
|
if (!admin) return;
|
|
|
|
|
|
2026-03-23 11:46:45 +08:00
|
|
|
let dbOk = false;
|
|
|
|
|
try {
|
|
|
|
|
db.select().from(schema.settings).limit(1).all();
|
|
|
|
|
dbOk = true;
|
2026-03-25 09:24:37 +08:00
|
|
|
} catch {
|
|
|
|
|
/* db unreachable */
|
|
|
|
|
}
|
2026-03-23 11:46:45 +08:00
|
|
|
return {
|
|
|
|
|
status: dbOk ? "healthy" : "degraded",
|
|
|
|
|
version: APP_VERSION,
|
2026-03-25 09:24:37 +08:00
|
|
|
uptime: `${process.uptime().toFixed(0)}s`,
|
2026-03-23 11:46:45 +08:00
|
|
|
storage: { mode: env.STORAGE_MODE, available: "N/A" },
|
|
|
|
|
database: dbOk ? "ok" : "error",
|
|
|
|
|
queue: { active: 0, pending: 0 },
|
2026-04-05 19:12:45 +08:00
|
|
|
ai: { gpu: isGpuAvailable() },
|
2026-03-23 11:46:45 +08:00
|
|
|
};
|
|
|
|
|
});
|
2026-03-22 02:46:34 +08:00
|
|
|
|
2026-03-22 11:04:20 +08:00
|
|
|
// Public config endpoint (for frontend to know if auth is required)
|
|
|
|
|
app.get("/api/v1/config/auth", async () => ({
|
|
|
|
|
authEnabled: env.AUTH_ENABLED,
|
|
|
|
|
}));
|
|
|
|
|
|
2026-03-22 03:09:33 +08:00
|
|
|
// Serve SPA in production
|
|
|
|
|
if (process.env.NODE_ENV === "production") {
|
|
|
|
|
await registerStatic(app);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Start workspace cleanup cron
|
2026-03-29 17:23:41 +08:00
|
|
|
const cleanupCron = startCleanupCron();
|
2026-03-22 03:09:33 +08:00
|
|
|
|
2026-03-22 02:46:34 +08:00
|
|
|
// Start
|
|
|
|
|
try {
|
|
|
|
|
await app.listen({ port: env.PORT, host: "0.0.0.0" });
|
2026-04-14 20:55:42 +08:00
|
|
|
console.log(`ashim API running on port ${env.PORT}`);
|
2026-03-22 02:46:34 +08:00
|
|
|
} catch (err) {
|
|
|
|
|
app.log.error(err);
|
|
|
|
|
process.exit(1);
|
|
|
|
|
}
|
2026-03-29 17:23:41 +08:00
|
|
|
|
|
|
|
|
// Graceful shutdown
|
2026-04-10 13:21:06 +08:00
|
|
|
const SHUTDOWN_TIMEOUT_MS = 8000;
|
2026-03-29 17:23:41 +08:00
|
|
|
let shuttingDown = false;
|
|
|
|
|
async function shutdown(signal: string) {
|
|
|
|
|
if (shuttingDown) return;
|
|
|
|
|
shuttingDown = true;
|
|
|
|
|
console.log(`\n${signal} received, shutting down gracefully...`);
|
|
|
|
|
|
2026-04-10 13:21:06 +08:00
|
|
|
const forceExit = setTimeout(() => {
|
|
|
|
|
console.error("Shutdown timed out, forcing exit");
|
|
|
|
|
process.exit(1);
|
|
|
|
|
}, SHUTDOWN_TIMEOUT_MS);
|
|
|
|
|
forceExit.unref();
|
|
|
|
|
|
2026-03-29 17:23:41 +08:00
|
|
|
cleanupCron.stop();
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
await app.close();
|
|
|
|
|
console.log("HTTP server closed");
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error("Error closing HTTP server:", err);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
await shutdownWorkerPool();
|
|
|
|
|
console.log("Worker pool shut down");
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error("Error shutting down worker pool:", err);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
2026-04-14 20:55:42 +08:00
|
|
|
const { shutdownDispatcher } = await import("@ashim/ai");
|
2026-03-29 17:23:41 +08:00
|
|
|
shutdownDispatcher();
|
|
|
|
|
console.log("Python dispatcher shut down");
|
|
|
|
|
} catch {
|
|
|
|
|
// AI package may not be available
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const { sqlite: sqliteConn } = await import("./db/index.js");
|
|
|
|
|
sqliteConn.close();
|
|
|
|
|
console.log("Database connection closed");
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error("Error closing database:", err);
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-10 13:21:06 +08:00
|
|
|
clearTimeout(forceExit);
|
2026-03-29 17:23:41 +08:00
|
|
|
process.exit(0);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
|
|
|
|
process.on("SIGINT", () => shutdown("SIGINT"));
|