-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
404 lines (348 loc) · 13 KB
/
Copy pathserver.ts
File metadata and controls
404 lines (348 loc) · 13 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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
import "dotenv/config";
import express from "express";
import path from "path";
import cors from "cors";
import helmet from "helmet";
import morgan from "morgan";
import { createServer as createViteServer } from "vite";
import Groq from "groq-sdk";
import { authRouter } from "./src/server/routes/auth";
import { apiRouter } from "./src/server/routes/api";
import { authenticate, AuthRequest } from "./src/server/auth";
import {
generalLimiter,
authLimiter,
authStrictLimiter,
authBackoffMiddleware,
aiLimiter,
writeLimiter,
} from "./src/server/rateLimit";
const INAPPROPRIATE_PATTERNS = [
/\badult\s*(actor|actress|video|film|movie|content|entertainment|star|star)\b/i,
/\bporn(?:o|ographic)?(?:\s*(?:star|actor|actress|video|film|movie|content|site|hub))?\b/i,
/\bnsfw\b/i,
/\bxxx\b/i,
/\bsexual(?:ly)?\s*(?:explicit|suggestive|content|innuendo)\b/i,
/\bescort(?:s)?\b/i,
/\bstripper|striptease|lapdance\b/i,
/\bnude(?:ty|s)?\b/i,
/\bplayboy|playgirl\b/i,
/\berotic(?:a|ally)?\b/i,
/\blust\b/i,
/\bhookup|one\s*night\s*stand\b/i,
/\bonly\s*fans\b/i,
/\bsex\s*chat\b/i,
/\bintimate\s*relationship\b/i,
];
function isAppropriateContent(text: string): boolean {
return !INAPPROPRIATE_PATTERNS.some((pattern) => pattern.test(text));
}
const INAPPROPRIATE_RESPONSE =
"I'm StudySync AI, your educational study assistant. I can only help with academic topics like math, science, programming, history, literature, and more. Please search for educational content related to your studies. Is there a school subject I can help you with?";
async function startServer() {
const app = express();
const PORT = parseInt(process.env.PORT || "3000", 10);
// Trust proxy (required for rate limiting behind reverse proxy)
app.set("trust proxy", 1);
// Security headers
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
styleSrc: [
"'self'",
"'unsafe-inline'",
"https://fonts.googleapis.com",
],
fontSrc: ["'self'", "https://fonts.gstatic.com"],
imgSrc: ["'self'", "data:"],
connectSrc: ["'self'"],
},
},
crossOriginEmbedderPolicy: false,
}),
);
// CORS
const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(",") || [
"http://localhost:3000",
];
app.use(
cors({
origin: allowedOrigins,
credentials: true,
}),
);
// Body parsing
app.use(express.json({ limit: "100kb" }));
// Logging
app.use(morgan("combined"));
// Global rate limiter
app.use("/api", generalLimiter);
app.use("/auth", generalLimiter);
// Auth routes with strict rate limiting + exponential backoff
app.use("/auth", authLimiter);
app.use("/auth", authStrictLimiter);
app.use("/auth", authBackoffMiddleware);
app.use("/auth", authRouter);
// Protected API routes with write limiter for mutations
app.use("/api", apiRouter);
// AI Routes (authenticated + AI-specific rate limit)
app.post(
"/api/ai/chat",
authenticate,
aiLimiter,
async (req: AuthRequest, res) => {
try {
const { message, history } = req.body;
if (
!message ||
typeof message !== "string" ||
message.trim().length === 0
) {
return res.status(400).json({ error: "Message is required" });
}
if (message.length > 5000) {
return res
.status(400)
.json({ error: "Message too long (max 5000 characters)" });
}
if (!isAppropriateContent(message)) {
return res.json({ response: INAPPROPRIATE_RESPONSE });
}
if (!process.env.GROQ_API_KEY) {
return res
.status(503)
.json({ error: "AI service is not configured." });
}
const groq = new Groq({ apiKey: process.env.GROQ_API_KEY });
const systemMessage = `You are StudySync AI, an expert AI productivity assistant and learning tutor for students.
You provide clear, concise, and educational answers. Use markdown formatting to make your responses easy to read.
Break down complex topics into simple terms. If the user asks for a quiz, provide a few multiple choice questions.
STRICT RULES:
- You MUST ONLY answer questions related to educational and academic topics (e.g. math, science, programming, history, literature, languages, business, engineering, etc.).
- You MUST REFUSE any question related to adult content, sexual material, adult actors/actresses, adult videos, pornographic content, NSFW topics, or any sexually suggestive material.
- If the user asks about such content, respond with: "I'm StudySync AI, your educational study assistant. I can only help with academic topics. Please search for educational content related to your studies. Is there a school subject I can help you with?"
- Never provide links to or discuss adult/sexual content under any circumstances.`;
const sanitizedMessage = message.trim().slice(0, 5000);
const safeHistory = Array.isArray(history) ? history.slice(-5) : [];
const messages: Array<{
role: "system" | "user" | "assistant";
content: string;
}> = [{ role: "system", content: systemMessage }];
for (const msg of safeHistory) {
if (msg && typeof msg.content === "string") {
messages.push({
role: msg.role === "user" ? "user" : "assistant",
content: String(msg.content).trim().slice(0, 2000),
});
}
}
messages.push({ role: "user", content: sanitizedMessage });
const response = await groq.chat.completions.create({
model: "llama-3.3-70b-versatile",
messages,
temperature: 0.7,
});
res.json({ response: response.choices[0]?.message?.content || "" });
} catch (error: any) {
console.error("AI Chat Error:", error?.message || error);
res.status(500).json({ error: "Failed to generate AI response." });
}
},
);
app.post(
"/api/ai/suggestion",
authenticate,
aiLimiter,
async (req: AuthRequest, res) => {
try {
if (!process.env.GROQ_API_KEY) {
return res.json({
suggestion:
"Set up your Groq API key to get personalized study suggestions.",
});
}
const groq = new Groq({ apiKey: process.env.GROQ_API_KEY });
const prompt =
"Generate a short, encouraging 1-sentence study suggestion for a computer science student. Example: 'Focus more on Database Normalization and practice past year questions.'";
const response = await groq.chat.completions.create({
model: "llama-3.3-70b-versatile",
messages: [{ role: "user", content: prompt }],
temperature: 0.9,
});
res.json({ suggestion: response.choices[0]?.message?.content || "" });
} catch (error) {
console.error("AI Suggestion Error:", (error as any)?.message || error);
res.json({
suggestion:
"Review your upcoming assignments and start preparing early.",
});
}
},
);
app.post(
"/api/ai/flashcards",
authenticate,
aiLimiter,
async (req: AuthRequest, res) => {
try {
const { topic } = req.body;
if (!topic || typeof topic !== "string" || topic.trim().length === 0) {
return res.status(400).json({ error: "Topic is required" });
}
if (topic.length > 500) {
return res
.status(400)
.json({ error: "Topic too long (max 500 characters)" });
}
if (!isAppropriateContent(topic)) {
return res.status(400).json({
error:
"This topic is not appropriate for educational content. Please choose an academic subject.",
});
}
if (!process.env.GROQ_API_KEY) {
return res
.status(503)
.json({ error: "AI service is not configured." });
}
const groq = new Groq({ apiKey: process.env.GROQ_API_KEY });
const sanitizedTopic = topic.trim().slice(0, 500);
const prompt = `Generate 5 educational flashcards for the topic: "${sanitizedTopic}". Return ONLY a valid JSON array of objects with "front" and "back" keys. Do not include markdown formatting or the word json.`;
const response = await groq.chat.completions.create({
model: "llama-3.3-70b-versatile",
messages: [{ role: "user", content: prompt }],
});
const text = response.choices[0]?.message?.content || "[]";
let flashcards = [];
try {
flashcards = JSON.parse(text);
} catch (e) {
const cleaned = text
.replace(/```json/g, "")
.replace(/```/g, "")
.trim();
try {
flashcards = JSON.parse(cleaned);
} catch (e2) {
return res
.status(500)
.json({ error: "Failed to parse flashcard data from AI." });
}
}
res.json(flashcards);
} catch (error) {
console.error("Flashcard AI Error:", (error as any)?.message || error);
res.status(500).json({ error: "Failed to generate flashcards." });
}
},
);
app.post(
"/api/ai/quiz",
authenticate,
aiLimiter,
async (req: AuthRequest, res) => {
try {
const { topic, difficulty, questions } = req.body;
if (!topic || typeof topic !== "string" || topic.trim().length === 0) {
return res.status(400).json({ error: "Topic is required" });
}
if (topic.length > 500) {
return res
.status(400)
.json({ error: "Topic too long (max 500 characters)" });
}
if (!isAppropriateContent(topic)) {
return res.status(400).json({
error:
"This topic is not appropriate for educational content. Please choose an academic subject.",
});
}
const validDifficulties = ["Beginner", "Intermediate", "Advanced"];
const safeDifficulty = validDifficulties.includes(difficulty)
? difficulty
: "Intermediate";
const safeQuestions =
typeof questions === "number" && questions >= 1 && questions <= 20
? Math.floor(questions)
: 10;
if (!process.env.GROQ_API_KEY) {
return res
.status(503)
.json({ error: "AI service is not configured." });
}
const groq = new Groq({ apiKey: process.env.GROQ_API_KEY });
const sanitizedTopic = topic.trim().slice(0, 500);
const prompt = `Generate a ${safeDifficulty} level multiple choice quiz about "${sanitizedTopic}" with ${safeQuestions} questions.
Return ONLY a valid JSON array of objects. Each object should have:
- "question" (string)
- "options" (array of exactly 4 string options)
- "correctAnswer" (integer, 0-3 index of the correct option)
Do not include markdown formatting or the word json.`;
const response = await groq.chat.completions.create({
model: "llama-3.3-70b-versatile",
messages: [{ role: "user", content: prompt }],
});
const text = response.choices[0]?.message?.content || "[]";
let quiz = [];
try {
quiz = JSON.parse(text);
} catch (e) {
const cleaned = text
.replace(/```json/g, "")
.replace(/```/g, "")
.trim();
try {
quiz = JSON.parse(cleaned);
} catch (e2) {
return res
.status(500)
.json({ error: "Failed to parse quiz data from AI." });
}
}
res.json(quiz);
} catch (error) {
console.error("Quiz AI Error:", (error as any)?.message || error);
res.status(500).json({ error: "Failed to generate quiz." });
}
},
);
// Vite middleware for development
if (process.env.NODE_ENV !== "production") {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "spa",
});
app.use(vite.middlewares);
} else {
const distPath = path.join(process.cwd(), "dist");
app.use(express.static(distPath));
app.get("*", (req, res) => {
res.sendFile(path.join(distPath, "index.html"));
});
}
// Global error handler — never leak stack traces or internal details
app.use(
(
err: Error,
_req: express.Request,
res: express.Response,
_next: express.NextFunction,
) => {
console.error("Unhandled error:", err?.message || err);
if (process.env.NODE_ENV !== "production") {
console.error("Stack:", err?.stack);
}
res.status(500).json({ error: "Internal server error" });
},
);
app.listen(PORT, "0.0.0.0", () => {
console.log(`Server running on http://localhost:${PORT}`);
});
}
startServer().catch((err) => {
console.error("Failed to start server:", (err as any)?.message || err);
process.exit(1);
});