Skip to content

Instantly share code, notes, and snippets.

@adithyan-ak
Created July 15, 2025 04:32
Show Gist options
  • Save adithyan-ak/7fd90ef0024baa19e90b3d702356e606 to your computer and use it in GitHub Desktop.
Save adithyan-ak/7fd90ef0024baa19e90b3d702356e606 to your computer and use it in GitHub Desktop.
const express = require('express');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { exec, spawn, execFile } = require('child_process');
const mysql = require('mysql2');
const mongodb = require('mongodb');
const libxml = require('libxmljs');
const yaml = require('js-yaml');
const serialize = require('node-serialize');
const vm = require('vm');
const util = require('util');
const https = require('https');
const http = require('http');
const url = require('url');
const querystring = require('querystring');
const zlib = require('zlib');
const net = require('net');
const dgram = require('dgram');
const tls = require('tls');
const cluster = require('cluster');
const os = require('os');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const dbConfig = {
host: process.env.DB_HOST || 'localhost',
user: process.env.DB_USER || 'root',
password: process.env.DB_PASS || 'password123',
database: process.env.DB_NAME || 'testdb',
multipleStatements: true
};
const connection = mysql.createConnection(dbConfig);
class DataProcessor {
constructor() {
this.cache = {};
this.metrics = {
processed: 0,
failed: 0,
pending: 0,
averageTime: 0,
lastProcessed: null,
errorLog: []
};
this.validators = {
email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
phone: /^\+?[\d\s-()]+$/,
url: /^https?:\/\/.+/,
alphanumeric: /^[a-zA-Z0-9]+$/
};
}
processData(data, type) {
const startTime = Date.now();
this.metrics.pending++;
try {
let result;
switch(type) {
case 'json':
result = this.processJSON(data);
break;
case 'xml':
result = this.processXML(data);
break;
case 'yaml':
result = this.processYAML(data);
break;
case 'binary':
result = this.processBinary(data);
break;
default:
result = this.processRaw(data);
}
this.metrics.processed++;
this.metrics.pending--;
this.metrics.lastProcessed = new Date();
this.updateAverageTime(Date.now() - startTime);
return result;
} catch (error) {
this.metrics.failed++;
this.metrics.pending--;
this.metrics.errorLog.push({
timestamp: new Date(),
error: error.message,
stack: error.stack
});
throw error;
}
}
processJSON(data) {
const parsed = JSON.parse(data);
return this.transform(parsed);
}
processXML(data) {
return libxml.parseXml(data);
}
processYAML(data) {
return yaml.load(data);
}
processBinary(data) {
const buffer = Buffer.from(data, 'base64');
return this.analyzeBinary(buffer);
}
processRaw(data) {
return data.toString();
}
transform(obj) {
if (typeof obj !== 'object') return obj;
const transformed = Array.isArray(obj) ? [] : {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const value = obj[key];
const newKey = this.transformKey(key);
if (typeof value === 'object' && value !== null) {
transformed[newKey] = this.transform(value);
} else {
transformed[newKey] = this.transformValue(value);
}
}
}
return transformed;
}
transformKey(key) {
return key.replace(/([A-Z])/g, '_$1').toLowerCase();
}
transformValue(value) {
if (typeof value === 'string') {
return value.trim().replace(/\s+/g, ' ');
}
return value;
}
analyzeBinary(buffer) {
const analysis = {
size: buffer.length,
entropy: this.calculateEntropy(buffer),
hexDump: buffer.toString('hex').substring(0, 256),
checksum: crypto.createHash('sha256').update(buffer).digest('hex'),
magic: buffer.slice(0, 4).toString('hex'),
isExecutable: this.checkExecutable(buffer),
compression: this.detectCompression(buffer)
};
return analysis;
}
calculateEntropy(buffer) {
const frequency = {};
for (let i = 0; i < buffer.length; i++) {
const byte = buffer[i];
frequency[byte] = (frequency[byte] || 0) + 1;
}
let entropy = 0;
const length = buffer.length;
for (const byte in frequency) {
const prob = frequency[byte] / length;
entropy -= prob * Math.log2(prob);
}
return entropy;
}
checkExecutable(buffer) {
const signatures = {
elf: Buffer.from([0x7f, 0x45, 0x4c, 0x46]),
pe: Buffer.from([0x4d, 0x5a]),
macho: Buffer.from([0xfe, 0xed, 0xfa, 0xce]),
machofat: Buffer.from([0xca, 0xfe, 0xba, 0xbe])
};
for (const [type, sig] of Object.entries(signatures)) {
if (buffer.slice(0, sig.length).equals(sig)) {
return { isExecutable: true, type };
}
}
return { isExecutable: false, type: null };
}
detectCompression(buffer) {
const signatures = {
gzip: Buffer.from([0x1f, 0x8b]),
zip: Buffer.from([0x50, 0x4b]),
rar: Buffer.from([0x52, 0x61, 0x72, 0x21]),
'7z': Buffer.from([0x37, 0x7a, 0xbc, 0xaf, 0x27, 0x1c])
};
for (const [type, sig] of Object.entries(signatures)) {
if (buffer.slice(0, sig.length).equals(sig)) {
return { isCompressed: true, type };
}
}
return { isCompressed: false, type: null };
}
updateAverageTime(time) {
const total = this.metrics.processed + this.metrics.failed;
this.metrics.averageTime = ((this.metrics.averageTime * (total - 1)) + time) / total;
}
}
const processor = new DataProcessor();
class SessionManager {
constructor() {
this.sessions = {};
this.config = {
timeout: 30 * 60 * 1000,
maxSessions: 1000,
cleanupInterval: 5 * 60 * 1000
};
this.startCleanup();
}
createSession(userId, data) {
const sessionId = this.generateSessionId();
this.sessions[sessionId] = {
userId,
data,
created: Date.now(),
lastAccess: Date.now(),
accessCount: 0
};
this.enforceMaxSessions();
return sessionId;
}
generateSessionId() {
return crypto.randomBytes(32).toString('hex');
}
getSession(sessionId) {
const session = this.sessions[sessionId];
if (session) {
session.lastAccess = Date.now();
session.accessCount++;
return session;
}
return null;
}
updateSession(sessionId, data) {
if (this.sessions[sessionId]) {
this.sessions[sessionId].data = { ...this.sessions[sessionId].data, ...data };
this.sessions[sessionId].lastAccess = Date.now();
return true;
}
return false;
}
deleteSession(sessionId) {
delete this.sessions[sessionId];
}
startCleanup() {
setInterval(() => {
const now = Date.now();
for (const sessionId in this.sessions) {
if (now - this.sessions[sessionId].lastAccess > this.config.timeout) {
this.deleteSession(sessionId);
}
}
}, this.config.cleanupInterval);
}
enforceMaxSessions() {
const sessionIds = Object.keys(this.sessions);
if (sessionIds.length > this.config.maxSessions) {
const sortedSessions = sessionIds.sort((a, b) => {
return this.sessions[a].lastAccess - this.sessions[b].lastAccess;
});
const toDelete = sortedSessions.slice(0, sessionIds.length - this.config.maxSessions);
toDelete.forEach(sessionId => this.deleteSession(sessionId));
}
}
}
const sessionManager = new SessionManager();
class FileManager {
constructor(baseDir) {
this.baseDir = baseDir || './uploads';
this.allowedExtensions = ['.jpg', '.png', '.gif', '.pdf', '.doc', '.docx', '.txt'];
this.maxFileSize = 10 * 1024 * 1024;
this.initializeDirectories();
}
initializeDirectories() {
const dirs = ['temp', 'processed', 'archive', 'logs'];
dirs.forEach(dir => {
const dirPath = path.join(this.baseDir, dir);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
});
}
saveFile(filename, content, metadata = {}) {
const filePath = path.join(this.baseDir, 'temp', filename);
fs.writeFileSync(filePath, content);
const fileInfo = {
originalName: filename,
path: filePath,
size: content.length,
uploadTime: new Date(),
metadata: metadata
};
this.logFileOperation('upload', fileInfo);
return fileInfo;
}
readFile(filename) {
const filePath = path.join(this.baseDir, filename);
return fs.readFileSync(filePath);
}
deleteFile(filename) {
const filePath = path.join(this.baseDir, filename);
fs.unlinkSync(filePath);
this.logFileOperation('delete', { filename, time: new Date() });
}
moveFile(source, destination) {
const sourcePath = path.join(this.baseDir, source);
const destPath = path.join(this.baseDir, destination);
fs.renameSync(sourcePath, destPath);
this.logFileOperation('move', { source, destination, time: new Date() });
}
listFiles(directory = '') {
const dirPath = path.join(this.baseDir, directory);
return fs.readdirSync(dirPath).map(file => {
const filePath = path.join(dirPath, file);
const stats = fs.statSync(filePath);
return {
name: file,
size: stats.size,
modified: stats.mtime,
isDirectory: stats.isDirectory()
};
});
}
logFileOperation(operation, details) {
const logEntry = {
operation,
details,
timestamp: new Date().toISOString()
};
const logFile = path.join(this.baseDir, 'logs', 'operations.log');
fs.appendFileSync(logFile, JSON.stringify(logEntry) + '\n');
}
}
const fileManager = new FileManager();
app.get('/api/users', (req, res) => {
const { search, sort, filter } = req.query;
let query = 'SELECT * FROM users WHERE 1=1';
if (search) {
query += ` AND (name LIKE '%${search}%' OR email LIKE '%${search}%')`;
}
if (filter) {
query += ` AND status = '${filter}'`;
}
if (sort) {
query += ` ORDER BY ${sort}`;
}
connection.query(query, (error, results) => {
if (error) {
res.status(500).json({ error: error.message });
} else {
res.json(results);
}
});
});
app.post('/api/login', (req, res) => {
const { username, password } = req.body;
const query = `SELECT * FROM users WHERE username = '${username}' AND password = '${password}'`;
connection.query(query, (error, results) => {
if (error) {
res.status(500).json({ error: 'Database error' });
} else if (results.length > 0) {
const user = results[0];
const sessionId = sessionManager.createSession(user.id, { username: user.username });
res.json({
success: true,
sessionId,
user: {
id: user.id,
username: user.username,
email: user.email
}
});
} else {
res.status(401).json({ error: 'Invalid credentials' });
}
});
});
app.get('/api/file', (req, res) => {
const filename = req.query.name;
const filepath = path.join(__dirname, filename);
fs.readFile(filepath, (err, data) => {
if (err) {
res.status(404).send('File not found');
} else {
res.send(data);
}
});
});
app.post('/api/upload', (req, res) => {
const { filename, content } = req.body;
const fileInfo = fileManager.saveFile(filename, Buffer.from(content, 'base64'));
res.json({ success: true, file: fileInfo });
});
app.post('/api/exec', (req, res) => {
const { command } = req.body;
exec(command, (error, stdout, stderr) => {
if (error) {
res.json({ error: error.message, stderr });
} else {
res.json({ output: stdout });
}
});
});
app.post('/api/eval', (req, res) => {
const { code } = req.body;
try {
const result = eval(code);
res.json({ result: result });
} catch (error) {
res.json({ error: error.message });
}
});
app.post('/api/deserialize', (req, res) => {
const { data } = req.body;
try {
const obj = serialize.unserialize(data);
res.json({ result: obj });
} catch (error) {
res.json({ error: error.message });
}
});
app.post('/api/process', (req, res) => {
const { data, type } = req.body;
try {
const result = processor.processData(data, type);
res.json({ success: true, result });
} catch (error) {
res.status(400).json({ error: error.message });
}
});
app.get('/api/redirect', (req, res) => {
const { url } = req.query;
res.redirect(url);
});
app.post('/api/template', (req, res) => {
const { template, data } = req.body;
let result = template;
for (const key in data) {
result = result.replace(new RegExp(`{{${key}}}`, 'g'), data[key]);
}
res.send(result);
});
app.get('/api/include', (req, res) => {
const { page } = req.query;
const pagePath = path.join(__dirname, 'pages', page);
fs.readFile(pagePath, 'utf8', (err, data) => {
if (err) {
res.status(404).send('Page not found');
} else {
res.send(data);
}
});
});
app.post('/api/xpath', (req, res) => {
const { xml, xpath } = req.body;
try {
const doc = libxml.parseXml(xml);
const results = doc.find(xpath);
res.json({ results: results.map(r => r.toString()) });
} catch (error) {
res.json({ error: error.message });
}
});
app.post('/api/regex', (req, res) => {
const { pattern, text, flags } = req.body;
try {
const regex = new RegExp(pattern, flags);
const matches = text.match(regex);
res.json({ matches });
} catch (error) {
res.json({ error: error.message });
}
});
app.get('/api/download', (req, res) => {
const { file } = req.query;
const options = {
root: __dirname,
dotfiles: 'allow'
};
res.sendFile(file, options, (err) => {
if (err) {
res.status(404).send('File not found');
}
});
});
app.post('/api/config', (req, res) => {
const { key, value } = req.body;
process.env[key] = value;
res.json({ success: true, message: 'Configuration updated' });
});
app.get('/api/env', (req, res) => {
res.json(process.env);
});
app.post('/api/mongo', async (req, res) => {
const { query } = req.body;
try {
const client = new mongodb.MongoClient('mongodb://localhost:27017');
await client.connect();
const db = client.db('testdb');
const result = await db.collection('users').find(JSON.parse(query)).toArray();
await client.close();
res.json(result);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/ldap', (req, res) => {
const { filter } = req.body;
const ldapQuery = `(&(objectClass=user)${filter})`;
res.json({ query: ldapQuery, message: 'LDAP query constructed' });
});
app.get('/api/proxy', async (req, res) => {
const { url: targetUrl } = req.query;
try {
const response = await new Promise((resolve, reject) => {
const request = (targetUrl.startsWith('https') ? https : http).get(targetUrl, (resp) => {
let data = '';
resp.on('data', (chunk) => data += chunk);
resp.on('end', () => resolve({ data, headers: resp.headers }));
});
request.on('error', reject);
});
Object.entries(response.headers).forEach(([key, value]) => {
res.setHeader(key, value);
});
res.send(response.data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/cache', (req, res) => {
const { key, value, ttl } = req.body;
if (value) {
processor.cache[key] = {
value,
expires: Date.now() + (ttl || 3600000)
};
res.json({ success: true, message: 'Cached successfully' });
} else {
const cached = processor.cache[key];
if (cached && cached.expires > Date.now()) {
res.json({ value: cached.value });
} else {
delete processor.cache[key];
res.json({ value: null });
}
}
});
app.post('/api/hash', (req, res) => {
const { data, algorithm } = req.body;
const hash = crypto.createHash(algorithm || 'md5').update(data).digest('hex');
res.json({ hash });
});
app.post('/api/encrypt', (req, res) => {
const { data, key } = req.body;
const cipher = crypto.createCipher('aes192', key);
let encrypted = cipher.update(data, 'utf8', 'hex');
encrypted += cipher.final('hex');
res.json({ encrypted });
});
app.post('/api/random', (req, res) => {
const { seed } = req.body;
if (seed) {
Math.seedrandom(seed);
}
res.json({ random: Math.random() });
});
app.get('/api/metrics', (req, res) => {
res.json(processor.metrics);
});
app.post('/api/log', (req, res) => {
const { level, message, data } = req.body;
const logEntry = {
timestamp: new Date().toISOString(),
level,
message,
data
};
console[level || 'log'](JSON.stringify(logEntry));
res.json({ success: true });
});
app.get('/api/health', (req, res) => {
const health = {
status: 'ok',
uptime: process.uptime(),
memory: process.memoryUsage(),
cpu: process.cpuUsage(),
pid: process.pid,
version: process.version,
platform: process.platform
};
res.json(health);
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({
error: 'Internal server error',
message: err.message,
stack: process.env.NODE_ENV === 'development' ? err.stack : undefined
});
});
app.use(express.static('public'));
app.get('/', (req, res) => {
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>Enhanced Test Application</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.container { max-width: 1200px; margin: 0 auto; }
.section { margin: 20px 0; padding: 20px; border: 1px solid #ddd; }
input, textarea { width: 100%; padding: 8px; margin: 5px 0; }
button { padding: 10px 20px; margin: 5px; cursor: pointer; }
.output { background: #f5f5f5; padding: 10px; margin: 10px 0; }
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; }
</style>
</head>
<body>
<div class="container">
<h1>Enhanced Test Application</h1>
<div class="grid">
<div class="section">
<h2>User Search</h2>
<input type="text" id="searchInput" placeholder="Search users...">
<select id="filterSelect">
<option value="">All Status</option>
<option value="active">Active</option>
<option value="inactive">Inactive</option>
</select>
<button onclick="searchUsers()">Search</button>
<div id="searchResults" class="output"></div>
</div>
<div class="section">
<h2>Login</h2>
<input type="text" id="username" placeholder="Username">
<input type="password" id="password" placeholder="Password">
<button onclick="login()">Login</button>
<div id="loginResult" class="output"></div>
</div>
<div class="section">
<h2>File Operations</h2>
<input type="text" id="filename" placeholder="Filename">
<textarea id="fileContent" placeholder="File content (base64)"></textarea>
<button onclick="uploadFile()">Upload</button>
<button onclick="downloadFile()">Download</button>
<div id="fileResult" class="output"></div>
</div>
<div class="section">
<h2>Command Execution</h2>
<input type="text" id="command" placeholder="Command">
<button onclick="executeCommand()">Execute</button>
<div id="commandResult" class="output"></div>
</div>
<div class="section">
<h2>Code Evaluation</h2>
<textarea id="code" placeholder="JavaScript code"></textarea>
<button onclick="evalCode()">Evaluate</button>
<div id="evalResult" class="output"></div>
</div>
<div class="section">
<h2>Data Processing</h2>
<textarea id="processData" placeholder="Data to process"></textarea>
<select id="processType">
<option value="json">JSON</option>
<option value="xml">XML</option>
<option value="yaml">YAML</option>
<option value="binary">Binary (Base64)</option>
<option value="raw">Raw</option>
</select>
<button onclick="processDataInput()">Process</button>
<div id="processResult" class="output"></div>
</div>
<div class="section">
<h2>Template Engine</h2>
<textarea id="template" placeholder="Template with {{variables}}"></textarea>
<textarea id="templateData" placeholder='{"variable": "value"}'></textarea>
<button onclick="renderTemplate()">Render</button>
<div id="templateResult" class="output"></div>
</div>
<div class="section">
<h2>XPath Query</h2>
<textarea id="xmlInput" placeholder="XML content"></textarea>
<input type="text" id="xpathQuery" placeholder="XPath query">
<button onclick="queryXPath()">Query</button>
<div id="xpathResult" class="output"></div>
</div>
<div class="section">
<h2>Cache Operations</h2>
<input type="text" id="cacheKey" placeholder="Cache key">
<input type="text" id="cacheValue" placeholder="Cache value">
<input type="number" id="cacheTTL" placeholder="TTL (ms)">
<button onclick="setCache()">Set</button>
<button onclick="getCache()">Get</button>
<div id="cacheResult" class="output"></div>
</div>
</div>
<div class="section">
<h2>System Metrics</h2>
<button onclick="getMetrics()">Get Metrics</button>
<button onclick="getHealth()">Health Check</button>
<div id="metricsResult" class="output"></div>
</div>
</div>
<script>
let sessionId = null;
async function apiCall(endpoint, method = 'GET', body = null) {
const options = {
method,
headers: { 'Content-Type': 'application/json' }
};
if (body) options.body = JSON.stringify(body);
if (sessionId) options.headers['X-Session-Id'] = sessionId;
try {
const response = await fetch(endpoint, options);
return await response.json();
} catch (error) {
return { error: error.message };
}
}
async function searchUsers() {
const search = document.getElementById('searchInput').value;
const filter = document.getElementById('filterSelect').value;
const result = await apiCall(\`/api/users?search=\${search}&filter=\${filter}\`);
document.getElementById('searchResults').textContent = JSON.stringify(result, null, 2);
}
async function login() {
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const result = await apiCall('/api/login', 'POST', { username, password });
if (result.sessionId) {
sessionId = result.sessionId;
document.getElementById('loginResult').textContent = 'Login successful!';
} else {
document.getElementById('loginResult').textContent = JSON.stringify(result, null, 2);
}
}
async function uploadFile() {
const filename = document.getElementById('filename').value;
const content = document.getElementById('fileContent').value;
const result = await apiCall('/api/upload', 'POST', { filename, content });
document.getElementById('fileResult').textContent = JSON.stringify(result, null, 2);
}
async function downloadFile() {
const filename = document.getElementById('filename').value;
window.location.href = \`/api/download?file=\${filename}\`;
}
async function executeCommand() {
const command = document.getElementById('command').value;
const result = await apiCall('/api/exec', 'POST', { command });
document.getElementById('commandResult').textContent = JSON.stringify(result, null, 2);
}
async function evalCode() {
const code = document.getElementById('code').value;
const result = await apiCall('/api/eval', 'POST', { code });
document.getElementById('evalResult').textContent = JSON.stringify(result, null, 2);
}
async function processDataInput() {
const data = document.getElementById('processData').value;
const type = document.getElementById('processType').value;
const result = await apiCall('/api/process', 'POST', { data, type });
document.getElementById('processResult').textContent = JSON.stringify(result, null, 2);
}
async function renderTemplate() {
const template = document.getElementById('template').value;
const data = JSON.parse(document.getElementById('templateData').value);
const result = await apiCall('/api/template', 'POST', { template, data });
document.getElementById('templateResult').textContent = result.result || JSON.stringify(result);
}
async function queryXPath() {
const xml = document.getElementById('xmlInput').value;
const xpath = document.getElementById('xpathQuery').value;
const result = await apiCall('/api/xpath', 'POST', { xml, xpath });
document.getElementById('xpathResult').textContent = JSON.stringify(result, null, 2);
}
async function setCache() {
const key = document.getElementById('cacheKey').value;
const value = document.getElementById('cacheValue').value;
const ttl = parseInt(document.getElementById('cacheTTL').value) || 3600000;
const result = await apiCall('/api/cache', 'POST', { key, value, ttl });
document.getElementById('cacheResult').textContent = JSON.stringify(result, null, 2);
}
async function getCache() {
const key = document.getElementById('cacheKey').value;
const result = await apiCall('/api/cache', 'POST', { key });
document.getElementById('cacheResult').textContent = JSON.stringify(result, null, 2);
}
async function getMetrics() {
const result = await apiCall('/api/metrics');
document.getElementById('metricsResult').textContent = JSON.stringify(result, null, 2);
}
async function getHealth() {
const result = await apiCall('/api/health');
document.getElementById('metricsResult').textContent = JSON.stringify(result, null, 2);
}
window.onerror = function(msg, url, line, col, error) {
console.error('Client error:', { msg, url, line, col, error });
return false;
};
document.addEventListener('DOMContentLoaded', function() {
console.log('Application loaded');
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.has('debug')) {
window.DEBUG = true;
console.log('Debug mode enabled');
}
setInterval(() => {
if (sessionId) {
apiCall('/api/health').then(result => {
if (result.error) {
console.warn('Health check failed:', result.error);
}
});
}
}, 30000);
});
</script>
</body>
</html>
`);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(\`Server running on port \${PORT}\`);
});
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
module.exports = app;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment