-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpairing.html
More file actions
378 lines (348 loc) · 16.2 KB
/
pairing.html
File metadata and controls
378 lines (348 loc) · 16.2 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
<!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 – Pairing</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">🔗 Pairing</div>
<div class="sub">Accoppia i tuoi device in P2P. Cifrato end-to-end.</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">🔍 Security</a>
<a href="logs.html">📋 Log</a>
<a href="pairing.html" class="active">🔗 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>📤 Modalità "device da controllare"</h2>
<p class="dim">Esegui su questa pagina dal device che vuoi essere monitorato (es. laptop). Mostra il QR e scansionalo dall'altro device entro pochi minuti.</p>
<div class="btn-row">
<button class="btn primary" id="genBtn">Genera codice di pairing</button>
</div>
<div id="qrWrap" style="display:none;margin-top:16px">
<div id="qrContainer"></div>
<div id="qrError" class="small" style="display:none;color:var(--warn);margin-top:8px"></div>
<div style="margin-top:12px" class="small dim">Oppure copia manualmente questo codice:</div>
<textarea id="codeText" readonly style="width:100%;height:80px;margin-top:6px;background:var(--panel-2);color:var(--text);border:1px solid var(--border);border-radius:8px;padding:10px;font-family:var(--mono);font-size:12px"></textarea>
<div class="btn-row">
<button class="btn" id="copyBtn">📋 Copia</button>
<button class="btn danger" id="cancelBtn">Annulla</button>
</div>
<div class="kv"><span class="k">Stato</span><span class="v" id="genStatus"><span class="badge warn">in attesa…</span></span></div>
</div>
</div>
<div class="card">
<h2>📥 Modalità "controller"</h2>
<p class="dim">Esegui su questa pagina dal device con cui vuoi controllare l'altro (es. smartphone). Incolla il codice generato sopra, o scansiona il QR con la fotocamera e poi incolla qui sotto.</p>
<textarea id="pasteCode" placeholder="Incolla qui il codice JSON generato dall'altro device…" style="width:100%;height:100px;background:var(--panel-2);color:var(--text);border:1px solid var(--border);border-radius:8px;padding:10px;font-family:var(--mono);font-size:12px"></textarea>
<div style="margin-top:10px">
<input id="peerName" type="text" placeholder="Nome da dare a questo pairing (es. MacBook di casa)" />
<select id="peerKind">
<option value="laptop">💻 Laptop</option>
<option value="desktop">🖥️ Desktop</option>
<option value="smartphone">📱 Smartphone</option>
<option value="tablet">📱 Tablet</option>
<option value="other">🧩 Altro</option>
</select>
</div>
<div class="btn-row">
<button class="btn primary" id="pairBtn">Accoppia</button>
</div>
</div>
<div class="card">
<h2>📚 Device accoppiati</h2>
<div id="peerList"></div>
</div>
</div>
<script src="js/common.js"></script>
<script src="js/db.js"></script>
<script src="js/peer.js"></script>
<script src="js/notifications.js"></script>
<script src="js/security.js"></script>
<!-- Libreria QR locale (Kazuhiko Arase, MIT) - nessuna dipendenza da CDN -->
<script src="js/qrcode.js"></script>
<script>
const genBtn = document.getElementById('genBtn');
const qrWrap = document.getElementById('qrWrap');
const qrContainer = document.getElementById('qrContainer');
const qrError = document.getElementById('qrError');
const codeText = document.getElementById('codeText');
const genStatus = document.getElementById('genStatus');
let host = null;
let currentCode = null;
// ---------- Base64URL helpers (per hash URL sicuro) ----------
function b64urlEncode(s) {
return btoa(unescape(encodeURIComponent(s)))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function b64urlDecode(s) {
s = s.replace(/-/g, '+').replace(/_/g, '/');
while (s.length % 4) s += '=';
return decodeURIComponent(escape(atob(s)));
}
// Costruisce l'URL assoluto della pagina pairing con il codice in hash.
// Uso l'hash (#) e non la query (?) perché il browser NON lo invia al server,
// quindi il codice non finisce nei log HTTP.
function buildPairingURL(jsonCode) {
const origin = window.location.origin;
const path = window.location.pathname;
return origin + path + '#code=' + b64urlEncode(jsonCode);
}
// ---------- Renderer QR ----------
function renderQR(text) {
qrContainer.innerHTML = '';
qrError.style.display = 'none';
if (typeof qrcode !== 'function') {
qrError.textContent = '⚠️ Libreria QR non caricata. Usa il codice qui sotto via copia/incolla.';
qrError.style.display = 'block';
return;
}
try {
// Il QR contiene un URL, non il JSON nudo.
// Così dall'iPhone la Fotocamera mostra un link tappabile che apre
// direttamente la PWA con il codice di pairing pre-compilato.
const url = buildPairingURL(text);
// QR versione auto (0), error correction L (payload più grande = QR più denso).
// Per URL medio-lungo con correzione L stiamo comodi.
const qr = qrcode(0, 'L');
qr.addData(url);
qr.make();
qrContainer.innerHTML = qr.createSvgTag({ cellSize: 5, margin: 2, scalable: true });
const svg = qrContainer.querySelector('svg');
if (svg) {
svg.style.width = '280px';
svg.style.height = '280px';
svg.style.maxWidth = '100%';
}
} catch (e) {
qrError.textContent = '⚠️ Errore disegno QR: ' + (e.message || e) + '. Usa il codice qui sotto.';
qrError.style.display = 'block';
}
}
genBtn.onclick = async () => {
genBtn.disabled = true;
genStatus.innerHTML = '<span class="badge warn">inizializzazione P2P…</span>';
try {
host = await MDG.peer.hostAsTracker({
onStatus: s => {
if (s.state === 'ready') {
currentCode = JSON.stringify({
v: 1,
peerId: s.peerId,
key: s.key,
name: MDG.getDeviceName() || 'Device',
kind: MDG.getDeviceKind()
});
codeText.value = currentCode;
qrWrap.style.display = 'block';
genStatus.innerHTML = '<span class="badge ok">pronto – scansiona dal controller</span>';
renderQR(currentCode);
} else if (s.state === 'error') {
genStatus.innerHTML = '<span class="badge danger">errore: ' + s.error + '</span>';
genBtn.disabled = false;
}
},
onIncoming: conn => {
conn.onOpen = () => {
genStatus.innerHTML = '<span class="badge ok">controller connesso ✓</span>';
MDG.toast('🔗 Pairing completato');
MDG.db.addEvent({
type: 'controller_connected',
deviceId: MDG.getOrCreateDeviceId(),
deviceName: MDG.getDeviceName(),
peer: conn.peer
});
};
conn.onMessage = async msg => {
if (msg.cmd === 'get_status') {
conn.send({
type: 'status',
deviceId: MDG.getOrCreateDeviceId(),
deviceName: MDG.getDeviceName(),
deviceKind: MDG.getDeviceKind(),
userAgent: navigator.userAgent,
ts: Date.now()
});
} else if (msg.cmd === 'get_logs') {
const events = await MDG.db.getAllEvents({ limit: 100 });
const alerts = await MDG.db.getAllAlerts({ limit: 100 });
const mine = events.filter(e => e.deviceId === MDG.getOrCreateDeviceId());
conn.send({ type: 'logs', events: mine, alerts, ts: Date.now() });
} else if (msg.cmd === 'run_audit') {
// Security module caricato su questa pagina? se sì lo usa, altrimenti fallback minimo
if (window.MDG && MDG.security && MDG.security.runAudit) {
const results = await MDG.security.runAudit();
conn.send({ type: 'audit', results, ts: Date.now() });
} else {
conn.send({ type: 'audit', results: [{
key: 'nosec', label: 'Audit', status: 'warn',
value: 'Modulo security non caricato su questa pagina',
hint: 'Apri tracker.html o security.html sul device per l\'audit completo.'
}], ts: Date.now() });
}
}
};
}
});
} catch (e) {
genStatus.innerHTML = '<span class="badge danger">errore: ' + (e.message || e) + '</span>';
genBtn.disabled = false;
}
};
document.getElementById('copyBtn').onclick = () => {
codeText.select();
navigator.clipboard.writeText(codeText.value).then(() => MDG.toast('Copiato'));
};
document.getElementById('cancelBtn').onclick = () => {
if (host) { host.close(); host = null; }
qrWrap.style.display = 'none';
genBtn.disabled = false;
};
// ---------- PAIR FROM CODE ----------
document.getElementById('pairBtn').onclick = async () => {
const raw = document.getElementById('pasteCode').value.trim();
if (!raw) { MDG.toast('Incolla il codice'); return; }
let data;
try { data = JSON.parse(raw); }
catch (e) { MDG.toast('Codice non valido'); return; }
if (!data.peerId || !data.key) { MDG.toast('Codice incompleto'); return; }
const name = document.getElementById('peerName').value.trim() || data.name || 'Device';
const kind = document.getElementById('peerKind').value || data.kind || 'other';
MDG.toast('Tentativo di connessione…');
try {
const conn = await MDG.peer.connectAsController({
peerId: data.peerId,
keyB64: data.key,
onOpen: () => MDG.toast('Canale aperto – salvo pairing'),
onMessage: () => {},
onError: e => MDG.toast('Errore: ' + (e.message || e))
});
conn.send({ cmd: 'get_status' });
await MDG.db.savePeer({
peerId: data.peerId,
key: data.key,
name, kind,
addedAt: Date.now()
});
await MDG.db.addEvent({ type: 'peer_paired', deviceId: MDG.getOrCreateDeviceId(), peer: data.peerId, peerName: name });
MDG.toast('✅ Device accoppiato');
document.getElementById('pasteCode').value = '';
document.getElementById('peerName').value = '';
renderList();
setTimeout(() => conn.close(), 1500);
} catch (e) {
MDG.toast('Impossibile connettersi: ' + (e.message || e));
}
};
// ---------- LISTA ----------
async function renderList() {
const peers = await MDG.db.getAllPeers();
const el = document.getElementById('peerList');
if (!peers.length) { el.innerHTML = '<div class="empty">Nessun device accoppiato.</div>'; return; }
el.innerHTML = peers.map(p => `
<div class="kv">
<span class="k">${escapeHtml(p.name)} <span class="badge dim">${escapeHtml(p.kind)}</span></span>
<span class="v small mono">${escapeHtml(p.peerId)} <button class="btn danger" data-rm="${escapeHtml(p.peerId)}" style="padding:4px 10px;margin-left:8px">×</button></span>
</div>
`).join('');
el.querySelectorAll('[data-rm]').forEach(b => b.onclick = async () => {
if (!confirm('Rimuovere pairing?')) return;
await MDG.db.deletePeer(b.dataset.rm);
renderList();
});
}
function escapeHtml(s) {
return String(s || '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
}
renderList();
// ---------- RILEVAMENTO MODALITÀ DI APERTURA ----------
// Capisco se la pagina è in modalità PWA installata (standalone) o in browser normale.
// Servirà per suggerire all'utente di passare alla PWA installata se ce l'ha.
function isStandalone() {
return window.matchMedia && window.matchMedia('(display-mode: standalone)').matches
|| window.navigator.standalone === true;
}
// ---------- AUTO-FILL DA URL HASH + AUTO-PAIR ----------
// Quando la pagina è aperta da un link QR tipo pairing.html#code=BASE64URL(...)
// decodifichiamo il codice, lo mettiamo nel box e mostriamo un banner con
// bottone "Accoppia ora". L'utente completa in 1 tap.
(function autofillFromHash() {
const hash = window.location.hash || '';
if (!hash.startsWith('#code=')) return;
let data, decoded;
try {
const encoded = hash.slice('#code='.length);
decoded = b64urlDecode(encoded);
data = JSON.parse(decoded);
if (!data.peerId || !data.key) throw new Error('codice incompleto');
} catch (e) {
MDG.toast('Link pairing non valido');
return;
}
// Precompila i campi della modalità controller
const pasteBox = document.getElementById('pasteCode');
pasteBox.value = decoded;
if (data.name) document.getElementById('peerName').value = data.name;
if (data.kind) document.getElementById('peerKind').value = data.kind;
// Banner verde con bottone Accoppia subito e suggerimenti
const controllerCard = pasteBox.closest('.card');
const banner = document.createElement('div');
banner.className = 'card';
banner.style.background = 'rgba(0,227,148,0.12)';
banner.style.borderColor = 'var(--accent)';
const standaloneHint = isStandalone()
? ''
: `<p class="small dim" style="margin-top:8px">
💡 Suggerimento: se hai già installato <strong>MyDeviceGuard</strong> come app sul device,
aprila da lì e incolla il codice (bottone Copia qui sotto) per mantenere i pairing
sempre nella stessa app. Altrimenti questo pairing resterà in questo browser.
</p>`;
banner.innerHTML = `
<h2>📲 Codice di pairing ricevuto</h2>
<p class="dim">Ti vuoi accoppiare con <strong>${escapeHtml(data.name || 'device')}</strong> (${escapeHtml(data.kind || 'device')}).</p>
<div class="btn-row">
<button class="btn primary" id="autoPairBtn">✅ Accoppia ora</button>
<button class="btn" id="autoCopyBtn">📋 Copia codice</button>
</div>
${standaloneHint}
`;
controllerCard.parentNode.insertBefore(banner, controllerCard);
banner.scrollIntoView({ behavior: 'smooth', block: 'start' });
// "Accoppia ora" → stesso flusso del bottone manuale ma diretto
banner.querySelector('#autoPairBtn').onclick = () => {
document.getElementById('pairBtn').click();
};
// "Copia codice" → mette in clipboard per incollare nella PWA installata
banner.querySelector('#autoCopyBtn').onclick = () => {
navigator.clipboard.writeText(decoded).then(() => {
MDG.toast('Codice copiato – ora apri la tua PWA e incolla');
}).catch(() => {
pasteBox.select();
document.execCommand && document.execCommand('copy');
MDG.toast('Codice copiato');
});
};
// Pulisco l'hash dall'URL per non lasciarlo in cronologia / condivisione
history.replaceState(null, '', window.location.pathname);
MDG.toast('Codice di pairing ricevuto');
})();
window.addEventListener('beforeunload', () => { if (host) host.close(); });
</script>
</body>
</html>