-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurity.html
More file actions
490 lines (450 loc) · 20.1 KB
/
security.html
File metadata and controls
490 lines (450 loc) · 20.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
<!DOCTYPE html>
<html lang="it" data-theme="dark">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"/>
<title>MyDeviceGuard – Security Audit</title>
<meta name="theme-color" content="#0b0f14" />
<link rel="manifest" href="manifest.json" />
<link rel="icon" href="icon/mydeviceguard-192.png" />
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="wrap">
<div class="header">
<div>
<div class="logo">🔍 Security Audit</div>
<div class="sub">Diagnostica di sicurezza del device. Tutto locale, niente invii.</div>
</div>
<button class="icon-btn" onclick="MDG.toggleTheme()" title="Cambia tema">🌓</button>
</div>
<div class="nav">
<a href="index.html">🏠 Home</a>
<a href="tracker.html">📍 Tracker</a>
<a href="controller.html">🎮 Controller</a>
<a href="security.html" class="active">🔍 Security</a>
<a href="logs.html">📋 Log</a>
<a href="pairing.html">🔗 Pairing</a>
<a href="backup.html">💾 Backup</a>
<a href="stats.html">📊 Stats</a>
<a href="help.html">📖 Manuale</a>
</div>
<div class="card">
<h2>🧪 Esegui scansione</h2>
<p class="dim">Controlla permessi, storage, rete, HID, tipo di connessione, anomalie di digitazione.</p>
<div class="btn-row">
<button class="btn primary" id="runBtn">▶️ Avvia audit</button>
<button class="btn" id="typingBtn">⌨️ Monitor digitazione: OFF</button>
<button class="btn" id="hidBtn">🔌 Ispeziona HID</button>
</div>
<p class="small dim" style="margin-top:10px">
Il monitor digitazione rileva raffiche di tasti anomale (tipo Rubber Ducky / BadUSB) e registra un alert locale.
</p>
</div>
<div class="card">
<h2>🔔 Notifiche push locali</h2>
<p class="dim">Ricevi avvisi di sistema nel Centro Notifiche quando vengono rilevati cambiamenti o anomalie, anche se la PWA non è in primo piano.</p>
<div class="kv"><span class="k">Supporto browser</span><span class="v" id="notifSupport">–</span></div>
<div class="kv"><span class="k">Permesso</span><span class="v" id="notifPerm">–</span></div>
<div class="kv"><span class="k">Livello</span><span class="v">
<select id="notifLevel" style="min-width:auto">
<option value="off">Nessuna</option>
<option value="danger">Solo critici</option>
<option value="warn">Avvisi e critici</option>
<option value="all">Tutte</option>
</select>
</span></div>
<div class="btn-row">
<button class="btn primary" id="notifRequestBtn">Abilita notifiche</button>
<button class="btn" id="notifTestBtn">🧪 Invia test</button>
</div>
<p class="small dim" style="margin-top:10px">
📱 Su iPhone le notifiche funzionano solo se hai <strong>installato la PWA sulla schermata Home</strong> (iOS 16.4+). In Safari/Chrome web normale non sono disponibili.
</p>
</div>
<div class="card">
<h2>⏱️ Audit schedulato</h2>
<p class="dim">Quando attivo, la PWA esegue l'audit periodicamente in background e genera alert se qualcosa cambia rispetto all'ultima scansione (permessi concessi, nuovi dispositivi HID, HTTPS spento, ecc.).</p>
<div class="kv"><span class="k">Stato</span><span class="v" id="schedState"><span class="badge dim">disattivo</span></span></div>
<div class="kv"><span class="k">Ultimo audit</span><span class="v" id="schedLast">–</span></div>
<div class="kv"><span class="k">Frequenza</span><span class="v">
<select id="schedInterval" style="min-width:auto">
<option value="15">15 min</option>
<option value="30">30 min</option>
<option value="60">60 min</option>
<option value="180">3 ore</option>
<option value="360">6 ore</option>
<option value="720">12 ore</option>
</select>
</span></div>
<div class="btn-row">
<button class="btn primary" id="schedToggle">Attiva</button>
<button class="btn" id="schedRunNow">▶️ Esegui adesso</button>
</div>
</div>
<div id="resultGrid"></div>
<div class="card" id="hidCard" style="display:none">
<h2>🔌 Dispositivi HID rilevati</h2>
<table>
<thead><tr><th>Nome</th><th>ID (VID:PID)</th><th>Stato</th><th>Azioni</th></tr></thead>
<tbody id="hidList"></tbody>
</table>
</div>
<div class="card">
<h2>🔒 Whitelist HID</h2>
<p class="dim">Solo i dispositivi HID in questa lista sono considerati "noti". Se uno scan rileva un HID non in whitelist mentre il watch è attivo, viene generato un alert critico + notifica push.</p>
<div class="kv"><span class="k">Watch attivo</span><span class="v" id="hidWatchState"><span class="badge dim">spento</span></span></div>
<div class="kv"><span class="k">Dispositivi in whitelist</span><span class="v" id="hidWhitelistCount">0</span></div>
<div class="btn-row">
<button class="btn primary" id="hidWatchToggle">Attiva watch</button>
<button class="btn" id="hidScanNow">🔍 Scansiona ora</button>
<button class="btn" id="hidRequestDevice">➕ Aggiungi dispositivo…</button>
</div>
<div id="hidWhitelistList" style="margin-top:12px"></div>
<p class="small dim" style="margin-top:10px">
Nota: WebHID espone solo i dispositivi già autorizzati al browser. La prima volta devi usare <em>Aggiungi dispositivo</em> per ciascun HID (es. tastiera principale, mouse) e poi promuoverlo in whitelist. Da quel momento, qualunque HID nuovo autorizzato scatena un alert.
</p>
</div>
<div class="card">
<h2>🚨 Alert recenti</h2>
<table>
<thead><tr><th>Quando</th><th>Tipo</th><th>Gravità</th><th>Descrizione</th></tr></thead>
<tbody id="alertList"><tr><td colspan="4" class="dim">Nessun alert.</td></tr></tbody>
</table>
</div>
</div>
<script src="js/common.js"></script>
<script src="js/db.js"></script>
<script src="js/notifications.js"></script>
<script src="js/security.js"></script>
<script>
const runBtn = document.getElementById('runBtn');
const typingBtn = document.getElementById('typingBtn');
const hidBtn = document.getElementById('hidBtn');
const grid = document.getElementById('resultGrid');
function statusBadge(s) {
const map = { ok: 'ok', warn: 'warn', danger: 'danger', info: 'info' };
return `<span class="badge ${map[s] || 'dim'}">${s}</span>`;
}
async function renderAudit() {
grid.innerHTML = '<div class="card dim">Scansione in corso…</div>';
const res = await MDG.security.runAudit();
await MDG.db.addEvent({
type: 'security_audit',
deviceId: MDG.getOrCreateDeviceId(),
deviceName: MDG.getDeviceName(),
summary: {
total: res.length,
warn: res.filter(r => r.status === 'warn').length,
danger: res.filter(r => r.status === 'danger').length
}
});
grid.innerHTML = `
<div class="card">
<h2>📋 Risultati (${res.length})</h2>
${res.map(r => `
<div class="kv">
<span class="k">${r.label}</span>
<span class="v">${statusBadge(r.status)} ${escapeHtml(r.value || '')}</span>
</div>
<div class="small dim" style="margin: -4px 0 10px">${escapeHtml(r.hint || '')}</div>
`).join('')}
</div>
`;
}
function escapeHtml(s) {
return String(s || '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
}
runBtn.onclick = renderAudit;
// ---------- Typing watcher toggle ----------
let typingOn = false;
typingBtn.onclick = () => {
if (typingOn) {
MDG.security.stopTypingWatcher();
typingOn = false;
typingBtn.textContent = '⌨️ Monitor digitazione: OFF';
} else {
MDG.security.startTypingWatcher();
typingOn = true;
typingBtn.textContent = '⌨️ Monitor digitazione: ON';
MDG.toast('Monitor attivo – digita rapidamente per testare');
}
};
// ---------- HID scan (usa whitelist) ----------
async function renderHidList(devices) {
const card = document.getElementById('hidCard');
const list = document.getElementById('hidList');
card.style.display = 'block';
if (!devices.length) {
list.innerHTML = '<tr><td colspan="4" class="dim">Nessun dispositivo HID autorizzato al browser.</td></tr>';
return;
}
list.innerHTML = devices.map(d => {
const statusBadge = d.isKnown
? '<span class="badge ok">nota</span>'
: '<span class="badge danger">ignota</span>';
const action = d.isKnown
? `<button class="btn danger" data-hid-remove="${escapeHtml(d.id)}" style="padding:4px 10px">Rimuovi</button>`
: `<button class="btn primary" data-hid-add='${escapeHtml(JSON.stringify({productName:d.productName, vendorId:d.vendorId, productId:d.productId}))}' style="padding:4px 10px">✅ Approva</button>`;
const name = d.nickname || d.productName || '—';
return `
<tr>
<td>${escapeHtml(name)}</td>
<td class="mono small">${escapeHtml(d.id)}</td>
<td>${statusBadge}</td>
<td>${action}</td>
</tr>
`;
}).join('');
// Delegation handler
list.querySelectorAll('[data-hid-add]').forEach(b => b.onclick = async () => {
const dev = JSON.parse(b.getAttribute('data-hid-add'));
const nick = prompt('Nome amichevole per questo HID:', dev.productName || '') || dev.productName;
MDG.security.addToWhitelist(dev, nick);
MDG.toast('Aggiunto alla whitelist');
refreshHidAll();
});
list.querySelectorAll('[data-hid-remove]').forEach(b => b.onclick = () => {
if (!confirm('Rimuovere dalla whitelist?')) return;
MDG.security.removeFromWhitelist(b.getAttribute('data-hid-remove'));
MDG.toast('Rimosso');
refreshHidAll();
});
}
async function refreshHidAll() {
const devices = await MDG.security.scanHidAgainstWhitelist({ notify: false });
renderHidList(devices);
// Whitelist pannello
const wl = MDG.security.getHidWhitelist();
const keys = Object.keys(wl);
document.getElementById('hidWhitelistCount').textContent = keys.length;
const wlEl = document.getElementById('hidWhitelistList');
if (keys.length === 0) {
wlEl.innerHTML = '<div class="dim small">Whitelist vuota. Usa "Scansiona ora" o "Aggiungi dispositivo" per popolarla.</div>';
} else {
wlEl.innerHTML = keys.map(k => {
const e = wl[k];
return `
<div class="kv">
<span class="k">${escapeHtml(e.nickname)}</span>
<span class="v small mono">${escapeHtml(e.id)}
<button class="btn" data-rename="${escapeHtml(k)}" style="padding:4px 10px;margin-left:8px">✏️</button>
<button class="btn danger" data-remove="${escapeHtml(k)}" style="padding:4px 10px">×</button>
</span>
</div>
`;
}).join('');
wlEl.querySelectorAll('[data-rename]').forEach(b => b.onclick = () => {
const k = b.getAttribute('data-rename');
const cur = wl[k].nickname;
const v = prompt('Nuovo nome:', cur);
if (v && v.trim()) { MDG.security.renameInWhitelist(k, v.trim()); refreshHidAll(); }
});
wlEl.querySelectorAll('[data-remove]').forEach(b => b.onclick = () => {
if (!confirm('Rimuovere?')) return;
MDG.security.removeFromWhitelist(b.getAttribute('data-remove'));
refreshHidAll();
});
}
// Stato watch
const watchOn = MDG.security.getHidWatchEnabled();
document.getElementById('hidWatchState').innerHTML = watchOn
? '<span class="badge ok">attivo</span>'
: '<span class="badge dim">spento</span>';
const btn = document.getElementById('hidWatchToggle');
btn.textContent = watchOn ? 'Disattiva watch' : 'Attiva watch';
btn.className = watchOn ? 'btn danger' : 'btn primary';
}
hidBtn.onclick = async () => {
// Il vecchio "Ispeziona HID": se non ci sono HID autorizzati, chiede di selezionarne uno.
const devices = await MDG.security.listHidDevices();
if (!devices.length) {
try {
await MDG.security.requestHidDevice();
} catch (e) {
MDG.toast(e.message || 'HID non disponibile');
return;
}
}
await refreshHidAll();
await MDG.db.addEvent({
type: 'hid_scan',
deviceId: MDG.getOrCreateDeviceId(),
deviceName: MDG.getDeviceName(),
count: (await MDG.security.listHidDevices()).length
});
};
document.getElementById('hidScanNow').onclick = () => refreshHidAll();
document.getElementById('hidRequestDevice').onclick = async () => {
try {
await MDG.security.requestHidDevice();
MDG.toast('Dispositivo autorizzato – ora puoi approvarlo');
refreshHidAll();
} catch (e) {
MDG.toast('Nessun dispositivo selezionato');
}
};
document.getElementById('hidWatchToggle').onclick = () => {
const on = MDG.security.getHidWatchEnabled();
MDG.security.setHidWatchEnabled(!on);
MDG.toast(!on ? 'Watch HID attivato' : 'Watch HID disattivato');
refreshHidAll();
};
// Popola whitelist UI al caricamento se c'è qualcosa, senza aprire hidCard
(async () => {
const wl = MDG.security.getHidWhitelist();
if (Object.keys(wl).length || MDG.security.getHidWatchEnabled()) {
await refreshHidAll();
} else {
// Almeno inizializza counters della card whitelist
document.getElementById('hidWhitelistCount').textContent = '0';
const wlEl = document.getElementById('hidWhitelistList');
wlEl.innerHTML = '<div class="dim small">Whitelist vuota. Usa "Scansiona ora" o "Aggiungi dispositivo" per popolarla.</div>';
}
})();
// ---------- Alert feed ----------
async function refreshAlerts() {
const alerts = await MDG.db.getAllAlerts({ limit: 30 });
const tbody = document.getElementById('alertList');
if (!alerts.length) {
tbody.innerHTML = '<tr><td colspan="4" class="dim">Nessun alert.</td></tr>';
return;
}
tbody.innerHTML = alerts.map(a => `
<tr>
<td>${MDG.fmtRelative(a.ts)}</td>
<td>${escapeHtml(a.type)}</td>
<td>${statusBadge(a.severity)}</td>
<td>${escapeHtml(a.description || '')}</td>
</tr>
`).join('');
}
refreshAlerts();
setInterval(refreshAlerts, 5000);
// ---------- Scheduler UI ----------
const schedState = document.getElementById('schedState');
const schedLast = document.getElementById('schedLast');
const schedInterval = document.getElementById('schedInterval');
const schedToggle = document.getElementById('schedToggle');
const schedRunNow = document.getElementById('schedRunNow');
function refreshSchedUI() {
const on = MDG.security.getAutoEnabled();
schedState.innerHTML = on ? '<span class="badge ok">attivo</span>' : '<span class="badge dim">disattivo</span>';
schedToggle.textContent = on ? 'Disattiva' : 'Attiva';
schedToggle.className = on ? 'btn danger' : 'btn primary';
schedInterval.value = String(MDG.security.getIntervalMinutes());
const last = MDG.security.getLastSnapshot();
if (last && last.ts) {
const ago = MDG.fmtRelative(last.ts);
const warn = last.warn || 0, danger = last.danger || 0;
let badge = '<span class="badge ok">pulito</span>';
if (danger > 0) badge = `<span class="badge danger">${danger} critici</span>`;
else if (warn > 0) badge = `<span class="badge warn">${warn} avvisi</span>`;
schedLast.innerHTML = ago + ' · ' + badge;
} else {
schedLast.innerHTML = '<span class="dim">mai eseguito</span>';
}
}
schedToggle.onclick = () => {
MDG.security.setAutoEnabled(!MDG.security.getAutoEnabled());
refreshSchedUI();
MDG.toast(MDG.security.getAutoEnabled() ? 'Audit schedulato attivato' : 'Audit schedulato disattivato');
};
schedInterval.onchange = () => {
MDG.security.setIntervalMinutes(parseInt(schedInterval.value, 10));
MDG.toast('Frequenza aggiornata');
refreshSchedUI();
};
schedRunNow.onclick = async () => {
MDG.toast('Audit in corso…');
const res = await MDG.security.runScheduledAudit();
refreshSchedUI();
refreshAlerts();
if (res && res.changes && res.changes.length) {
MDG.toast(`${res.changes.length} cambiamenti rilevati – vedi Alert`);
} else {
MDG.toast('Audit completato, nessun cambiamento');
}
};
refreshSchedUI();
setInterval(refreshSchedUI, 30000);
// ---------- Notifiche push UI ----------
const notifSupport = document.getElementById('notifSupport');
const notifPerm = document.getElementById('notifPerm');
const notifLevel = document.getElementById('notifLevel');
const notifRequestBtn = document.getElementById('notifRequestBtn');
const notifTestBtn = document.getElementById('notifTestBtn');
function refreshNotifUI() {
const supp = MDG.notifications.isSupported();
notifSupport.innerHTML = supp
? '<span class="badge ok">sì</span>'
: '<span class="badge danger">non supportato</span>';
const perm = MDG.notifications.getPermission();
const permMap = {
granted: '<span class="badge ok">concesso</span>',
denied: '<span class="badge danger">negato</span>',
default: '<span class="badge warn">da richiedere</span>',
unsupported: '<span class="badge dim">—</span>'
};
notifPerm.innerHTML = permMap[perm] || perm;
notifLevel.value = MDG.notifications.getLevel();
if (!supp) {
notifRequestBtn.disabled = true;
notifTestBtn.disabled = true;
notifRequestBtn.textContent = 'Non supportato';
} else if (perm === 'granted') {
notifRequestBtn.textContent = '✅ Già abilitate';
notifRequestBtn.disabled = true;
notifRequestBtn.className = 'btn';
notifTestBtn.disabled = false;
} else if (perm === 'denied') {
notifRequestBtn.textContent = 'Negato – sblocca dalle impostazioni browser';
notifRequestBtn.disabled = true;
notifTestBtn.disabled = true;
} else {
notifRequestBtn.textContent = 'Abilita notifiche';
notifRequestBtn.disabled = false;
notifRequestBtn.className = 'btn primary';
notifTestBtn.disabled = true;
}
}
notifRequestBtn.onclick = async () => {
try {
const r = await MDG.notifications.requestPermission();
MDG.toast('Permesso: ' + r);
refreshNotifUI();
} catch (e) {
MDG.toast('Errore: ' + (e.message || e));
}
};
notifLevel.onchange = () => {
MDG.notifications.setLevel(notifLevel.value);
MDG.toast('Livello notifiche aggiornato');
};
notifTestBtn.onclick = async () => {
if (MDG.notifications.getPermission() !== 'granted') {
MDG.toast('Prima abilita le notifiche');
return;
}
const ok = await MDG.notifications.notify('🧪 Notifica di test', {
body: 'Se vedi questa nel Centro Notifiche, il sistema funziona. Tocca per tornare alla PWA.',
severity: 'warn',
tag: 'mdg-test',
data: { url: 'security.html' }
});
if (!ok) {
MDG.toast('Livello corrente filtra questa severity – alza il livello o cambialo');
} else {
MDG.toast('Notifica inviata');
}
};
refreshNotifUI();
// Quando la pagina torna visibile, rileggi lo stato permesso (potrebbe essere cambiato dalle impostazioni browser)
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') refreshNotifUI();
});
// run automatico all'apertura
renderAudit();
</script>
</body>
</html>