Publish the relay list (NIP-65) from settings

This commit is contained in:
raucao committed 2026-11-18 22:19:46 +04:00
1 parent 29ed14a556
commit 92a36cf3f7
13 files changed
+211 -25

No files matched your search

@@ -1,7 +1,10 @@
<div class="w-[72vw] md:w-[500px]">
<h3 class="mb-6">Edit relays</h3>
<%= form_with url: "#", local: true,
html: { data: { controller: "relay-list-editor" } } do |f| %>
html: { data: {
controller: "relay-list-editor",
action: "submit->relay-list-editor#save"
} } do |f| %>
<ul data-relay-list-editor-target="list" class="mb-4 space-y-2">
<% @relays.each do |relay| %>
<li class="flex gap-x-2 items-center">
@@ -57,6 +60,9 @@
Add relay
</button>
<%= f.submit "Save relay list", class: "btn-md btn-blue w-full" %>
<p class="error-msg mt-2 mb-4 hidden" data-relay-list-editor-target="error"></p>
<%= f.submit "Save relay list", class: "btn-md btn-blue w-full",
data: { :'relay-list-editor-target' => "submit" } %>
<% end %>
</div>
@@ -13,7 +13,7 @@ module Settings
site_relay = Setting.nostr_relay_url
if @nip65_event.blank?
relays = Setting.nostr_discovery_relays.map { |url| { url: url, marker: nil, added: true } }
relays = Setting.nostr_discovery_relays.map { |url| { url: url, marker: nil, added: false } }
if site_relay.present?
relays.reject! { |r| r[:url] == site_relay }
relays.unshift({ url: site_relay, marker: nil, added: true })
+7 -2
View File
@@ -154,7 +154,8 @@ class SettingsController < ApplicationController
case params[:step]
when "relays"
nip65_event = NostrManager::DiscoverUserEvent.call(
pubkey: @user.nostr_pubkey, kind: NostrManagerService::RELAY_LIST_KIND
pubkey: @user.nostr_pubkey, kind: NostrManagerService::RELAY_LIST_KIND,
relays: discovery_relay_urls
)
write_relays = nip65_event ? extract_write_relays(nip65_event) : []
@@ -169,7 +170,7 @@ class SettingsController < ApplicationController
Rails.cache.write(nostr_metadata_cache_key("nip65"), nip65_event, expires_in: 5.minutes)
Rails.cache.write(nostr_metadata_cache_key("write_relays"), write_relays, expires_in: 5.minutes)
render json: { next: "profile" }
render json: { next: "profile", event_id: nip65_event&.dig("id") }
when "profile"
write_relays = Rails.cache.read(nostr_metadata_cache_key("write_relays")) || []
@@ -208,6 +209,10 @@ class SettingsController < ApplicationController
NostrManagerService.metadata_cache_key(@user.id, suffix)
end
def discovery_relay_urls
([Setting.nostr_relay_url] + Array(Setting.nostr_discovery_relays)).compact.uniq
end
def stale?(event, threshold = 30.minutes)
Time.at(event["created_at"]) < threshold.ago
end
@@ -1,5 +1,8 @@
import { Controller } from "@hotwired/stimulus"
const REFRESH_ATTEMPTS = 5
const REFRESH_DELAY = 2000
export default class extends Controller {
static targets = [ "status", "loading", "content" ]
static values = { url: String }
@@ -8,7 +11,16 @@ export default class extends Controller {
this.runStep("relays")
}
async runStep (step) {
refresh (event) {
const expectedId = event.detail ? event.detail.eventId : null
this.contentTarget.classList.add("hidden")
this.contentTarget.innerHTML = ""
this.loadingTarget.classList.remove("hidden")
this.runStep("relays", { expectedId, attempts: 0 })
}
async runStep (step, options = {}) {
const messages = {
relays: "Looking up your relay list…",
profile: "Fetching your profile…",
@@ -38,8 +50,19 @@ export default class extends Controller {
this.contentTarget.innerHTML = html
} else {
const data = await res.json()
if (this.awaitingUpdate(step, data, options)) {
const attempts = (options.attempts || 0) + 1
this.statusTarget.textContent = "Waiting for your relay list to update…"
setTimeout(
() => this.runStep("relays", { ...options, attempts }),
REFRESH_DELAY
)
return
}
if (data.next) {
this.runStep(data.next)
this.runStep(data.next, options)
}
}
} catch (error) {
@@ -47,4 +70,11 @@ export default class extends Controller {
this.statusTarget.textContent = "Something went wrong. Please reload."
}
}
awaitingUpdate (step, data, options) {
return step === "relays" &&
options.expectedId &&
data.event_id !== options.expectedId &&
(options.attempts || 0) < REFRESH_ATTEMPTS
}
}
@@ -1,18 +1,22 @@
import { Controller } from "@hotwired/stimulus"
import { signAndPublish, hasNostrExtension } from "lib/nostr_publish"
const RELAY_LIST_KIND = 10002
export default class extends Controller {
static targets = [ "list", "template", "addedBadge" ]
static targets = [ "list", "template", "addedBadge", "error", "submit" ]
add (event) {
event.preventDefault()
const row = this.templateTarget.content.cloneNode(true)
this.listTarget.appendChild(row)
this.clearError()
}
remove (event) {
event.preventDefault()
const row = event.target.closest("li")
row.remove()
event.target.closest("li").remove()
this.clearError()
}
checkAdded (event) {
@@ -37,4 +41,76 @@ export default class extends Controller {
if (badge) badge.classList.add("hidden")
}
}
async save (event) {
event.preventDefault()
this.clearError()
const relays = this.relays()
if (relays.length === 0) {
this.showError("Please add at least one relay.")
return
}
if (!hasNostrExtension()) {
this.showError("No Nostr extension (NIP-07) found.")
return
}
this.setBusy(true)
try {
const signedEvent = await signAndPublish({
kind: RELAY_LIST_KIND,
created_at: Math.floor(Date.now() / 1000),
tags: relays.map(({ url, marker }) => marker ? ["r", url, marker] : ["r", url]),
content: ""
})
this.element.dispatchEvent(new CustomEvent("nostr:publish", {
bubbles: true,
detail: { eventId: signedEvent.id }
}))
} catch (error) {
this.showError(error.message)
} finally {
this.setBusy(false)
}
}
relays () {
return Array.from(this.listTarget.querySelectorAll("li")).map((row) => {
const input = row.querySelector("input[name='relay_urls[]']")
const select = row.querySelector("select[name='relay_markers[]']")
return {
url: input ? input.value.trim() : "",
marker: select ? select.value : ""
}
}).filter((relay) => relay.url.length > 0)
}
setBusy (busy) {
if (!this.hasSubmitTarget) return
if (busy) {
this.submitTarget.dataset.originalValue = this.submitTarget.value
this.submitTarget.disabled = true
this.submitTarget.value = "Saving…"
} else {
this.submitTarget.disabled = false
this.submitTarget.value = this.submitTarget.dataset.originalValue || this.submitTarget.value
}
}
showError (message) {
if (!this.hasErrorTarget) return
this.errorTarget.textContent = message
this.errorTarget.classList.remove("hidden")
}
clearError () {
if (!this.hasErrorTarget) return
this.errorTarget.textContent = ""
this.errorTarget.classList.add("hidden")
}
}
+2 -1
View File
@@ -10,7 +10,8 @@ export async function signAndPublish (eventTemplate, { url = DEFAULT_URL } = {})
}
const signedEvent = await window.nostr.signEvent(eventTemplate)
return publish(signedEvent, { url })
await publish(signedEvent, { url })
return signedEvent
}
export async function publish (signedEvent, { url = DEFAULT_URL } = {}) {
@@ -15,7 +15,7 @@ module NostrManager
def relays
urls = []
urls << Setting.nostr_relay_url
urls.concat(RelayUrlValidator.filter(user_relays))
urls.concat(RelayUrlValidator.filter(user_relays).take(MAX_RELAY_LIST_SIZE))
urls.reject(&:blank?).uniq
end
+2
View File
@@ -7,6 +7,8 @@ class NostrManagerService < ApplicationService
METADATA_CACHE_SUFFIXES = %w[nip65 write_relays profile].freeze
MAX_RELAY_LIST_SIZE = 10
def self.metadata_cache_key(user_id, suffix)
"nostr_metadata:#{user_id}:#{suffix}"
end
+2 -1
View File
@@ -89,7 +89,8 @@
<% if current_user.nostr_pubkey.present? %>
<div data-controller="nostr-metadata"
data-nostr-metadata-url-value="<%= nostr_metadata_settings_path %>">
data-nostr-metadata-url-value="<%= nostr_metadata_settings_path %>"
data-action="nostr:publish->nostr-metadata#refresh">
<div data-nostr-metadata-target="loading"
class="flex flex-col items-center justify-center py-16">
<div class="mb-4 h-12 w-12"></div>
@@ -11,16 +11,38 @@ RSpec.describe Settings::NostrEditRelaysComponent, type: :component do
])
end
it "wires the form to the relay list editor" do
rendered = render_inline(described_class.new(nip65_event: nil))
form = rendered.css("form").first
expect(form["data-controller"]).to eq("relay-list-editor")
expect(form["data-action"]).to include("submit->relay-list-editor#save")
expect(rendered.css("[data-relay-list-editor-target='error']")).to be_present
expect(rendered.css("[data-relay-list-editor-target='submit']")).to be_present
end
describe "when user has no relay list (nip65_event is nil)" do
it "renders all relays with added status and badges" do
it "prepends the site relay as added and suggests discovery relays without a badge" do
rendered = render_inline(described_class.new(nip65_event: nil))
expect(rendered.css("input[value='wss://nostr.kosmos.org']")).to be_present
expect(rendered.css("input[value='wss://nos.lol']")).to be_present
expect(rendered.css("input[value='wss://relay.damus.io']")).to be_present
list = rendered.css("[data-relay-list-editor-target='list']").first
relay_inputs = list.css("input[name='relay_urls[]']").map { |el| el["value"] }
expect(relay_inputs).to eq([
"wss://nostr.kosmos.org",
"wss://nos.lol",
"wss://relay.damus.io"
])
badges = rendered.css("span.rounded-full").select { |el| el.text.strip == "added" }
expect(badges.size).to eq(3)
expect(badges.size).to eq(1)
site_input = rendered.css("input[value='wss://nostr.kosmos.org']").first
expect(site_input["data-added-value"]).to eq("wss://nostr.kosmos.org")
suggestion_input = rendered.css("input[value='wss://nos.lol']").first
expect(suggestion_input["data-added-value"]).to be_nil
expect(suggestion_input["class"]).not_to include("border-emerald-500")
end
end
+27 -3
View File
@@ -45,18 +45,42 @@ RSpec.describe "Settings::NostrEvents", type: :request do
expect(JSON.parse(response.body)).to eq("ok" => true)
end
it "accepts a relay list event" do
it "accepts a relay list event with read/write markers" do
event = signed_event(
kind: NostrManagerService::RELAY_LIST_KIND,
tags: [["r", "wss://relay.example.com"]]
tags: [
["r", "wss://relay.example.com"],
["r", "wss://read.example.com", "read"],
["r", "wss://write.example.com", "write"]
]
)
expect(NostrPublishUserEventJob).to receive(:perform_later)
expect(NostrPublishUserEventJob).to receive(:perform_later) do |args|
expect(args[:event]["kind"]).to eq(NostrManagerService::RELAY_LIST_KIND)
expect(args[:event]["tags"]).to eq([
["r", "wss://relay.example.com"],
["r", "wss://read.example.com", "read"],
["r", "wss://write.example.com", "write"]
])
end
post_signed_event(event)
expect(response).to have_http_status(:ok)
end
context "with many relays" do
it "accepts the event (the fan-out is bounded, not the list size)" do
tags = (1..12).map { |n| ["r", "wss://relay#{n}.example.com"] }
expect(NostrPublishUserEventJob).to receive(:perform_later)
post_signed_event(
signed_event(kind: NostrManagerService::RELAY_LIST_KIND, tags: tags)
)
expect(response).to have_http_status(:ok)
end
end
context "when the account has no public key" do
before { allow_any_instance_of(User).to receive(:nostr_pubkey).and_return(nil) }
+13 -4
View File
@@ -156,6 +156,13 @@ RSpec.describe "Settings", type: :request do
before do
allow_any_instance_of(User).to receive(:nostr_pubkey).and_return("abc123")
allow_any_instance_of(User).to receive(:display_name).and_return("Mark")
allow(Setting).to receive(:nostr_relay_url).and_return("wss://site.example.com")
allow(Setting).to receive(:nostr_discovery_relays)
.and_return(["wss://discovery.example.com"])
end
let(:discovery_relays) do
["wss://site.example.com", "wss://discovery.example.com"]
end
context "without a pubkey" do
@@ -174,14 +181,15 @@ RSpec.describe "Settings", type: :request do
context "with step=relays" do
it "discovers the relay list and asks for the profile next" do
expect(NostrManager::DiscoverUserEvent).to receive(:call)
.with(pubkey: "abc123", kind: NostrManagerService::RELAY_LIST_KIND)
.with(pubkey: "abc123", kind: NostrManagerService::RELAY_LIST_KIND,
relays: discovery_relays)
.and_return(nil)
get nostr_metadata_settings_path(step: "relays"),
headers: { "HTTP_ACCEPT" => "application/json" }
expect(response).to have_http_status(:ok)
expect(JSON.parse(response.body)).to eq("next" => "profile")
expect(JSON.parse(response.body)).to eq("next" => "profile", "event_id" => nil)
end
context "with a stale relay list" do
@@ -199,7 +207,8 @@ RSpec.describe "Settings", type: :request do
it "refetches the relay list from the user's write relays" do
expect(NostrManager::DiscoverUserEvent).to receive(:call)
.with(pubkey: "abc123", kind: NostrManagerService::RELAY_LIST_KIND)
.with(pubkey: "abc123", kind: NostrManagerService::RELAY_LIST_KIND,
relays: discovery_relays)
.and_return(stale_event)
expect(NostrManager::DiscoverUserEvent).to receive(:call)
.with(pubkey: "abc123", kind: NostrManagerService::RELAY_LIST_KIND,
@@ -210,7 +219,7 @@ RSpec.describe "Settings", type: :request do
headers: { "HTTP_ACCEPT" => "application/json" }
expect(response).to have_http_status(:ok)
expect(JSON.parse(response.body)).to eq("next" => "profile")
expect(JSON.parse(response.body)).to eq("next" => "profile", "event_id" => "old")
end
end
end
@@ -52,6 +52,16 @@ RSpec.describe NostrManager::PublishUserEvent, type: :model do
described_class.call(event: list)
end
it "bounds the fan-out to the maximum number of relays" do
tags = (1..15).map { |n| ["r", "wss://relay#{n}.example.com"] }
list = build_event(kind: NostrManagerService::RELAY_LIST_KIND, tags: tags)
expect(NostrManager::PublishEvent).to receive(:call)
.exactly(NostrManagerService::MAX_RELAY_LIST_SIZE + 1).times
described_class.call(event: list)
end
end
describe "for a profile event (kind 0)" do