-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathwebserver.js
More file actions
executable file
·221 lines (174 loc) · 6.42 KB
/
Copy pathwebserver.js
File metadata and controls
executable file
·221 lines (174 loc) · 6.42 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
//
// webserver.js
//
import express from "express";
import rateLimit from "express-rate-limit";
import path from "path";
import { fileURLToPath } from "url";
import dotenv from "dotenv";
import axios from "axios";
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// --- Environment validation -------------------------------------------------
const REQUIRED_WEB_ENV = ["GITHUB_TOKEN", "REPO_DEV", "REPO_DATA_REPORT"];
function validateWebEnv() {
const missing = REQUIRED_WEB_ENV.filter(name => !process.env[name]?.trim());
if (missing.length) {
throw new Error(
`Missing required environment variables for webserver: ${missing.join(", ")}`
);
}
}
validateWebEnv();
// --- App setup --------------------------------------------------------------
const app = express();
const PORT = process.env.PORT || 3000;
// Trust the first proxy so express-rate-limit sees real client IPs behind a
// reverse proxy (nginx, Cloudflare, etc.). Without this every request appears
// to come from the proxy IP and rate limiting throttles everyone collectively.
app.set("trust proxy", 1);
const DATA_REPO = process.env.REPO_DATA_REPORT;
const DEV_REPO = process.env.REPO_DEV;
const GITHUB_HEADERS = {
Authorization: `token ${process.env.GITHUB_TOKEN}`,
Accept: "application/vnd.github+json",
"User-Agent": "tarkovtracker-webserver"
};
// --- Field length caps ------------------------------------------------------
const MAX_TITLE = 200;
const MAX_DISCORD = 64;
const MAX_CATEGORY = 64;
const MAX_REFERENCE = 500;
const MAX_DESCRIPTION = 8000;
function truncate(value, max) {
const v = (value ?? "").toString().trim();
return v.length > max ? v.slice(0, max) : v;
}
// --- Rate limiting ----------------------------------------------------------
// Separate limiter instances so /data and /issue have independent per-IP quotas.
const rateLimitConfig = {
windowMs: 60_000,
max: 5,
standardHeaders: true,
legacyHeaders: false,
message: { error: "Too many submissions. Please wait a minute and try again." }
};
const dataLimiter = rateLimit(rateLimitConfig);
const issueLimiter = rateLimit(rateLimitConfig);
// --- Origin allowlist -------------------------------------------------------
// Trailing slashes are stripped so that "https://example.com/" and
// "https://example.com" are treated identically.
const ALLOWED_ORIGINS = new Set(
(process.env.ALLOWED_ORIGINS || "")
.split(",")
.map(o => o.trim().replace(/\/+$/, ""))
.filter(Boolean)
);
function checkOrigin(req, res, next) {
if (ALLOWED_ORIGINS.size === 0) return next();
const origin = req.headers.origin || req.headers.referer || "";
// Exact match or the allowed origin followed by a "/" boundary.
// This blocks suffix attacks like "https://tarkovtracker.org.evil.com".
const allowed = [...ALLOWED_ORIGINS].some(
o => origin === o || origin.startsWith(`${o}/`)
);
if (!allowed) {
return res.status(403).json({ error: "Forbidden origin." });
}
next();
}
// --- Middleware -------------------------------------------------------------
app.use(express.urlencoded({ extended: true, limit: "32kb" }));
app.use(express.json({ limit: "32kb" }));
app.use(express.static(path.join(__dirname, "web")));
app.get("/health", (req, res) => res.json({ status: "ok" }));
// --- Honeypot + validation helpers -----------------------------------------
const HONEYPOT_FIELD = "company";
function hasHoneypotHit(body) {
return Boolean((body?.[HONEYPOT_FIELD] ?? "").toString().trim());
}
function sanitizeReportFields({ title, discord, category, description, reference }) {
return {
title: truncate(title, MAX_TITLE),
discord: truncate(discord, MAX_DISCORD),
category: truncate(category, MAX_CATEGORY),
description: truncate(description, MAX_DESCRIPTION),
reference: reference ? truncate(reference, MAX_REFERENCE) : ""
};
}
// --- Routes -----------------------------------------------------------------
/**
* Data bug report
*/
app.post("/data", dataLimiter, checkOrigin, async (req, res) => {
try {
if (hasHoneypotHit(req.body)) {
return res.json({ ok: true });
}
const { title, discord, category, description, reference } = sanitizeReportFields(req.body);
if (![title, discord, category, description].every(v => v?.trim())) {
return res
.status(400)
.json({ error: "All required fields must be provided." });
}
const lines = [
`**Discord handle:** ${discord}`,
`**Category:** ${category}`
];
if (reference) {
lines.push(`**Reference:** ${reference}`);
}
lines.push("", "**Details:**", description);
await axios.post(
`https://api.github.com/repos/${DATA_REPO}/issues`,
{
title: `[${category}] ${title}`,
body: lines.join("\n")
},
{ headers: GITHUB_HEADERS, timeout: 10_000 }
);
res.json({ ok: true });
} catch (err) {
logSanitizedError("POST /data", err);
res.status(500).json({ error: "Failed to submit the data report." });
}
});
/**
* Dev-only issue report
*/
app.post("/issue", issueLimiter, checkOrigin, async (req, res) => {
try {
if (hasHoneypotHit(req.body)) {
return res.json({ ok: true });
}
const { title, discord, description } = sanitizeReportFields(req.body);
if (![title, discord, description].every(v => v?.trim())) {
return res.status(400).json({ error: "Fields marked * are required." });
}
const body = `**Discord handle:** ${discord}
**Description:**
${description}`;
await axios.post(
`https://api.github.com/repos/${DEV_REPO}/issues`,
{ title, body },
{ headers: GITHUB_HEADERS, timeout: 10_000 }
);
res.json({ ok: true });
} catch (err) {
logSanitizedError("POST /issue", err);
res.status(500).json({ error: "Error during the bug report." });
}
});
// --- Sanitized error logging ------------------------------------------------
// Never log the full axios error object — it contains err.config.headers
// which includes the raw Authorization header (the GitHub token).
function logSanitizedError(route, err) {
const status = err.response?.status ?? "no-response";
const message = err.message ?? "unknown error";
console.error(`[${route}] GitHub API error: status=${status} message=${message}`);
}
// --- Start ------------------------------------------------------------------
app.listen(PORT, () => {
console.log(`Webserver running on port ${PORT}`);
});