-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathapp.js
More file actions
351 lines (296 loc) · 11.1 KB
/
Copy pathapp.js
File metadata and controls
351 lines (296 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// backend/app.js
// SPDX-License-Identifier: Apache-2.0
import fs from "fs";
import path from "path";
import https from "https";
import cors from "cors";
import session from "express-session";
import cookieParser from "cookie-parser";
import express from "express";
import { PrismaClient } from "@prisma/client";
import { fileURLToPath } from "url";
import dotenv from "dotenv";
// ----------------------------------------------------------------------
// Environment loading (production + development)
// ----------------------------------------------------------------------
// Production default
const systemEnv = "/etc/kudos/kudos.env";
// Development default
const localEnv = path.resolve("./.env");
let envLoaded = false;
// Try system env first
if (fs.existsSync(systemEnv)) {
dotenv.config({ path: systemEnv });
console.log(`Loaded environment from ${systemEnv}`);
envLoaded = true;
}
// If no system env, try local checkout .env
else if (fs.existsSync(localEnv)) {
dotenv.config({ path: localEnv });
console.log(`Loaded environment from ${localEnv}`);
envLoaded = true;
}
if (!envLoaded) {
console.log("No dotenv file found; relying only on system environment.");
}
// ----------------------------------------------------------------------
// Route imports
// ----------------------------------------------------------------------
import { mountAuth } from "./routes/auth.js";
import { mountStatsRoutes } from "./routes/stats.js";
import { mountUserProfileRoutes } from "./routes/user_profile.js";
import { mountUserRoutes } from "./routes/users.js";
import { mountKudosRoutes } from "./routes/kudos.js";
import { mountBadgesRoutes } from "./routes/badges.js";
import { mountAdminRoutes } from "./routes/admin.js";
import { mountWhoamiRoutes } from "./routes/whoami.js";
import { mountSummaryRoutes } from "./routes/summary.js";
import { mountNowRoutes } from "./routes/now.js";
import { mountNotificationsRoutes } from "./routes/notifications.js";
import { mountFollowRoutes } from "./routes/follow.js";
import { setupActivityPipeline } from "./services/activityPipeline.js";
// ----------------------------------------------------------------------
// App and database init
// ----------------------------------------------------------------------
const app = express();
const prisma = new PrismaClient();
setupActivityPipeline(prisma);
// ----------------------------------------------------------------------
// Origin settings
// ----------------------------------------------------------------------
const FRONTEND_ORIGIN =
process.env.FRONTEND_ORIGIN ||
process.env.VITE_DEV_SERVER ||
"https://localhost:5173";
const BACKEND_ORIGIN =
process.env.BACKEND_ORIGIN ||
"https://localhost:3000";
const ALLOWED_ORIGINS = (process.env.CORS_ALLOWED_ORIGINS || FRONTEND_ORIGIN)
.split(",")
.map((o) => o.trim());
// ----------------------------------------------------------------------
// Async wrapper for top-level await
// ----------------------------------------------------------------------
(async () => {
// --------------------------------------------------------------------
// CORS middleware
// --------------------------------------------------------------------
app.use(
cors({
origin: ALLOWED_ORIGINS,
credentials: true,
})
);
// --------------------------------------------------------------------
// Core middleware
// --------------------------------------------------------------------
app.use(express.json());
app.use(cookieParser());
// --------------------------------------------------------------------
// Session configuration
// --------------------------------------------------------------------
app.set("trust proxy", 1);
const { default: FileStore } = await import("session-file-store");
const FileStoreSession = FileStore(session);
const isLocal =
FRONTEND_ORIGIN.includes("localhost") ||
FRONTEND_ORIGIN.includes("127.0.0.1");
const isHttps =
FRONTEND_ORIGIN.startsWith("https://") ||
BACKEND_ORIGIN.startsWith("https://");
const cookieDomain = !isLocal
? new URL(FRONTEND_ORIGIN).hostname
: undefined;
const sessionPath =
process.env.SESSION_STORE_PATH || "/var/lib/kudos/sessions";
app.use(
session({
store: new FileStoreSession({ path: sessionPath, ttl: 86400 }),
secret: process.env.SESSION_SECRET || "development-secret",
resave: false,
saveUninitialized: false,
name: "connect.sid",
proxy: true,
cookie: {
httpOnly: true,
secure: isHttps,
sameSite: isHttps ? "none" : "lax",
domain: cookieDomain,
maxAge: 7 * 24 * 60 * 60 * 1000,
},
})
);
// --------------------------------------------------------------------
// Mount API routes
// --------------------------------------------------------------------
await mountAuth(app, prisma);
mountStatsRoutes(app, prisma);
mountUserProfileRoutes(app, prisma);
mountUserRoutes(app, prisma);
mountKudosRoutes(app, prisma);
mountBadgesRoutes(app, prisma);
mountAdminRoutes(app, prisma);
mountWhoamiRoutes(app, prisma);
mountSummaryRoutes(app, prisma);
mountNowRoutes(app, prisma);
mountNotificationsRoutes(app, prisma);
mountFollowRoutes(app, prisma);
// --------------------------------------------------------------------
// Serve production frontend
// --------------------------------------------------------------------
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const publicDir = path.resolve(__dirname, "../public");
console.log("Serving frontend from:", publicDir);
app.use(express.static(publicDir));
// Simple API route index
app.get("/api", (req, res) => {
const routes = [];
app._router.stack.forEach((middleware) => {
if (middleware.route) {
const methods = Object.keys(middleware.route.methods)
.map((m) => m.toUpperCase())
.join(", ");
routes.push({ path: middleware.route.path, methods });
} else if (middleware.name === "router" && middleware.handle.stack) {
middleware.handle.stack.forEach((handler) => {
const route = handler.route;
if (route) {
const methods = Object.keys(route.methods)
.map((m) => m.toUpperCase())
.join(", ");
routes.push({
path:
(middleware.regexp.source
.replace("^\\", "")
.replace("\\/?(?=\\/|$)", "")
.replace(/\\\//g, "/")
.replace(/\$$/, "")) + route.path,
methods,
});
}
});
}
});
routes.sort((a, b) => a.path.localeCompare(b.path));
res.json({ backend: BACKEND_ORIGIN, routes });
});
app.get("/api/health", (req, res) => res.json({ status: "ok" }));
// --------------------------------------------------------------------
// Additional diagnostic and utility routes
// --------------------------------------------------------------------
// Display current session diagnostics
app.get("/api/debug/session", (req, res) => {
res.json({
hasSession: !!req.session,
sessionID: req.sessionID,
sessionData: req.session,
});
});
// Slack OAuth redirect confirmation
app.get("/api/slack/oauth_redirect", (req, res) => {
res.send(`
<html>
<body style="font-family: sans-serif; padding: 2em;">
<h2>Slack bot installed</h2>
<p>You can close this tab.</p>
</body>
</html>
`);
});
// --------------------------------------------------------------------
// Pretty HTML API browser (restored)
// --------------------------------------------------------------------
app.get("/api/html", (req, res) => {
const routes = [];
app._router.stack.forEach((middleware) => {
if (middleware.route) {
const methods = Object.keys(middleware.route.methods)
.map((m) => m.toUpperCase())
.join(", ");
routes.push({ path: middleware.route.path, methods });
} else if (middleware.name === "router" && middleware.handle.stack) {
middleware.handle.stack.forEach((handler) => {
const route = handler.route;
if (route) {
const methods = Object.keys(route.methods)
.map((m) => m.toUpperCase())
.join(", ");
routes.push({
path:
(middleware.regexp.source
.replace("^\\", "")
.replace("\\/?(?=\\/|$)", "")
.replace(/\\\//g, "/")
.replace(/\$$/, "")) + route.path,
methods,
});
}
});
}
});
routes.sort((a, b) => a.path.localeCompare(b.path));
const routeList = routes
.map(
(r) => `
<li>
<span class="method method-${r.methods.toLowerCase()}">${r.methods}</span>
<a href="${r.path}">${r.path}</a>
</li>`
)
.join("\n");
res.send(`
<style>
body {
font-family: system-ui, sans-serif;
background: #1a1525;
color: #e6e6e6;
max-width: 720px;
margin: 4em auto;
padding: 0 1.5em;
}
h1 { color: #b083f0; }
a { color: #1e8feb; text-decoration: none; }
a:hover { color: #73ba25; }
.method { display: inline-block; min-width: 56px; text-align: center; padding: 3px 6px; border-radius: 6px; color: white; font-size: 0.8rem; }
.method-get { background: #73ba25; }
.method-post { background: #1e8feb; }
.method-put { background: #e6a700; }
.method-delete { background: #ff5c5c; }
</style>
<h1>openSUSE Kudos API Browser</h1>
<p>Backend: <code>${BACKEND_ORIGIN}</code></p>
<h2>API Endpoints</h2>
<ul>${routeList}</ul>
<footer>Open Source • Express • Prisma</footer>
`);
});
// --------------------------------------------------------------------
// SPA fallback
// --------------------------------------------------------------------
app.get("*", (req, res, next) => {
if (req.path.startsWith("/api")) return next();
res.sendFile(path.join(publicDir, "index.html"));
});
// --------------------------------------------------------------------
// HTTPS / HTTP startup
// --------------------------------------------------------------------
const CERT_KEY = process.env.CERT_KEY_PATH || "/etc/kudos/certs/localhost-key.pem";
const CERT_CRT = process.env.CERT_CRT_PATH || "/etc/kudos/certs/localhost.pem";
const hasCerts = fs.existsSync(CERT_KEY) && fs.existsSync(CERT_CRT);
const port = process.env.PORT || 3000;
if (hasCerts) {
const key = fs.readFileSync(CERT_KEY);
const cert = fs.readFileSync(CERT_CRT);
https.createServer({ key, cert }, app).listen(port, () => {
console.log(`HTTPS backend running at ${BACKEND_ORIGIN}`);
});
} else {
console.warn("No HTTPS certificates found; falling back to HTTP.");
app.listen(port, () => {
console.log(
`HTTP backend running at ${BACKEND_ORIGIN.replace("https", "http")}`
);
});
}
})();