Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
335 lines (299 loc) · 10.5 KB
/
Copy pathserver.js
File metadata and controls
335 lines (299 loc) · 10.5 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
import express from 'express';
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import { fileURLToPath } from 'url';
import nodemailer from 'nodemailer';
import { resolveRoute, applyMetaToHtml } from './seo-meta.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const distDir = path.join(__dirname, 'dist');
// Always read fresh so a new build is picked up without waiting for a restart.
function loadIndexHtml() {
try {
return fs.readFileSync(path.join(distDir, 'index.html'), 'utf8');
} catch (err) {
return null;
}
}
const NOT_FOUND_HTML = `<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="robots" content="noindex" />
<title>404 - Page Not Found | MakeWorking</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: system-ui, -apple-system, sans-serif;
background: #07070f; color: #e8e8f0;
min-height: 100vh; display: flex; align-items: center; justify-content: center;
text-align: center; padding: 24px;
}
.code { font-size: clamp(72px, 18vw, 160px); font-weight: 800; line-height: 1;
background: linear-gradient(90deg, #00f0ff, #7000ff, #ff00ff);
-webkit-background-clip: text; background-clip: text; color: transparent; }
h1 { font-size: 1.4rem; margin: 12px 0 8px; }
p { color: #9a9ab0; margin-bottom: 28px; }
a.btn {
display: inline-block; padding: 12px 28px; border-radius: 10px; font-weight: 600;
text-decoration: none; color: #07070f; background: linear-gradient(90deg, #00f0ff, #7000ff);
color: #fff;
}
a.home { color: #00f0ff; display: inline-block; margin-top: 18px; font-size: 0.95rem; }
</style>
</head>
<body>
<div>
<div class="code">404</div>
<h1>This page doesn't exist</h1>
<p>The link may be broken or the page may have moved.</p>
<a class="btn" href="/">Back to MakeWorking</a>
<br />
<a class="home" href="/blog">Blog</a> · <a class="home" href="/audit">Free Website Audit</a> · <a class="home" href="/services/RDP">Cloud RDP</a>
</div>
</body>
</html>`;
const app = express();
app.disable("x-powered-by");
app.use(express.json());
const LEADS_PASSWORD = process.env.LEADS_PASSWORD || 'makeworking2026';
const activeTokens = new Map();
function generateToken() {
return crypto.randomBytes(32).toString('hex');
}
function authMiddleware(req, res, next) {
const token = req.headers.authorization?.replace('Bearer ', '');
if (!token || !activeTokens.has(token)) {
return res.status(401).json({ error: 'Unauthorized' });
}
next();
}
// Email configuration (local Postfix)
const transporter = nodemailer.createTransport({
host: '127.0.0.1',
port: 25,
secure: false,
tls: { rejectUnauthorized: false }
});
// Function to send email notification
async function sendEmailNotification(lead) {
const mailOptions = {
from: 'me@codebyjawad.com',
to: 'me@codebyjawad.com',
subject: `🎯 New Website Audit Lead - ${lead.name}`,
html: `
<h2>New Website Audit Lead</h2>
<p><strong>Name:</strong> ${lead.name}</p>
<p><strong>Email:</strong> ${lead.email}</p>
<p><strong>Website:</strong> <a href="${lead.website}">${lead.website}</a></p>
<p><strong>Type:</strong> ${lead.type || 'audit'}</p>
<p><strong>Source:</strong> ${lead.source || 'website_audit_tool'}</p>
<p><strong>Timestamp:</strong> ${new Date(lead.timestamp).toLocaleString('en-US', { timeZone: 'Asia/Karachi' })}</p>
<hr>
<p><small>This is an automated notification from MakeWorking.com</small></p>
`
};
try {
await transporter.sendMail(mailOptions);
console.log('Email notification sent successfully');
} catch (error) {
console.error('Error sending email:', error.message);
}
}
async function sendContactEmail(contact) {
const mailOptions = {
from: 'me@codebyjawad.com',
to: 'me@codebyjawad.com',
subject: `📩 New Contact Form - ${contact.name}`,
html: `
<h2>New Contact Form Submission</h2>
<p><strong>Name:</strong> ${contact.name}</p>
<p><strong>Email:</strong> ${contact.email}</p>
<p><strong>Message:</strong></p>
<p>${contact.message.replace(/\n/g, '<br>')}</p>
<p><strong>Timestamp:</strong> ${new Date(contact.timestamp).toLocaleString('en-US', { timeZone: 'Asia/Karachi' })}</p>
<hr>
<p><small>This is an automated notification from MakeWorking.com</small></p>
`
};
try {
await transporter.sendMail(mailOptions);
console.log('Contact email notification sent successfully');
} catch (error) {
console.error('Error sending contact email:', error.message);
}
}
// Auth route
app.post('/leads-api/auth', (req, res) => {
const { password } = req.body;
if (password !== LEADS_PASSWORD) {
return res.status(401).json({ error: 'Invalid password' });
}
const token = generateToken();
activeTokens.set(token, Date.now());
res.json({ token });
});
// API routes
app.get('/leads-api', authMiddleware, (req, res) => {
const leadsFile = path.join(__dirname, 'leads.json');
if (!fs.existsSync(leadsFile)) {
return res.json([]);
}
try {
const data = fs.readFileSync(leadsFile, 'utf8');
res.json(JSON.parse(data));
} catch (error) {
console.error('Error reading leads:', error);
res.status(500).json({ error: 'Failed to read leads' });
}
});
app.post('/leads-api', (req, res) => {
const leadsFile = path.join(__dirname, 'leads.json');
const newLead = req.body;
let leads = [];
if (fs.existsSync(leadsFile)) {
try {
const data = fs.readFileSync(leadsFile, 'utf8');
leads = JSON.parse(data);
} catch (error) {
console.error('Error reading existing leads:', error);
}
}
const leadWithTimestamp = {
...newLead,
timestamp: new Date().toISOString()
};
leads.push(leadWithTimestamp);
try {
fs.writeFileSync(leadsFile, JSON.stringify(leads, null, 2));
console.log('New lead saved:', leadWithTimestamp);
// Send email notification (async, don't wait)
sendEmailNotification(leadWithTimestamp).catch(err =>
console.error('Email notification failed:', err.message)
);
res.json({ success: true, lead: leadWithTimestamp });
} catch (error) {
console.error('Error saving lead:', error);
res.status(500).json({ error: 'Failed to save lead' });
}
});
// Contact form endpoint
app.post('/contact-api', (req, res) => {
const contactsFile = path.join(__dirname, 'contacts.json');
const newContact = req.body;
let contacts = [];
if (fs.existsSync(contactsFile)) {
try {
const data = fs.readFileSync(contactsFile, 'utf8');
contacts = JSON.parse(data);
} catch (error) {
console.error('Error reading existing contacts:', error);
}
}
const contactWithTimestamp = {
...newContact,
timestamp: new Date().toISOString()
};
contacts.push(contactWithTimestamp);
try {
fs.writeFileSync(contactsFile, JSON.stringify(contacts, null, 2));
console.log('New contact saved:', contactWithTimestamp);
sendContactEmail(contactWithTimestamp).catch(err =>
console.error('Contact email notification failed:', err.message)
);
res.json({ success: true, contact: contactWithTimestamp });
} catch (error) {
console.error('Error saving contact:', error);
res.status(500).json({ error: 'Failed to save contact' });
}
});
// Agents dashboard API
app.get('/agents-api/reports', (req, res) => {
const dataDir = '/root/projects/agents/data';
const reports = {};
try {
const files = fs.readdirSync(dataDir).filter(f => f.endsWith('.json'));
for (const file of files) {
const content = fs.readFileSync(path.join(dataDir, file), 'utf8');
reports[file.replace('.json', '')] = JSON.parse(content);
}
res.json(reports);
} catch (error) {
res.status(500).json({ error: 'Failed to read agent reports' });
}
});
app.get('/agents-api/logs', (req, res) => {
const logDir = '/root/projects/agents/logs';
const logs = [];
try {
const files = fs.readdirSync(logDir).filter(f => f.endsWith('.log')).sort().reverse().slice(0, 20);
for (const file of files) {
const content = fs.readFileSync(path.join(logDir, file), 'utf8');
logs.push({ name: file, content: content.slice(-2000) });
}
res.json(logs);
} catch (error) {
res.json([]);
}
});
// Serve prerendered route pages directly (no trailing-slash redirect hop).
// Mounted before express.static; falls through when no prerendered file exists.
function servePrerendered(req, res, next) {
if (req.method !== 'GET' && req.method !== 'HEAD') return next();
let pathname;
try {
pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
} catch {
return next();
}
if (pathname === '/' || pathname === '') {
const idx = path.join(distDir, 'index.html');
if (fs.existsSync(idx)) {
res.setHeader('Cache-Control', 'no-cache');
return res.sendFile(idx);
}
return next();
}
if (pathname.includes('..') || pathname.includes('\0')) return next();
const normalized = pathname.replace(/\/+$/, '');
const file = path.join(distDir, normalized, 'index.html');
if (!file.startsWith(distDir + path.sep) || !fs.existsSync(file)) return next();
res.setHeader('Cache-Control', 'no-cache');
res.sendFile(file);
}
// Serve static files from dist with a sane caching policy:
// - fingerprinted /assets/* -> 1 year, immutable
// - html (incl. prerendered pages) -> no-cache (always revalidate)
// - other public files (images, robots, sitemap) -> 1 day
app.use(servePrerendered);
app.use(
express.static(distDir, {
setHeaders(res, filePath) {
if (filePath.endsWith('.html')) {
res.setHeader('Cache-Control', 'no-cache');
} else if (filePath.includes(`${path.sep}assets${path.sep}`)) {
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
} else {
res.setHeader('Cache-Control', 'public, max-age=86400');
}
},
})
);
// SPA fallback for known routes; real 404 for everything else.
app.use((req, res) => {
const { status, meta } = resolveRoute(req.path);
if (status === 404 || !meta) {
return res.status(404).type('html').send(NOT_FOUND_HTML);
}
const html = loadIndexHtml();
if (!html) {
return res.status(500).type('text').send('index.html missing - run npm run build');
}
res.status(200).send(applyMetaToHtml(html, meta));
});
const PORT = process.env.PORT || 3002;
app.listen(PORT, () => {
console.log(`MakeWorking server running on port ${PORT}`);
});