Files
akkounts/app/javascript/controllers/nostr_signer_connect_controller.js
raucao 70faa4f329 Update the signer section in place instead of reloading the page
Disconnecting, cancelling and (when a key already exists) connecting now swap the Nostr Connect section via Turbo Streams, so the page's relay/profile/media lookups are not re-fetched. A replace still reloads because it changes the key, and a first-time connect reloads to reveal the pubkey and metadata.
2026-11-28 13:42:38 +04:00

248 lines
7.2 KiB
JavaScript

import { Controller } from "@hotwired/stimulus"
import { csrfToken } from "lib/csrf"
const POLL_INTERVAL = 2000
const MAX_ATTEMPTS = 160
export default class extends Controller {
static targets = [ "status", "error", "authWrapper", "authLink", "details", "retry", "signerHint", "qr", "qrToggle", "replace", "replaceExisting", "replaceSigner" ]
static values = { statusUrl: String, replaceUrl: String, destroyUrl: String, sectionUrl: String }
connect () {
this.attempts = 0
this.stopped = false
this.poll()
}
disconnect () {
this.stopped = true
clearTimeout(this.timer)
}
async poll () {
if (this.stopped) return
this.attempts += 1
try {
const response = await fetch(this.statusUrlValue, {
credentials: "include",
headers: { "Accept": "application/json" }
})
const data = await response.json().catch(() => ({}))
if (!response.ok) {
throw new Error(data.error || `HTTP ${response.status}`)
}
if (data.status === "connected") {
this.finishConnection(data.redirect_url)
return
}
if (data.status === "replace_required") {
this.showReplace(data.existing_npub, data.signer_npub)
return
}
if (data.status === "failed" || data.status === "expired" || data.status === "disconnected") {
this.showTerminalError(data.error || "The connection failed. Please try again.")
return
}
this.showAuthUrl(data.auth_url)
if (this.attempts >= MAX_ATTEMPTS) {
this.showTerminalError("Timed out waiting for your signer. Please try again.")
return
}
this.timer = setTimeout(() => this.poll(), POLL_INTERVAL)
} catch (error) {
this.showError(error.message)
}
}
openSigner () {
if (!this.hasSignerHintTarget) return
this.signerHintTarget.classList.add("hidden")
const attempt = this.launchAttempt = (this.launchAttempt || 0) + 1
let launched = false
let timer
let onNavigateError
const finish = () => {
clearTimeout(timer)
document.removeEventListener("visibilitychange", onVisibility)
window.removeEventListener("blur", onBlur)
if (onNavigateError && "navigation" in window) {
navigation.removeEventListener("navigateerror", onNavigateError)
}
}
const revealHint = () => {
if (attempt !== this.launchAttempt || !this.hasSignerHintTarget) return
this.signerHintTarget.classList.remove("hidden")
}
const markLaunched = () => {
launched = true
finish()
}
const onVisibility = () => {
if (document.visibilityState === "hidden") markLaunched()
}
const onBlur = () => markLaunched()
document.addEventListener("visibilitychange", onVisibility)
window.addEventListener("blur", onBlur, { once: true })
if ("navigation" in window) {
onNavigateError = (event) => {
if (!event.destination?.url?.startsWith("nostrconnect:")) return
finish()
revealHint()
}
navigation.addEventListener("navigateerror", onNavigateError)
}
timer = setTimeout(() => {
if (launched || attempt !== this.launchAttempt) return
finish()
revealHint()
}, 2000)
}
showQr () {
if (!this.hasQrTarget) return
this.qrTarget.classList.remove("hidden")
this.qrTarget.classList.add("flex")
if (this.hasQrToggleTarget) this.qrToggleTarget.classList.add("hidden")
}
showReplace (existingNpub, signerNpub) {
this.stopped = true
clearTimeout(this.timer)
if (this.hasReplaceExistingTarget) {
this.replaceExistingTarget.textContent = existingNpub || ""
}
if (this.hasReplaceSignerTarget) {
this.replaceSignerTarget.textContent = signerNpub || ""
}
this.statusTarget.classList.add("hidden")
if (this.hasDetailsTarget) this.detailsTarget.classList.add("hidden")
if (this.hasAuthWrapperTarget) this.authWrapperTarget.classList.add("hidden")
if (this.hasReplaceTarget) this.replaceTarget.classList.remove("hidden")
}
async replace () {
if (!this.hasReplaceUrlValue || !this.replaceUrlValue) return
try {
const response = await fetch(this.replaceUrlValue, {
method: "POST", credentials: "include",
headers: { "Accept": "application/json", "X-CSRF-Token": csrfToken() }
})
const data = await response.json().catch(() => ({}))
if (!response.ok) {
throw new Error(data.error || `HTTP ${response.status}`)
}
if (data.status === "connected") {
// Replacing links a different key, so the pubkey field, profile and
// media server lists elsewhere on the page are stale — full reload.
window.location.reload()
return
}
this.showError(data.error || "Could not replace the key. Please try again.")
} catch (error) {
this.showError(error.message)
}
}
async cancel () {
try {
if (this.hasDestroyUrlValue && this.destroyUrlValue) {
await fetch(this.destroyUrlValue, {
method: "DELETE", credentials: "include",
headers: { "Accept": "application/json", "X-CSRF-Token": csrfToken() }
})
}
} catch (error) {
// Ignore; the section update below reflects whatever state the server is in.
}
this.finishConnection()
}
// After the connection is established (or cancelled), update just the signer
// section so the page's Nostr metadata isn't re-fetched from relays. Falls
// back to a full reload when there is no section to update (login flow) or
// when the account had no key yet (the pubkey field and metadata need a fresh
// page).
finishConnection (redirectUrl) {
if (!this.hasSectionUrlValue || !this.sectionUrlValue) {
if (this.hasStatusTarget) this.statusTarget.textContent = "Connected. Redirecting…"
window.location.href = redirectUrl || window.location.href
return
}
if (!this.hasAccountKey()) {
window.location.reload()
return
}
if (this.hasStatusTarget) this.statusTarget.textContent = "Connected. Updating…"
this.refreshSection()
}
hasAccountKey () {
return Boolean(document.querySelector('[data-controller~="nostr-metadata"]'))
}
async refreshSection () {
try {
const response = await fetch(this.sectionUrlValue, {
credentials: "include",
headers: { "Accept": "text/vnd.turbo-stream.html" }
})
if (!response.ok || response.redirected) {
window.location.reload()
return
}
window.Turbo.renderStreamMessage(await response.text())
} catch (error) {
window.location.reload()
}
}
showAuthUrl (url) {
if (!url) {
this.authWrapperTarget.classList.add("hidden")
return
}
this.authLinkTarget.href = url
this.authWrapperTarget.classList.remove("hidden")
}
showError (message) {
this.errorTarget.textContent = message
this.errorTarget.classList.remove("hidden")
}
showTerminalError (message) {
this.showError(message)
this.statusTarget.textContent = "Connection request ended."
if (this.hasDetailsTarget) this.detailsTarget.classList.add("hidden")
if (this.hasRetryTarget) this.retryTarget.classList.remove("hidden")
}
}