HTTPS தொகுதிக்கு அறிமுகம்
HTTPS தொகுதி என்பது Node.js இன் முக்கிய தொகுதியாகும், இது HTTPS நெறிமுறையின் செயலாக்கத்தை வழங்குகிறது, இது அடிப்படையில் TLS/SSL மூலம் HTTP ஆகும்.
இது HTTP தொகுதியின் பாதுகாப்பான பதிப்பாகும், இது கிளையன்ட்கள் மற்றும் சேவையகங்களுக்கு இடையே குறியாக்கப்பட்ட தகவல்தொடர்பை வழங்குகிறது.
தரவு குறியாக்கம்
பார்வையிடுதலில் இருந்து பாதுகாக்கிறது
சேவையக அங்கீகாரம்
சேவையகத்தின் அடையாளத்தை சரிபார்க்கிறது
தரவு ஒருமைப்பாடு
தரவு மாற்றம் அல்லது சிதைவைத் தடுக்கிறது
HTTPS ஏன் பயன்படுத்த வேண்டும்?
HTTPS நவீன வலை பயன்பாடுகளுக்கு முக்கியமானது, ஏனெனில் இது:
குறிப்பு:
நவீன HTTPS TLS (டிரான்ஸ்போர்ட் லேயர் செக்யூரிட்டி) ஐப் பயன்படுத்துகிறது, இது SSL (செக்யூர் சாக்கெட்ஸ் லேயர்) இன் வாரிசாகும். இந்த சொற்கள் பெரும்பாலும் ஒன்றுக்கொன்று பயன்படுத்தப்படுகின்றன, ஆனால் SSL இப்போது காலாவதியானதாகக் கருதப்படுகிறது.
முக்கியமானது:
2023 ஆம் ஆண்டு நிலவரப்படி, அனைத்து முக்கிய உலாவிகளும் புதிய வலை அம்சங்கள் மற்றும் APIகளுக்கு HTTPS ஐத் தேவைப்படுத்துகின்றன. பல உலாவிகள் HTTPS இல்லாத தளங்களை "பாதுகாப்பற்றது" என்றும் குறிக்கின்றன.
HTTPS எவ்வாறு செயல்படுகிறது
HTTPS உடன் தொடங்குதல்
தொகுதியை இறக்குமதி செய்தல்
உங்கள் Node.js பயன்பாட்டில் HTTPS தொகுதியைப் பயன்படுத்த, CommonJS அல்லது ES தொகுதிகள் இலக்கணத்தைப் பயன்படுத்தி அதை இறக்குமதி செய்யலாம்:
CommonJS (Node.js default)
// Using require()
const https = require('https');
ES Modules (Node.js 14+)
// Using import (requires "type": "module" in package.json)
import https from 'https';
HTTPS vs HTTP API
HTTPS தொகுதிக்கு HTTP தொகுதியின் அதே இடைமுகம் உள்ளது, முக்கிய வேறுபாடு என்னவென்றால் இது TLS/SSL ஐப் பயன்படுத்தி இணைப்புகளை உருவாக்குகிறது.
இதன் பொருள் HTTP தொகுதியில் கிடைக்கும் அனைத்து முறைகள் மற்றும் நிகழ்வுகளும் HTTPS தொகுதியில் கிடைக்கும்.
குறிப்பு:
பயன்பாட்டில் முக்கிய வேறுபாடு என்னவென்றால், HTTPS க்கு SSL/TLS சான்றிதழ்கள் தேவைப்படுகின்றன, அதே நேரத்தில் HTTP க்கு தேவையில்லை.
SSL/TLS சான்றிதழ்கள்
HTTPS க்கு பாதுகாப்பான இணைப்புகளை நிறுவ SSL/TLS சான்றிதழ்கள் தேவைப்படுகின்றன. பல வகையான சான்றிதழ்கள் உள்ளன:
| சான்றிதழ் வகை | பயன்பாடு | சரிபார்ப்பு நிலை |
|---|---|---|
| சுய-கையொப்பமிடப்பட்ட சான்றிதழ்கள் | மேம்பாடு மற்றும் சோதனைக்காக (உலாவிகளால் நம்பப்படுவதில்லை) | எந்த சரிபார்ப்பும் இல்லை |
| டொமைன் சரிபார்க்கப்பட்ட (DV) | அடிப்படை சரிபார்ப்பு, டொமைன் உரிமையை மட்டும் சரிபார்க்கிறது | டொமைன் உரிமை |
| அமைப்பு சரிபார்க்கப்பட்ட (OV) | அமைப்பு விவரங்களை சரிபார்க்கிறது | அமைப்பு விவரங்கள் |
| நீட்டிக்கப்பட்ட சரிபார்ப்பு (EV) | அதிக மட்ட சரிபார்ப்பு, உலாவியில் நிறுவனப் பெயரைக் காட்டுகிறது | முழுமையான சட்டபூர்வ சரிபார்ப்பு |
| வைல்ட்கார்ட் சான்றிதழ்கள் | ஒரு டொமைனின் அனைத்து உபடொமைன்களையும் பாதுகாக்கிறது | டொமைன் மற்றும் அனைத்து உபடொமைன்கள் |
| பல-டொமைன் (SAN) சான்றிதழ்கள் | ஒரு சான்றிதழுடன் பல டொமைன்களை பாதுகாக்கிறது | பல டொமைன்கள் |
சுய-கையொப்பமிடப்பட்ட சான்றிதழ்களை உருவாக்குதல்
மேம்பாட்டிற்காக, நீங்கள் OpenSSL ஐப் பயன்படுத்தி சுய-கையொப்பமிடப்பட்ட சான்றிதழ்களை உருவாக்கலாம்:
அடிப்படை சுய-கையொப்பமிடப்பட்ட சான்றிதழ்
# Generate a private key (RSA 2048-bit)
openssl genrsa -out key.pem 2048
# Generate a self-signed certificate (valid for 365 days)
openssl req -new -x509 -key key.pem -out cert.pem -days 365 -nodes
Subject Alternative Names (SAN) உடன்
# Create a config file (san.cnf)
cat > san.cnf << EOF
[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = US
ST = State
L = City
O = Organization
OU = Organizational Unit
CN = localhost
[v3_req]
keyUsage = keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
IP.1 = 127.0.0.1
EOF
# Generate key and certificate with SAN
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout key.pem -out cert.pem -config san.cnf -extensions 'v3_req'
பாதுகாப்பு குறிப்பு:
சுய-கையொப்பமிடப்பட்ட சான்றிதழ்கள் உலாவிகளில் பாதுகாப்பு எச்சரிக்கைகளைத் தூண்டும், ஏனெனில் அவை நம்பப்படும் சான்றிதழ் அதிகாரத்தால் கையொப்பமிடப்படவில்லை.
மேம்பாடு மற்றும் சோதனை நோக்கங்களுக்காக மட்டுமே அவற்றைப் பயன்படுத்தவும்.
நம்பப்படும் சான்றிதழ்களைப் பெறுதல்
உற்பத்திக்காக, நம்பப்படும் சான்றிதழ் அதிகாரங்களிடமிருந்து சான்றிதழ்களைப் பெறவும்:
பணம் செலுத்தப்பட்ட CAs
DigiCert, GlobalSign, Comodo, முதலியன
இலவச CAs
Let's Encrypt, ZeroSSL, Cloudflare
Let's Encrypt:
Let's Encrypt என்பது ஒரு பிரபலமான இலவச, தானியங்கி, மற்றும் திறந்த சான்றிதழ் அதிகாரமாகும், இது நம்பப்படும் சான்றிதழ்களை வழங்குகிறது.
HTTPS சேவையகத்தை உருவாக்குதல்
உங்கள் SSL/TLS சான்றிதழ்கள் தயாராக இருக்கும்போது, நீங்கள் Node.js இல் ஒரு HTTPS சேவையகத்தை உருவாக்கலாம்.
HTTPS சேவையக API HTTP சேவையக API போன்றே உள்ளது, முக்கிய வேறுபாடு SSL/TLS கட்டமைப்பு ஆகும்.
அடிப்படை HTTPS சேவையக எடுத்துக்காட்டு
const https = require('https');
const fs = require('fs');
const path = require('path');
// Path to your SSL/TLS certificate and key
const sslOptions = {
key: fs.readFileSync(path.join(__dirname, 'key.pem')),
cert: fs.readFileSync(path.join(__dirname, 'cert.pem')),
// Enable all security features
minVersion: 'TLSv1.2',
// Recommended security settings
secureOptions: require('constants').SSL_OP_NO_SSLv3 |
require('constants').SSL_OP_NO_TLSv1 |
require('constants').SSL_OP_NO_TLSv1_1
};
// Create the HTTPS server
const server = https.createServer(sslOptions, (req, res) => {
// Security headers
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
res.setHeader('X-XSS-Protection', '1; mode=block');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
// Handle different routes
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end('Welcome to the Secure Server
Your connection is encrypted!
');
} else if (req.url === '/api/status') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok', time: new Date().toISOString() }));
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
});
// Handle server errors
server.on('error', (error) => {
console.error('Server error:', error);
});
// Start the server on port 3000 (HTTPS default is 443 but requires root)
const PORT = process.env.PORT || 3000;
server.listen(PORT, '0.0.0.0', () => {
console.log(`Server running at https://localhost:${PORT}`);
console.log('Press Ctrl+C to stop the server');
});
குறிப்பு:
யூனிக்ஸ் போன்ற அமைப்புகளில், 1024 க்கும் குறைவான போர்ட்களுக்கு ரூட் அனுமதிகள் தேவைப்படுகின்றன. உற்பத்திக்காக, உயர் போர்ட்டில் (3000, 8080 போன்றவை) Node.js ஐ இயக்கவும், SSL முடிவுக்கு Nginx அல்லது Apache போன்ற ரிவர்ஸ் ப்ராக்ஸியைப் பயன்படுத்தவும் இது பொதுவானது.
மேம்பட்ட சேவையக கட்டமைப்பு
உற்பத்தி சூழல்களுக்கு, உங்களுக்கு மேம்பட்ட SSL/TLS கட்டமைப்பு தேவைப்படலாம்:
OCSP Stapling மற்றும் Session Resumption உடன் மேம்பட்ட HTTPS சேவையகம்
const https = require('https');
const fs = require('fs');
const path = require('path');
const tls = require('tls');
// Path to your SSL/TLS files
const sslOptions = {
// Certificate and key
key: fs.readFileSync(path.join(__dirname, 'privkey.pem')),
cert: fs.readFileSync(path.join(__dirname, 'cert.pem')),
ca: [
fs.readFileSync(path.join(__dirname, 'chain.pem'))
],
// Recommended security settings
minVersion: 'TLSv1.2',
maxVersion: 'TLSv1.3',
ciphers: [
'TLS_AES_256_GCM_SHA384',
'TLS_CHACHA20_POLY1305_SHA256',
'TLS_AES_128_GCM_SHA256',
'ECDHE-ECDSA-AES256-GCM-SHA384',
'ECDHE-RSA-AES256-GCM-SHA384',
'ECDHE-ECDSA-CHACHA20-POLY1305',
'ECDHE-RSA-CHACHA20-POLY1305',
'ECDHE-ECDSA-AES128-GCM-SHA256',
'ECDHE-RSA-AES128-GCM-SHA256'
].join(':'),
honorCipherOrder: true,
// Enable OCSP Stapling
requestCert: true,
rejectUnauthorized: true,
// Enable session resumption
sessionTimeout: 300, // 5 minutes
sessionIdContext: 'my-secure-app'
};
// Create the HTTPS server
const server = https.createServer(sslOptions, (req, res) => {
// Security headers
const securityHeaders = {
'Strict-Transport-Security': 'max-age=63072000; includeSubDomains; preload',
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block',
'Content-Security-Policy': "default-src 'self'",
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Permissions-Policy': 'geolocation=(), microphone=(), camera=()',
};
Object.entries(securityHeaders).forEach(([key, value]) => {
res.setHeader(key, value);
});
// Handle requests
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end('Secure Node.js Server
Your connection is secure!
');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
});
// Handle server errors
server.on('error', (error) => {
console.error('Server error:', error);
});
// Handle uncaught exceptions
process.on('uncaughtException', (error) => {
console.error('Uncaught exception:', error);
// Perform graceful shutdown
server.close(() => process.exit(1));
});
// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
// Handle graceful shutdown
const gracefulShutdown = () => {
console.log('Shutting down gracefully...');
server.close(() => {
console.log('Server closed');
process.exit(0);
});
// Force close server after 10 seconds
setTimeout(() => {
console.error('Forcing shutdown...');
process.exit(1);
}, 10000);
};
// Listen for shutdown signals
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);
// Start the server
const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '0.0.0.0';
server.listen(PORT, HOST, () => {
const { address, port } = server.address();
console.log(`Server running at https://${address}:${port}`);
// Output server information
console.log('Node.js version:', process.version);
console.log('Environment:', process.env.NODE_ENV || 'development');
console.log('PID:', process.pid);
});
பாதுகாப்பு சிறந்த நடைமுறைகள்:
- பாதுகாப்பு புதுப்பிப்புகளுக்கு எப்போதும் Node.js இன் சமீபத்திய நிலையான பதிப்பைப் பயன்படுத்தவும்
npm auditமற்றும்npm updateஐப் பயன்படுத்தி உங்கள் சார்புகளை நாள்பட்ட வைத்திருங்கள்- உணர்திறன் கட்டமைப்புக்கு சூழல் மாறிகள் பயன்படுத்தவும் (ரகசியங்களை பதிப்பு கட்டுப்பாட்டிற்கு ஒருபோதும் கமிட் செய்யாதீர்கள்)
- துஷ்பிரயோகத்தைத் தடுக்க விகித வரம்பை செயல்படுத்தவும்
- உங்கள் SSL/TLS சான்றிதழ்களை தவறாமல் சுழற்றவும்
- பாதுகாப்பு பாதிப்புக்காக உங்கள் சேவையகத்தை கண்காணிக்கவும்
- கூடுதல் பாதுகாப்பு அம்சங்களுக்காக உற்பத்தியில் Nginx அல்லது Apache போன்ற ரிவர்ஸ் ப்ராக்ஸியைப் பயன்படுத்தவும்
உங்கள் HTTPS சேவையகத்தை சோதித்தல்
உங்கள் HTTPS சேவையகத்தை சோதிக்க, நீங்கள் curl அல்லது வலை உலாவியைப் பயன்படுத்தலாம்:
curl ஐப் பயன்படுத்துதல்
# Skip certificate verification (for self-signed certs)
curl -k https://localhost:3000
# With certificate verification (for trusted certs)
curl --cacert /path/to/ca.pem https://yourdomain.com
வலை உலாவியைப் பயன்படுத்துதல்
# உங்கள் வலை உலாவியைத் திறந்து https://localhost:3000 க்குச் செல்லவும்
# சுய-கையொப்பமிடப்பட்ட சான்றிதழைப் பயன்படுத்தினால், பாதுகாப்பு எச்சரிக்கையை ஏற்க வேண்டும்
# மேம்பாட்டிற்காக, உங்கள் சுய-கையொப்பமிடப்பட்ட சான்றிதழை நம்பப்படும் ரூட் சான்றிதழ்களில் சேர்க்கலாம்
HTTPS கோரிக்கைகளைச் செய்தல்
HTTPS தொகுதி மற்ற சேவையகங்களுக்கு பாதுகாப்பான HTTP கோரிக்கைகளைச் செய்ய உங்களை அனுமதிக்கிறது.
பாதுகாப்பான APIகள் மற்றும் வலை சேவைகளுடன் தொடர்பு கொள்வதற்கு இது அத்தியாவசியமானது.
அடிப்படை GET கோரிக்கை
const https = require('https');
const { URL } = require('url');
// Parse the target URL
const apiUrl = new URL('https://api.example.com/data');
// Request options
const options = {
hostname: apiUrl.hostname,
port: 443,
path: apiUrl.pathname + apiUrl.search,
method: 'GET',
headers: {
'User-Agent': 'MySecureApp/1.0',
'Accept': 'application/json',
'Cache-Control': 'no-cache'
},
// Security settings
rejectUnauthorized: true, // Verify the server certificate (default: true)
// Timeout in milliseconds
timeout: 10000, // 10 seconds
};
console.log(`Making request to: https://${options.hostname}${options.path}`);
// Make the HTTPS request
const req = https.request(options, (res) => {
const { statusCode, statusMessage, headers } = res;
const contentType = headers['content-type'] || '';
console.log(`Status: ${statusCode} ${statusMessage}`);
console.log('Headers:', headers);
// Handle redirects
if (statusCode >= 300 && statusCode < 400 && headers.location) {
console.log(`Redirecting to: ${headers.location}`);
// In a real app, you'd handle the redirect
res.resume(); // Discard the response body
return;
}
// Check for successful response
let error;
if (statusCode !== 200) {
error = new Error(`Request Failed.\nStatus Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) {
error = new Error(`Invalid content-type.\nExpected application/json but received ${contentType}`);
}
if (error) {
console.error(error.message);
res.resume(); // Consume response data to free up memory
return;
}
// Process the response
let rawData = '';
res.setEncoding('utf8');
// Collect chunks of data
res.on('data', (chunk) => {
rawData += chunk;
});
// Process the complete response
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
console.log('Response data:', parsedData);
} catch (e) {
console.error('Error parsing JSON:', e.message);
}
});
});
// Handle request errors
req.on('error', (e) => {
console.error(`Request error: ${e.message}`);
});
// End the request (required to send it)
req.end();
எளிய கோரிக்கைகளுக்கு https.get() பயன்படுத்துதல்
const https = require('https');
const { URL } = require('url');
// Parse the URL
const url = new URL('https://jsonplaceholder.typicode.com/posts/1');
// Request options
const options = {
hostname: url.hostname,
path: url.pathname,
method: 'GET',
headers: {
'Accept': 'application/json',
'User-Agent': 'MySecureApp/1.0'
}
};
console.log(`Fetching data from: ${url}`);
// Make the GET request
const req = https.get(options, (res) => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
if (statusCode !== 200) {
console.error(`Request failed with status code: ${statusCode}`);
res.resume(); // Consume response data to free up memory
return;
}
if (!/^application\/json/.test(contentType)) {
console.error(`Expected JSON but got ${contentType}`);
res.resume();
return;
}
let rawData = '';
res.setEncoding('utf8');
// Collect data chunks
res.on('data', (chunk) => {
rawData += chunk;
});
// Process complete response
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
console.log('Received data:', parsedData);
} catch (e) {
console.error('Error parsing JSON:', e.message);
}
});
});
// Handle errors
req.on('error', (e) => {
console.error(`Error: ${e.message}`);
});
// Set a timeout
req.setTimeout(10000, () => {
console.error('Request timeout');
req.destroy();
});
எடுத்துக்காட்டு வெளியீடு:
Response: {
userId: 1,
id: 1,
title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
body: "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
POST கோரிக்கைகளைச் செய்தல்
const https = require('https');
const { URL } = require('url');
// Request data
const postData = JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
});
// Parse the URL
const url = new URL('https://jsonplaceholder.typicode.com/posts');
// Request options
const options = {
hostname: url.hostname,
port: 443,
path: url.pathname,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData),
'User-Agent': 'MySecureApp/1.0',
'Accept': 'application/json'
},
timeout: 10000 // 10 seconds
};
console.log('Sending POST request to:', url.toString());
// Create the request
const req = https.request(options, (res) => {
console.log(`Status Code: ${res.statusCode}`);
console.log('Headers:', res.headers);
let responseData = '';
res.setEncoding('utf8');
// Collect response data
res.on('data', (chunk) => {
responseData += chunk;
});
// Process complete response
res.on('end', () => {
try {
const parsedData = JSON.parse(responseData);
console.log('Response:', parsedData);
} catch (e) {
console.error('Error parsing response:', e.message);
}
});
});
// Handle errors
req.on('error', (e) => {
console.error(`Request error: ${e.message}`);
});
// Set a timeout
req.setTimeout(15000, () => {
req.destroy(new Error('Request timeout after 15 seconds'));
});
// Write data to request body
req.write(postData);
// End the request
req.end();
HTTPS கோரிக்கைகளுக்கான சிறந்த நடைமுறைகள்:
- கோரிக்கையில் அனுப்புவதற்கு முன் எப்போதும் உள்ளீட்டுத் தரவைச் சரிபார்க்கவும் மற்றும் சுத்திகரிக்கவும்
- API விசைகள் போன்ற உணர்திறன் தகவல்களுக்கு சூழல் மாறிகள் பயன்படுத்தவும்
- சரியான பிழை கையாளுதல் மற்றும் நேர முடிவுகளை செயல்படுத்தவும்
- பொருத்தமான தலைப்புகளை அமைக்கவும் (Content-Type, Accept, User-Agent)
- திருப்பி விடுதல்களை சரியாக கையாளவும் (3xx நிலை குறியீடுகள்)
- தற்காலிக தோல்விகளுக்கு மீண்டும் முயற்சி தர்க்கத்தை செயல்படுத்தவும்
- மிகவும் சிக்கலான சூழ்நிலைகளுக்கு axios அல்லது node-fetch போன்ற நூலகத்தைப் பயன்படுத்தவும்
Express.js உடன் HTTPS சேவையகம்
நீங்கள் முக்கிய HTTPS தொகுதியை நேரடியாகப் பயன்படுத்தலாம், ஆனால் பெரும்பாலான Node.js பயன்பாடுகள் HTTP/HTTPS கோரிக்கைகளைக் கையாள Express.js போன்ற வலை கட்டமைப்பைப் பயன்படுத்துகின்றன.
Express.js உடன் அடிப்படை HTTPS சேவையகம்
const express = require('express');
const https = require('https');
const fs = require('fs');
const path = require('path');
const helmet = require('helmet'); // Security middleware
// Create Express app
const app = express();
// Security middleware
app.use(helmet());
// Parse JSON and URL-encoded bodies
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Serve static files from 'public' directory
app.use(express.static(path.join(__dirname, 'public'), {
dotfiles: 'ignore',
etag: true,
extensions: ['html', 'htm'],
index: 'index.html',
maxAge: '1d',
redirect: true
}));
// Routes
app.get('/', (req, res) => {
res.send('Welcome to Secure Express Server
');
});
app.get('/api/status', (req, res) => {
res.json({
status: 'operational',
timestamp: new Date().toISOString(),
environment: process.env.NODE_ENV || 'development',
nodeVersion: process.version
});
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
// 404 handler
app.use((req, res) => {
res.status(404).json({ error: 'Not Found' });
});
// SSL/TLS options
const sslOptions = {
key: fs.readFileSync(path.join(__dirname, 'key.pem')),
cert: fs.readFileSync(path.join(__dirname, 'cert.pem')),
// Enable HTTP/2 if available
allowHTTP1: true,
// Recommended security options
minVersion: 'TLSv1.2',
ciphers: [
'TLS_AES_256_GCM_SHA384',
'TLS_CHACHA20_POLY1305_SHA256',
'TLS_AES_128_GCM_SHA256',
'ECDHE-RSA-AES128-GCM-SHA256',
'!DSS',
'!aNULL',
'!eNULL',
'!EXPORT',
'!DES',
'!RC4',
'!3DES',
'!MD5',
'!PSK'
].join(':'),
honorCipherOrder: true
};
// Create HTTPS server
const PORT = process.env.PORT || 3000;
const server = https.createServer(sslOptions, app);
// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
// Handle uncaught exceptions
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
// Perform cleanup and exit if needed
process.exit(1);
});
// Graceful shutdown
const gracefulShutdown = (signal) => {
console.log(`\nReceived ${signal}. Shutting down gracefully...`);
server.close(() => {
console.log('HTTP server closed.');
// Close database connections, etc.
process.exit(0);
});
// Force close server after 10 seconds
setTimeout(() => {
console.error('Forcing shutdown...');
process.exit(1);
}, 10000);
};
// Listen for shutdown signals
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);
// Start the server
const HOST = process.env.HOST || '0.0.0.0';
server.listen(PORT, HOST, () => {
console.log(`Express server running at https://${HOST}:${PORT}`);
console.log('Environment:', process.env.NODE_ENV || 'development');
console.log('Press Ctrl+C to stop the server');
});
சூழல் மாறிகளைப் பயன்படுத்துதல்
.env கோப்பு
NODE_ENV=development
PORT=3000
HOST=0.0.0.0
SSL_KEY_PATH=./key.pem
SSL_CERT_PATH=./cert.pem
சூழல் மாறிகளை ஏற்றுதல்
require('dotenv').config();
// Access environment variables
const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '0.0.0.0';
const sslOptions = {
key: fs.readFileSync(process.env.SSL_KEY_PATH),
cert: fs.readFileSync(process.env.SSL_CERT_PATH)
// ... other options
};
உற்பத்தி விரிவாக்கம்
உற்பத்தியில், உங்கள் Node.js பயன்பாட்டின் முன்னால் Nginx அல்லது Apache போன்ற ரிவர்ஸ் ப்ராக்ஸியைப் பயன்படுத்த பரிந்துரைக்கப்படுகிறது. இது வழங்குகிறது:
எடுத்துக்காட்டு Nginx கட்டமைப்பு
server {
listen 443 ssl http2;
server_name yourdomain.com;
# SSL configuration
ssl_certificate /path/to/your/cert.pem;
ssl_certificate_key /path/to/your/key.pem;
# Security headers
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
# Proxy to Node.js app
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Serve static files directly
location /static/ {
root /path/to/your/app/public;
expires 30d;
access_log off;
}
}
# Redirect HTTP to HTTPS
server {
listen 80;
server_name yourdomain.com;
return 301 https://$host$request_uri;
}
Express.js உடன் HTTPS க்கான சிறந்த நடைமுறைகள்:
- பாதுகாப்பு தலைப்புகளுக்கு எப்போதும் ஹெல்மெட் மிடில்வேர் பயன்படுத்தவும்
- பாதுகாப்பான அமர்வு விருப்பங்களை அமைக்கவும் (அமர்வுகளைப் பயன்படுத்தினால்)
- கட்டமைப்புக்கு சூழல் மாறிகள் பயன்படுத்தவும்
- சரியான பிழை கையாளுதல் மற்றும் லாக்கிங் செயல்படுத்தவும்
- உற்பத்தியில் ரிவர்ஸ் ப்ராக்ஸி பயன்படுத்தவும்
- உங்கள் சார்புகளை நாள்பட்ட வைத்திருங்கள்
- சிறந்த செயல்திறனுக்கு HTTP/2 பயன்படுத்தவும்
- துஷ்பிரயோகத்தைத் தடுக்க விகித வரம்பை செயல்படுத்தவும்
- உங்கள் API வெவ்வேறு டொமைன்களில் இருந்து அணுகப்பட்டால் CORS மிடில்வேர் பயன்படுத்தவும்
Node.js உடன் HTTP/2
HTTP/2 என்பது HTTP நெறிமுறையின் ஒரு முக்கிய திருத்தமாகும், இது HTTP/1.1 க்கு மேல் குறிப்பிடத்தக்க செயல்திறன் மேம்பாடுகளை வழங்குகிறது. HTTPS உடன் இணைந்து, இது நவீன வலை பயன்பாடுகளுக்கு பாதுகாப்பு மற்றும் செயல்திறன் நன்மைகளை வழங்குகிறது.
HTTP/2 இன் நன்மைகள்
HTTP/2 சேவையக எடுத்துக்காட்டு
const http2 = require('http2');
const fs = require('fs');
const path = require('path');
// SSL/TLS options
const serverOptions = {
key: fs.readFileSync(path.join(__dirname, 'key.pem')),
cert: fs.readFileSync(path.join(__dirname, 'cert.pem')),
allowHTTP1: true, // Fallback to HTTP/1.1 if needed
// Recommended security settings
minVersion: 'TLSv1.2',
ciphers: [
'TLS_AES_256_GCM_SHA384',
'TLS_CHACHA20_POLY1305_SHA256',
'TLS_AES_128_GCM_SHA256',
'ECDHE-ECDSA-AES256-GCM-SHA384',
'!aNULL',
'!eNULL',
'!EXPORT',
'!DES',
'!RC4',
'!3DES',
'!MD5',
'!PSK'
].join(':'),
honorCipherOrder: true
};
// Create HTTP/2 server
const server = http2.createSecureServer(serverOptions);
// Handle incoming requests
server.on('stream', (stream, headers) => {
const method = headers[':method'];
const path = headers[':path'];
const scheme = headers[':scheme'];
const authority = headers[':authority'];
console.log(`${method} ${path} (HTTP/2)`);
// Handle different routes
if (path === '/') {
// Set response headers
stream.respond({
'content-type': 'text/html; charset=utf-8',
':status': 200,
'x-powered-by': 'Node.js HTTP/2',
'cache-control': 'public, max-age=3600'
});
// Send HTML response
stream.end(`
HTTP/2 Server
Hello from HTTP/2 Server!
This page is served over HTTP/2.
Loading data...
`);
}
// API endpoint
else if (path === '/api/data' && method === 'GET') {
stream.respond({
'content-type': 'application/json',
':status': 200,
'cache-control': 'no-cache'
});
stream.end(JSON.stringify({
message: 'Data from HTTP/2 API',
timestamp: new Date().toISOString(),
protocol: 'HTTP/2',
server: 'Node.js HTTP/2 Server'
}));
}
// Server Push example
else if (path === '/push') {
// Push additional resources
stream.pushStream({ ':path': '/styles.css' }, (err, pushStream) => {
if (err) {
console.error('Push stream error:', err);
return;
}
pushStream.respond({
'content-type': 'text/css',
':status': 200
});
pushStream.end('body { font-family: Arial, sans-serif; margin: 2em; }');
});
stream.respond({
'content-type': 'text/html; charset=utf-8',
':status': 200
});
stream.end('Server Push Example
');
}
// 404 Not Found
else {
stream.respond({
'content-type': 'text/plain',
':status': 404
});
stream.end('404 - Not Found');
}
});
// Handle errors
server.on('error', (err) => {
console.error('Server error:', err);
process.exit(1);
});
// Start the server
const PORT = process.env.PORT || 8443;
server.listen(PORT, '0.0.0.0', () => {
console.log(`HTTP/2 server running at https://localhost:${PORT}`);
console.log('Environment:', process.env.NODE_ENV || 'development');
console.log('Press Ctrl+C to stop the server');
});
// Graceful shutdown
const gracefulShutdown = (signal) => {
console.log(`\nReceived ${signal}. Shutting down gracefully...`);
server.close(() => {
console.log('HTTP/2 server closed.');
process.exit(0);
});
// Force close server after 10 seconds
setTimeout(() => {
console.error('Forcing shutdown...');
process.exit(1);
}, 10000);
};
// Listen for shutdown signals
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);
குறிப்பு:
HTTP/2 க்கு உலாவிகளில் HTTPS தேவைப்படுகிறது, நெறிமுறை தன்னை குறியாக்கம் தேவைப்படவில்லை. அனைத்து முக்கிய உலாவிகளும் TLS (HTTPS) மூலம் HTTP/2 ஐ மட்டுமே ஆதரிக்கின்றன.
HTTP மற்றும் HTTPS ஐ ஒப்பிடுதல்
| அம்சம் | HTTP | HTTPS |
|---|---|---|
| தரவு குறியாக்கம் | இல்லை (எளிய உரை) | ஆம் (குறியாக்கப்பட்டது) |
| சேவையக அங்கீகாரம் | இல்லை | ஆம் (சான்றிதழ்கள் மூலம்) |
| தரவு ஒருமைப்பாடு | பாதுகாப்பு இல்லை | பாதுகாக்கப்பட்டது (திருத்தம் கண்டறியப்பட்டது) |
| இயல்புநிலை போர்ட் | 80 | 443 |
| செயல்திறன் | வேகமான | சிறிது மேலோட்டம் (ஆனால் HTTP/2 உடன் மேம்படுத்தப்பட்டது) |
| SEO தரவரிசை | குறைந்த | அதிக (Google HTTPS ஐ விரும்புகிறது) |
| அமைப்பு சிக்கலானது | எளிமையான | மிகவும் சிக்கலான (சான்றிதழ்கள் தேவை) |
சுருக்கம் மற்றும் சிறந்த நடைமுறைகள்
இந்த விரிவான வழிகாட்டியில், Node.js HTTPS தொகுதி மற்றும் பாதுகாப்பான வலை பயன்பாடுகளை உருவாக்குவதற்கான அதன் திறன்களை ஆராய்ந்தோம். முக்கிய புள்ளிகள் மற்றும் சிறந்த நடைமுறைகளின் சுருக்கம் இங்கே:
முக்கிய Takeaways
பாதுகாப்பு சரிபார்ப்புப் பட்டியல்
உங்கள் HTTPS-இயலும் பயன்பாட்டை உற்பத்தியில் விரிவாக்குவதற்கு முன், சரிபார்க்கவும்:
நினைவில் கொள்ளுங்கள்:
பாதுகாப்பு என்பது தொடர்ச்சியான செயல்முறையாகும். உங்கள் விண்ணப்பத்தை தவறாமல் தணிக்கை செய்யுங்கள், சார்புகளை புதுப்பித்த வைத்திருங்கள், மற்றும் சமீபத்திய பாதுகாப்பு சிறந்த நடைமுறைகள் மற்றும் பாதிப்புகள் பற்றி தகவல் வைத்திருங்கள்.