-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
514 lines (443 loc) · 16.3 KB
/
server.js
File metadata and controls
514 lines (443 loc) · 16.3 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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
import express from "express";
import fs from "fs";
import path from "path";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import cookieParser from "cookie-parser";
import bodyParser from "body-parser";
import cors from "cors";
import multer from "multer";
import { fileURLToPath } from "url";
import crypto from "crypto";
import nodemailer from "nodemailer";
import dotenv from "dotenv";
dotenv.config();
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express();
const PORT = 3000;
const DATA_DIR = path.join(__dirname, "accounts");
const PICTURES_DIR = path.join(__dirname, "pictures");
const ACCOUNTS_FILE = path.join(DATA_DIR, "accounts.json");
const CLIENTS_FILE = path.join(DATA_DIR, "clients.json");
const AUTHCODES_FILE = path.join(DATA_DIR, "authcodes.json");
const RESET_FILE = path.join(DATA_DIR, "resetTokens.json");
const PRIVATE_KEY_PATH = path.join(__dirname, "keys", "private.pem");
const PUBLIC_KEY_PATH = path.join(__dirname, "keys", "public.pem");
fs.mkdirSync(DATA_DIR, { recursive: true });
fs.mkdirSync(PICTURES_DIR, { recursive: true });
// Generate RSA keypair if missing
if (!fs.existsSync(PRIVATE_KEY_PATH) || !fs.existsSync(PUBLIC_KEY_PATH)) {
console.log("Generating RSA key pair...");
const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", {
modulusLength: 2048,
publicKeyEncoding: { type: "spki", format: "pem" },
privateKeyEncoding: { type: "pkcs8", format: "pem" },
});
fs.mkdirSync(path.join(__dirname, "keys"), { recursive: true });
fs.writeFileSync(PRIVATE_KEY_PATH, privateKey);
fs.writeFileSync(PUBLIC_KEY_PATH, publicKey);
console.log("RSA key pair generated.");
}
const privateKey = fs.readFileSync(PRIVATE_KEY_PATH);
const publicKey = fs.readFileSync(PUBLIC_KEY_PATH);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(cors({ origin: true, credentials: true }));
app.use(express.static(path.join(__dirname, "public")));
app.use("/pictures", express.static(PICTURES_DIR));
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, PICTURES_DIR),
filename: (req, file, cb) => {
const safeUser =
req.user && req.user.username
? req.user.username.replace(/[^a-zA-Z0-9_-]/g, "")
: "anonymous";
const ext = path.extname(file.originalname).toLowerCase();
cb(null, `${safeUser}-${Date.now()}${ext}`);
},
});
const allowedMimes = ["image/png", "image/jpeg", "image/jpg", "image/webp"];
const upload = multer({
storage,
fileFilter: (req, file, cb) =>
allowedMimes.includes(file.mimetype)
? cb(null, true)
: cb(new Error("Invalid file type")),
limits: { fileSize: 2 * 1024 * 1024 },
});
function load(file, empty = []) {
try {
return JSON.parse(fs.readFileSync(file, "utf8"));
} catch {
fs.writeFileSync(file, JSON.stringify(empty, null, 2));
return [...empty];
}
}
function save(file, data) {
fs.writeFileSync(file, JSON.stringify(data, null, 2));
}
function verifyToken(req, res, next) {
const token = req.cookies.token;
if (!token) return next();
try {
const decoded = jwt.verify(token, publicKey, { algorithms: ["RS256"] });
req.user = decoded;
} catch { }
next();
}
// RATE LIMIT + BRUTE FORCE PROTECTION
const registerRateLimit = new Map();
const REGISTER_INTERVAL = 60 * 60 * 1000;
const LOCK_CONFIG = {
maxAttempts: 5,
lockTimes: [60 * 1000, 5 * 60 * 1000, 10 * 60 * 1000],
};
app.get("/", verifyToken, (req, res) => {
res.redirect(req.user ? "/account.html" : "/login.html");
});
// AUTH SECTION
app.post("/api/register", (req, res) => {
const ip = req.headers["x-forwarded-for"] || req.socket.remoteAddress;
const last = registerRateLimit.get(ip);
if (last && Date.now() - last < REGISTER_INTERVAL) {
return res.status(429).json({
error: "Too many registrations from this IP. Please wait 1 hour.",
});
}
const { username, password, email, redirect } = req.body;
if (!username || !password)
return res.status(400).json({ error: "Missing username or password" });
const trimmedUser = username.trim();
if (trimmedUser.length < 3)
return res
.status(400)
.json({ error: "Username must be at least 3 characters long." });
if (trimmedUser.length > 25)
return res
.status(400)
.json({ error: "Username cannot exceed 25 characters." });
// Password strength validation
const strong = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$/;
if (!strong.test(password))
return res.status(400).json({
error:
"Weak password: include upper, lower, number, and symbol (8+ chars)",
});
const accounts = load(ACCOUNTS_FILE);
if (accounts.find((x) => x.username === trimmedUser))
return res.status(400).json({ error: "Username already exists" });
const hash = bcrypt.hashSync(password, 10);
accounts.push({
username: trimmedUser,
email,
password: hash,
displayName: trimmedUser,
pfp: null,
fails: 0,
lockStage: 0,
lockedUntil: 0,
});
save(ACCOUNTS_FILE, accounts);
registerRateLimit.set(ip, Date.now());
const token = jwt.sign({ username: trimmedUser }, privateKey, {
algorithm: "RS256",
expiresIn: "7d",
issuer: "catci.net",
});
res.cookie("token", token, { httpOnly: true, sameSite: "lax" });
res.json({ success: true, redirect: redirect || "/account.html" });
});
app.post("/api/login", async (req, res) => {
const { username, password, redirect } = req.body;
const accounts = load(ACCOUNTS_FILE);
const user = accounts.find((a) => a.username === username);
if (!user) return res.status(400).json({ error: "Invalid credentials" });
const now = Date.now();
if (user.lockedUntil > now) {
const waitSec = Math.ceil((user.lockedUntil - now) / 1000);
return res
.status(429)
.json({ error: `Account locked. Try again in ${waitSec}s.` });
}
const ok = await bcrypt.compare(password, user.password);
if (!ok) {
user.fails = (user.fails || 0) + 1;
if (user.fails >= LOCK_CONFIG.maxAttempts) {
user.lockStage = Math.min((user.lockStage || 0) + 1, 2);
user.lockedUntil =
Date.now() + LOCK_CONFIG.lockTimes[user.lockStage || 0];
user.fails = 0;
}
save(ACCOUNTS_FILE, accounts);
return res.status(400).json({ error: "Invalid credentials" });
}
user.fails = 0;
user.lockStage = 0;
user.lockedUntil = 0;
save(ACCOUNTS_FILE, accounts);
const token = jwt.sign({ username }, privateKey, {
algorithm: "RS256",
expiresIn: "7d",
issuer: "catci.net",
});
res.cookie("token", token, { httpOnly: true, sameSite: "lax" });
res.json({ success: true, redirect: redirect || "/account.html" });
});
app.post("/api/logout", (req, res) => {
res.clearCookie("token");
res.json({ success: true });
});
// ACCOUNT MANAGEMENT
app.get("/api/account", verifyToken, (req, res) => {
if (!req.user) return res.status(401).json({ error: "Not logged in" });
const accounts = load(ACCOUNTS_FILE);
const acc = accounts.find((a) => a.username === req.user.username);
if (!acc) return res.status(404).json({ error: "User not found" });
res.json({
username: acc.username,
email: acc.email || "",
displayName: acc.displayName || acc.username,
pfp: acc.pfp || "/public/default-pfp.png",
});
});
app.post("/api/account/email", verifyToken, (req, res) => {
if (!req.user) return res.status(401).json({ error: "Not logged in" });
const { email } = req.body;
const accounts = load(ACCOUNTS_FILE);
const u = accounts.find((a) => a.username === req.user.username);
if (!u) return res.status(404).json({ error: "User not found" });
u.email = email;
save(ACCOUNTS_FILE, accounts);
res.json({ success: true, message: "Email updated" });
});
app.post("/api/account/display", verifyToken, (req, res) => {
if (!req.user) return res.status(401).json({ error: "Not logged in" });
const { displayName } = req.body;
if (!displayName || displayName.trim().length < 2)
return res
.status(400)
.json({ error: "Display name must be at least 2 characters long." });
if (displayName.trim().length > 25)
return res
.status(400)
.json({ error: "Display name cannot exceed 25 characters." });
const accounts = load(ACCOUNTS_FILE);
const u = accounts.find((a) => a.username === req.user.username);
if (!u) return res.status(404).json({ error: "User not found" });
u.displayName = displayName.trim();
save(ACCOUNTS_FILE, accounts);
res.json({ success: true, message: "Display name updated" });
});
app.post("/api/account/pfp", verifyToken, upload.single("pfp"), (req, res) => {
if (!req.user) return res.status(401).json({ error: "Not logged in" });
if (!req.file) return res.status(400).json({ error: "No file uploaded" });
const fileUrl = `/pictures/${req.file.filename}`;
const accounts = load(ACCOUNTS_FILE);
const user = accounts.find((u) => u.username === req.user.username);
if (!user) return res.status(404).json({ error: "User not found" });
user.pfp = fileUrl;
save(ACCOUNTS_FILE, accounts);
res.json({ success: true, message: "Profile picture updated", pfp: fileUrl });
});
// OAUTH 2.0 LOGIC
app.get("/oauth/authorize", verifyToken, (req, res) => {
const { client_id, redirect_uri, state, code_challenge } = req.query;
if (!client_id || !redirect_uri)
return res.status(400).send("Missing client_id or redirect_uri");
const clients = load(CLIENTS_FILE);
const client = clients.find((c) => c.client_id === client_id);
if (!client) return res.status(400).send("Unknown client_id");
if (!client.redirect_uris.includes(redirect_uri))
return res.status(400).send("Invalid redirect_uri");
if (!req.user)
return res.redirect(
`/login.html?redirect=${encodeURIComponent(req.originalUrl)}`
);
if (client.first_party) {
const code = crypto.randomBytes(16).toString("hex");
const codes = load(AUTHCODES_FILE);
codes.push({ code, username: req.user.username, client_id, created: Date.now() });
save(AUTHCODES_FILE, codes);
return res.redirect(
`${redirect_uri}?code=${code}${state ? `&state=${encodeURIComponent(state)}` : ""
}`
);
}
res.sendFile(path.join(__dirname, "public", "oauth-consent.html"));
});
app.post("/api/oauth/authorize", verifyToken, (req, res) => {
if (!req.user) return res.status(401).json({ error: "Not logged in" });
const { client_id, redirect_uri, allow, code_challenge, state } = req.body;
const clients = load(CLIENTS_FILE);
const client = clients.find((c) => c.client_id === client_id);
if (!client || !client.redirect_uris.includes(redirect_uri))
return res.status(400).json({ error: "Invalid client or redirect_uri" });
if (!allow)
return res.redirect(
`${redirect_uri}?error=access_denied${state ? `&state=${encodeURIComponent(state)}` : ""
}`
);
const code = crypto.randomBytes(16).toString("hex");
const codes = load(AUTHCODES_FILE);
codes.push({
code,
username: req.user.username,
client_id,
created: Date.now(),
code_challenge,
});
save(AUTHCODES_FILE, codes);
res.redirect(
`${redirect_uri}?code=${code}${state ? `&state=${encodeURIComponent(state)}` : ""
}`
);
});
app.post("/api/oauth/token", (req, res) => {
const { client_id, client_secret, code, code_verifier } = req.body;
const clients = load(CLIENTS_FILE);
const client = clients.find(
(c) => c.client_id === client_id && c.client_secret === client_secret
);
if (!client) return res.status(400).json({ error: "Invalid client" });
const codes = load(AUTHCODES_FILE);
const i = codes.findIndex((c) => c.code === code);
if (i === -1) return res.status(400).json({ error: "Invalid or used code" });
const record = codes[i];
if (Date.now() - record.created > 5 * 60 * 1000)
return res.status(400).json({ error: "Code expired" });
if (record.code_challenge && code_verifier) {
const expected = crypto
.createHash("sha256")
.update(code_verifier)
.digest("base64url");
if (expected !== record.code_challenge)
return res.status(400).json({ error: "PKCE verification failed" });
}
codes.splice(i, 1);
save(AUTHCODES_FILE, codes);
const accounts = load(ACCOUNTS_FILE);
const user = accounts.find((a) => a.username === record.username);
if (!user) return res.status(404).json({ error: "User not found" });
const token = jwt.sign(
{
sub: user.username,
email: user.email || "",
iss: "catci.net",
aud: client_id,
},
privateKey,
{ algorithm: "RS256", expiresIn: "1h" }
);
res.json({ access_token: token, token_type: "Bearer", expires_in: 3600 });
});
app.get("/api/oauth/user", (req, res) => {
const auth = req.headers.authorization;
if (!auth) return res.status(401).json({ error: "Missing Authorization" });
const [, token] = auth.split(" ");
try {
const decoded = jwt.verify(token, publicKey, { algorithms: ["RS256"] });
res.json({
username: decoded.sub,
email: decoded.email || "",
issuer: decoded.iss,
});
} catch {
res.status(401).json({ error: "Invalid token" });
}
});
app.get("/jwks.json", (req, res) => {
const pubPem = fs.readFileSync(PUBLIC_KEY_PATH, "utf8");
const body = pubPem.match(
/-----BEGIN PUBLIC KEY-----(?<b64>[^-]+)-----END PUBLIC KEY-----/s
).groups.b64;
const jwk = {
kty: "RSA",
use: "sig",
alg: "RS256",
kid: "catci-key-1",
n: Buffer.from(body.replace(/\n/g, ""), "base64").toString("base64url"),
e: "AQAB",
};
res.json({ keys: [jwk] });
});
// EMAIL
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT),
secure: false,
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
tls: {
ciphers: "TLSv1.2"
},
});
// PASSWORD RECOVERY
app.post("/api/forgot", async (req, res) => {
const { email } = req.body;
if (!email) return res.status(400).json({ error: "Email required" });
const accounts = load(ACCOUNTS_FILE);
const user = accounts.find(
(a) => a.email && a.email.toLowerCase() === email.toLowerCase()
);
if (!user)
return res.status(400).json({ error: "No account found with that email" });
const token = crypto.randomBytes(32).toString("hex");
const expires = Date.now() + 30 * 60 * 1000;
const resets = load(RESET_FILE);
resets.push({ email, token, expires });
save(RESET_FILE, resets);
const fs = await import("fs/promises");
const link = `http://localhost:${PORT}/reset.html?token=${token}`;
const templatePath = path.join(__dirname, "email", "template.html");
let htmlTemplate = await fs.readFile(templatePath, "utf8");
htmlTemplate = htmlTemplate
.replace(/{{USERNAME}}/g, user.username)
.replace(/{{RESET_LINK}}/g, link);
const mailOpts = {
from: `"Catci Account Recovery" <${process.env.EMAIL_USER}>`,
to: email,
subject: "Reset your Catci password",
html: htmlTemplate,
};
transporter.sendMail(mailOpts, (err) => {
if (err) {
console.error("Email send error:", err);
return res.status(500).json({ error: "Failed to send reset email." });
}
res.json({ success: true, message: "Reset link sent to your email." });
});
});
app.post("/api/reset", (req, res) => {
const { token, password } = req.body;
if (!token || !password)
return res.status(400).json({ error: "Missing token or password" });
const resets = load(RESET_FILE);
const recordIndex = resets.findIndex(
(r) => r.token === token && Date.now() < r.expires
);
if (recordIndex === -1)
return res.status(400).json({ error: "Invalid or expired token" });
const { email } = resets[recordIndex];
const accounts = load(ACCOUNTS_FILE);
const user = accounts.find(
(a) => a.email && a.email.toLowerCase() === email.toLowerCase()
);
if (!user)
return res.status(400).json({ error: "Account no longer exists" });
const strong = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$/;
if (!strong.test(password))
return res.status(400).json({
error: "Weak password: include upper, lower, number, and symbol (8+ chars)",
});
user.password = bcrypt.hashSync(password, 10);
save(ACCOUNTS_FILE, accounts);
resets.splice(recordIndex, 1);
save(RESET_FILE, resets);
res.json({ success: true, message: "Password reset successful." });
});
app.listen(PORT, () => {
console.log(`Catci Login + OAuth + Recovery server running: http://localhost:${PORT}`);
});