43 lines
1.2 KiB
JavaScript
43 lines
1.2 KiB
JavaScript
window.nostr = {
|
|
requests: {},
|
|
|
|
async getPublicKey() {
|
|
return await this.broadcast('getPubKey');
|
|
},
|
|
|
|
async signEvent(event) {
|
|
return await this.broadcast('signEvent', event);
|
|
},
|
|
|
|
broadcast(kind, payload) {
|
|
let reqId = Math.random().toString();
|
|
return new Promise((resolve, _reject) => {
|
|
this.requests[reqId] = resolve;
|
|
console.log(`Event ${reqId}: ${kind}, payload: `, payload);
|
|
window.postMessage({kind, reqId, payload}, '*');
|
|
});
|
|
},
|
|
|
|
|
|
nip04: {
|
|
async encrypt(pubKey, plainText) {
|
|
return await window.nostr.broadcast('nip04.encrypt', {pubKey, plainText});
|
|
},
|
|
|
|
async decrypt(pubKey, cipherText) {
|
|
return await window.nostr.broadcast('nip04.decrypt', {pubKey, cipherText});
|
|
}
|
|
}
|
|
}
|
|
|
|
window.addEventListener('message', (message) => {
|
|
const validEvents = ['getPubKey', 'signEvent', 'nip04.encrypt', 'nip04.decrypt'].map(e => `return_${e}`);
|
|
let {kind, reqId, payload} = message.data;
|
|
|
|
if (!validEvents.includes(kind))
|
|
return;
|
|
|
|
console.log(`Event ${reqId}: Received payload:`, payload);
|
|
window.nostr.requests[reqId](payload);
|
|
delete window.nostr.requests[reqId];
|
|
}); |