import { render, html } from '/uhtml.js'; function rand() { let str = ''; const lookups = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.split(''); while (str.length < 16) { const n = Math.random() * lookups.length; str += lookups[Math.floor(n)]; } return str; } async function auth() { const sig = await openpgp.sign({ message: new openpgp.CleartextMessage('vybe_auth ' + window.session, ''), signingKeys: window.keys.priv }); window.socket.emit( 'authenticate', { name: window.name, message: sig, pubkey: window.keys.armored.publicKey }, async msg => { let register = document.getElementById('register'); if (!msg.success) { console.log('authenticate failed', msg); document.getElementById('result').innerText = msg.message; register.classList.remove('hidden'); return; } localStorage.setItem('keys', JSON.stringify(window.keys.armored)); localStorage.setItem('name', window.name); register.classList.add('hidden'); window.displayname = msg.displayname; const { authRequest } = await import('/app.js'); msg.authrequests.forEach(authRequest); } ); } async function submit(event) { event.preventDefault(); const name = document.getElementById('name').value; if (!name) return; const keys = await openpgp.generateKey({ userIDs: [{ name }] }); const priv = await openpgp.readKey({ armoredKey: keys.privateKey }); const pub = await openpgp.readKey({ armoredKey: keys.publicKey }); window.keys = { priv, pub, armored: keys }; window.name = name; if (this.id === 'registerform') { window.emit('create_user', { name, pubkey: keys.publicKey }, (msg) => { if (!msg.success) { document.getElementById('result').innerText = msg.message; return; } auth(); } ); } else { await auth(); document.getElementById('result').innerHTML = `now open your profile on your other device to approve this authentication. this session's ID is ${pub.getFingerprint().slice(0,8)}`; } } render(document.body, html` `); function gensession() { window.session = rand(); window.emit = (type, data, callback) => window.socket.emit( type, { ...data, __session: window.session, }, callback ); } window.onload = async () => { window.socket = io(); gensession(); let keys = localStorage.getItem('keys'); if (keys) { window.name = localStorage.getItem('name'); keys = JSON.parse(keys); window.keys = { priv: await openpgp.readKey({ armoredKey: keys.privateKey }), pub: await openpgp.readKey({ armoredKey: keys.publicKey }), armored: keys }; await auth(); } else document.getElementById('register').classList.remove('hidden'); window.socket.io.on('reconnect', async attempt => { gensession(); if (window.keys) await auth(); }); };