nostrband / nostrlogin.org

Promoting nostr as an identity layer for the web
Creative Commons Zero v1.0 Universal
4 stars 0 forks source link

Having some trouble with publishing/signing new events #3

Open pparonson opened 1 month ago

pparonson commented 1 month ago

I've been attempting to use the npm nostr-login package with the @nostr-dev-kit/ndk, NDKNip46Signer packages. Initializing and fetching seems to be working, but I'm having issues publishing new events. Can you help me identify what I'm doing wrong?

Console errors:

@nostr-dev-kit_ndk.js?v=0271c622:12222 Uncaught (in promise) TypeError: this.signer.user is not a function
    at Proxy.sendRequest (@nostr-dev-kit_ndk.js?v=0271c622:12222:41)
    at @nostr-dev-kit_ndk.js?v=0271c622:12603:16
    at new Promise (<anonymous>)
    at Proxy.sign (@nostr-dev-kit_ndk.js?v=0271c622:12602:21)
    at _NDKEvent.sign (@nostr-dev-kit_ndk.js?v=0271c622:8160:29)
    at async _NDKEvent.publish (@nostr-dev-kit_ndk.js?v=0271c622:8187:7)
    at async Proxy.publishEvent (nostr.js?t=1726341404422:241:1)
    at async Proxy.handleSave (NoteEventDetail.vue:67:21)`

Here are some relevant snippets from my code: Attempting to initialize:

{
            localStorage.setItem("debug", "ndk:*"); // TODO: TESTING debug NDK internals
            const authStore = useAuthStore();
            let { loginMethod, toggleModal, setLoginStatus } = authStore;
            // let signer;
            let remoteNpub;
            try {
                if (!ndk) {
                    ndk = new NDK();
                }
                if (loginMethod === "nostr-login") {
                    try {
                        await initNostrLogin({
                            bunkers: 'nsec.app',
                            theme: 'ocean',
                            darkMode: true,
                            perms: 'sign_event:1, nip04_encrypt',
                            noBanner: true,
                            isSignInWithExtension: false, // TODO: not working as expected
                            onAuth: async (npub, options) => {
                                console.log(`User authenticated with pubkey: ${npub}`, options);
                                remoteNpub = npub;
                            },
                        }).catch((ex) => {
                            console.error('Error initializing Nostr Login:', ex);
                        });
                    } catch (ex) {
                        console.error('Error initializing Nostr Login:', ex);
                    }

                    await launchNostrLoginDialog({ 
                        startScreen: 'login-bunker-url' // TODO: Not workng as expected
                    });

                    if (window.nostr) {
                        this.signer = new NDKNip46Signer(ndk, remoteNpub, window.nostr);
                    } else {
                        throw new Error('Nostr Login not initialized');
                    }

                } else {
                    throw new Error(`Unsupported login method: ${loginMethod}`);
                }

                const user = await this.signer.user();
                if (user?.npub) {
                    const userData = await useIndexedDB().get(user.npub || "");
                    if (userData) {
                        if (!userData.encryptionKey) {
                            this.missingEncryptionKey = true;
                        }  
                        if (
                            !userData.encryptedAnnotAPIAcct || 
                            !userData.encryptedAnnotAPIKey || 
                            !userData.relayUrls || 
                            userData.relayUrls.length === 0
                        ) {
                            const missingOptionalCredentials = !userData.encryptedAnnotAPIAcct || 
                                !userData.encryptedAnnotAPIKey 
                                || !userData.relayUrls 
                                || userData.relayUrls.length === 0;

                            if (missingOptionalCredentials) {
                                this.missingOptionalCredentials = true;
                            }
                        }
                    } else {
                        this.missingEncryptionKey = true;
                    }

                    const explicitRelayUrls = userData?.relayUrls?.length ? userData.relayUrls : [];

                    ndk = new NDK({ explicitRelayUrls, signer: this.signer });
                    await ndk.connect();
                    console.log("NDK Connected..");

                    const resp = await this.fetchUser(user.npub);
                    if (resp) {
                        setLoginStatus(true);
                        toggleModal(false);
                    }
                }
            }catch (error) {
                console.error("Error connecting to NDK:", error);
                throw error;
            }
        }

Attempting to Publish:

            const eventProperties = await this.handleCreateUpdate({ ...note, content: encrypted }, isUpdate);
            eventProperties.tags.push(["encrypted", "1"]);

            let ndkEvent = new NDKEvent(ndk, eventProperties);
            // eventProperties.created_at = Math.floor(Date.now() / 1000);

            try {
                // const signedEvent = await window.nostr.signEvent(event);
                // const signedEvent = await ndk.publish(event);
                // const signedEvent = await ndkEvent.publish();
                // console.log("Signed Event: ", signedEvent);
                const ndkEvent = new NDKEvent(ndk);
                ndkEvent.kind = 1;
                ndkEvent.content = "Hello, world!";
                ndkEvent.publish()
            } catch (error) {
                console.error("Error publishing event:", error);
                throw error;
            } finally {
                this.isPublishingEvent = false;
            }
nostrband commented 1 month ago

Hi, try creating NDKNip07Signer instead of NDKNip46Signer - nostr-login creates window.nostr object through which you access the keys, window.nostr is nip07.

NDKNip46Signer is used if you want to specifically use ndk's nip46 client, in which case you wouldn't need to use nostr-login.

-- Artur

On Saturday, September 14th, 2024 at 11:31 PM, pparonson @.***> wrote:

I've been attempting to use the npm nostr-login package with the @nostr-dev-kit/ndk package. Initializing and fetching seems to be working, but I'm having issues publishing new events. Can you help me identify what I'm doing wrong?

Console errors:

@nostr-dev-kit_ndk.js?v=0271c622:12222 Uncaught (in promise) TypeError: this.signer.user is not a function at Proxy.sendRequest @._ndk.js?v=0271c622:12222:41) at @nostr-dev-kit_ndk.js?v=0271c622:12603:16 at new Promise () at Proxy.sign @._ndk.js?v=0271c622:12602:21) at _NDKEvent.sign @._ndk.js?v=0271c622:8160:29) at async _NDKEvent.publish @._ndk.js?v=0271c622:8187:7) at async Proxy.publishEvent (nostr.js?t=1726341404422:241:1) at async Proxy.handleSave (NoteEventDetail.vue:67:21)`

Here are some relevant snippets from my code: Attempting to initialize:

{ localStorage.setItem("debug", "ndk:*"); // TODO: TESTING debug NDK internals const authStore = useAuthStore(); let { loginMethod, toggleModal, setLoginStatus } = authStore; // let signer; let remoteNpub; try { if (!ndk) { ndk = new NDK(); } if (loginMethod === "nostr-login") { try { await initNostrLogin({ bunkers: 'nsec.app', theme: 'ocean', darkMode: true, perms: 'sign_event:1, nip04_encrypt', noBanner: true, isSignInWithExtension: false, // TODO: not working as expected onAuth: async (npub, options) => { console.log(User authenticated with pubkey: ${npub}, options); remoteNpub = npub; }, }).catch((ex) => { console.error('Error initializing Nostr Login:', ex); }); } catch (ex) { console.error('Error initializing Nostr Login:', ex); }

                await launchNostrLoginDialog({
                    startScreen: 'login-bunker-url' // TODO: Not workng as expected
                });

                if (window.nostr) {
                    this.signer = new NDKNip46Signer(ndk, remoteNpub, window.nostr);
                } else {
                    throw new Error('Nostr Login not initialized');
                }

            } else {
                throw new Error(`Unsupported login method: ${loginMethod}`);
            }

            const user = await this.signer.user();
            if (user?.npub) {
                const userData = await useIndexedDB().get(user.npub || "");
                if (userData) {
                    if (!userData.encryptionKey) {
                        this.missingEncryptionKey = true;
                    }
                    if (
                        !userData.encryptedAnnotAPIAcct ||
                        !userData.encryptedAnnotAPIKey ||
                        !userData.relayUrls ||
                        userData.relayUrls.length === 0
                    ) {
                        const missingOptionalCredentials = !userData.encryptedAnnotAPIAcct ||
                            !userData.encryptedAnnotAPIKey
                            || !userData.relayUrls
                            || userData.relayUrls.length === 0;

                        if (missingOptionalCredentials) {
                            this.missingOptionalCredentials = true;
                        }
                    }
                } else {
                    this.missingEncryptionKey = true;
                }

                const explicitRelayUrls = userData?.relayUrls?.length ? userData.relayUrls : [];

                ndk = new NDK({ explicitRelayUrls, signer: this.signer });
                await ndk.connect();
                console.log("NDK Connected..");

                const resp = await this.fetchUser(user.npub);
                if (resp) {
                    setLoginStatus(true);
                    toggleModal(false);
                }
            }
        }catch (error) {
            console.error("Error connecting to NDK:", error);
            throw error;
        }
    }

Attempting to Publish:

const eventProperties = await this.handleCreateUpdate({ ...note, content: encrypted }, isUpdate); eventProperties.tags.push(["encrypted", "1"]);

        let ndkEvent = new NDKEvent(ndk, eventProperties);
        // eventProperties.created_at = Math.floor(Date.now() / 1000);

        try {
            // const signedEvent = await window.nostr.signEvent(event);
            // const signedEvent = await ndk.publish(event);
            // const signedEvent = await ndkEvent.publish();
            // console.log("Signed Event: ", signedEvent);
            const ndkEvent = new NDKEvent(ndk);
            ndkEvent.kind = 1;
            ndkEvent.content = "Hello, world!";
            ndkEvent.publish()
        } catch (error) {
            console.error("Error publishing event:", error);
            throw error;
        } finally {
            this.isPublishingEvent = false;
        }

— Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you are subscribed to this thread.Message ID: @.***>

pparonson commented 1 month ago

Beautiful! Thank you.