-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.mjs
More file actions
351 lines (293 loc) · 9.88 KB
/
server.mjs
File metadata and controls
351 lines (293 loc) · 9.88 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
// @ts-check
import http from "node:http";
import fs from "node:fs";
import path from "node:path";
import crypto from "node:crypto";
import { openDb } from "./db.mjs";
import { newId, makePassword, hashPassword, safeEqualHex } from "./auth.mjs";
const PORT = Number(process.env.PORT ?? 3000);
const HOST = process.env.HOST ?? "127.0.0.1";
const DB_PATH =
process.env.TASKFLOW_DB_PATH ?? path.join(process.cwd(), "data", "taskflow.db");
const db = openDb(DB_PATH);
/**
* @param {import("node:http").ServerResponse} res
* @param {number} status
* @param {unknown} obj
*/
function json(res, status, obj) {
const body = JSON.stringify(obj);
res.writeHead(status, {
"content-type": "application/json; charset=utf-8",
"content-length": Buffer.byteLength(body),
});
res.end(body);
}
/**
* @param {import("node:http").ServerResponse} res
* @param {number} status
* @param {string} text
*/
function sendText(res, status, text) {
res.writeHead(status, { "content-type": "text/plain; charset=utf-8" });
res.end(text);
}
/** @param {import("node:http").ServerResponse} res */
function notFound(res) {
sendText(res, 404, "not found");
}
/** @param {import("node:http").ServerResponse} res */
function unauthorized(res) {
json(res, 401, { error: "unauthorized" });
}
/**
* @param {import("node:http").IncomingMessage} req
* @param {number} [limitBytes]
*/
async function readJsonBody(req, limitBytes = 1024 * 1024) {
/** @type {Buffer[]} */
const chunks = [];
let total = 0;
await new Promise((resolve, reject) => {
req.on("data", (chunk) => {
total += chunk.length;
if (total > limitBytes) {
reject(new Error("body too large"));
return;
}
chunks.push(chunk);
});
req.on("end", resolve);
req.on("error", reject);
});
const raw = Buffer.concat(chunks).toString("utf-8").trim();
if (!raw) return null;
return JSON.parse(raw);
}
/**
* @param {string | undefined} cookieHeader
* @returns {Record<string, string>}
*/
function parseCookies(cookieHeader) {
/** @type {Record<string, string>} */
const out = {};
if (!cookieHeader) return out;
const parts = cookieHeader.split(";");
for (const p of parts) {
const [k, ...rest] = p.trim().split("=");
if (!k) continue;
out[k] = rest.join("=");
}
return out;
}
/**
* @param {import("node:http").ServerResponse} res
* @param {string} name
* @param {string} value
* @param {{ httpOnly?: boolean, maxAge?: number, sameSite?: "Lax" | "Strict" | "None", path?: string }} [opts]
*/
function setCookie(res, name, value, opts = {}) {
const parts = [];
parts.push(`${name}=${value}`);
parts.push(`Path=${opts.path ?? "/"}`);
parts.push(`SameSite=${opts.sameSite ?? "Lax"}`);
if (opts.httpOnly ?? true) parts.push("HttpOnly");
if (typeof opts.maxAge === "number") parts.push(`Max-Age=${opts.maxAge}`);
// NOTE: production HTTPSなら Secure を付ける(今回はローカル想定なので付けない)
res.setHeader("Set-Cookie", parts.join("; "));
}
/** @returns {string} */
function nowIso() {
return new Date().toISOString();
}
/**
* @param {number} days
* @returns {string}
*/
function addDaysIso(days) {
const d = new Date();
d.setDate(d.getDate() + days);
return d.toISOString();
}
/**
* @param {import("node:http").IncomingMessage} req
* @returns {{ userId: string, sid: string } | null}
*/
function getAuth(req) {
const cookies = parseCookies(req.headers.cookie);
const sid = cookies.sid;
if (!sid) return null;
const session = db.getSession(sid);
if (!session) return null;
const exp = Date.parse(session.expiresAt);
if (!Number.isFinite(exp) || exp <= Date.now()) {
db.deleteSession(sid);
return null;
}
return { userId: session.userId, sid };
}
/** @param {string} filePath */
function contentType(filePath) {
const ext = path.extname(filePath).toLowerCase();
if (ext === ".html") return "text/html; charset=utf-8";
if (ext === ".css") return "text/css; charset=utf-8";
if (ext === ".js") return "text/javascript; charset=utf-8";
if (ext === ".png") return "image/png";
if (ext === ".svg") return "image/svg+xml";
return "application/octet-stream";
}
const publicDir = path.join(process.cwd(), "public");
const server = http.createServer(async (req, res) => {
try {
const u = new URL(req.url ?? "/", `http://${HOST}:${PORT}`);
const pathname = u.pathname;
// ---- API ----
if (pathname === "/api/healthz" && req.method === "GET") {
return json(res, 200, { ok: true, node: process.version });
}
if (pathname === "/api/signup" && req.method === "POST") {
const body = await readJsonBody(req);
const email = body?.email;
const password = body?.password;
if (typeof email !== "string" || email.trim() === "") {
return json(res, 400, { error: "email is required" });
}
if (typeof password !== "string" || password.length < 8) {
return json(res, 400, { error: "password must be at least 8 chars" });
}
const { salt, passwordHash } = makePassword(password);
const user = {
id: newId(),
email: email.trim().toLowerCase(),
passwordHash,
salt,
createdAt: nowIso(),
};
try {
db.createUser(user);
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
if (msg.includes("UNIQUE") && msg.includes("users.email")) {
return json(res, 409, { error: "email already exists" });
}
return json(res, 500, { error: "failed to create user" });
}
// signup時にログイン状態にする(最小運用)
const sid = crypto.randomUUID();
db.createSession({
id: sid,
userId: user.id,
createdAt: nowIso(),
expiresAt: addDaysIso(7),
});
setCookie(res, "sid", sid, { httpOnly: true, sameSite: "Lax", path: "/" });
return json(res, 201, { user: { id: user.id, email: user.email, createdAt: user.createdAt } });
}
if (pathname === "/api/login" && req.method === "POST") {
const body = await readJsonBody(req);
const email = body?.email;
const password = body?.password;
if (typeof email !== "string" || email.trim() === "") {
return json(res, 400, { error: "email is required" });
}
if (typeof password !== "string" || password === "") {
return json(res, 400, { error: "password is required" });
}
const user = db.getUserByEmail(email.trim().toLowerCase());
if (!user) return json(res, 401, { error: "invalid credentials" });
const computed = hashPassword(password, user.salt);
if (!safeEqualHex(computed, user.passwordHash)) {
return json(res, 401, { error: "invalid credentials" });
}
const sid = crypto.randomUUID();
db.createSession({
id: sid,
userId: user.id,
createdAt: nowIso(),
expiresAt: addDaysIso(7),
});
setCookie(res, "sid", sid, { httpOnly: true, sameSite: "Lax", path: "/" });
return json(res, 200, { ok: true });
}
if (pathname === "/api/logout" && req.method === "POST") {
const cookies = parseCookies(req.headers.cookie);
const sid = cookies.sid;
if (sid) db.deleteSession(sid);
// cookie削除
setCookie(res, "sid", "", { httpOnly: true, sameSite: "Lax", path: "/", maxAge: 0 });
res.writeHead(204);
return res.end();
}
if (pathname === "/api/me" && req.method === "GET") {
const auth = getAuth(req);
if (!auth) return unauthorized(res);
const user = db.getUserPublicById(auth.userId);
if (!user) return unauthorized(res);
return json(res, 200, { user });
}
// tasks: require auth
if (pathname === "/api/tasks" && req.method === "GET") {
const auth = getAuth(req);
if (!auth) return unauthorized(res);
const tasks = db.listTasksByUser(auth.userId);
return json(res, 200, { tasks });
}
if (pathname === "/api/tasks" && req.method === "POST") {
const auth = getAuth(req);
if (!auth) return unauthorized(res);
const body = await readJsonBody(req);
const title = body?.title;
if (typeof title !== "string" || title.trim() === "") {
return json(res, 400, { error: "title is required" });
}
const task = {
id: crypto.randomUUID(),
userId: auth.userId,
title: title.trim(),
done: false,
createdAt: nowIso(),
};
db.insertTask(task);
return json(res, 201, { task });
}
const m = pathname.match(/^\/api\/tasks\/([^/]+)$/);
if (m && req.method === "PATCH") {
const auth = getAuth(req);
if (!auth) return unauthorized(res);
const id = m[1];
const body = await readJsonBody(req);
const done = body?.done;
if (typeof done !== "boolean") {
return json(res, 400, { error: "done(boolean) is required" });
}
const updated = db.setDone(auth.userId, id, done);
if (!updated) return notFound(res);
return json(res, 200, { task: updated });
}
if (m && req.method === "DELETE") {
const auth = getAuth(req);
if (!auth) return unauthorized(res);
const id = m[1];
const ok = db.deleteTask(auth.userId, id);
if (!ok) return notFound(res);
res.writeHead(204);
return res.end();
}
// ---- Static ----
const rel = pathname === "/" ? "/index.html" : pathname;
const filePath = path.join(publicDir, path.normalize(rel));
if (!filePath.startsWith(publicDir)) return notFound(res);
fs.readFile(filePath, (err, buf) => {
if (err) return notFound(res);
res.writeHead(200, { "content-type": contentType(filePath) });
res.end(buf);
});
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
return json(res, 500, { error: msg });
}
});
server.listen(PORT, HOST, () => {
// eslint-disable-next-line no-console
console.log(`http://localhost:${PORT}`);
});