10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Recipe-12-HTTPSCommunicatin/server.js:
--------------------------------------------------------------------------------
1 | const https = require('https');
2 | const fs = require('fs');
3 |
4 | const options = {
5 | key: fs.readFileSync('server.key'),
6 | cert: fs.readFileSync('server.cert')
7 | };
8 |
9 | const server = https.createServer(options, (req, res) => {
10 | res.writeHead(200);
11 | res.end('Hello, secure world!');
12 | });
13 |
14 | const PORT = 443; // Standard HTTPS port
15 |
16 | server.listen(PORT, () => {
17 | console.log(`Server running on https://localhost:${PORT}`);
18 | });
19 |
--------------------------------------------------------------------------------
/Recipe-13-SecurelyHandlingCookies/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Secure Cookies Example
7 |
8 |
9 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/Recipe-13-SecurelyHandlingCookies/server.js:
--------------------------------------------------------------------------------
1 | /*In this example:
2 |
3 | To set HTTP-only and secure flags for cookies on the server side in a Node.js application, you typically do this within your server code. Here's a brief example using Express, a popular web framework for Node.js:
4 |
5 |
6 | First, install Express if you haven't already:
7 | npm install express
8 |
9 |
10 | The cookie-parser middleware is used to parse cookies in the request.
11 | The / route sets a cookie using the res.cookie method with the httpOnly and secure options.
12 | Make sure to adjust the secure option based on your deployment environment. In the example, it is set to true only in a production environment, assuming that you are using HTTPS in production.
13 |
14 | Remember to handle sensitive information carefully and follow security best practices in your application.
15 | */
16 | const express = require('express');
17 | const cookieParser = require('cookie-parser');
18 |
19 | const app = express();
20 | const port = 3000;
21 |
22 | app.use(cookieParser());
23 |
24 | app.get('/', (req, res) => {
25 | // Set HTTP-only and secure cookie
26 | res.cookie('exampleCookie', 'exampleValue', {
27 | maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
28 | httpOnly: true,
29 | secure: process.env.NODE_ENV === 'production', // Set to true in production (requires HTTPS)
30 | });
31 |
32 | res.send('Cookie set successfully!');
33 | });
34 |
35 | app.listen(port, () => {
36 | console.log(`Server is running at http://localhost:${port}`);
37 | });
38 |
--------------------------------------------------------------------------------
/Recipe-14-ManInTheMiddleAttack/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Secure Webpage
7 |
35 |
36 |
37 |
Secure Webpage
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/Recipe-14-ManInTheMiddleAttack/server.js:
--------------------------------------------------------------------------------
1 | const https = require('https');
2 | const fs = require('fs');
3 |
4 | // Load your SSL certificate and private key
5 | const options = {
6 | key: fs.readFileSync('path/to/private-key.pem'),
7 | cert: fs.readFileSync('path/to/certificate.pem')
8 | };
9 |
10 | // Define the expected public key hash (SHA-256)
11 | const expectedPublicKeyHash = 'YOUR_PUBLIC_KEY_HASH';
12 |
13 | // Create an HTTPS server
14 | const server = https.createServer(options, (req, res) => {
15 | res.writeHead(200, {'Content-Type': 'text/plain'});
16 | res.end('Hello, this is a secure server!\n');
17 | });
18 |
19 | // Listen on a specific port
20 | const PORT = 3000;
21 | server.listen(PORT, () => {
22 | console.log(`Server running on https://localhost:${PORT}`);
23 | });
24 |
25 | // Add a listener for the 'secureConnection' event to perform certificate pinning
26 | server.on('secureConnection', (tlsSocket) => {
27 | const peerCertificate = tlsSocket.getPeerCertificate();
28 |
29 | // Check if the public key hash matches the expected hash
30 | if (peerCertificate && peerCertificate.fingerprint256 === expectedPublicKeyHash) {
31 | console.log('Certificate is valid. Connection secure.');
32 | } else {
33 | console.error('Certificate verification failed. Potential MitM attack!');
34 | // Handle the error or close the connection as needed
35 | tlsSocket.destroy();
36 | }
37 | });
38 |
--------------------------------------------------------------------------------
/Recipe-15-ValidateFileType/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Secure File Upload
8 |
9 |
10 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Recipe-15-ValidateFileType/server.js:
--------------------------------------------------------------------------------
1 | // Make sure to install the required Node.js packages using:
2 | // npm install express multer
3 |
4 | // These examples provide basic file type validation. You may want to enhance security by considering file size limits, using a content security policy, and implementing additional measures depending on your specific use case.
5 |
6 | // server.js
7 | const express = require('express');
8 | const multer = require('multer');
9 | const app = express();
10 | const port = 3000;
11 |
12 | // Configure multer to handle file uploads
13 | const storage = multer.memoryStorage();
14 | const upload = multer({ storage: storage });
15 |
16 | app.use(express.static('public'));
17 |
18 | app.post('/upload', upload.single('file'), (req, res) => {
19 | const file = req.file;
20 |
21 | if (!file) {
22 | return res.status(400).send('No file uploaded.');
23 | }
24 |
25 | const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png'];
26 | if (allowedTypes.includes(file.mimetype)) {
27 | // Save or process the file as needed
28 | res.send('File uploaded successfully.');
29 | } else {
30 | // Delete the file and send an error response
31 | res.status(400).send('Invalid file type. Please upload a JPG or PNG file.');
32 | }
33 | });
34 |
35 | app.listen(port, () => {
36 | console.log(`Server listening at http://localhost:${port}`);
37 | });
38 |
--------------------------------------------------------------------------------
/Recipe-15-ValidateFileType/upload.js:
--------------------------------------------------------------------------------
1 | // upload.js
2 | function uploadFile() {
3 | const fileInput = document.getElementById('fileInput');
4 | const file = fileInput.files[0];
5 |
6 | if (file) {
7 | const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png'];
8 | if (allowedTypes.includes(file.type)) {
9 | // Proceed with file upload
10 | alert('File is valid. Uploading...');
11 | // You can submit the form or send the file to the server using AJAX
12 | } else {
13 | alert('Invalid file type. Please upload a JPG or PNG file.');
14 | }
15 | } else {
16 | alert('Please choose a file before uploading.');
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/Recipe-16-FileSizeRestrictions/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | File Upload
8 |
9 |
10 |
11 |
12 |
13 |
14 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/Recipe-16-FileSizeRestrictions/server.js:
--------------------------------------------------------------------------------
1 | /*This server-side code uses the multer middleware to handle file uploads and sets a file size limit of 1MB (adjust as needed). The upload.single('file') middleware processes a single file with the field name 'file'. You can adapt the server-side code based on your specific needs.
2 |
3 | Make sure to install the required Node.js packages by running:
4 |
5 | npm install express multer
6 | */
7 |
8 | const express = require('express');
9 | const multer = require('multer');
10 |
11 | const app = express();
12 | const port = 3000;
13 |
14 | const storage = multer.memoryStorage(); // Store the file in memory (adjust as needed)
15 | const upload = multer({ storage: storage, limits: { fileSize: 1024 * 1024 } }); // 1MB limit
16 |
17 | app.post('/upload', upload.single('file'), (req, res) => {
18 | if (!req.file) {
19 | return res.status(400).send('No file uploaded.');
20 | }
21 |
22 | // Process the file or do further validation
23 |
24 | res.send('File uploaded successfully.');
25 | });
26 |
27 | app.listen(port, () => {
28 | console.log(`Server is listening at http://localhost:${port}`);
29 | });
30 |
--------------------------------------------------------------------------------
/Recipe-17-AntiVirusScan/server.js:
--------------------------------------------------------------------------------
1 | // server.js
2 | const express = require('express');
3 | const multer = require('multer');
4 | const { ClamScan } = require('@claviska/clamscan');
5 |
6 | const app = express();
7 | const port = 3000;
8 |
9 | const storage = multer.memoryStorage();
10 | const upload = multer({ storage: storage });
11 |
12 | const clamscan = new ClamScan({
13 | clamscan: {
14 | path: '/usr/bin/clamscan', // Path to the ClamAV binary
15 | db: '/var/lib/clamav'
16 | },
17 | preference: 'clamdscan'
18 | });
19 |
20 | app.post('/upload', upload.single('file'), async (req, res) => {
21 | try {
22 | const { buffer } = req.file;
23 | const isSafe = await clamscan.isInfected(buffer);
24 |
25 | if (isSafe) {
26 | // Process the file since it's safe
27 | res.status(200).json({ message: 'File is safe!' });
28 | } else {
29 | // Reject the file if it's infected
30 | res.status(400).json({ error: 'File is infected!' });
31 | }
32 | } catch (error) {
33 | console.error(error);
34 | res.status(500).json({ error: 'Internal server error' });
35 | }
36 | });
37 |
38 | app.listen(port, () => {
39 | console.log(`Server is running on port ${port}`);
40 | });
41 |
--------------------------------------------------------------------------------
/Recipe-18-SecureWebStorage/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Secure Web Storage
8 |
9 |
10 |
11 |
12 |
13 |
14 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/Recipe-18-SecureWebStorage/server.js:
--------------------------------------------------------------------------------
1 | /**
2 | To securely store sensitive information using web storage, you can follow these steps:
3 |
4 | 1. Use a strong encryption algorithm to encrypt the sensitive data.
5 | 2. Store the encrypted data in the web storage (localStorage or sessionStorage).
6 | 3. Decrypt the data when needed.
7 |
8 | Below is a simple example using Node.js and the crypto library for encryption and decryption.
9 | Note that this is a basic example, and in a real-world scenario, you may want to use more
10 | robust encryption libraries and additional security measures.
11 |
12 | **/
13 |
14 | // Node.js server using Express
15 | const express = require('express');
16 | const crypto = require('crypto');
17 | const bodyParser = require('body-parser');
18 | const app = express();
19 | const PORT = 3000;
20 |
21 | app.use(bodyParser.json());
22 |
23 | // Encryption key (should be stored securely)
24 | const encryptionKey = 'your_secret_encryption_key';
25 |
26 | // Encryption function
27 | function encrypt(text) {
28 | const cipher = crypto.createCipher('aes-256-cbc', encryptionKey);
29 | let encrypted = cipher.update(text, 'utf-8', 'hex');
30 | encrypted += cipher.final('hex');
31 | return encrypted;
32 | }
33 |
34 | // Decryption function
35 | function decrypt(text) {
36 | const decipher = crypto.createDecipher('aes-256-cbc', encryptionKey);
37 | let decrypted = decipher.update(text, 'hex', 'utf-8');
38 | decrypted += decipher.final('utf-8');
39 | return decrypted;
40 | }
41 |
42 | // Example route to store encrypted data
43 | app.post('/store', (req, res) => {
44 | const sensitiveData = req.body.data;
45 | const encryptedData = encrypt(sensitiveData);
46 | // Store encrypted data in localStorage or sessionStorage
47 | // In a real application, you might want to implement proper error handling and validation.
48 | localStorage.setItem('encryptedData', encryptedData);
49 | res.send('Data stored securely.');
50 | });
51 |
52 | // Example route to retrieve and decrypt data
53 | app.get('/retrieve', (req, res) => {
54 | // Retrieve encrypted data from localStorage or sessionStorage
55 | const encryptedData = localStorage.getItem('encryptedData');
56 | if (encryptedData) {
57 | // Decrypt the data when needed
58 | const decryptedData = decrypt(encryptedData);
59 | res.send(`Decrypted Data: ${decryptedData}`);
60 | } else {
61 | res.send('No data found.');
62 | }
63 | });
64 |
65 | app.listen(PORT, () => {
66 | console.log(`Server is running on http://localhost:${PORT}`);
67 | });
68 |
--------------------------------------------------------------------------------
/Recipe-19-EnableHSTS/server.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const helmet = require('helmet');
3 |
4 | const app = express();
5 |
6 | // Use helmet with HSTS middleware
7 | app.use(helmet({
8 | hsts: {
9 | maxAge: 31536000, // 1 year in seconds
10 | includeSubDomains: true,
11 | preload: true
12 | }
13 | }));
14 |
15 | // Your other routes and middleware go here...
16 |
17 | // Start the server
18 | const PORT = process.env.PORT || 3000;
19 | app.listen(PORT, () => {
20 | console.log(`Server is running on port ${PORT}`);
21 | });
22 |
--------------------------------------------------------------------------------
/Recipe-20-XContentTypeOptions/server.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const helmet = require('helmet');
3 |
4 | const app = express();
5 |
6 | // Use the helmet middleware to set security headers
7 | app.use(helmet());
8 |
9 | // Your other middleware and route handlers go here
10 |
11 | const PORT = process.env.PORT || 3000;
12 | app.listen(PORT, () => {
13 | console.log(`Server is running on port ${PORT}`);
14 | });
15 |
--------------------------------------------------------------------------------
/Recipe-21-AvoidEvalMethod/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Dynamic Code Execution
8 |
9 |
10 |
11 |
12 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/Recipe-22-HandlePromises/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Secure Promise Handling
8 |
9 |
10 |
11 |
12 |
51 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/Recipe-23-EnforceStrictMode/index.html:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 | Strict Mode Example
12 |
13 |
14 |
15 |
16 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/Recipe-24-SecureMobileAppComm/script.js:
--------------------------------------------------------------------------------
1 | fetch('https://your-api-endpoint.com/data')
2 | .then(response => response.json())
3 | .then(data => console.log(data))
4 | .catch(error => console.error('Error:', error));
5 |
--------------------------------------------------------------------------------
/Recipe-24-SecureMobileAppComm/server.js:
--------------------------------------------------------------------------------
1 | // Import required modules
2 | const https = require('https');
3 | const fs = require('fs');
4 |
5 | // Read the SSL certificate files
6 | const privateKey = fs.readFileSync('path/to/private-key.pem', 'utf8');
7 | const certificate = fs.readFileSync('path/to/certificate.pem', 'utf8');
8 | const ca = fs.readFileSync('path/to/ca.pem', 'utf8');
9 |
10 | // Create HTTPS server options
11 | const credentials = { key: privateKey, cert: certificate, ca: ca };
12 |
13 | // Your Express or HTTP server logic
14 | const express = require('express');
15 | const app = express();
16 |
17 | // Define your routes and other application logic here
18 |
19 | // Create HTTPS server
20 | const httpsServer = https.createServer(credentials, app);
21 |
22 | // Set the server to listen on a specific port
23 | const PORT = 3000;
24 | httpsServer.listen(PORT, () => {
25 | console.log(`Server is running on https://localhost:${PORT}`);
26 | });
27 |
--------------------------------------------------------------------------------
/Recipe-25-TouchId/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Biometric Authentication
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/Recipe-25-TouchId/main.js:
--------------------------------------------------------------------------------
1 |
2 | // Note that this is a simplified example, and in a real-world scenario,
3 | // you would need to implement server-side verification of the biometric credentials.
4 |
5 | document.addEventListener("DOMContentLoaded", function () {
6 | const biometricBtn = document.getElementById("biometricBtn");
7 |
8 | biometricBtn.addEventListener("click", () => {
9 | authenticateWithBiometrics()
10 | .then((success) => {
11 | if (success) {
12 | alert("Biometric authentication successful!");
13 | // Implement your logic for authenticated actions here
14 | } else {
15 | alert("Biometric authentication failed.");
16 | }
17 | })
18 | .catch((error) => {
19 | console.error("Biometric authentication error:", error);
20 | });
21 | });
22 |
23 | async function authenticateWithBiometrics() {
24 | try {
25 | const credentials = await navigator.credentials.get({
26 | publicKey: {
27 | challenge: new Uint8Array(32),
28 | rp: { name: "Example Web App" },
29 | user: { id: new Uint8Array(16), name: "user@example.com", displayName: "User" },
30 | pubKeyCredParams: [{ type: "public-key", alg: -7 }],
31 | },
32 | });
33 |
34 | // Check if the biometric authentication was successful
35 | if (credentials) {
36 | return true;
37 | } else {
38 | return false;
39 | }
40 | } catch (error) {
41 | throw error;
42 | }
43 | }
44 | });
45 |
--------------------------------------------------------------------------------
/Recipe-26-ClientSideLogging/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Client-side Logging Example
8 |
9 |
10 |
11 |