| 1 | import Fastify from "fastify"; |
| 2 | import cors from "@fastify/cors"; |
| 3 | import jwt from "@fastify/jwt"; |
| 4 | import { initDatabase } from "./services/database.js"; |
| 5 | import { authRoutes } from "./routes/auth.js"; |
| 6 | import { instanceRoutes } from "./routes/instances.js"; |
| 7 | import { orgRoutes } from "./routes/orgs.js"; |
| 8 | |
| 9 | const app = Fastify({ |
| 10 | logger: { |
| 11 | level: process.env.LOG_LEVEL ?? "info", |
| 12 | transport: |
| 13 | process.env.NODE_ENV !== "production" |
| 14 | ? { target: "pino-pretty" } |
| 15 | : undefined, |
| 16 | }, |
| 17 | }); |
| 18 | |
| 19 | await app.register(cors, { |
| 20 | origin: (process.env.CORS_ORIGIN ?? "https://grove.host") |
| 21 | .split(",") |
| 22 | .map((origin) => origin.trim()) |
| 23 | .filter(Boolean), |
| 24 | }); |
| 25 | |
| 26 | await app.register(jwt, { |
| 27 | secret: process.env.JWT_SECRET ?? "grove-dev-secret", |
| 28 | sign: { expiresIn: "7d" }, |
| 29 | }); |
| 30 | |
| 31 | // Auth decorator |
| 32 | app.decorate("authenticate", async function (request: any, reply: any) { |
| 33 | try { |
| 34 | await request.jwtVerify(); |
| 35 | } catch (err) { |
| 36 | reply.code(401).send({ error: "Unauthorized" }); |
| 37 | } |
| 38 | }); |
| 39 | |
| 40 | // Initialize database |
| 41 | const db = initDatabase(process.env.DATABASE_PATH ?? "./data/hub.db"); |
| 42 | app.decorate("db", db); |
| 43 | |
| 44 | // In-memory challenge store |
| 45 | const challenges = new Map< |
| 46 | string, |
| 47 | { username?: string; displayName?: string; userId?: number; expiresAt: number } |
| 48 | >(); |
| 49 | app.decorate("challenges", challenges); |
| 50 | |
| 51 | // Cleanup expired challenges every 5 minutes |
| 52 | setInterval(() => { |
| 53 | const now = Date.now(); |
| 54 | for (const [key, val] of challenges) { |
| 55 | if (val.expiresAt < now) challenges.delete(key); |
| 56 | } |
| 57 | }, 5 * 60 * 1000); |
| 58 | |
| 59 | // Health check |
| 60 | app.get("/health", async () => ({ status: "ok", service: "grove-hub-api" })); |
| 61 | app.get("/api/health", async () => ({ status: "ok", service: "grove-hub-api" })); |
| 62 | |
| 63 | // Routes |
| 64 | await app.register(authRoutes, { prefix: "/api/auth" }); |
| 65 | await app.register(instanceRoutes, { prefix: "/api/instances" }); |
| 66 | await app.register(orgRoutes, { prefix: "/api/orgs" }); |
| 67 | |
| 68 | // Start |
| 69 | const port = parseInt(process.env.PORT ?? "4000", 10); |
| 70 | const host = process.env.HOST ?? "0.0.0.0"; |
| 71 | |
| 72 | try { |
| 73 | await app.listen({ port, host }); |
| 74 | app.log.info(`Grove Hub API running at http://${host}:${port}`); |
| 75 | } catch (err) { |
| 76 | app.log.error(err); |
| 77 | process.exit(1); |
| 78 | } |
| 79 | |