import { Controller } from "@hotwired/stimulus" // Connects to data-controller="settings--nostr-pubkey" export default class extends Controller { static targets = [ "noExtension", "setPubkey", "pubkeyBech32Input" ] static values = { userAddress: String, pubkeyHex: String, site: String, sharedSecret: String } connect () { if (window.nostr) { if (this.hasSetPubkeyTarget) { this.setPubkeyTarget.disabled = false } } else { this.noExtensionTarget.classList.remove("hidden") } } async setPubkey () { this.setPubkeyTarget.disabled = true try { // Auth based on NIP-42 const signedEvent = await window.nostr.signEvent({ created_at: Math.floor(Date.now() / 1000), kind: 22242, tags: [ ["site", this.siteValue], ["challenge", this.sharedSecretValue] ], content: "" }) const res = await fetch("/settings/set_nostr_pubkey", { method: "POST", credentials: "include", headers: { "Accept": "application/json", 'Content-Type': 'application/json', "X-CSRF-Token": this.csrfToken }, body: JSON.stringify({ signed_event: signedEvent }) }); window.location.reload() } catch (error) { console.warn('Unable to verify pubkey:', error.message) this.setPubkeyTarget.disabled = false } } get csrfToken () { const element = document.head.querySelector('meta[name="csrf-token"]') return element.getAttribute("content") } }