-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
280 lines (249 loc) · 9.76 KB
/
server.js
File metadata and controls
280 lines (249 loc) · 9.76 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
import { createServer } from "node:http";
import { promises as fs } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import crypto from "node:crypto";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PORT = process.env.PORT || 3000;
const DATA_DIR = path.join(__dirname, "data");
const DB_FILE = path.join(DATA_DIR, "db.json");
const PUBLIC_DIR = path.join(__dirname, "public");
const TOKEN_SECRET = process.env.TOKEN_SECRET || "dev-task-manager-secret-change-me";
const clients = new Set();
const defaultDb = { users: [], tasks: [] };
async function ensureDb() {
await fs.mkdir(DATA_DIR, { recursive: true });
try {
await fs.access(DB_FILE);
} catch {
await fs.writeFile(DB_FILE, JSON.stringify(defaultDb, null, 2));
}
}
async function readDb() {
await ensureDb();
const raw = await fs.readFile(DB_FILE, "utf8");
return JSON.parse(raw || JSON.stringify(defaultDb));
}
async function writeDb(db) {
await fs.writeFile(DB_FILE, JSON.stringify(db, null, 2));
}
function json(res, status, payload) {
res.writeHead(status, {
"content-type": "application/json",
"cache-control": "no-store"
});
res.end(JSON.stringify(payload));
}
function readBody(req) {
return new Promise((resolve, reject) => {
let body = "";
req.on("data", (chunk) => {
body += chunk;
if (body.length > 1_000_000) {
reject(new Error("Request body is too large"));
req.destroy();
}
});
req.on("end", () => {
try {
resolve(body ? JSON.parse(body) : {});
} catch {
reject(new Error("Invalid JSON"));
}
});
req.on("error", reject);
});
}
function hashPassword(password, salt = crypto.randomBytes(16).toString("hex")) {
const hash = crypto.pbkdf2Sync(password, salt, 120000, 32, "sha256").toString("hex");
return `${salt}:${hash}`;
}
function verifyPassword(password, stored) {
const [salt] = stored.split(":");
const fresh = hashPassword(password, salt);
return crypto.timingSafeEqual(Buffer.from(fresh), Buffer.from(stored));
}
function signToken(payload) {
const body = Buffer.from(JSON.stringify(payload)).toString("base64url");
const signature = crypto.createHmac("sha256", TOKEN_SECRET).update(body).digest("base64url");
return `${body}.${signature}`;
}
function verifyToken(token) {
if (!token || !token.includes(".")) return null;
const [body, signature] = token.split(".");
const expected = crypto.createHmac("sha256", TOKEN_SECRET).update(body).digest("base64url");
if (signature.length !== expected.length) return null;
if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) return null;
const payload = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
if (payload.exp < Date.now()) return null;
return payload;
}
function getAuth(req, url = null) {
const header = req.headers.authorization || "";
const token = header.startsWith("Bearer ") ? header.slice(7) : url?.searchParams.get("token") || "";
return verifyToken(token);
}
function publicUser(user) {
return { id: user.id, name: user.name, email: user.email };
}
function taskForUser(task, userId) {
return task.ownerId === userId;
}
function broadcast(userId, event, payload) {
const data = JSON.stringify({ event, payload });
for (const client of clients) {
if (client.userId === userId) {
client.res.write(`event: ${event}\n`);
client.res.write(`data: ${data}\n\n`);
}
}
}
async function handleApi(req, res, url) {
const pathname = url.pathname;
try {
if (pathname === "/api/auth/register" && req.method === "POST") {
const { name = "", email = "", password = "" } = await readBody(req);
const normalizedEmail = email.trim().toLowerCase();
if (name.trim().length < 2 || !normalizedEmail.includes("@") || password.length < 6) {
return json(res, 400, { error: "Use a name, valid email, and password of at least 6 characters." });
}
const db = await readDb();
if (db.users.some((user) => user.email === normalizedEmail)) {
return json(res, 409, { error: "An account with that email already exists." });
}
const user = {
id: crypto.randomUUID(),
name: name.trim(),
email: normalizedEmail,
passwordHash: hashPassword(password),
createdAt: new Date().toISOString()
};
db.users.push(user);
await writeDb(db);
const token = signToken({ sub: user.id, exp: Date.now() + 7 * 24 * 60 * 60 * 1000 });
return json(res, 201, { token, user: publicUser(user) });
}
if (pathname === "/api/auth/login" && req.method === "POST") {
const { email = "", password = "" } = await readBody(req);
const db = await readDb();
const user = db.users.find((item) => item.email === email.trim().toLowerCase());
if (!user || !verifyPassword(password, user.passwordHash)) {
return json(res, 401, { error: "Invalid email or password." });
}
const token = signToken({ sub: user.id, exp: Date.now() + 7 * 24 * 60 * 60 * 1000 });
return json(res, 200, { token, user: publicUser(user) });
}
const auth = getAuth(req, url);
if (!auth) return json(res, 401, { error: "Authentication required." });
if (pathname === "/api/me" && req.method === "GET") {
const db = await readDb();
const user = db.users.find((item) => item.id === auth.sub);
if (!user) return json(res, 401, { error: "Authentication required." });
return json(res, 200, { user: publicUser(user) });
}
if (pathname === "/api/tasks/stream" && req.method === "GET") {
res.writeHead(200, {
"content-type": "text/event-stream",
"cache-control": "no-cache",
connection: "keep-alive"
});
res.write("event: ready\ndata: {}\n\n");
const client = { userId: auth.sub, res };
clients.add(client);
req.on("close", () => clients.delete(client));
return;
}
if (pathname === "/api/tasks" && req.method === "GET") {
const db = await readDb();
const tasks = db.tasks.filter((task) => taskForUser(task, auth.sub));
return json(res, 200, { tasks });
}
if (pathname === "/api/tasks" && req.method === "POST") {
const body = await readBody(req);
if (!body.title || body.title.trim().length < 2) {
return json(res, 400, { error: "Task title is required." });
}
const db = await readDb();
const now = new Date().toISOString();
const task = {
id: crypto.randomUUID(),
ownerId: auth.sub,
title: body.title.trim(),
description: (body.description || "").trim(),
status: ["todo", "in-progress", "done"].includes(body.status) ? body.status : "todo",
priority: ["low", "medium", "high"].includes(body.priority) ? body.priority : "medium",
dueDate: body.dueDate || "",
createdAt: now,
updatedAt: now
};
db.tasks.unshift(task);
await writeDb(db);
broadcast(auth.sub, "tasksChanged", { action: "created", task });
return json(res, 201, { task });
}
const taskMatch = pathname.match(/^\/api\/tasks\/([^/]+)$/);
if (taskMatch && ["PUT", "DELETE"].includes(req.method)) {
const db = await readDb();
const index = db.tasks.findIndex((task) => task.id === taskMatch[1] && taskForUser(task, auth.sub));
if (index === -1) return json(res, 404, { error: "Task not found." });
if (req.method === "DELETE") {
const [task] = db.tasks.splice(index, 1);
await writeDb(db);
broadcast(auth.sub, "tasksChanged", { action: "deleted", task });
return json(res, 200, { task });
}
const body = await readBody(req);
const current = db.tasks[index];
const next = {
...current,
title: typeof body.title === "string" && body.title.trim() ? body.title.trim() : current.title,
description: typeof body.description === "string" ? body.description.trim() : current.description,
status: ["todo", "in-progress", "done"].includes(body.status) ? body.status : current.status,
priority: ["low", "medium", "high"].includes(body.priority) ? body.priority : current.priority,
dueDate: typeof body.dueDate === "string" ? body.dueDate : current.dueDate,
updatedAt: new Date().toISOString()
};
db.tasks[index] = next;
await writeDb(db);
broadcast(auth.sub, "tasksChanged", { action: "updated", task: next });
return json(res, 200, { task: next });
}
return json(res, 404, { error: "Route not found." });
} catch (error) {
return json(res, 500, { error: error.message || "Something went wrong." });
}
}
async function serveStatic(req, res, pathname) {
const safePath = pathname === "/" ? "/index.html" : pathname;
const filePath = path.normalize(path.join(PUBLIC_DIR, safePath));
if (!filePath.startsWith(PUBLIC_DIR)) {
res.writeHead(403);
return res.end("Forbidden");
}
try {
const file = await fs.readFile(filePath);
const ext = path.extname(filePath);
const types = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".json": "application/json"
};
res.writeHead(200, { "content-type": types[ext] || "application/octet-stream" });
res.end(file);
} catch {
const fallback = await fs.readFile(path.join(PUBLIC_DIR, "index.html"));
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
res.end(fallback);
}
}
await ensureDb();
createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
if (url.pathname.startsWith("/api/")) {
return handleApi(req, res, url);
}
return serveStatic(req, res, url.pathname);
}).listen(PORT, () => {
console.log(`Task Manager running at http://localhost:${PORT}`);
});