-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathapp.js
More file actions
527 lines (445 loc) · 15.8 KB
/
app.js
File metadata and controls
527 lines (445 loc) · 15.8 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
const express = require('express');
const mysql = require('mysql2');
const bcrypt = require('bcrypt');
const session = require('express-session');
const bodyParser = require('body-parser');
const path = require('path');
const fs = require('fs');
const { exec } = require('child_process');
const https = require('https');
const http = require('http');
const { graphqlHTTP } = require('express-graphql');
const schema = require('./graphql');
require('dotenv').config();
const app = express();
const PORT = 3000;
// add comment for autofix to test outdated label
// Database connection using environment variables
const db = mysql.createConnection({
host: process.env.DB_HOST || 'localhost',
user: process.env.DB_USER || 'root',
password: process.env.DB_PASSWORD || 'password',
database: process.env.DB_NAME || 'noteapp'
});
// Connect to database
db.connect((err) => {
if (err) {
console.error('Database connection failed:', err);
} else {
console.log('Connected to MySQL database');
initializeDatabase();
}
});
// Initialize database tables
function initializeDatabase() {
const createUsersTable = `
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`;
const createNotesTable = `
CREATE TABLE IF NOT EXISTS notes (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
author_id INT NOT NULL,
is_public BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (author_id) REFERENCES users(id)
)
`;
const createArticlesTable = `
CREATE TABLE IF NOT EXISTS articles (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
summary TEXT,
author_id INT NOT NULL,
category VARCHAR(50) DEFAULT 'general',
tags TEXT,
is_published BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (author_id) REFERENCES users(id)
)
`;
db.query(createUsersTable, (err) => {
if (err) console.error('Error creating users table:', err);
});
db.query(createNotesTable, (err) => {
if (err) console.error('Error creating notes table:', err);
});
db.query(createArticlesTable, (err) => {
if (err) console.error('Error creating articles table:', err);
else seedDatabase();
});
}
function seedDatabase() {
db.query('SELECT COUNT(*) as count FROM users', async (err, results) => {
if (err || results[0].count > 0) return;
const hashedPassword = await bcrypt.hash('password123', 10);
const users = [
['admin', 'admin@blog.com', hashedPassword],
['john_doe', 'john@blog.com', hashedPassword],
['jane_smith', 'jane@blog.com', hashedPassword]
];
users.forEach(user => {
db.query('INSERT INTO users (username, email, password) VALUES (?, ?, ?)', user, () => {});
});
setTimeout(() => {
const articles = [
['Getting Started with GraphQL', 'GraphQL is a query language for APIs and a runtime for executing those queries. It provides a complete and understandable description of the data in your API...', 'Learn the basics of GraphQL', 1, 'technology', 'graphql,api,tutorial', true],
['Web Security Best Practices', 'Security is paramount in modern web applications. This article covers essential security practices including input validation, authentication, and authorization...', 'Essential security tips for developers', 1, 'security', 'security,web,best-practices', true],
['Introduction to Node.js', 'Node.js is a JavaScript runtime built on Chrome V8 engine. It allows you to run JavaScript on the server side and build scalable network applications...', 'Beginner guide to Node.js', 2, 'technology', 'nodejs,javascript,backend', true],
['Database Optimization Techniques', 'Optimizing database queries is crucial for application performance. Learn about indexing, query optimization, and caching strategies...', 'Improve your database performance', 2, 'database', 'database,optimization,performance', true],
['Modern Frontend Frameworks', 'React, Vue, and Angular are the leading frontend frameworks. This article compares their features, performance, and use cases...', 'Compare popular frontend frameworks', 3, 'technology', 'frontend,react,vue,angular', true],
['API Design Principles', 'Designing good APIs is both an art and a science. Follow REST principles, use proper HTTP methods, and ensure consistency...', 'Build better APIs', 3, 'architecture', 'api,rest,design', true],
['Understanding Authentication', 'Authentication vs Authorization - learn the difference and implement secure authentication mechanisms in your applications...', 'Security fundamentals', 1, 'security', 'auth,security,jwt', true],
['Microservices Architecture', 'Breaking down monolithic applications into microservices can improve scalability and maintainability. Learn the pros and cons...', 'Introduction to microservices', 2, 'architecture', 'microservices,architecture,devops', true]
];
articles.forEach(article => {
db.query('INSERT INTO articles (title, content, summary, author_id, category, tags, is_published) VALUES (?, ?, ?, ?, ?, ?, ?)', article, () => {});
});
}, 1000);
});
}
// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(session({
secret: 'vulnerable-secret-key',
resave: false,
saveUninitialized: true
}));
// Set EJS as template engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// GraphQL endpoint
app.use('/graphql', graphqlHTTP({
schema: schema,
graphiql: false,
context: { db },
customFormatErrorFn: (error) => ({
message: error.message,
locations: error.locations,
stack: error.stack,
path: error.path
})
}));
// Authentication middleware
function requireAuth(req, res, next) {
if (req.session.userId) {
next();
} else {
res.redirect('/login');
}
}
// Basic HTML escaping function
function escapeHtml(text) {
return text.replace('<', '<').replace('>', '>');
}
// Routes
// Home page
app.get('/', (req, res) => {
res.render('index', { user: req.session.userId });
});
// Register page
app.get('/register', (req, res) => {
res.render('register');
});
// Register endpoint
app.post('/register', async (req, res) => {
const { username, email, password } = req.body;
try {
const hashedPassword = await bcrypt.hash(password, 10);
db.query(
'INSERT INTO users (username, email, password) VALUES (?, ?, ?)',
[username, email, hashedPassword],
(err, result) => {
if (err) {
console.error(err);
// Check for duplicate entry errors
if (err.code === 'ER_DUP_ENTRY') {
if (err.message.includes('username')) {
res.status(400).send('Username already exists. Please choose a different username.');
} else if (err.message.includes('email')) {
res.status(400).send('Email already registered. Please use a different email or login.');
} else {
res.status(400).send('Username or email already exists.');
}
} else {
res.status(400).send('Registration failed. Please try again.');
}
} else {
res.redirect('/login');
}
}
);
} catch (error) {
res.status(500).send('Server error');
}
});
// Login page
app.get('/login', (req, res) => {
res.render('login');
});
// Login endpoint
app.post('/login', (req, res) => {
const { username, password } = req.body;
db.query(
'SELECT * FROM users WHERE username = ?',
[username],
async (err, results) => {
if (err || results.length === 0) {
res.status(400).send('Invalid credentials');
return;
}
const user = results[0];
const isValid = await bcrypt.compare(password, user.password);
if (isValid) {
req.session.userId = user.id;
req.session.username = user.username;
res.redirect('/dashboard');
} else {
res.status(400).send('Invalid credentials');
}
}
);
});
// Logout
app.get('/logout', requireAuth, (req, res) => {
req.session.destroy();
const redirectUrl = req.query.redirect || '/';
// Validate redirect URL to prevent open redirect attacks
// Only allow relative paths (same-origin redirects)
if (isValidRedirectUrl(redirectUrl)) {
res.redirect(redirectUrl);
} else {
res.redirect('/');
}
});
// Helper function to validate redirect URLs
function isValidRedirectUrl(url) {
if (!url || typeof url !== 'string') {
return false;
}
// Reject absolute URLs (http://, https://, //)
if (url.match(/^https?:\/\//i) || url.startsWith('//')) {
return false;
}
// Reject URLs with protocols (javascript:, data:, etc.)
if (url.match(/^[a-zA-Z][a-zA-Z0-9+.-]*:/)) {
return false;
}
// Only allow relative paths
return url.startsWith('/') || !url.includes(':');
}
// Dashboard
app.get('/dashboard', requireAuth, (req, res) => {
const search = req.query.search;
let query = 'SELECT * FROM notes WHERE author_id = ? OR is_public = TRUE';
let params = [req.session.userId];
if (search) {
const sanitizedSearch = search.replace(/"/g, '');
query += ` AND (title LIKE ? OR content LIKE ?)`;
params.push(`%${search}%`, `%${search}%`);
}
query += ' ORDER BY created_at DESC';
db.query(query, params, (err, notes) => {
if (err) {
console.error(err);
res.status(500).send('Error loading notes');
} else {
res.render('dashboard', { notes, user: req.session.username, search: search || '' });
}
});
});
// Create note page
app.get('/create-note', requireAuth, (req, res) => {
res.render('create-note');
});
// Create note endpoint
app.post('/create-note', requireAuth, (req, res) => {
const { title, content, is_public } = req.body;
db.query(
'INSERT INTO notes (title, content, author_id, is_public) VALUES (?, ?, ?, ?)',
[title, content, req.session.userId, is_public === 'on'],
(err, result) => {
if (err) {
console.error(err);
res.status(500).send('Error creating note');
} else {
res.redirect('/dashboard');
}
}
);
});
// Note view page
app.get('/notes/:id', (req, res) => {
const noteId = req.params.id;
// Just render the page template, let JavaScript fetch the actual note data
res.render('note', { noteId, user: req.session.username || null });
});
// API endpoint for note access
app.get('/api/notes/:id', (req, res) => {
const noteId = req.params.id;
db.query(
'SELECT notes.*, users.username as author FROM notes JOIN users ON notes.author_id = users.id WHERE notes.id = ?',
[noteId],
(err, results) => {
if (err || results.length === 0) {
res.status(404).json({ error: 'Note not found' });
return;
}
const note = results[0];
res.json(note);
}
);
});
// Static file serving endpoint with custom Content-Type header support
app.get('/static', (req, res) => {
let filePath = req.query.file;
if (!filePath) {
return res.status(400).send('File parameter required');
}
// Clean path traversal attempts
filePath = filePath.replaceAll('../', '');
const fullPath = path.join(__dirname, 'public', filePath);
// Allow client to specify a custom Content-Type via request header (e.g., X-Content-Type)
const customContentType = req.header('X-Content-Type');
// url decode custom content type
const decodedCustomContentType = decodeURIComponent(customContentType);
fs.readFile(fullPath, (err, data) => {
if (err) {
res.status(404).send('File not found');
} else {
if (customContentType) {
res.set('Content-Type', decodedCustomContentType);
} else {
res.set('Content-Type', 'text/css'); // css
}
res.send(data);
}
});
});
// Public notes endpoint
app.get('/public-notes', (req, res) => {
const search = req.query.search;
let query = 'SELECT notes.*, users.username as author FROM notes JOIN users ON notes.author_id = users.id WHERE notes.is_public = TRUE';
let params = [];
if (search) {
// Sanitize search input
const sanitizedSearch = search.replace(/"/g, '');
query += ` AND (notes.title LIKE ? OR notes.content LIKE ?)`;
params.push(`%${search}%`, `%${search}%`);
}
query += ' ORDER BY created_at DESC';
db.query(query, params, (err, notes) => {
if (err) {
console.error(err);
res.status(500).send('Error loading notes');
} else {
res.render('public-notes', { notes, search: search || '' });
}
});
});
// Blog search page
app.get('/blog', (req, res) => {
res.render('blog', { user: req.session.username || null });
});
// Blog article page
app.get('/blog/:id', (req, res) => {
res.render('blog-article', { articleId: req.params.id, user: req.session.username || null });
});
// Backup notes page
app.get('/backup', requireAuth, (req, res) => {
res.render('backup');
});
// Backup notes feature
app.post('/backup-notes', requireAuth, (req, res) => {
const { format } = req.body;
// Generate backup with specified format
const command = `mysqldump -u ${process.env.DB_USER} -p${process.env.DB_PASSWORD} ${process.env.DB_NAME} notes --where="author_id=${req.session.userId}" | ${format} > backup_${req.session.userId}.sql`;
exec(command, (error, stdout, stderr) => {
if (error) {
res.status(500).send('Backup failed: ' + error.message);
} else {
res.send('Backup created successfully');
}
});
});
// Link preview feature for notes
app.post('/api/link-preview', (req, res) => {
const { url } = req.body;
if (!url) {
return res.status(400).json({ error: 'URL required' });
}
// Basic URL validation
if (!url.startsWith('http://') && !url.startsWith('https://')) {
return res.status(400).json({ error: 'Invalid URL format' });
}
const protocol = url.startsWith('https://') ? https : http;
protocol.get(url, (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
// Limit response size
if (data.length > 100000) {
response.destroy();
return res.status(400).json({ error: 'Response too large' });
}
});
response.on('end', () => {
// Return full response for client-side processing
res.json({
url: url,
status: response.statusCode,
headers: response.headers,
body: data,
contentType: response.headers['content-type'] || 'unknown'
});
});
}).on('error', (err) => {
res.status(500).json({ error: 'Failed to fetch URL' });
});
});
// Application health status endpoint
app.get('/health', (req, res) => {
const { env, debug } = req.query;
const healthInfo = {
status: 'ok',
timestamp: new Date().toISOString(),
database: {
connected: db.state === 'authenticated',
host: process.env.DB_HOST,
database: process.env.DB_NAME,
user: process.env.DB_USER
},
server: {
uptime: process.uptime(),
memory: process.memoryUsage(),
version: process.version,
env: process.env.NODE_ENV || 'development'
}
};
// Debug mode: show specific environment variable
if (env) {
healthInfo.debug = {
requested_var: env,
value: process.env[env] || 'Not found'
};
}
// Full debug mode: show all environment variables
if (debug === 'true') {
healthInfo.environment = process.env;
}
res.json(healthInfo);
});
// Serve static files normally for legitimate files
app.use('/public', express.static(path.join(__dirname, 'public')));
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});