- sistemato timeout corto
- corretto errori sulla generazione del PDF - corretto alcune directory - corretto fs.promise - corretto CORS !
This commit is contained in:
@@ -9,7 +9,7 @@ const { ObjectId } = require('mongodb');
|
|||||||
mongoose.Promise = global.Promise;
|
mongoose.Promise = global.Promise;
|
||||||
mongoose.level = "F";
|
mongoose.level = "F";
|
||||||
|
|
||||||
const fs = require('fs');
|
const fs = require('fs'); // 👈 Usa il modulo promises
|
||||||
|
|
||||||
// Resolving error Unknown modifier: $pushAll
|
// Resolving error Unknown modifier: $pushAll
|
||||||
mongoose.plugin(schema => {
|
mongoose.plugin(schema => {
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ const tools = require('../tools/general');
|
|||||||
|
|
||||||
const Macro = require('../modules/Macro'); // Importa la classe Macro
|
const Macro = require('../modules/Macro'); // Importa la classe Macro
|
||||||
|
|
||||||
const fs = require('fs');
|
const fs = require('fs'); // 👈 Usa il modulo promises
|
||||||
|
|
||||||
const { City } = require('../models/city');
|
const { City } = require('../models/city');
|
||||||
const Product = require('../models/product');
|
const Product = require('../models/product');
|
||||||
@@ -140,7 +140,9 @@ async function compressPdf(inputFile, outputFile, compressione) {
|
|||||||
const hasTempFolder = tools.isFileExists(tempFolder);
|
const hasTempFolder = tools.isFileExists(tempFolder);
|
||||||
|
|
||||||
if (!hasTempFolder) {
|
if (!hasTempFolder) {
|
||||||
|
console.log('creo directory', tempFolder);
|
||||||
await fs.mkdir(tempFolder); // Usa la versione promessa di mkdir
|
await fs.mkdir(tempFolder); // Usa la versione promessa di mkdir
|
||||||
|
console.log('✅ directory creata', tempFolder);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
|||||||
27
src/server/router/api_router.js
Normal file
27
src/server/router/api_router.js
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
const express = require("express");
|
||||||
|
const { authenticate } = require("../middleware/authenticate");
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
router.post('/test-lungo', authenticate, (req, res) => {
|
||||||
|
const timeout = req.body.timeout;
|
||||||
|
|
||||||
|
console.log(`🕙 Richiesta iniziata con timeout=${timeout}`);
|
||||||
|
|
||||||
|
// Simuliamo un'elaborazione lunga
|
||||||
|
const durataMs = timeout - 2000;
|
||||||
|
setTimeout(() => {
|
||||||
|
console.log(`✅ Elaborazione completata di ${durataMs} ms`);
|
||||||
|
res.json({ ok: true, message: `✅ Richiesta completata con successo! (${durataMs})` });
|
||||||
|
}, durataMs);
|
||||||
|
|
||||||
|
// Verifico se la richiesta va a buon fine
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!res.headersSent) {
|
||||||
|
res.status(500).json({ ok: false, message: '❌ Errore durante l\'elaborazione della richiesta!' });
|
||||||
|
}
|
||||||
|
}, durataMs + 1000);
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
|
|
||||||
@@ -2351,7 +2351,7 @@ function uploadFile(req, res, version) {
|
|||||||
// console.log('mydir', mydir);
|
// console.log('mydir', mydir);
|
||||||
|
|
||||||
// Create Dir if doesn't exist:
|
// Create Dir if doesn't exist:
|
||||||
const rismk = tools.mkdirpath(mydir);
|
const rismk = await tools.mkdirpath(mydir);
|
||||||
|
|
||||||
let filename = file.originalFilename;
|
let filename = file.originalFilename;
|
||||||
let ext = path.extname(filename);
|
let ext = path.extname(filename);
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ const _ = require('lodash');
|
|||||||
const cors = require('cors');
|
const cors = require('cors');
|
||||||
|
|
||||||
// console.log(" 2) fs");
|
// console.log(" 2) fs");
|
||||||
const fs = require('fs');
|
const fs = require('fs'); // 👈 Usa il modulo promises
|
||||||
|
|
||||||
var https = require('https');
|
var https = require('https');
|
||||||
var http = require('http');
|
var http = require('http');
|
||||||
@@ -136,6 +136,7 @@ connectToDatabase(connectionUrl, options)
|
|||||||
const mygen_router = require('./router/mygen_router');
|
const mygen_router = require('./router/mygen_router');
|
||||||
const aitools_router = require('./router/aitools_router');
|
const aitools_router = require('./router/aitools_router');
|
||||||
const article_router = require('./router/articleRoutes');
|
const article_router = require('./router/articleRoutes');
|
||||||
|
const api_router = require('./router/api_router');
|
||||||
|
|
||||||
const { MyEvent } = require('./models/myevent');
|
const { MyEvent } = require('./models/myevent');
|
||||||
|
|
||||||
@@ -245,6 +246,7 @@ connectToDatabase(connectionUrl, options)
|
|||||||
app.use('/mygen', mygen_router);
|
app.use('/mygen', mygen_router);
|
||||||
app.use('/aitools', aitools_router);
|
app.use('/aitools', aitools_router);
|
||||||
app.use('/apisqlsrv', article_router);
|
app.use('/apisqlsrv', article_router);
|
||||||
|
app.use('/api', api_router);
|
||||||
|
|
||||||
mystart();
|
mystart();
|
||||||
});
|
});
|
||||||
@@ -531,16 +533,16 @@ connectToDatabase(connectionUrl, options)
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
// console.log('checkdir', folderprof);
|
// console.log('checkdir', folderprof);
|
||||||
if (!fs.existsSync(folderprof)) {
|
if (!tools.existsSync(folderprof)) {
|
||||||
console.log('*** Creadir', folderprof);
|
console.log('*** Creadir', folderprof);
|
||||||
fs.mkdirSync(folderprof);
|
await fs.mkdirSync(folderprof);
|
||||||
}
|
}
|
||||||
|
|
||||||
folderprof = dir + 'profile/' + myuser.username + '/' + table;
|
folderprof = dir + 'profile/' + myuser.username + '/' + table;
|
||||||
// console.log('checkdir', folderprof);
|
// console.log('checkdir', folderprof);
|
||||||
if (!fs.existsSync(folderprof)) {
|
if (!tools.existsSync(folderprof)) {
|
||||||
console.log('creadir', folderprof);
|
console.log('creadir', folderprof);
|
||||||
fs.mkdirSync(folderprof);
|
await fs.mkdirSync(folderprof);
|
||||||
}
|
}
|
||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
}
|
}
|
||||||
@@ -671,99 +673,106 @@ connectToDatabase(connectionUrl, options)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Funzione migliorata per ottenere chiave e certificato
|
||||||
function getCredentials(hostname) {
|
function getCredentials(hostname) {
|
||||||
|
try {
|
||||||
|
let keyPath, certPath;
|
||||||
|
|
||||||
if (NUOVO_METODO_TEST) {
|
if (NUOVO_METODO_TEST) {
|
||||||
if (METODO_MULTI_CORS) {
|
if (METODO_MULTI_CORS) {
|
||||||
const fileprivkey = `/etc/letsencrypt/live/${hostname}/` + process.env.PATH_CERT_KEY;
|
// Percorso basato su hostname (Let's Encrypt)
|
||||||
const filecert = `/etc/letsencrypt/live/${hostname}/` + process.env.PATH_SERVER_CRT;
|
keyPath = `/etc/letsencrypt/live/${hostname}/${process.env.PATH_CERT_KEY}`;
|
||||||
|
certPath = `/etc/letsencrypt/live/${hostname}/${process.env.PATH_SERVER_CRT}`;
|
||||||
|
} else {
|
||||||
|
// Percorso relativo
|
||||||
|
keyPath = path.resolve(`./${process.env.PATH_CERT_KEY}`);
|
||||||
|
certPath = path.resolve(`./${process.env.PATH_SERVER_CRT}`);
|
||||||
|
}
|
||||||
|
|
||||||
console.log('fileprivkey: ', fileprivkey, ' filecert: ', filecert);
|
// Verifica esistenza file
|
||||||
|
if (!tools.existsSync(keyPath)) {
|
||||||
|
throw new Error(`Chiave privata non trovata: ${keyPath}`);
|
||||||
|
}
|
||||||
|
if (!tools.existsSync(certPath)) {
|
||||||
|
throw new Error(`Certificato non trovato: ${certPath}`);
|
||||||
|
}
|
||||||
|
|
||||||
/* return {
|
// Leggi chiave e certificato
|
||||||
|
const key = fs.readFileSync(keyPath, 'utf8');
|
||||||
|
const cert = fs.readFileSync(certPath, 'utf8');
|
||||||
|
|
||||||
SNICallback: function (hostname, callback) {
|
// Restituisci oggetto con credenziali + configurazione TLS avanzata
|
||||||
console.log('hostname: ', hostname);
|
return {
|
||||||
if (domains.includes(hostname)) {
|
key,
|
||||||
const fileprivkey = `/etc/letsencrypt/live/${hostname}/privkey.pem`;
|
cert,
|
||||||
const filecert = `/etc/letsencrypt/live/${hostname}/fullchain.pem`;
|
ciphers:
|
||||||
|
'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384',
|
||||||
// console.log('fileprivkey: ', fileprivkey, ' filecert: ', filecert);
|
honorCipherOrder: true,
|
||||||
|
secureOptions: require('constants').OPENSSL_OPTIONS_TLS_NODELAY,
|
||||||
const domainCert = {
|
secureProtocol: 'TLSv1_2_method', // Forza TLS 1.2+ (meglio se usi TLSv1_3)
|
||||||
key: fs.readFileSync(fileprivkey, "utf8"),
|
|
||||||
cert: fs.readFileSync(filecert, "utf8"),
|
|
||||||
};
|
};
|
||||||
callback(null, domainCert);
|
|
||||||
} else {
|
} else {
|
||||||
callback(null, { key: privateKey, cert: certificate });
|
// Metodo legacy (opzionale)
|
||||||
|
throw new Error('Metodo legacy non supportato');
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
};*/
|
|
||||||
|
|
||||||
try {
|
|
||||||
const key = fs.readFileSync(fileprivkey, 'utf8');
|
|
||||||
const cert = fs.readFileSync(filecert, 'utf8');
|
|
||||||
return { key, cert };
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`Errore nel caricamento delle credenziali per ${hostname}:`, error);
|
console.error(`[getCredentials] Errore per ${hostname}:`, error.message);
|
||||||
// Gestisci l'errore, per esempio ritorna null o lancia un'eccezione
|
throw error;
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const keyStream = path.resolve(`./${process.env.PATH_CERT_KEY}`);
|
|
||||||
const certificateStream = path.resolve(`./${process.env.PATH_SERVER_CRT}`);
|
|
||||||
|
|
||||||
const privateKey = fs.readFileSync(keyStream, 'utf8');
|
|
||||||
const certificate = fs.readFileSync(certificateStream, 'utf8');
|
|
||||||
|
|
||||||
return { key: privateKey, cert: certificate };
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Caso di default non specificato, potrebbe essere necessario aggiungere una gestione degli errori qui
|
// 🔧 Funzione factory per creare e configurare un server HTTPS
|
||||||
|
function createHttpsServer({ hostname, port, website, app, credentials, timeoutMinutes = 5 }) {
|
||||||
|
const server = https.createServer(credentials, app);
|
||||||
|
|
||||||
|
const timeoutMs = 1000 * 60 * timeoutMinutes;
|
||||||
|
|
||||||
|
// ⏱️ Timeout globale per la connessione TCP
|
||||||
|
server.setTimeout(timeoutMs, () => {
|
||||||
|
console.log(`TCP timeout su server: ${hostname}:${port}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ⏱️ Timeout per singola richiesta HTTP
|
||||||
|
server.on('request', (req, res) => {
|
||||||
|
req.setTimeout(timeoutMs);
|
||||||
|
res.setTimeout(timeoutMs);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 📡 Eventuali altri eventi utili
|
||||||
|
server.on('clientError', (err, socket) => {
|
||||||
|
console.error(`Client error su ${hostname}:${port}:`, err.message);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Avvia il server
|
||||||
|
server.listen(port, () => {
|
||||||
|
console.log(
|
||||||
|
'⭐️⭐️⭐️⭐️⭐️ HTTPS server: %s Port: %d%s',
|
||||||
|
hostname,
|
||||||
|
port,
|
||||||
|
website ? ' WebSite = ' + website : ''
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
return server;
|
||||||
}
|
}
|
||||||
|
|
||||||
function startServer(app, port) {
|
function parseDomains() {
|
||||||
try {
|
|
||||||
const isProduction = ['production', 'test'].includes(process.env.NODE_ENV);
|
|
||||||
|
|
||||||
let domains = [];
|
let domains = [];
|
||||||
let domains_allowed = [];
|
let domainsAllowed = [];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (process.env.DOMAINS) domains = JSON.parse(process.env.DOMAINS);
|
if (process.env.DOMAINS) domains = JSON.parse(process.env.DOMAINS);
|
||||||
if (process.env.DOMAINS_ALLOWED) domains_allowed = JSON.parse(process.env.DOMAINS_ALLOWED);
|
if (process.env.DOMAINS_ALLOWED) domainsAllowed = JSON.parse(process.env.DOMAINS_ALLOWED);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Errore durante la conversione della stringa DOMAINS:', error);
|
console.error('Errore parsing DOMAINS:', error);
|
||||||
|
}
|
||||||
|
return { domains, domainsAllowed };
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('domains', domains);
|
function buildAllowedOrigins(domains, domainsAllowed, isProduction) {
|
||||||
|
|
||||||
let httpsServer = null;
|
|
||||||
let httpServer = null;
|
|
||||||
|
|
||||||
console.log('isProduction', isProduction);
|
|
||||||
|
|
||||||
const NOCORS = false;
|
|
||||||
|
|
||||||
const ISDEBUG = false;
|
|
||||||
|
|
||||||
let corsOptions = {};
|
|
||||||
|
|
||||||
if (NOCORS) {
|
|
||||||
console.log('NOCORS');
|
|
||||||
corsOptions = {
|
|
||||||
exposedHeaders: ['x-auth', 'x-refrtok'], // Intestazioni da esporre al client
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
console.log('WITH CORS');
|
|
||||||
let credentials = true;
|
|
||||||
|
|
||||||
let allowedOrigins = null;
|
|
||||||
|
|
||||||
if (!isProduction) {
|
if (!isProduction) {
|
||||||
allowedOrigins = 'https://localhost:3000';
|
return ['https://localhost:3000', 'https://localhost:8089', 'https://localhost:8084', 'https://localhost:8088'];
|
||||||
} else {
|
}
|
||||||
allowedOrigins = domains.flatMap((domain) => [
|
|
||||||
|
const baseOrigins = domains.flatMap((domain) => [
|
||||||
`https://${domain.hostname}`,
|
`https://${domain.hostname}`,
|
||||||
`https://api.${domain.hostname}`,
|
`https://api.${domain.hostname}`,
|
||||||
`https://test.${domain.hostname}`,
|
`https://test.${domain.hostname}`,
|
||||||
@@ -774,49 +783,43 @@ connectToDatabase(connectionUrl, options)
|
|||||||
`http://testapi.${domain.hostname}`,
|
`http://testapi.${domain.hostname}`,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Aggiungi i domini da DOMAINS_ALLOWED
|
const allowedExtra = domainsAllowed.flatMap((domain) => [`https://${domain}`, `http://${domain}`]);
|
||||||
allowedOrigins = allowedOrigins.concat(
|
|
||||||
domains_allowed.map((domain) => [`https://${domain}`, `http://${domain}`]).flat()
|
return [...baseOrigins, ...allowedExtra];
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('allowedOrigins', allowedOrigins);
|
function createCorsOptions(domains, domainsAllowed, isProduction, noCors = false) {
|
||||||
|
if (noCors) {
|
||||||
let myorigin = '*';
|
console.log('NOCORS mode enabled');
|
||||||
|
return {
|
||||||
if (domains.length > 0) {
|
exposedHeaders: ['x-auth', 'x-refrtok'],
|
||||||
myorigin = (origin, callback) => {
|
|
||||||
try {
|
|
||||||
// Validazione dell'input
|
|
||||||
if (origin === undefined) {
|
|
||||||
console.log('✅ Origin UNDEFINED... vado avanti lo stesso !');
|
|
||||||
return callback(null, true);
|
|
||||||
}
|
|
||||||
if (!origin || typeof origin !== 'string' || !/^https?:\/\/[^\s/$.?#].[^\s]*$/.test(origin)) {
|
|
||||||
console.error('❌ Origine non valida:', origin);
|
|
||||||
return callback(new Error('Origine non valida'), false);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Controllo delle origini consentite
|
|
||||||
if (allowedOrigins.includes(origin)) {
|
|
||||||
// console.log('✅ Origine consentita:', origin);
|
|
||||||
return callback(null, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Blocco delle origini non autorizzate
|
|
||||||
console.warn('❌ Origine bloccata:', origin);
|
|
||||||
return callback(new Error('CORS non permesso per questa origine'), false);
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Errore durante la verifica dell'origine:", error.message);
|
|
||||||
return callback(error, false);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Configurazione CORS dettagliata
|
const allowedOrigins = buildAllowedOrigins(domains, domainsAllowed, isProduction);
|
||||||
const corsOptions = {
|
|
||||||
origin: myorigin,
|
const originValidator = (origin, callback) => {
|
||||||
credentials,
|
if (!origin) {
|
||||||
|
console.log('✅ Origin undefined or empty — allowing');
|
||||||
|
return callback(null, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof origin !== 'string' || !/^https?:\/\/[^\s/$.?#].[^\s]*$/.test(origin)) {
|
||||||
|
console.error('❌ Invalid origin:', origin);
|
||||||
|
return callback(new Error('Origine non valida'), false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (allowedOrigins.includes(origin)) {
|
||||||
|
return callback(null, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.warn('❌ Origin blocked:', origin);
|
||||||
|
return callback(new Error('CORS non permesso per questa origine'), false);
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
origin: originValidator,
|
||||||
|
credentials: true,
|
||||||
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
|
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
|
||||||
allowedHeaders: [
|
allowedHeaders: [
|
||||||
'Origin',
|
'Origin',
|
||||||
@@ -828,52 +831,32 @@ connectToDatabase(connectionUrl, options)
|
|||||||
'x-refrtok',
|
'x-refrtok',
|
||||||
],
|
],
|
||||||
exposedHeaders: ['x-auth', 'x-refrtok'],
|
exposedHeaders: ['x-auth', 'x-refrtok'],
|
||||||
maxAge: 86400, // Preflight cache 24 ore
|
maxAge: 86400,
|
||||||
preflightContinue: false,
|
preflightContinue: false,
|
||||||
optionsSuccessStatus: 204,
|
optionsSuccessStatus: 204,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Applica CORS come primo middleware
|
|
||||||
app.use(cors(corsOptions));
|
|
||||||
|
|
||||||
// HO AGGIUNTO QUESTA RIGA PER IL CORS !!!!!!!
|
|
||||||
app.use(express.json()); // Middleware per il parsing del corpo JSON
|
|
||||||
|
|
||||||
app.options('*', cors(corsOptions)); // Gestisce tutte le richieste OPTIONS
|
|
||||||
|
|
||||||
// Middleware personalizzato per assicurare gli headers CORS
|
|
||||||
/*app.use((req, res, next) => {
|
|
||||||
const origin = req.headers.origin || '*';
|
|
||||||
if (allowedOrigins.includes(origin) || corsOptions.origin === '*') {
|
|
||||||
// console.log(' ... ORIGIN', origin);
|
|
||||||
res.setHeader('Access-Control-Allow-Origin', origin);
|
|
||||||
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
|
||||||
res.setHeader('Access-Control-Allow-Credentials', 'true');
|
|
||||||
res.setHeader('Access-Control-Expose-Headers', 'x-auth, x-refrtok');
|
|
||||||
}
|
}
|
||||||
next();
|
|
||||||
});*/
|
|
||||||
|
|
||||||
// Log middleware per debug
|
function setupMiddleware(app, corsOptions, isDebug = false) {
|
||||||
|
app.use(cors(corsOptions));
|
||||||
|
app.use(express.json());
|
||||||
|
app.options('*', cors(corsOptions));
|
||||||
|
|
||||||
|
if (isDebug) {
|
||||||
app.use((req, res, next) => {
|
app.use((req, res, next) => {
|
||||||
if (ISDEBUG) {
|
|
||||||
console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
|
console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
|
||||||
console.log('Request Headers:', req.headers);
|
console.log('Request Headers:', req.headers);
|
||||||
}
|
|
||||||
|
|
||||||
// Intercetta la risposta per loggare gli headers
|
|
||||||
const oldSend = res.send;
|
const oldSend = res.send;
|
||||||
res.send = function (...args) {
|
res.send = function (...args) {
|
||||||
if (ISDEBUG) {
|
|
||||||
console.log('Response Headers:', res.getHeaders());
|
console.log('Response Headers:', res.getHeaders());
|
||||||
}
|
|
||||||
return oldSend.apply(res, args);
|
return oldSend.apply(res, args);
|
||||||
};
|
};
|
||||||
|
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Gestione errori CORS
|
|
||||||
app.use((err, req, res, next) => {
|
app.use((err, req, res, next) => {
|
||||||
if (err.message === 'CORS non permesso per questa origine') {
|
if (err.message === 'CORS non permesso per questa origine') {
|
||||||
console.error('❌ Errore CORS:', {
|
console.error('❌ Errore CORS:', {
|
||||||
@@ -881,106 +864,88 @@ connectToDatabase(connectionUrl, options)
|
|||||||
method: req.method,
|
method: req.method,
|
||||||
path: req.path,
|
path: req.path,
|
||||||
});
|
});
|
||||||
res.status(403).json({
|
return res.status(403).json({
|
||||||
error: '❌ CORS non permesso per questa origine (' + req.headers.origin + ')',
|
error: `❌ CORS non permesso per questa origine (${req.headers.origin})`,
|
||||||
origin: req.headers.origin,
|
origin: req.headers.origin,
|
||||||
});
|
});
|
||||||
} else {
|
|
||||||
next(err);
|
|
||||||
}
|
}
|
||||||
|
next(err);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function createHttpOrHttpsServer(app, port, isProduction, domains) {
|
||||||
if (isProduction) {
|
if (isProduction) {
|
||||||
for (let i = 0; i < domains.length; i++) {
|
domains.forEach((domain) => {
|
||||||
const mycredentials = getCredentials(domains[i].hostname);
|
const credentials = getCredentials(domain.hostname);
|
||||||
// console.log('credentials: ', credentials);
|
createHttpsServer({
|
||||||
httpsServer = https.createServer(mycredentials, app);
|
hostname: domain.hostname,
|
||||||
console.log(
|
port: domain.port,
|
||||||
'⭐️⭐️⭐️⭐️⭐️ HTTPS server: ' + domains[i].hostname + ' Port:',
|
website: domain.website,
|
||||||
domains[i].port + (domains[i].website ? 'WebSite = ' + domains[i].website : '')
|
app,
|
||||||
);
|
credentials,
|
||||||
httpsServer.listen(domains[i].port);
|
timeoutMinutes: 6,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
if (process.env.HTTPS_LOCALHOST === 'true') {
|
if (process.env.HTTPS_LOCALHOST === 'true') {
|
||||||
let mycredentials = null;
|
|
||||||
try {
|
try {
|
||||||
const keyStream = path.resolve(`./${process.env.PATH_CERT_KEY}`);
|
const key = fs.readFileSync(path.resolve(`./${process.env.PATH_CERT_KEY}`), 'utf8');
|
||||||
const certificateStream = path.resolve(`./${process.env.PATH_SERVER_CRT}`);
|
const cert = fs.readFileSync(path.resolve(`./${process.env.PATH_SERVER_CRT}`), 'utf8');
|
||||||
|
|
||||||
const privateKey = fs.readFileSync(keyStream, 'utf8');
|
const credentials = {
|
||||||
const certificate = fs.readFileSync(certificateStream, 'utf8');
|
key,
|
||||||
|
cert,
|
||||||
mycredentials = {
|
|
||||||
key: privateKey,
|
|
||||||
cert: certificate,
|
|
||||||
ciphers:
|
ciphers:
|
||||||
'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES256-SHA384',
|
'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES256-SHA384',
|
||||||
honorCipherOrder: true,
|
honorCipherOrder: true,
|
||||||
secureProtocol: 'TLSv1_2_method',
|
secureProtocol: 'TLSv1_2_method',
|
||||||
};
|
};
|
||||||
} catch (error) {
|
|
||||||
console.error('Errore durante la lettura dei file di certificazione, error:', error.message);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mycredentials) {
|
const httpsServer = https.createServer(credentials, app);
|
||||||
httpsServer = https.createServer(mycredentials, app);
|
|
||||||
console.log('⭐️⭐️⭐️ HTTPS server IN LOCALE : port', port);
|
|
||||||
httpsServer.listen(port);
|
httpsServer.listen(port);
|
||||||
} else {
|
console.log('⭐️ HTTPS server running locally on port', port);
|
||||||
httpServer = http.createServer(app);
|
return httpsServer;
|
||||||
if (httpServer) {
|
} catch (error) {
|
||||||
console.log('⭐️⭐️⭐️ HTTP server IN LOCALE : port', port);
|
console.error('Errore caricamento certificati HTTPS locali:', error.message);
|
||||||
|
// fallback HTTP server
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const httpServer = http.createServer(app);
|
||||||
httpServer.listen(port);
|
httpServer.listen(port);
|
||||||
}
|
console.log('⭐️ HTTP server running on port', port);
|
||||||
|
return httpServer;
|
||||||
}
|
}
|
||||||
|
|
||||||
// console.log('credentials', credentials);
|
function setupWebSocketServer(httpOrHttpsServer) {
|
||||||
} else {
|
if (!httpOrHttpsServer) {
|
||||||
httpServer = http.createServer(app);
|
console.error('Nessun server HTTP o HTTPS disponibile per WebSocket');
|
||||||
if (httpServer) {
|
return null;
|
||||||
console.log('⭐️⭐️⭐️ HTTP server IN LOCALE : port', port);
|
|
||||||
httpServer.listen(port);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let wss = null;
|
const wss = new WebSocket.Server({ server: httpOrHttpsServer });
|
||||||
|
|
||||||
if (httpsServer) {
|
|
||||||
wss = new WebSocket.Server({ server: httpsServer });
|
|
||||||
} else if (httpServer) {
|
|
||||||
wss = new WebSocket.Server({ server: httpServer });
|
|
||||||
} else {
|
|
||||||
// console.error('Nessun server HTTP o HTTPS disponibile per WebSocket');
|
|
||||||
// process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (wss) {
|
|
||||||
wss.on('connection', (ws) => {
|
wss.on('connection', (ws) => {
|
||||||
console.log('Client socket connected...');
|
console.log('Client socket connected...');
|
||||||
|
|
||||||
const { User } = require('./models/user');
|
const { User } = require('./models/user');
|
||||||
|
const pty = require('node-pty');
|
||||||
let scriptProcess = null;
|
let scriptProcess = null;
|
||||||
|
|
||||||
const pty = require('node-pty');
|
|
||||||
|
|
||||||
ws.on('message', (message) => {
|
ws.on('message', (message) => {
|
||||||
const parsedMessage = JSON.parse(message);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (parsedMessage.type === 'start_script' && User.isAdminById(parsedMessage.user_id)) {
|
const parsed = JSON.parse(message);
|
||||||
if (scriptProcess) {
|
|
||||||
scriptProcess.kill();
|
if (parsed.type === 'start_script' && User.isAdminById(parsed.user_id)) {
|
||||||
|
if (scriptProcess) scriptProcess.kill();
|
||||||
|
|
||||||
|
const scriptPath = path.join(__dirname, '..', '..', parsed.scriptName);
|
||||||
|
if (!tools.existsSync(scriptPath)) {
|
||||||
|
return ws.send(JSON.stringify({ type: 'error', data: 'Script non trovato o non autorizzato' }));
|
||||||
}
|
}
|
||||||
|
|
||||||
const scriptPath = path.join(__dirname, '..', '..', '', parsedMessage.scriptName);
|
|
||||||
|
|
||||||
// Verifica che lo script esista e sia all'interno della directory consentita
|
|
||||||
if (fs.existsSync(scriptPath)) {
|
|
||||||
scriptProcess = pty.spawn('bash', [scriptPath], {
|
scriptProcess = pty.spawn('bash', [scriptPath], {
|
||||||
name: 'xterm-color',
|
name: 'xterm-color',
|
||||||
cols: 80,
|
cols: 80,
|
||||||
@@ -992,62 +957,68 @@ connectToDatabase(connectionUrl, options)
|
|||||||
let buffer = '';
|
let buffer = '';
|
||||||
scriptProcess.on('data', (data) => {
|
scriptProcess.on('data', (data) => {
|
||||||
buffer += data;
|
buffer += data;
|
||||||
|
ws.send(JSON.stringify({ type: 'output', data }));
|
||||||
|
|
||||||
// Invia l'output al client
|
|
||||||
ws.send(JSON.stringify({ type: 'output', data: data }));
|
|
||||||
|
|
||||||
// Controlla se c'è una richiesta di input
|
|
||||||
if (
|
if (
|
||||||
buffer &&
|
buffer.endsWith(': ') ||
|
||||||
(buffer.endsWith(': ') ||
|
|
||||||
buffer.includes('? ') ||
|
buffer.includes('? ') ||
|
||||||
buffer.toLowerCase().includes('password') ||
|
buffer.toLowerCase().includes('password') ||
|
||||||
buffer.includes('Inserisci') ||
|
buffer.includes('Inserisci') ||
|
||||||
buffer.includes('Inserted') ||
|
buffer.includes('Inserted') ||
|
||||||
buffer.includes('(Y'))
|
buffer.includes('(Y)')
|
||||||
) {
|
) {
|
||||||
ws.send(JSON.stringify({ type: 'input_required', prompt: data.trim() }));
|
ws.send(JSON.stringify({ type: 'input_required', prompt: data.trim() }));
|
||||||
buffer = '';
|
buffer = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pulisci il buffer se diventa troppo grande
|
if (buffer.length > 5024) buffer = buffer.slice(-500);
|
||||||
if (buffer.length > 5024) {
|
|
||||||
buffer = buffer.slice(-500);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
scriptProcess.on('exit', (code) => {
|
scriptProcess.on('exit', (code) => {
|
||||||
if (code === 0) {
|
const closeMsg = code === 0 ? '*** FINE SCRIPT ***' : `Script terminato con codice ${code}`;
|
||||||
ws.send(JSON.stringify({ type: 'close', data: `*** FINE SCRIPT ***` }));
|
ws.send(JSON.stringify({ type: 'close', data: closeMsg }));
|
||||||
} else {
|
|
||||||
ws.send(JSON.stringify({ type: 'close', data: `Script terminato con codice ${code}` }));
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
} else {
|
} else if (parsed.type === 'input') {
|
||||||
ws.send(JSON.stringify({ type: 'error', data: 'Script non trovato o non autorizzato' }));
|
|
||||||
}
|
|
||||||
} else if (parsedMessage.type === 'input') {
|
|
||||||
if (scriptProcess) {
|
if (scriptProcess) {
|
||||||
scriptProcess.write(parsedMessage.data + '\n');
|
scriptProcess.write(parsed.data + '\n');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (err) {
|
||||||
console.error("Errore durante l'elaborazione del messaggio:", error.message);
|
console.error("Errore durante l'elaborazione del messaggio:", err.message);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
ws.on('close', () => {
|
ws.on('close', () => {
|
||||||
console.log('*** Client socket disconnected');
|
console.log('*** Client socket disconnected');
|
||||||
if (scriptProcess) {
|
if (scriptProcess) scriptProcess.kill();
|
||||||
scriptProcess.kill();
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
} else {
|
|
||||||
console.error('Nessuna Socket Aperta con WebSocket !!');
|
return wss;
|
||||||
}
|
}
|
||||||
} catch (e) {
|
|
||||||
console.log('error startServer: ' + e);
|
function startServer(app, port) {
|
||||||
|
try {
|
||||||
|
const isProduction = ['production', 'test'].includes(process.env.NODE_ENV);
|
||||||
|
const ISDEBUG = false;
|
||||||
|
const NOCORS = false;
|
||||||
|
|
||||||
|
const { domains, domainsAllowed } = parseDomains();
|
||||||
|
|
||||||
|
console.log('domains:', domains);
|
||||||
|
console.log('isProduction:', isProduction);
|
||||||
|
|
||||||
|
const corsOptions = createCorsOptions(domains, domainsAllowed, isProduction, NOCORS);
|
||||||
|
|
||||||
|
setupMiddleware(app, corsOptions, ISDEBUG);
|
||||||
|
|
||||||
|
const server = createHttpOrHttpsServer(app, port, isProduction, domains);
|
||||||
|
|
||||||
|
const wss = setupWebSocketServer(server);
|
||||||
|
|
||||||
|
return { server, wss };
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Errore in startServer:', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -4160,7 +4160,7 @@ class Telegram {
|
|||||||
if (res.photos[0]) {
|
if (res.photos[0]) {
|
||||||
var file_id = res.photos[0][2].file_id;
|
var file_id = res.photos[0][2].file_id;
|
||||||
var file = bot.getFile(file_id);
|
var file = bot.getFile(file_id);
|
||||||
file.then(function (result) {
|
file.then(async function (result) {
|
||||||
|
|
||||||
const file_path = result.file_path;
|
const file_path = result.file_path;
|
||||||
const photo_url = 'https://api.telegram.org/file/bot' + token +
|
const photo_url = 'https://api.telegram.org/file/bot' + token +
|
||||||
@@ -4170,7 +4170,7 @@ class Telegram {
|
|||||||
myfileprofile += filename;
|
myfileprofile += filename;
|
||||||
|
|
||||||
const pathfile = tools.extractFilePath(myfileprofile);
|
const pathfile = tools.extractFilePath(myfileprofile);
|
||||||
tools.mkdirpath(pathfile);
|
await tools.mkdirpath(pathfile);
|
||||||
|
|
||||||
// console.log('2) myfileprofile', pathfile);
|
// console.log('2) myfileprofile', pathfile);
|
||||||
return tools.downloadImage(photo_url, myfileprofile).
|
return tools.downloadImage(photo_url, myfileprofile).
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
const os = require('os');
|
const os = require('os');
|
||||||
const fs = require('fs');
|
const fs = require('fs'); // 👈 Usa il modulo promises
|
||||||
const xml2js = require('xml2js');
|
const xml2js = require('xml2js');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const WebSocket = require('ws');
|
const WebSocket = require('ws');
|
||||||
@@ -445,7 +445,7 @@ class ImageDownloader {
|
|||||||
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
||||||
try {
|
try {
|
||||||
// Verifica se il filepath esiste già
|
// Verifica se il filepath esiste già
|
||||||
if (fs.existsSync(filepath)) {
|
if (await this.existsSync(filepath)) {
|
||||||
fs.unlinkSync(filepath);
|
fs.unlinkSync(filepath);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -533,7 +533,7 @@ class ImageDownloader {
|
|||||||
console.error(`❌ Errore nel tentativo ${attempt}/${maxRetries}:`, error.message);
|
console.error(`❌ Errore nel tentativo ${attempt}/${maxRetries}:`, error.message);
|
||||||
|
|
||||||
// Pulizia del file in caso di errore
|
// Pulizia del file in caso di errore
|
||||||
if (fs.existsSync(filepath)) {
|
if (await this.existsSync(filepath)) {
|
||||||
fs.unlinkSync(filepath);
|
fs.unlinkSync(filepath);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -554,6 +554,15 @@ class ImageDownloader {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async existsSync(tempFolder) {
|
||||||
|
try {
|
||||||
|
await fs.access(tempFolder);
|
||||||
|
// La directory esiste
|
||||||
|
} catch {
|
||||||
|
// La directory NON esiste
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Funzione per estrarre il nome del file dall'URL
|
// Funzione per estrarre il nome del file dall'URL
|
||||||
extractFileNameFromUrl(url) {
|
extractFileNameFromUrl(url) {
|
||||||
const match = url.match(/\/([^/?#]+)(?:[?#]|$)/);
|
const match = url.match(/\/([^/?#]+)(?:[?#]|$)/);
|
||||||
@@ -727,6 +736,15 @@ module.exports = {
|
|||||||
console.log(args);
|
console.log(args);
|
||||||
},
|
},
|
||||||
|
|
||||||
|
existsSync: async function (tempFolder) {
|
||||||
|
try {
|
||||||
|
await fs.access(tempFolder);
|
||||||
|
// La directory esiste
|
||||||
|
} catch {
|
||||||
|
// La directory NON esiste
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
mylogserr: function (...args) {
|
mylogserr: function (...args) {
|
||||||
console.error(args);
|
console.error(args);
|
||||||
},
|
},
|
||||||
@@ -4184,15 +4202,15 @@ module.exports = {
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
mkdirpath(dirPath) {
|
async mkdirpath(dirPath) {
|
||||||
try {
|
try {
|
||||||
if (!fs.existsSync(dirPath)) {
|
if (!await this.existsSync(dirPath)) {
|
||||||
fs.mkdirSync(dirPath, { recursive: true });
|
fs.mkdirSync(dirPath, { recursive: true });
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (dirPath !== path.dirname(dirPath)) {
|
if (dirPath !== path.dirname(dirPath)) {
|
||||||
const myname = path.dirname(dirPath);
|
const myname = path.dirname(dirPath);
|
||||||
this.mkdirpath(myname);
|
await this.mkdirpath(myname);
|
||||||
// this.mkdirpath(dirPath);
|
// this.mkdirpath(dirPath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4242,9 +4260,9 @@ module.exports = {
|
|||||||
return namesurname;
|
return namesurname;
|
||||||
},
|
},
|
||||||
|
|
||||||
isFileExists(filename) {
|
async isFileExists(filename) {
|
||||||
try {
|
try {
|
||||||
return fs.existsSync(filename);
|
return await this.existsSync(filename);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -5958,7 +5976,7 @@ module.exports = {
|
|||||||
img = dir + img;
|
img = dir + img;
|
||||||
|
|
||||||
/*if (checkifExist) {
|
/*if (checkifExist) {
|
||||||
if (!fs.existsSync(img)) {
|
if (!this.existsSync(img)) {
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
}*/
|
}*/
|
||||||
@@ -6132,9 +6150,9 @@ module.exports = {
|
|||||||
server_constants.DIR_UPLOAD + '/products/' + productInfo.image_link.split('/').pop();
|
server_constants.DIR_UPLOAD + '/products/' + productInfo.image_link.split('/').pop();
|
||||||
const savePath = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine
|
const savePath = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine
|
||||||
|
|
||||||
let scaricaimg = !productInfo.imagefile || !fs.existsSync(savePath);
|
let scaricaimg = !productInfo.imagefile || !await this.existsSync(savePath);
|
||||||
|
|
||||||
if (!productInfo.imagefile && fs.existsSync(savePath)) {
|
if (!productInfo.imagefile && await this.existsSync(savePath)) {
|
||||||
// esiste il file, ma sul DB non è corretto
|
// esiste il file, ma sul DB non è corretto
|
||||||
const stats = fs.statSync(savePath); // Ottieni informazioni sul file
|
const stats = fs.statSync(savePath); // Ottieni informazioni sul file
|
||||||
|
|
||||||
@@ -6148,7 +6166,7 @@ module.exports = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
if (productInfo.imagefile && fs.existsSync(savePath)) {
|
if (productInfo.imagefile && await this.existsSync(savePath)) {
|
||||||
// esiste il file, ma sul DB non è corretto
|
// esiste il file, ma sul DB non è corretto
|
||||||
const stats = fs.statSync(savePath); // Ottieni informazioni sul file
|
const stats = fs.statSync(savePath); // Ottieni informazioni sul file
|
||||||
|
|
||||||
@@ -6191,7 +6209,7 @@ module.exports = {
|
|||||||
const filecompleto = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine
|
const filecompleto = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine
|
||||||
|
|
||||||
// Se non esiste lo scarico !
|
// Se non esiste lo scarico !
|
||||||
fileesistente = fs.existsSync(filecompleto);
|
fileesistente = await this.existsSync(filecompleto);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!vecchiomodo && (!productInfo.image_link || !fileesistente)) {
|
if (!vecchiomodo && (!productInfo.image_link || !fileesistente)) {
|
||||||
@@ -6296,4 +6314,5 @@ module.exports = {
|
|||||||
return filename;
|
return filename;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
const os = require('os');
|
const os = require('os');
|
||||||
|
|
||||||
const fs = require('fs');
|
const fs = require('fs'); // 👈 Usa il modulo promises
|
||||||
|
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
|
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
1.2.42
|
1.2.44
|
||||||
Reference in New Issue
Block a user