import os import subprocess import secrets import json import pathlib def run(cmd, check=True): """Esegue un comando di sistema mostrando l'avanzamento.""" print(f"-> Eseguo: {cmd}") env = os.environ.copy() env["DEBIAN_FRONTEND"] = "noninteractive" env["NEEDRESTART_MODE"] = "a" subprocess.run(cmd, shell=True, check=check, env=env) def main(): print("=== [1/5] Sblocco aggiornamenti automatici Ubuntu ===") run( "systemctl stop unattended-upgrades apt-daily.timer apt-daily-upgrade.timer " "apt-daily.service apt-daily-upgrade.service 2>/dev/null || true", check=False, ) run("pkill -9 -f unattended-upgrade 2>/dev/null || true", check=False) run("pkill -9 -x apt 2>/dev/null || true", check=False) run("pkill -9 -x apt-get 2>/dev/null || true", check=False) run("pkill -9 -x dpkg 2>/dev/null || true", check=False) for lock_file in [ "/var/lib/dpkg/lock-frontend", "/var/lib/dpkg/lock", "/var/cache/apt/archives/lock", ]: try: os.remove(lock_file) except FileNotFoundError: pass run("dpkg --configure -a", check=False) print("=== [2/5] Installazione Nginx, Node.js e Firewall ===") run("apt-get update -y") run("apt-get install -y software-properties-common curl openssl") run("add-apt-repository -y universe 2>/dev/null || true", check=False) run("apt-get update -y") run("apt-get install -y nginx nodejs ufw certbot python3-certbot-nginx") print("=== [3/5] Configurazione Firewall UFW ===") run("ufw allow 22/tcp") run("ufw allow 80/tcp") run("ufw allow 443/tcp") run("ufw --force enable") print("=== [4/5] Creazione Server API e Password Gestionale ===") pathlib.Path("/var/www/soccorsopc").mkdir(parents=True, exist_ok=True) pathlib.Path("/var/lib/soccorsopc-data/backups").mkdir(parents=True, exist_ok=True) os.chmod("/var/lib/soccorsopc-data", 0o700) pathlib.Path("/opt/soccorsopc-api").mkdir(parents=True, exist_ok=True) auth_path = pathlib.Path("/var/lib/soccorsopc-data/auth.json") pass_txt = pathlib.Path("/root/PASSWORD_GESTIONALE.txt") if not auth_path.exists(): init_pass = secrets.token_hex(5) token_secret = secrets.token_hex(24) auth_path.write_text( json.dumps({"password": init_pass, "secret": token_secret}), encoding="utf-8", ) pass_txt.write_text(init_pass + "\n", encoding="utf-8") os.chmod(auth_path, 0o600) os.chmod(pass_txt, 0o600) server_js = r"""const http = require('http'); const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); const DATA_DIR = '/var/lib/soccorsopc-data'; const AUTH_FILE = path.join(DATA_DIR, 'auth.json'); const STATE_FILE = path.join(DATA_DIR, 'db_state.json'); const CLIENTS_FILE = path.join(DATA_DIR, 'db_clients.json'); function readJson(file, fallback) { try { if (!fs.existsSync(file)) return fallback; return JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { return fallback; } } function writeJsonAtomic(file, data) { const tmp = file + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(data)); fs.renameSync(tmp, file); } function makeToken(auth) { return crypto.createHmac('sha256', auth.secret || 'soccorsopc').update(auth.password).digest('hex'); } function isAuthorized(req) { const auth = readJson(AUTH_FILE, { password: '', secret: '' }); const header = req.headers['authorization'] || ''; const token = header.replace(/^Bearer\s+/i, '').trim(); return token && token === makeToken(auth); } function collectBody(req, cb) { let body = ''; req.on('data', chunk => { body += chunk; if (body.length > 60 * 1024 * 1024) req.destroy(); }); req.on('end', () => { try { cb(null, JSON.parse(body || '{}')); } catch (err) { cb(err); } }); } function findTicketByCode(tickets, code) { const cleanCode = String(code || '').replace(/\D/g, '').trim(); if (!cleanCode || !Array.isArray(tickets)) return -1; return tickets.findIndex(t => { const tCode = `${t.year || ''}${t.number || ''}`; return tCode === cleanCode || String(t.number || '') === cleanCode; }); } const server = http.createServer((req, res) => { res.setHeader('Content-Type', 'application/json; charset=utf-8'); res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate'); if (req.method === 'GET' && req.url === '/api/health') { res.end(JSON.stringify({ ok: true, authRequired: true, serverTime: new Date().toISOString() })); return; } if (req.method === 'POST' && req.url === '/api/login') { collectBody(req, (err, data) => { if (err) { res.statusCode = 400; res.end(JSON.stringify({ ok: false })); return; } const auth = readJson(AUTH_FILE, { password: '', secret: '' }); if (data.password && data.password === auth.password) { res.end(JSON.stringify({ ok: true, token: makeToken(auth) })); } else { res.statusCode = 401; res.end(JSON.stringify({ ok: false, error: 'Password errata' })); } }); return; } const cleanUrl = (req.url || '').split('?')[0]; const signMatch = cleanUrl.match(/^\/api\/public-sign\/(\d+)$/); if (req.method === 'GET' && signMatch) { const state = readJson(STATE_FILE, { settings: null, tickets: [] }); const idx = findTicketByCode(state.tickets, signMatch[1]); if (idx === -1) { res.statusCode = 404; res.end(JSON.stringify({ ok: false, error: 'Scheda non trovata' })); return; } const t = state.tickets[idx]; res.end(JSON.stringify({ ok: true, ticket: { year: t.year, number: t.number, dateIn: t.dateIn || '', clientName: t.clientName || '', brand: t.brand || '', model: t.model || '', accessories: t.accessories || [], accessoriesExtra: t.accessoriesExtra || '', condition: t.condition || '', conditionNotes: t.conditionNotes || '', defects: t.defects || '', signed: !!t.signed, signedAt: t.signedAt || '', signatureData: t.signatureData || '' } })); return; } if (req.method === 'POST' && signMatch) { collectBody(req, (err, data) => { if (err || !data.signatureData || typeof data.signatureData !== 'string') { res.statusCode = 400; res.end(JSON.stringify({ ok: false, error: 'Firma non valida' })); return; } const state = readJson(STATE_FILE, { settings: null, tickets: [] }); const idx = findTicketByCode(state.tickets, signMatch[1]); if (idx === -1) { res.statusCode = 404; res.end(JSON.stringify({ ok: false, error: 'Scheda non trovata' })); return; } const signedAt = String(data.signedAt || new Date().toLocaleString('it-IT')).slice(0, 32); state.tickets[idx].signed = true; state.tickets[idx].signedAt = signedAt; state.tickets[idx].signatureData = data.signatureData; writeJsonAtomic(STATE_FILE, state); res.end(JSON.stringify({ ok: true, signedAt })); }); return; } if (!isAuthorized(req)) { res.statusCode = 401; res.end(JSON.stringify({ ok: false, error: 'Non autorizzato' })); return; } if (req.method === 'POST' && req.url === '/api/change-password') { collectBody(req, (err, data) => { if (err || !data.newPassword || String(data.newPassword).trim().length < 4) { res.statusCode = 400; res.end(JSON.stringify({ ok: false, error: 'Password troppo corta' })); return; } const auth = readJson(AUTH_FILE, { password: '', secret: crypto.randomBytes(24).toString('hex') }); auth.password = String(data.newPassword).trim(); writeJsonAtomic(AUTH_FILE, auth); fs.writeFileSync('/root/PASSWORD_GESTIONALE.txt', auth.password + '\n'); res.end(JSON.stringify({ ok: true, token: makeToken(auth) })); }); return; } if (req.method === 'GET' && req.url === '/api/state') { res.end(JSON.stringify(readJson(STATE_FILE, { settings: null, tickets: [] }))); return; } if (req.method === 'GET' && req.url === '/api/clients') { res.end(JSON.stringify(readJson(CLIENTS_FILE, []))); return; } if (req.method === 'POST' && (req.url === '/api/state' || req.url === '/api/clients')) { collectBody(req, (err, parsed) => { if (err) { res.statusCode = 400; res.end(JSON.stringify({ ok: false, error: 'JSON non valido' })); return; } if (req.url === '/api/state') writeJsonAtomic(STATE_FILE, parsed); if (req.url === '/api/clients') writeJsonAtomic(CLIENTS_FILE, parsed); res.end(JSON.stringify({ ok: true })); }); return; } res.statusCode = 404; res.end(JSON.stringify({ ok: false, error: 'Endpoint non trovato' })); }); server.listen(3001, '127.0.0.1', () => { console.log('SoccorsoPC API attiva su 127.0.0.1:3001'); }); """ pathlib.Path("/opt/soccorsopc-api/server.js").write_text(server_js, encoding="utf-8") index_path = pathlib.Path("/var/www/soccorsopc/index.html") if not index_path.exists(): index_path.write_text( "