// FIDO2/WebAuthn (YubiKey & Co.) für die App-Sperre. // Chromium erlaubt WebAuthn nur auf HTTPS oder http://localhost – nicht unter file://. Deshalb läuft die // Abfrage in einem kleinen eigenen Fenster, dessen http://localhost-Seite über eine eigene Session // abgefangen wird (kein echter Server). rpId ist damit immer "localhost". // Aus dem Schlüssel wird per PRF-Erweiterung (CTAP hmac-secret) ein geheimer Wert abgeleitet, der den // Datenschlüssel des Vaults verpackt. userVerification "discouraged": Berühren genügt (Electron hat keine PIN-Eingabe). // Registrieren läuft unter Linux direkt per CTAP2 (ctap2.js), weil Electron keine PIN-Abfrage kennt und // Schlüssel mit gesetzter PIN sonst nach dem Berühren mit NotAllowedError scheitern. const { BrowserWindow, session } = require('electron'); const i18n = require('../i18n'); const ctap2 = require('./ctap2'); const PAGE = `
🔑
`; let fidoSession; function getSession() { if (fidoSession) return fidoSession; fidoSession = session.fromPartition('mrterm-fido'); fidoSession.protocol.handle('http', () => new Response(PAGE, { headers: { 'content-type': 'text/html; charset=utf-8' } })); return fidoSession; } // Gemeinsame Hilfsfunktionen im Fenster (base64url <-> Bytes) const HELPERS = ` const b64 = (u) => btoa(String.fromCharCode(...new Uint8Array(u))).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, ''); const unb64 = (s) => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0)); `; async function openWindow(parent, text) { const w = new BrowserWindow({ parent, modal: !!parent, width: 420, height: 230, frame: false, resizable: false, show: false, backgroundColor: '#1a1d27', webPreferences: { session: getSession(), contextIsolation: true, sandbox: true }, }); await w.loadURL('http://localhost/'); await w.webContents.executeJavaScript(`document.getElementById('t').textContent = ${JSON.stringify(text)}; document.getElementById('ok').textContent = ${JSON.stringify(i18n.t('OK'))}; const c = document.getElementById('c'); c.textContent = ${JSON.stringify(i18n.t('Cancel'))}; c.onclick = () => window.close(); 0;`); w.show(); w.focus(); return w; } async function ceremony(parent, text, script) { const w = await openWindow(parent, text); try { const closed = new Promise((resolve) => w.once('closed', () => resolve({ error: 'cancelled' }))); const r = await Promise.race([w.webContents.executeJavaScript(`(async () => { try { ${HELPERS} ${script} } catch (e) { return { error: e.name + ': ' + e.message }; } })()`, true), closed]); if (r?.error === 'cancelled' || /NotAllowedError|AbortError/.test(r?.error || '')) throw new Error(i18n.t('Security key prompt was cancelled or timed out.')); if (r?.error) throw new Error(r.error); return r; } finally { if (!w.isDestroyed()) w.destroy(); } } // Registrierung direkt per CTAP2 (Linux). Liefert die Credential-ID (base64url) oder null, wenn kein // FIDO2-Gerät per hidraw erreichbar ist (dann übernimmt Chromium). async function registerNative(parent) { const w = await openWindow(parent, i18n.t('Connecting to security key …')); let abort = () => {}; let cancelled = false; w.once('closed', () => { cancelled = true; abort(); }); const js = (code) => (w.isDestroyed() ? Promise.resolve(null) : w.webContents.executeJavaScript(code).catch(() => null)); const setText = (t) => js(`document.getElementById('t').textContent = ${JSON.stringify(t)}; 0;`); const ui = { async askPin(retries, wrong) { let t = i18n.t('Enter the PIN of your security key.'); if (wrong) t = i18n.t('Wrong PIN.') + ' ' + t; if (retries != null) t += ' ' + i18n.t('{n} attempts left.', { n: retries }); await setText(t); const closed = new Promise((resolve) => w.once('closed', () => resolve(null))); return Promise.race([closed, js(`new Promise((resolve) => { const f = document.getElementById('f'), p = document.getElementById('p'); f.hidden = false; p.value = ''; p.focus(); f.onsubmit = (e) => { e.preventDefault(); f.hidden = true; resolve(p.value); }; })`)]); }, touch(a) { abort = a; if (cancelled) a(); setText(i18n.t('Touch your security key to register it.')); }, }; try { const id = await ctap2.makeCredential(ui); return id && b64url(id); } catch (e) { if (cancelled || ctap2.CANCEL_CODES.has(e.code)) throw new Error(i18n.t('Security key prompt was cancelled or timed out.')); if (e.code === ctap2.PIN.BLOCKED || e.code === ctap2.PIN.AUTH_BLOCKED) throw new Error(i18n.t('The PIN of this security key is blocked. Remove and reinsert the key, or reset it.')); if (e.code === -1) throw new Error(i18n.t('This security key does not support the hmac-secret/PRF extension.')); throw e; } finally { if (!w.isDestroyed()) w.destroy(); } } // PRF-Abfrage direkt per CTAP2 (Linux); null, wenn kein FIDO2-Gerät per hidraw erreichbar ist async function deriveNative(parent, creds, text) { const w = await openWindow(parent, text || i18n.t('Touch your security key to unlock MrTerm.')); let abort = () => {}; let cancelled = false; w.once('closed', () => { cancelled = true; abort(); }); try { const r = await ctap2.getHmacSecret({ touch(a) { abort = a; if (cancelled) a(); } }, creds.map((c) => ({ credId: Buffer.from(c.credId, 'base64url'), salt: Buffer.from(c.prfSalt, 'base64url') }))); return r && { credId: b64url(r.credId), secret: r.secret }; } catch (e) { if (cancelled || ctap2.CANCEL_CODES.has(e.code)) throw new Error(i18n.t('Security key prompt was cancelled or timed out.')); if (e.code === 0x2e) throw new Error(i18n.t('Unknown security key.')); if (e.code === -1) throw new Error(i18n.t('This security key does not support the hmac-secret/PRF extension.')); throw e; } finally { if (!w.isDestroyed()) w.destroy(); } } const b64url = (buf) => Buffer.from(buf).toString('base64url'); // Neuen Schlüssel registrieren; liefert die Credential-ID (base64url) async function register(parent) { if (process.platform === 'linux') { const id = await registerNative(parent); if (id) return id; } const r = await ceremony(parent, i18n.t('Touch your security key to register it.'), ` const cred = await navigator.credentials.create({ publicKey: { challenge: crypto.getRandomValues(new Uint8Array(32)), rp: { name: 'MrTerm', id: 'localhost' }, user: { id: crypto.getRandomValues(new Uint8Array(16)), name: 'MrTerm', displayName: 'MrTerm' }, pubKeyCredParams: [{ type: 'public-key', alg: -7 }, { type: 'public-key', alg: -8 }, { type: 'public-key', alg: -257 }], authenticatorSelection: { userVerification: 'discouraged', residentKey: 'discouraged' }, timeout: 60000, extensions: { prf: {} }, } }); return { credId: b64(cred.rawId), prf: cred.getClientExtensionResults().prf?.enabled };`); if (r.prf === false) throw new Error(i18n.t('This security key does not support the hmac-secret/PRF extension.')); return r.credId; } // PRF-Wert für einen der Schlüssel abfragen. creds: [{ credId, prfSalt }] (base64url) // Liefert { credId, secret: Buffer(32) } async function derive(parent, creds, text) { if (process.platform === 'linux') { const r = await deriveNative(parent, creds, text); if (r) return r; } const r = await ceremony(parent, text || i18n.t('Touch your security key to unlock MrTerm.'), ` const creds = ${JSON.stringify(creds)}; const evalByCredential = Object.fromEntries(creds.map((c) => [c.credId, { first: unb64(c.prfSalt) }])); const a = await navigator.credentials.get({ publicKey: { challenge: crypto.getRandomValues(new Uint8Array(32)), rpId: 'localhost', timeout: 60000, userVerification: 'discouraged', allowCredentials: creds.map((c) => ({ type: 'public-key', id: unb64(c.credId) })), extensions: { prf: { evalByCredential } }, } }); const first = a.getClientExtensionResults().prf?.results?.first; return { credId: b64(a.rawId), secret: first ? b64(first) : null };`); if (!r.secret) throw new Error(i18n.t('This security key does not support the hmac-secret/PRF extension.')); return { credId: r.credId, secret: Buffer.from(r.secret, 'base64url') }; } module.exports = { register, derive };