Add NSpec and SoapboxSigner

This commit is contained in:
Alex Gleason
2024-02-11 12:40:14 -06:00
parent 6210ad3c25
commit cb14b34309
9 changed files with 150 additions and 27 deletions

View File

@ -0,0 +1,44 @@
import { hexToBytes } from '@noble/hashes/utils';
import { type NostrSigner, type NostrEvent, NSecSigner } from 'nspec';
/** Use key from `localStorage` if available, falling back to NIP-07. */
export class SoapboxSigner implements NostrSigner {
#signer: NostrSigner;
constructor() {
const privateKey = localStorage.getItem('soapbox:nostr:privateKey');
const signer = privateKey ? new NSecSigner(hexToBytes(privateKey)) : window.nostr;
if (!signer) {
throw new Error('No Nostr signer available');
}
this.#signer = signer;
}
async getPublicKey(): Promise<string> {
return this.#signer.getPublicKey();
}
async signEvent(event: Omit<NostrEvent, 'id' | 'pubkey' | 'sig'>): Promise<NostrEvent> {
return this.#signer.signEvent(event);
}
nip04 = {
encrypt: (pubkey: string, plaintext: string): Promise<string> => {
if (!this.#signer.nip04) {
throw new Error('NIP-04 not supported by signer');
}
return this.#signer.nip04.encrypt(pubkey, plaintext);
},
decrypt: (pubkey: string, ciphertext: string): Promise<string> => {
if (!this.#signer.nip04) {
throw new Error('NIP-04 not supported by signer');
}
return this.#signer.nip04.decrypt(pubkey, ciphertext);
},
};
}

View File

@ -6,6 +6,7 @@ import {
finishEvent,
nip04 as _nip04,
} from 'nostr-tools';
import { type NostrSigner } from 'nspec';
import { powWorker } from 'soapbox/workers';
@ -60,4 +61,10 @@ const nip04 = {
},
};
export { getPublicKey, signEvent, nip04 };
const signer: NostrSigner = {
getPublicKey,
signEvent,
nip04,
};
export { signer };