-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
248 lines (223 loc) · 8.57 KB
/
server.js
File metadata and controls
248 lines (223 loc) · 8.57 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
import { createServer } from "node:http";
import { appendFile, mkdir, readFile, writeFile } from "node:fs/promises";
import { createHash, randomBytes, scryptSync, timingSafeEqual } from "node:crypto";
import { dirname, extname, join, normalize, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const port = Number(process.env.PORT || 4401);
const appRoot = dirname(fileURLToPath(import.meta.url));
const root = join(appRoot, "public");
const sharedCss = join(appRoot, "shared.css");
const dataDir = resolve(process.env.AUTH_DATA_DIR || join(appRoot, "data"));
const usersPath = join(dataDir, "users.json");
const auditPath = join(dataDir, "audit.jsonl");
const sessions = new Map();
const rateLimits = new Map();
const fileTypes = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8"
};
await mkdir(dataDir, { recursive: true });
function json(res, status, body, headers = {}) {
const encoded = JSON.stringify(body);
res.writeHead(status, { "content-type": "application/json; charset=utf-8", ...headers });
res.end(encoded);
}
function publicUser(user) {
return {
id: user.id,
email: user.email,
name: user.name,
role: user.role,
createdAt: user.createdAt
};
}
async function readUsers() {
try {
return JSON.parse(await readFile(usersPath, "utf8"));
} catch {
return [];
}
}
async function saveUsers(users) {
await writeFile(usersPath, JSON.stringify(users, null, 2));
}
async function audit(event, details = {}) {
await appendFile(auditPath, JSON.stringify({ event, details, timestamp: new Date().toISOString() }) + "\n");
}
function hashPassword(password, salt = randomBytes(16).toString("hex")) {
const hash = scryptSync(password, salt, 64).toString("hex");
return { salt, hash };
}
function verifyPassword(password, user) {
const expected = Buffer.from(user.passwordHash, "hex");
const actual = Buffer.from(hashPassword(password, user.passwordSalt).hash, "hex");
return expected.length === actual.length && timingSafeEqual(expected, actual);
}
function parseCookies(req) {
return Object.fromEntries(
String(req.headers.cookie || "")
.split(";")
.map((part) => part.trim())
.filter(Boolean)
.map((part) => {
const index = part.indexOf("=");
return [decodeURIComponent(part.slice(0, index)), decodeURIComponent(part.slice(index + 1))];
})
);
}
function sessionCookie(token, maxAge = 60 * 60 * 8) {
return `sid=${encodeURIComponent(token)}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${maxAge}`;
}
function clearSessionCookie() {
return "sid=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0";
}
async function parseBody(req) {
return new Promise((resolveBody, reject) => {
let body = "";
req.on("data", (chunk) => {
body += chunk;
if (body.length > 16384) req.destroy();
});
req.on("end", () => {
try {
resolveBody(body ? JSON.parse(body) : {});
} catch (error) {
reject(error);
}
});
req.on("error", reject);
});
}
function clientKey(req, suffix) {
const ip = req.socket.remoteAddress || "unknown";
return createHash("sha256").update(`${ip}:${suffix}`).digest("hex");
}
function checkRateLimit(key, max = 10, windowMs = 60_000) {
const now = Date.now();
const record = rateLimits.get(key) || { count: 0, resetAt: now + windowMs };
if (now > record.resetAt) {
record.count = 0;
record.resetAt = now + windowMs;
}
record.count += 1;
rateLimits.set(key, record);
return record.count <= max;
}
async function currentUser(req) {
const token = parseCookies(req).sid;
if (!token) return null;
const session = sessions.get(token);
if (!session || session.expiresAt < Date.now()) {
sessions.delete(token);
return null;
}
const users = await readUsers();
return users.find((user) => user.id === session.userId) || null;
}
async function register(req, res) {
const body = await parseBody(req);
const email = String(body.email || "").trim().toLowerCase();
const name = String(body.name || "").trim();
const password = String(body.password || "");
if (!checkRateLimit(clientKey(req, "register"), 8)) return json(res, 429, { error: "Too many attempts. Try again shortly." });
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return json(res, 400, { error: "A valid email is required." });
if (name.length < 2) return json(res, 400, { error: "Name must be at least 2 characters." });
if (password.length < 12) return json(res, 400, { error: "Password must be at least 12 characters." });
const users = await readUsers();
if (users.some((user) => user.email === email)) return json(res, 409, { error: "Email is already registered." });
const { salt, hash } = hashPassword(password);
const user = {
id: randomBytes(16).toString("hex"),
email,
name,
role: users.length === 0 ? "admin" : "analyst",
passwordSalt: salt,
passwordHash: hash,
createdAt: new Date().toISOString()
};
users.push(user);
await saveUsers(users);
const token = createSession(user.id);
await audit("register", { userId: user.id, email: user.email, role: user.role });
json(res, 201, { user: publicUser(user) }, { "set-cookie": sessionCookie(token) });
}
async function login(req, res) {
const body = await parseBody(req);
const email = String(body.email || "").trim().toLowerCase();
const password = String(body.password || "");
if (!checkRateLimit(clientKey(req, `login:${email}`), 8)) return json(res, 429, { error: "Too many attempts. Try again shortly." });
const users = await readUsers();
const user = users.find((entry) => entry.email === email);
if (!user || !verifyPassword(password, user)) {
await audit("login_failed", { email });
return json(res, 401, { error: "Invalid email or password." });
}
const token = createSession(user.id);
await audit("login", { userId: user.id, email: user.email });
json(res, 200, { user: publicUser(user) }, { "set-cookie": sessionCookie(token) });
}
function createSession(userId) {
const token = randomBytes(32).toString("hex");
sessions.set(token, { userId, expiresAt: Date.now() + 1000 * 60 * 60 * 8 });
return token;
}
async function logout(req, res) {
const token = parseCookies(req).sid;
if (token) sessions.delete(token);
await audit("logout", { hadSession: Boolean(token) });
json(res, 200, { ok: true }, { "set-cookie": clearSessionCookie() });
}
async function readAudit() {
try {
return (await readFile(auditPath, "utf8"))
.trim()
.split("\n")
.filter(Boolean)
.slice(-30)
.map((line) => JSON.parse(line));
} catch {
return [];
}
}
function isInsideRoot(path) {
const target = normalize(path);
return target === root || target.startsWith(root + "\\") || target.startsWith(root + "/");
}
const server = createServer(async (req, res) => {
try {
const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
if (req.method === "POST" && url.pathname === "/api/register") return await register(req, res);
if (req.method === "POST" && url.pathname === "/api/login") return await login(req, res);
if (req.method === "POST" && url.pathname === "/api/logout") return await logout(req, res);
if (req.method === "GET" && url.pathname === "/api/me") {
const user = await currentUser(req);
if (!user) return json(res, 401, { error: "Not authenticated." });
await audit("session_check", { userId: user.id });
return json(res, 200, { user: publicUser(user) });
}
if (req.method === "GET" && url.pathname === "/api/audit") {
const user = await currentUser(req);
if (!user) return json(res, 401, { error: "Not authenticated." });
if (user.role !== "admin") return json(res, 403, { error: "Admin role required." });
return json(res, 200, { events: await readAudit() });
}
const route = url.pathname === "/" ? "/index.html" : decodeURIComponent(url.pathname);
const filePath = route === "/shared.css" ? sharedCss : join(root, route);
if (filePath !== sharedCss && !isInsideRoot(filePath)) {
res.writeHead(403);
res.end("Forbidden");
return;
}
const body = await readFile(filePath);
res.writeHead(200, { "content-type": fileTypes[extname(filePath)] || "application/octet-stream" });
res.end(body);
} catch (error) {
if (req.url?.startsWith("/api/")) return json(res, 400, { error: error.message });
res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
res.end("Not found");
}
});
server.listen(port, "127.0.0.1", () => {
console.log(`Secure Auth Template running at http://127.0.0.1:${port}`);
});