mirror of
https://github.com/mosh-hamedani/helpdesk.git
synced 2026-05-21 11:58:19 +02:00
73 lines
2 KiB
TypeScript
73 lines
2 KiB
TypeScript
import express from "express";
|
|
import cors from "cors";
|
|
import helmet from "helmet";
|
|
import rateLimit from "express-rate-limit";
|
|
import { toNodeHandler } from "better-auth/node";
|
|
import { auth } from "./lib/auth";
|
|
import { requireAuth } from "./middleware/require-auth";
|
|
import usersRouter from "./routes/users";
|
|
import ticketsRouter from "./routes/tickets";
|
|
import agentsRouter from "./routes/agents";
|
|
import webhooksRouter from "./routes/webhooks";
|
|
import repliesRouter from "./routes/replies";
|
|
|
|
|
|
if (!process.env.BETTER_AUTH_SECRET) {
|
|
throw new Error("BETTER_AUTH_SECRET environment variable is required");
|
|
}
|
|
|
|
const app = express();
|
|
const port = process.env.PORT || 3000;
|
|
|
|
app.use(helmet());
|
|
app.use(
|
|
cors({
|
|
origin: process.env.TRUSTED_ORIGINS?.split(",") ?? [],
|
|
credentials: true,
|
|
})
|
|
);
|
|
|
|
const isProduction = process.env.NODE_ENV === "production";
|
|
|
|
const authLimiter = rateLimit({
|
|
windowMs: 15 * 60 * 1000, // 15 minutes
|
|
limit: 20,
|
|
standardHeaders: "draft-8",
|
|
legacyHeaders: false,
|
|
message: { error: "Too many requests, please try again later" },
|
|
skip: () => !isProduction,
|
|
});
|
|
|
|
// Mount Better Auth handler BEFORE express.json()
|
|
// Better Auth parses its own request bodies
|
|
// toNodeHandler returns a promise; must be caught for Express 5
|
|
app.all("/api/auth/{*any}", authLimiter, (req, res, next) => {
|
|
toNodeHandler(auth)(req, res).catch(next);
|
|
});
|
|
|
|
app.use(express.json());
|
|
|
|
app.get("/api/health", (_req, res) => {
|
|
res.json({ status: "ok" });
|
|
});
|
|
|
|
app.get("/api/me", requireAuth, (req, res) => {
|
|
const { id, name, email, role } = req.user;
|
|
res.json({ user: { id, name, email, role } });
|
|
});
|
|
|
|
app.use("/api/users", usersRouter);
|
|
app.use("/api/tickets", ticketsRouter);
|
|
app.use("/api/agents", agentsRouter);
|
|
app.use("/api/tickets/:ticketId/replies", repliesRouter);
|
|
app.use("/api/webhooks", webhooksRouter);
|
|
|
|
|
|
if (!process.env.WEBHOOK_SECRET) {
|
|
console.warn("Warning: WEBHOOK_SECRET is not set. Webhook endpoints will return 500.");
|
|
}
|
|
|
|
app.listen(port, () => {
|
|
console.log(`Server running on http://localhost:${port}`);
|
|
});
|