-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
146 lines (124 loc) · 4.46 KB
/
Copy pathserver.js
File metadata and controls
146 lines (124 loc) · 4.46 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
// Zero-dependency Node.js server for k8s / self-hosted deployment.
// Serves static files from the repo root and handles POST /submit.
//
// Environment variables:
// GITHUB_TOKEN — fine-grained PAT, issues:write on this repo only
// GITHUB_REPO — e.g. "owner/repo"
// PORT — default 8080
import http from "http";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
const __dirname = dirname(import.meta.url);
const PORT = process.env.PORT || 8080;
const STATIC_DIR = __dirname;
const MIME = {
".html": "text/html; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".css": "text/css; charset=utf-8",
".ico": "image/x-icon",
".svg": "image/svg+xml",
".png": "image/png",
};
function dirname(u) {
return path.dirname(fileURLToPath(u));
}
const server = http.createServer(async (req, res) => {
// Health check
if (req.url === "/health") {
return send(res, 200, "application/json", JSON.stringify({ ok: true }));
}
// Form submission
if (req.method === "POST" && req.url === "/submit") {
return handleSubmit(req, res);
}
// Static file serving
let urlPath = req.url.split("?")[0];
if (urlPath === "/" || urlPath === "") urlPath = "/index.html";
// Security: prevent path traversal
const filePath = path.normalize(path.join(STATIC_DIR, urlPath));
if (!filePath.startsWith(STATIC_DIR)) {
return send(res, 403, "text/plain", "Forbidden");
}
fs.readFile(filePath, (err, data) => {
if (err) {
if (err.code === "ENOENT") return send(res, 404, "text/plain", "Not found");
return send(res, 500, "text/plain", "Server error");
}
const ext = path.extname(filePath);
const mime = MIME[ext] || "application/octet-stream";
send(res, 200, mime, data);
});
});
async function handleSubmit(req, res) {
const token = process.env.GITHUB_TOKEN;
const repo = process.env.GITHUB_REPO;
if (!token || !repo) {
console.error("GITHUB_TOKEN or GITHUB_REPO not set");
return send(res, 500, "application/json", JSON.stringify({ error: "Server misconfigured" }));
}
let body;
try {
body = await readBody(req);
body = JSON.parse(body);
} catch {
return send(res, 400, "application/json", JSON.stringify({ error: "Invalid JSON" }));
}
// Honeypot
if (body.bot_trap) return send(res, 200, "application/json", JSON.stringify({ ok: true }));
if (!body.feedback && !body.question) {
return send(res, 422, "application/json", JSON.stringify({ error: "At least one field required" }));
}
let config = {};
try { config = JSON.parse(fs.readFileSync(path.join(STATIC_DIR, "config.json"), "utf8")); }
catch { /* use defaults */ }
const labels = config.labels || ["feedback"];
const issue = buildIssue(body, labels);
let ghRes;
try {
ghRes = await fetch(`https://api.github.com/repos/${repo}/issues`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
Accept: "application/vnd.github+json",
},
body: JSON.stringify(issue),
});
} catch (err) {
console.error("GitHub fetch failed:", err);
return send(res, 502, "application/json", JSON.stringify({ error: "Could not reach GitHub" }));
}
if (!ghRes.ok) {
console.error("GitHub API error:", await ghRes.text());
return send(res, 502, "application/json", JSON.stringify({ error: "Failed to create issue" }));
}
const created = await ghRes.json();
send(res, 200, "application/json", JSON.stringify({ ok: true, issue_number: created.number }));
}
function buildIssue(body, labels) {
const lines = [];
if (body.feedback) lines.push(`## Feedback\n\n${body.feedback}`);
if (body.question) lines.push(`## Data question\n\n${body.question}`);
if (body.email) lines.push(`**Contact:** ${body.email}`);
lines.push(`**Submitted:** ${body.submitted_at || new Date().toISOString()}`);
return {
title: `Feedback${body.email ? " from " + body.email : ""}`,
body: lines.join("\n\n"),
labels,
};
}
function readBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
req.on("data", (c) => chunks.push(c));
req.on("end", () => resolve(Buffer.concat(chunks).toString()));
req.on("error", reject);
});
}
function send(res, status, contentType, body) {
res.writeHead(status, { "Content-Type": contentType });
res.end(body);
}
server.listen(PORT, () => console.log(`Listening on :${PORT}`));