-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
257 lines (224 loc) · 6.85 KB
/
Copy pathserver.js
File metadata and controls
257 lines (224 loc) · 6.85 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
import fs from "node:fs";
import path from "node:path";
import http from "node:http";
import { fileURLToPath } from "node:url";
import {
handleAdminLogin,
handleAdminLogout,
handleAdminSession,
handleContentGet,
handleResumeGet,
handleContentSave,
} from "./src/server/adminApi.js";
import { readContentStore } from "./src/server/contentStore.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const DIST_DIR = path.join(__dirname, "dist");
const INDEX_FILE = path.join(DIST_DIR, "index.html");
const PORT = Number(process.env.PORT || 5173);
const BOOTSTRAP_TOKEN = "__PORTFOLIO_BOOTSTRAP__";
const CONTENT_TYPES = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".gif": "image/gif",
".svg": "image/svg+xml",
".ico": "image/x-icon",
".webp": "image/webp",
".woff": "font/woff",
".woff2": "font/woff2",
};
function setNoStore(res) {
res.setHeader("Cache-Control", "no-store");
}
function setStaticCache(res) {
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
}
function sendText(res, status, text) {
res.statusCode = status;
res.setHeader("Content-Type", "text/plain; charset=utf-8");
setNoStore(res);
res.end(text);
}
function serializeForHtml(value) {
return JSON.stringify(value)
.replace(/</g, "\\u003c")
.replace(/>/g, "\\u003e")
.replace(/&/g, "\\u0026")
.replace(/\u2028/g, "\\u2028")
.replace(/\u2029/g, "\\u2029");
}
function trimText(value, maxLength = 160) {
if (typeof value !== "string") return "";
const text = value.trim();
if (!text) return "";
return text.length > maxLength ? `${text.slice(0, maxLength - 1)}…` : text;
}
function getRequestIp(req) {
const cfIp = req.headers["cf-connecting-ip"];
if (typeof cfIp === "string" && cfIp.trim()) return cfIp.trim();
const forwarded = req.headers["x-forwarded-for"];
if (typeof forwarded === "string" && forwarded.trim()) {
return forwarded.split(",")[0].trim();
}
return req.socket && typeof req.socket.remoteAddress === "string"
? req.socket.remoteAddress
: "";
}
function shouldLogRequest(pathname) {
if (!pathname || pathname === "/healthz") return false;
if (pathname === "/" || pathname === "/index.html") return true;
if (pathname.startsWith("/api/")) return true;
if (pathname.startsWith("/assets/")) return false;
return path.extname(pathname) === "";
}
function attachRequestLogger(req, res, pathname) {
if (!shouldLogRequest(pathname)) return;
const startedAt = process.hrtime.bigint();
res.on("finish", () => {
const durationMs = Number(process.hrtime.bigint() - startedAt) / 1e6;
const entry = {
time: new Date().toISOString(),
method: req.method || "GET",
path: pathname,
status: res.statusCode,
durationMs: Number(durationMs.toFixed(1)),
ip: trimText(getRequestIp(req), 80),
host: trimText(req.headers.host, 120),
referer: trimText(req.headers.referer, 160),
userAgent: trimText(req.headers["user-agent"], 200),
};
console.log(`[request] ${JSON.stringify(entry)}`);
});
}
async function routeApi(req, res, pathname) {
if (pathname === "/healthz") {
sendText(res, 200, "ok");
return true;
}
if (pathname === "/api/admin/session") {
handleAdminSession(req, res);
return true;
}
if (pathname === "/api/admin/login") {
await handleAdminLogin(req, res);
return true;
}
if (pathname === "/api/admin/logout") {
handleAdminLogout(req, res);
return true;
}
if (pathname === "/api/content") {
if (req.method === "GET") {
await handleContentGet(req, res);
} else {
await handleContentSave(req, res);
}
return true;
}
if (pathname === "/api/resume") {
await handleResumeGet(req, res);
return true;
}
if (pathname.startsWith("/api/")) {
sendText(res, 404, "Not found");
return true;
}
return false;
}
function canUsePath(candidatePath) {
const relative = path.relative(DIST_DIR, candidatePath);
return !relative.startsWith("..") && !path.isAbsolute(relative);
}
async function sendFile(res, filePath, method) {
if (!canUsePath(filePath)) {
sendText(res, 403, "Forbidden");
return;
}
try {
const stat = fs.statSync(filePath);
if (!stat.isFile()) {
sendText(res, 404, "Not found");
return;
}
const extension = path.extname(filePath).toLowerCase();
const contentType = CONTENT_TYPES[extension] || "application/octet-stream";
res.statusCode = 200;
res.setHeader("Content-Type", contentType);
if (filePath.includes(`${path.sep}assets${path.sep}`)) {
setStaticCache(res);
} else {
setNoStore(res);
}
if (method === "HEAD") {
res.end();
return;
}
const stream = fs.createReadStream(filePath);
stream.on("error", () => sendText(res, 500, "File stream error"));
stream.pipe(res);
} catch (error) {
sendText(res, 404, "Not found");
}
}
async function sendIndexHtml(res, method) {
try {
const html = fs.readFileSync(INDEX_FILE, "utf8");
let content = null;
try {
content = await readContentStore();
} catch (error) {
content = null;
}
const body = html.replace(BOOTSTRAP_TOKEN, serializeForHtml(content));
res.statusCode = 200;
res.setHeader("Content-Type", "text/html; charset=utf-8");
setNoStore(res);
if (method === "HEAD") {
res.end();
return;
}
res.end(body);
} catch (error) {
sendText(res, 500, "Could not render app shell");
}
}
async function serveStatic(req, res, pathname) {
if (req.method !== "GET" && req.method !== "HEAD") {
sendText(res, 405, "Method not allowed");
return;
}
const cleaned = pathname === "/" ? "/index.html" : pathname;
const staticFile = path.join(DIST_DIR, cleaned.replace(/^\/+/, ""));
const staticExists = fs.existsSync(staticFile) && fs.statSync(staticFile).isFile();
if (staticExists) {
if (path.resolve(staticFile) === path.resolve(INDEX_FILE)) {
await sendIndexHtml(res, req.method);
return;
}
await sendFile(res, staticFile, req.method);
return;
}
await sendIndexHtml(res, req.method);
}
const server = http.createServer(async (req, res) => {
try {
const host = req.headers.host || "localhost";
const url = new URL(req.url || "/", `http://${host}`);
const pathname = decodeURIComponent(url.pathname);
attachRequestLogger(req, res, pathname);
const handledApi = await routeApi(req, res, pathname);
if (handledApi) return;
await serveStatic(req, res, pathname);
} catch (error) {
sendText(res, 500, "Server error");
}
});
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
void readContentStore().catch(() => {});
});