-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
532 lines (460 loc) · 15 KB
/
server.js
File metadata and controls
532 lines (460 loc) · 15 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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
require("dotenv").config();
const express = require("express");
const path = require("path");
const helmet = require("helmet");
const rateLimit = require("express-rate-limit");
const http = require("http");
const app = express();
const PORT = process.env.PORT || 8080;
// RPC Configuration from environment variables
const RPC_CONFIG = {
user: process.env.RPC_USER,
password: process.env.RPC_PASSWORD,
host: process.env.RPC_HOST || "127.0.0.1",
port: parseInt(process.env.RPC_PORT) || 25332,
};
// Validate RPC config on startup
if (!RPC_CONFIG.user || !RPC_CONFIG.password) {
console.warn("⚠️ Warning: RPC credentials not set in environment variables");
console.warn(" RPC proxy endpoint will not function properly");
console.warn(" Create a .env file with RPC_USER and RPC_PASSWORD");
}
// Trust proxy - fixes rate limiter when behind nginx/cloudflare
app.set("trust proxy", 1);
// JSON body parser for RPC requests with size limit
app.use(express.json({ limit: "50kb" }));
// Security Middleware - Helmet with enhanced configuration
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"], // Required for static HTML with inline scripts
scriptSrcAttr: ["'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'", "https://cdnjs.cloudflare.com"], // Inline styles needed for dynamic theming Added cjsjs for Font Awesome CSS
imgSrc: ["'self'", "data:", "https:"],
connectSrc: ["'self'", "https://explorer.sha256coin.eu"],
fontSrc: ["'self'", "https://cdnjs.cloudflare.com"],
objectSrc: ["'none'"],
mediaSrc: ["'self'"],
frameSrc: [
"'self'",
"https://www.youtube.com",
"https://*.youtube.com",
],
baseUri: ["'self'"],
formAction: ["'self'"],
frameAncestors: ["'none'"],
upgradeInsecureRequests: [],
},
},
crossOriginEmbedderPolicy: false,
crossOriginOpenerPolicy: { policy: "same-origin" },
crossOriginResourcePolicy: { policy: "same-origin" },
referrerPolicy: { policy: "strict-origin-when-cross-origin" },
hsts: {
maxAge: 31536000, // 1 year
includeSubDomains: true,
preload: true,
},
noSniff: true,
xssFilter: true,
hidePoweredBy: true,
}),
);
// Additional security headers not covered by Helmet
app.use((req, res, next) => {
// Permissions Policy (formerly Feature-Policy)
res.setHeader(
"Permissions-Policy",
"accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=(), interest-cohort=()",
);
// Prevent caching of sensitive pages
if (req.path.includes("/api/") || req.path.includes("/rpc")) {
res.setHeader(
"Cache-Control",
"no-store, no-cache, must-revalidate, proxy-revalidate",
);
res.setHeader("Pragma", "no-cache");
res.setHeader("Expires", "0");
}
next();
});
// Rate Limiting - General
const generalLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 1200, // Limit each IP to 1200 requests per windowMs
message: "Too many requests from this IP, please try again later.",
standardHeaders: true,
legacyHeaders: false,
});
// Rate Limiting - API endpoints
const apiLimiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: 60, // 60 requests per minute
message: { error: "Too many API requests, please slow down." },
standardHeaders: true,
legacyHeaders: false,
});
// Rate Limiting - Downloads (more restrictive)
const downloadLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 20, // Limit downloads to 20 per 15 minutes
message: "Too many download requests, please try again later.",
});
// Rate Limiting - RPC (restrictive for security)
const rpcLimiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: 300, // Max 300 RPC requests per minute per IP
message: { error: "Too many RPC requests, please slow down." },
standardHeaders: true,
legacyHeaders: false,
});
// Apply general rate limiting to all routes
app.use(generalLimiter);
// Block access to sensitive files and hidden files
app.use((req, res, next) => {
const blockedPatterns = [
".env",
".git",
"node_modules",
"package.json",
"package-lock.json",
"server.js",
"web-wallet-server.js",
"deploy.sh",
".md",
".log",
".bak",
".sql",
".db",
".gemini",
".gitignore",
"ecosystem.config.js",
];
const requestedPath = req.path.toLowerCase();
// Block any hidden file or directory starting with a dot (except .well-known)
if (
requestedPath
.split("/")
.some((part) => part.startsWith(".") && part !== ".well-known")
) {
return res.status(403).json({ error: "Access denied" });
}
const isBlocked = blockedPatterns.some((pattern) =>
requestedPath.includes(pattern.toLowerCase()),
);
if (isBlocked) {
return res.status(403).json({ error: "Access denied" });
}
next();
});
// ============================================
// EXCHANGE API PROXY ENDPOINTS (with rate limiting)
// ============================================
// Input sanitization helper
function sanitizeTickerData(data) {
if (!data || typeof data !== "object") return null;
// Only allow expected fields with proper types
const sanitized = {};
const allowedFields = [
"ticker_id",
"last_price",
"high",
"low",
"base_volume",
"target_volume",
"quote_volume",
"bid",
"ask",
];
for (const field of allowedFields) {
if (data[field] !== undefined) {
// Ensure numeric fields are actually numbers
if (
[
"last_price",
"high",
"low",
"base_volume",
"target_volume",
"quote_volume",
"bid",
"ask",
].includes(field)
) {
const num = parseFloat(data[field]);
sanitized[field] = isNaN(num) ? 0 : num;
} else {
// String fields - escape HTML entities
sanitized[field] = String(data[field]).replace(/[<>&"']/g, "");
}
}
}
return sanitized;
}
// KlingEx API Proxy with timeout and response size limits
app.get("/api/price-klingex", apiLimiter, async (req, res) => {
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 10000);
const response = await fetch("https://api.klingex.io/api/tickers", {
signal: controller.signal,
});
clearTimeout(timeout);
if (!response.ok) {
return res.status(500).json({ error: "Failed to fetch price data" });
}
const tickers = await response.json();
if (!Array.isArray(tickers)) {
return res.status(500).json({ error: "Invalid response format" });
}
const s256Ticker = tickers.find((t) => t.ticker_id === "S256_USDT");
return res.json(
sanitizeTickerData(s256Ticker) || { error: "S256_USDT not found" },
);
} catch (err) {
if (err.name === "AbortError") {
return res.status(504).json({ error: "Request timeout" });
}
return res.status(500).json({ error: "Internal error" });
}
});
// Rabid Rabbit API Proxy with timeout and response size limits
app.get("/api/price-rabidrabbit", apiLimiter, async (req, res) => {
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 10000);
const response = await fetch(
"https://rabid-rabbit.org/api/public/v1/ticker?format=json",
{ signal: controller.signal },
);
clearTimeout(timeout);
if (!response.ok) {
return res.status(500).json({ error: "Failed to fetch price data" });
}
const tickers = await response.json();
if (typeof tickers !== "object") {
return res.status(500).json({ error: "Invalid response format" });
}
return res.json(
sanitizeTickerData(tickers["S256_USDT"]) || {
error: "S256_USDT not found",
},
);
} catch (err) {
if (err.name === "AbortError") {
return res.status(504).json({ error: "Request timeout" });
}
return res.status(500).json({ error: "Internal error" });
}
});
// ============================================
// RPC PROXY ENDPOINT (Secure)
// ============================================
// RPC parameter validation
function validateRpcParams(method, params) {
if (!Array.isArray(params)) return false;
// Method-specific validation
switch (method) {
case "getblock":
// Block hash should be 64 hex chars
if (params[0] && !/^[a-fA-F0-9]{64}$/.test(params[0])) return false;
break;
case "getrawtransaction":
// Txid should be 64 hex chars
if (params[0] && !/^[a-fA-F0-9]{64}$/.test(params[0])) return false;
break;
case "validateaddress":
case "getaddressinfo":
// Address validation (S256 addresses start with S, 8, or s21)
if (params[0] && !/^(S|8|s21)[a-zA-Z0-9]{25,90}$/.test(params[0]))
return false;
break;
case "sendrawtransaction":
// Raw tx should be hex
if (params[0] && !/^[a-fA-F0-9]+$/.test(params[0])) return false;
break;
case "signrawtransactionwithkey":
// 1st param: Raw tx hex string
if (params[0] && !/^[a-fA-F0-9]+$/.test(params[0])) return false;
// 2nd param: Array of WIF private keys
if (params[1] && Array.isArray(params[1])) {
for (const key of params[1]) {
// Validate WIF format (base58, typically 51-52 chars)
// Adjust regex if S256 WIFs have a specific length or starting character
if (
typeof key !== "string" ||
!/^[1-9A-HJ-NP-Za-km-z]{51,52}$/.test(key)
)
return false;
}
} else {
return false; // Expected array of keys as second parameter
}
break;
}
return true;
}
app.post("/rpc", rpcLimiter, async (req, res) => {
//console.log("DEBUG: Proxy received RPC request", JSON.stringify(req.body)); // <-- Add this for debugging incoming requests
// CORS headers for web wallet (restricted to sha256coin.eu)
const allowedOrigins = ["https://sha256coin.eu", "https://www.sha256coin.eu"];
const origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
}
res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
// Check RPC config
if (!RPC_CONFIG.user || !RPC_CONFIG.password) {
return res.status(503).json({ error: "RPC service not configured" });
}
// Validate request has required fields
if (!req.body || typeof req.body.method !== "string") {
return res.status(400).json({ error: "Invalid request format" });
}
// Whitelist allowed RPC methods (security)
const allowedMethods = [
"getblockchaininfo",
"getblockcount",
"getbestblockhash",
"getblock",
"getrawtransaction",
"sendrawtransaction",
"estimatesmartfee",
"scantxoutset",
"createrawtransaction",
"signrawtransactionwithkey",
"decoderawtransaction",
"validateaddress",
"getaddressinfo",
"getnetworkinfo",
"getmempoolinfo",
"getmininginfo"
];
const method = req.body.method.toLowerCase();
if (!allowedMethods.includes(method)) {
return res.status(403).json({ error: "Method not allowed" });
}
// Validate parameters
const params = req.body.params || [];
if (!validateRpcParams(method, params)) {
return res.status(400).json({ error: "Invalid parameters" });
}
// Build RPC request
const rpcRequest = JSON.stringify({
jsonrpc: "1.0",
id: "web-wallet",
method: method,
params: params,
});
//console.log("DEBUG: Forwarding to daemon:", rpcRequest); // <-- ADD THIS to log the exact RPC request being sent to the daemon for debugging purposes
// Basic auth for RPC
const auth = Buffer.from(
`${RPC_CONFIG.user}:${RPC_CONFIG.password}`,
).toString("base64");
// HTTP request options
const options = {
hostname: RPC_CONFIG.host,
port: RPC_CONFIG.port,
path: "/",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(rpcRequest),
Authorization: `Basic ${auth}`,
},
timeout: 30000,
};
// Forward request to S256 RPC
const rpcReq = http.request(options, (rpcRes) => {
let data = "";
rpcRes.on("data", (chunk) => {
data += chunk;
// Limit response size to 10MB
if (data.length > 10000000) {
rpcReq.destroy();
return res.status(500).json({ error: "Response too large" });
}
});
rpcRes.on("end", () => {
try {
//console.log("DEBUG: Daemon raw response:", data); // <-- ADD THIS to log the raw response from the daemon for debugging purposes
const response = JSON.parse(data);
res.json(response);
} catch (e) {
res.status(500).json({ error: "Invalid RPC response" });
}
});
});
rpcReq.on("error", () => {
res.status(500).json({ error: "RPC connection failed" });
});
rpcReq.on("timeout", () => {
rpcReq.destroy();
res.status(504).json({ error: "RPC timeout" });
});
rpcReq.write(rpcRequest);
rpcReq.end();
});
// Handle OPTIONS preflight for CORS
app.options("/rpc", (req, res) => {
const allowedOrigins = ["https://sha256coin.eu", "https://www.sha256coin.eu"];
const origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
}
res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
res.status(204).send();
});
// Serve static files
app.use(
express.static(path.join(__dirname), {
dotfiles: "deny",
index: ["index.html"],
maxAge: "1d", // Cache static assets
etag: true,
}),
);
// Apply stricter rate limiting to downloads
app.use("/downloads", downloadLimiter);
// Serve main page
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "index.html"));
});
// Serve whitepaper page
app.get("/whitepaper.html", (req, res) => {
res.sendFile(path.join(__dirname, "whitepaper.html"));
});
// Serve partners page
app.get("/partners.html", (req, res) => {
res.sendFile(path.join(__dirname, "partners.html"));
});
// Serve media page
app.get("/media.html", (req, res) => {
res.sendFile(path.join(__dirname, "media.html"));
});
// Serve media kit page
app.get("/media_kit.html", (req, res) => {
res.sendFile(path.join(__dirname, "media_kit.html"));
});
// Handle 404 - return proper 404, not index
app.use((req, res) => {
res.status(404).json({ error: "Not found" });
});
// Global error handler
app.use((err, req, res, next) => {
console.error("Server error:", err.message);
res.status(500).json({ error: "Internal server error" });
});
// Start server
app.listen(PORT, () => {
console.log(`S256 Website running on http://localhost:${PORT}`);
console.log("Security enabled: Helmet + Rate Limiting + Input Validation");
console.log("RPC Proxy available at /rpc (30 req/min per IP)");
if (!RPC_CONFIG.user) {
console.log("Note: Set RPC_USER and RPC_PASSWORD in .env for RPC proxy");
}
});