Nostr onboarding: publish profile, relay list and media server list #269
No files matched your search
@@ -87,6 +87,7 @@
|
||||
# NOSTR_PRIVATE_KEY='123456abcdef...'
|
||||
# NOSTR_PUBLIC_KEY='123456abcdef...'
|
||||
# NOSTR_RELAY_URL='wss://nostr.kosmos.org'
|
||||
# NOSTR_BLOSSOM_SERVER_URL='https://blossom.kosmos.org'
|
||||
|
||||
# RS_STORAGE_URL='https://storage.kosmos.org'
|
||||
# RS_REDIS_URL='redis://localhost:6379/2'
|
||||
@@ -47,3 +47,7 @@ dump.rdb
|
||||
|
||||
# Ignore generated ctags
|
||||
*.tags
|
||||
|
||||
# Ignore local agent tooling artifacts
|
||||
/.agents
|
||||
/skills-lock.json
|
||||
@@ -12,7 +12,7 @@
|
||||
</p>
|
||||
<% end %>
|
||||
|
||||
<%= tag.p class: "flex gap-x-1", data: {
|
||||
<%= tag.div class: "flex gap-x-1", data: {
|
||||
controller: @resettable ? "settings--resettable-field" : nil,
|
||||
} do %>
|
||||
<%= content %>
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
<div class="w-[72vw] md:w-[500px]">
|
||||
<h3 class="mb-6">Edit media servers</h3>
|
||||
<%= form_with url: "#", local: true,
|
||||
html: { data: {
|
||||
controller: "url-list-editor",
|
||||
action: "submit->url-list-editor#save",
|
||||
:'url-list-editor-kind-value' => NostrManagerService::MEDIA_SERVER_LIST_KIND,
|
||||
:'url-list-editor-tag-value' => "server",
|
||||
:'url-list-editor-markers-value' => false,
|
||||
:'url-list-editor-pattern-value' => "^https?://",
|
||||
:'url-list-editor-empty-message-value' => "Please add at least one media server.",
|
||||
:'url-list-editor-invalid-message-value' => "Media server URLs must start with http:// or https://."
|
||||
} } do |f| %>
|
||||
<ul data-url-list-editor-target="list" class="mb-4 space-y-2">
|
||||
<% @servers.each do |server| %>
|
||||
<li class="flex gap-x-2 items-center">
|
||||
<div class="relative grow">
|
||||
<% if server[:added] %>
|
||||
<input type="text" name="server_urls[]" value="<%= server[:url] %>"
|
||||
data-added-value="<%= server[:url] %>"
|
||||
data-action="input->url-list-editor#checkAdded"
|
||||
class="w-full pr-16 border-emerald-500 ring-1 ring-emerald-500 focus:border-emerald-500 focus:ring-emerald-500 bg-emerald-50/20" />
|
||||
<span class="absolute inset-y-0 right-2.5 flex items-center pointer-events-none"
|
||||
data-url-list-editor-target="addedBadge">
|
||||
<span class="rounded-full bg-emerald-100 px-2 py-0.5 text-xs font-semibold text-emerald-800">
|
||||
added
|
||||
</span>
|
||||
</span>
|
||||
<% else %>
|
||||
<input type="text" name="server_urls[]" value="<%= server[:url] %>" class="w-full" />
|
||||
<% end %>
|
||||
</div>
|
||||
<button type="button" class="btn-md btn-icon btn-outline text-red-700 shrink-0"
|
||||
data-action="click->url-list-editor#remove" title="Remove media server">
|
||||
<%= render partial: "icons/trash-2", locals: { custom_class: "h-4 w-4" } %>
|
||||
</button>
|
||||
</li>
|
||||
<% end %>
|
||||
</ul>
|
||||
|
||||
<template data-url-list-editor-target="template">
|
||||
<li class="flex gap-x-2 items-center">
|
||||
<div class="relative grow">
|
||||
<input type="text" name="server_urls[]" value="" class="w-full" />
|
||||
</div>
|
||||
<button type="button" class="btn-md btn-icon btn-outline text-red-700 shrink-0"
|
||||
data-action="click->url-list-editor#remove" title="Remove media server">
|
||||
<%= render partial: "icons/trash-2", locals: { custom_class: "h-4 w-4" } %>
|
||||
</button>
|
||||
</li>
|
||||
</template>
|
||||
|
||||
<button type="button" class="btn-md btn-gray w-full mb-6"
|
||||
data-action="click->url-list-editor#add">
|
||||
<%= render partial: "icons/plus", locals: { custom_class: "h-4 w-4 inline mr-1" } %>
|
||||
Add media server
|
||||
</button>
|
||||
|
||||
<p class="error-msg mt-2 mb-4 hidden" data-url-list-editor-target="error"></p>
|
||||
|
||||
<%= f.submit "Save media servers", class: "btn-md btn-blue w-full",
|
||||
data: { :'url-list-editor-target' => "submit" } %>
|
||||
<% end %>
|
||||
</div>
|
||||
@@ -0,0 +1,31 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Settings
|
||||
class NostrEditMediaServersComponent < ViewComponent::Base
|
||||
def initialize(media_list_event: nil)
|
||||
@media_list_event = media_list_event
|
||||
@servers = build_servers
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def build_servers
|
||||
site_server = Setting.nostr_blossom_server_url
|
||||
|
||||
if @media_list_event.blank?
|
||||
return [] if site_server.blank?
|
||||
|
||||
[{ url: site_server, added: true }]
|
||||
else
|
||||
existing = @media_list_event["tags"]
|
||||
.select { |t| t.is_a?(Array) && t[0] == "server" }
|
||||
.map { |t| { url: t[1], added: false } }
|
||||
|
||||
if site_server.present? && existing.none? { |s| s[:url] == site_server }
|
||||
existing.unshift({ url: site_server, added: true })
|
||||
end
|
||||
existing
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,162 @@
|
||||
<div class="w-[72vw] md:w-[500px]">
|
||||
<header class="absolute z-10 h-36 sm:h-44 inset-x-1 top-1 rounded-t
|
||||
bg-cover bg-center bg-gray-50"
|
||||
style="<%= "background-image: url('#{banner_url}');" if banner_url %>">
|
||||
<div class="inline-block z-20 size-28 sm:size-32 ml-4 mt-16 sm:mt-20">
|
||||
<% if picture_url.present? %>
|
||||
<img src="<%= picture_url %>"
|
||||
class="inline-block size:28 sm:size-32 rounded-full border-2 border-white" />
|
||||
<% else %>
|
||||
<span class="inline-block size:28 sm:size-32 overflow-hidden rounded-full border-2 border-white bg-gray-100">
|
||||
<svg class="size-full text-gray-300" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M24 20.993V24H0v-2.996A14.977 14.977 0 0112.004 15c4.904 0 9.26 2.354 11.996 5.993zM16.002 8.999a4 4 0 11-8 0 4 4 0 018 0z" />
|
||||
</svg>
|
||||
</span>
|
||||
<% end %>
|
||||
</div>
|
||||
</header>
|
||||
<main class="mt-44 sm:mt-52">
|
||||
<%= form_for(@user, url: "#", html: {
|
||||
:method => :put,
|
||||
data: {
|
||||
controller: "nostr-profile-editor",
|
||||
action: "submit->nostr-profile-editor#save",
|
||||
:'nostr-profile-editor-profile-value' => @profile.to_json,
|
||||
:'nostr-profile-editor-handle-value' => @user.cn
|
||||
}
|
||||
}) do |f| %>
|
||||
<%= render FormElements::FieldsetComponent.new(tag: "div", title: "Display name") do %>
|
||||
<%= f.text_field :display_name, value: @display_name, class: "w-full sm:w-3/5" %>
|
||||
<% end %>
|
||||
<%= render FormElements::FieldsetComponent.new(tag: "div", title: "Nostr address (NIP-05)") do %>
|
||||
<% if @nip05_state[:status] == :added %>
|
||||
<div class="w-full sm:w-3/5 flex flex-col" data-controller="field-suggestion"
|
||||
data-field-suggestion-added-value-value="<%= @user.address %>">
|
||||
<div class="relative">
|
||||
<%= f.text_field :nip05_address, value: @nip05_state[:value],
|
||||
data: {
|
||||
:'field-suggestion-target' => "input",
|
||||
action: "input->field-suggestion#checkAdded"
|
||||
},
|
||||
class: "w-full pr-16 border-emerald-500 ring-1 ring-emerald-500 focus:border-emerald-500 focus:ring-emerald-500 bg-emerald-50/20" %>
|
||||
<span class="absolute inset-y-0 right-2.5 flex items-center pointer-events-none"
|
||||
data-field-suggestion-target="badge">
|
||||
<span class="rounded-full bg-emerald-100 px-2 py-0.5 text-xs font-semibold text-emerald-800">
|
||||
added
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-1.5 flex items-center justify-between text-xs text-amber-800 bg-amber-50 rounded px-2.5 py-1.5 border border-amber-200 hidden"
|
||||
data-field-suggestion-target="suggestion">
|
||||
<span>Account address: <strong><%= @user.address %></strong></span>
|
||||
<button type="button" class="font-semibold text-blue-600 hover:text-blue-800 underline ml-2"
|
||||
data-action="click->field-suggestion#apply"
|
||||
data-field-suggestion-value-param="<%= @user.address %>">
|
||||
Use this
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<% elsif @nip05_state[:status] == :different %>
|
||||
<div class="w-full sm:w-3/5 flex flex-col" data-controller="field-suggestion"
|
||||
data-field-suggestion-added-value-value="<%= @nip05_state[:suggested] %>">
|
||||
<div class="relative">
|
||||
<%= f.text_field :nip05_address, value: @nip05_state[:value],
|
||||
data: {
|
||||
:'field-suggestion-target' => "input",
|
||||
action: "input->field-suggestion#checkAdded"
|
||||
},
|
||||
class: "w-full pr-20 border-amber-400 ring-1 ring-amber-400 focus:border-amber-400 focus:ring-amber-400" %>
|
||||
<span class="absolute inset-y-0 right-2.5 flex items-center pointer-events-none"
|
||||
data-field-suggestion-target="badge">
|
||||
<span class="rounded-full bg-amber-100 px-2 py-0.5 text-xs font-semibold text-amber-800">
|
||||
different
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-1.5 flex items-center justify-between text-xs text-amber-800 bg-amber-50 rounded px-2.5 py-1.5 border border-amber-200"
|
||||
data-field-suggestion-target="suggestion">
|
||||
<span>Account address: <strong><%= @nip05_state[:suggested] %></strong></span>
|
||||
<button type="button" class="font-semibold text-blue-600 hover:text-blue-800 underline ml-2"
|
||||
data-action="click->field-suggestion#apply"
|
||||
data-field-suggestion-value-param="<%= @nip05_state[:suggested] %>">
|
||||
Use this
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<% else %>
|
||||
<%= f.text_field :nip05_address, value: @nip05_state[:value], class: "w-full sm:w-3/5" %>
|
||||
<% end %>
|
||||
<% end %>
|
||||
<%= render FormElements::FieldsetComponent.new(tag: "div", title: "Lightning address for Zaps") do %>
|
||||
<% if @lud16_state[:status] == :added %>
|
||||
<div class="w-full sm:w-3/5 flex flex-col" data-controller="field-suggestion"
|
||||
data-field-suggestion-added-value-value="<%= @user.address %>">
|
||||
<div class="relative">
|
||||
<%= f.text_field :lud16_address, value: @lud16_state[:value],
|
||||
data: {
|
||||
:'field-suggestion-target' => "input",
|
||||
action: "input->field-suggestion#checkAdded"
|
||||
},
|
||||
class: "w-full pr-16 border-emerald-500 ring-1 ring-emerald-500 focus:border-emerald-500 focus:ring-emerald-500 bg-emerald-50/20" %>
|
||||
<span class="absolute inset-y-0 right-2.5 flex items-center pointer-events-none"
|
||||
data-field-suggestion-target="badge">
|
||||
<span class="rounded-full bg-emerald-100 px-2 py-0.5 text-xs font-semibold text-emerald-800">
|
||||
added
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-1.5 flex items-center justify-between text-xs text-amber-800 bg-amber-50 rounded px-2.5 py-1.5 border border-amber-200 hidden"
|
||||
data-field-suggestion-target="suggestion">
|
||||
<span>Account address: <strong><%= @user.address %></strong></span>
|
||||
<button type="button" class="font-semibold text-blue-600 hover:text-blue-800 underline ml-2"
|
||||
data-action="click->field-suggestion#apply"
|
||||
data-field-suggestion-value-param="<%= @user.address %>">
|
||||
Use this
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<% elsif @lud16_state[:status] == :different %>
|
||||
<div class="w-full sm:w-3/5 flex flex-col" data-controller="field-suggestion"
|
||||
data-field-suggestion-added-value-value="<%= @lud16_state[:suggested] %>">
|
||||
<div class="relative">
|
||||
<%= f.text_field :lud16_address, value: @lud16_state[:value],
|
||||
data: {
|
||||
:'field-suggestion-target' => "input",
|
||||
action: "input->field-suggestion#checkAdded"
|
||||
},
|
||||
class: "w-full pr-20 border-amber-400 ring-1 ring-amber-400 focus:border-amber-400 focus:ring-amber-400" %>
|
||||
<span class="absolute inset-y-0 right-2.5 flex items-center pointer-events-none"
|
||||
data-field-suggestion-target="badge">
|
||||
<span class="rounded-full bg-amber-100 px-2 py-0.5 text-xs font-semibold text-amber-800">
|
||||
different
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-1.5 flex items-center justify-between text-xs text-amber-800 bg-amber-50 rounded px-2.5 py-1.5 border border-amber-200"
|
||||
data-field-suggestion-target="suggestion">
|
||||
<span>Account address: <strong><%= @lud16_state[:suggested] %></strong></span>
|
||||
<button type="button" class="font-semibold text-blue-600 hover:text-blue-800 underline ml-2"
|
||||
data-action="click->field-suggestion#apply"
|
||||
data-field-suggestion-value-param="<%= @lud16_state[:suggested] %>">
|
||||
Use this
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<% else %>
|
||||
<%= f.text_field :lud16_address, value: @lud16_state[:value], class: "w-full sm:w-3/5" %>
|
||||
<% end %>
|
||||
<% end %>
|
||||
|
||||
<p class="error-msg mt-2 hidden" data-nostr-profile-editor-target="error"></p>
|
||||
|
||||
<p class="mt-8">
|
||||
<%= f.submit "Save profile", class: "btn-md btn-blue w-full",
|
||||
data: { :'nostr-profile-editor-target' => "submit" } %>
|
||||
</p>
|
||||
<% end %>
|
||||
</main>
|
||||
<footer>
|
||||
<%# <%= @profile.inspect %>
|
||||
<%# <%= @profile_event.inspect %>
|
||||
</footer>
|
||||
</div>
|
||||
@@ -0,0 +1,58 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Settings
|
||||
class NostrEditProfileComponent < ViewComponent::Base
|
||||
attr_reader :user, :profile, :profile_event, :display_name, :nip05_state, :lud16_state
|
||||
|
||||
def initialize(user:, profile_event: nil)
|
||||
@user = user
|
||||
@profile_event = profile_event
|
||||
@profile = {}
|
||||
@display_name = nil
|
||||
|
||||
if profile_event.present? && profile_event["content"].present?
|
||||
@profile = JSON.parse(profile_event["content"]) rescue {}
|
||||
@display_name = @profile["display_name"] || @profile["displayName"]
|
||||
end
|
||||
|
||||
@display_name ||= @user.display_name
|
||||
|
||||
@nip05_state = compute_field_state(@profile["nip05"])
|
||||
@lud16_state = compute_field_state(@profile["lud16"])
|
||||
end
|
||||
|
||||
def banner_url
|
||||
safe_image_url(@profile["banner"])
|
||||
end
|
||||
|
||||
def picture_url
|
||||
safe_image_url(@profile["picture"])
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def safe_image_url(value)
|
||||
return nil unless value.is_a?(String)
|
||||
return nil if value.blank? || value.length > 2048
|
||||
|
||||
uri = URI.parse(value)
|
||||
return nil unless %w[http https].include?(uri.scheme)
|
||||
|
||||
value
|
||||
rescue URI::InvalidURIError
|
||||
nil
|
||||
end
|
||||
|
||||
def compute_field_state(current_value)
|
||||
target_value = @user.address
|
||||
|
||||
if current_value.blank?
|
||||
{ status: :added, value: target_value, suggested: nil }
|
||||
elsif current_value == target_value
|
||||
{ status: :matched, value: current_value, suggested: nil }
|
||||
else
|
||||
{ status: :different, value: current_value, suggested: target_value }
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,74 @@
|
||||
<div class="w-[72vw] md:w-[500px]">
|
||||
<h3 class="mb-6">Edit relays</h3>
|
||||
<%= form_with url: "#", local: true,
|
||||
html: { data: {
|
||||
controller: "url-list-editor",
|
||||
action: "submit->url-list-editor#save",
|
||||
:'url-list-editor-kind-value' => NostrManagerService::RELAY_LIST_KIND,
|
||||
:'url-list-editor-tag-value' => "r",
|
||||
:'url-list-editor-markers-value' => true,
|
||||
:'url-list-editor-pattern-value' => "^wss?://",
|
||||
:'url-list-editor-empty-message-value' => "Please add at least one relay.",
|
||||
:'url-list-editor-invalid-message-value' => "Relay URLs must start with ws:// or wss://."
|
||||
} } do |f| %>
|
||||
<ul data-url-list-editor-target="list" class="mb-4 space-y-2">
|
||||
<% @relays.each do |relay| %>
|
||||
<li class="flex gap-x-2 items-center">
|
||||
<div class="relative grow">
|
||||
<% if relay[:added] %>
|
||||
<input type="text" name="relay_urls[]" value="<%= relay[:url] %>"
|
||||
data-added-value="<%= relay[:url] %>"
|
||||
data-action="input->url-list-editor#checkAdded"
|
||||
class="w-full pr-16 border-emerald-500 ring-1 ring-emerald-500 focus:border-emerald-500 focus:ring-emerald-500 bg-emerald-50/20" />
|
||||
<span class="absolute inset-y-0 right-2.5 flex items-center pointer-events-none"
|
||||
data-url-list-editor-target="addedBadge">
|
||||
<span class="rounded-full bg-emerald-100 px-2 py-0.5 text-xs font-semibold text-emerald-800">
|
||||
added
|
||||
</span>
|
||||
</span>
|
||||
<% else %>
|
||||
<input type="text" name="relay_urls[]" value="<%= relay[:url] %>" class="w-full" />
|
||||
<% end %>
|
||||
</div>
|
||||
<select name="relay_markers[]" class="shrink-0 w-36 sm:w-40">
|
||||
<option value=""<%= %( selected="selected") if relay[:marker].nil? %>>Read & write</option>
|
||||
<option value="read"<%= %( selected="selected") if relay[:marker] == "read" %>>Read only</option>
|
||||
<option value="write"<%= %( selected="selected") if relay[:marker] == "write" %>>Write only</option>
|
||||
</select>
|
||||
<button type="button" class="btn-md btn-icon btn-outline text-red-700 shrink-0"
|
||||
data-action="click->url-list-editor#remove" title="Remove relay">
|
||||
<%= render partial: "icons/trash-2", locals: { custom_class: "h-4 w-4" } %>
|
||||
</button>
|
||||
</li>
|
||||
<% end %>
|
||||
</ul>
|
||||
|
||||
<template data-url-list-editor-target="template">
|
||||
<li class="flex gap-x-2 items-center">
|
||||
<div class="relative grow">
|
||||
<input type="text" name="relay_urls[]" value="" class="w-full" />
|
||||
</div>
|
||||
<select name="relay_markers[]" class="shrink-0 w-36 sm:w-40">
|
||||
<option value="">Read & write</option>
|
||||
<option value="read">Read only</option>
|
||||
<option value="write">Write only</option>
|
||||
</select>
|
||||
<button type="button" class="btn-md btn-icon btn-outline text-red-700 shrink-0"
|
||||
data-action="click->url-list-editor#remove" title="Remove relay">
|
||||
<%= render partial: "icons/trash-2", locals: { custom_class: "h-4 w-4" } %>
|
||||
</button>
|
||||
</li>
|
||||
</template>
|
||||
|
||||
<button type="button" class="btn-md btn-gray w-full mb-6"
|
||||
data-action="click->url-list-editor#add">
|
||||
<%= render partial: "icons/plus", locals: { custom_class: "h-4 w-4 inline mr-1" } %>
|
||||
Add relay
|
||||
</button>
|
||||
|
||||
<p class="error-msg mt-2 mb-4 hidden" data-url-list-editor-target="error"></p>
|
||||
|
||||
<%= f.submit "Save relay list", class: "btn-md btn-blue w-full",
|
||||
data: { :'url-list-editor-target' => "submit" } %>
|
||||
<% end %>
|
||||
</div>
|
||||
@@ -0,0 +1,34 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Settings
|
||||
class NostrEditRelaysComponent < ViewComponent::Base
|
||||
def initialize(nip65_event: nil)
|
||||
@nip65_event = nip65_event
|
||||
@relays = build_relays
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def build_relays
|
||||
site_relay = Setting.nostr_relay_url
|
||||
|
||||
if @nip65_event.blank?
|
||||
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 })
|
||||
end
|
||||
relays
|
||||
else
|
||||
existing = @nip65_event["tags"]
|
||||
.select { |t| t[0] == "r" }
|
||||
.map { |t| { url: t[1], marker: t[2], added: false } }
|
||||
|
||||
if site_relay.present? && existing.none? { |r| r[:url] == site_relay }
|
||||
existing.unshift({ url: site_relay, marker: nil, added: true })
|
||||
end
|
||||
existing
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,18 @@
|
||||
<% @statuses.each do |status| %>
|
||||
<%= render StatusTextComponent.new(
|
||||
text: status[:text],
|
||||
icon_name: status[:icon_name],
|
||||
icon_color: status[:icon_color]
|
||||
) %>
|
||||
<% end %>
|
||||
|
||||
<div class="mt-8" data-controller="modal" data-action="keydown.esc->modal#close">
|
||||
<button data-action="click->modal#open" class="btn-md btn-blue w-full sm:w-auto">
|
||||
<%= @button_text %>
|
||||
</button>
|
||||
<%= render ModalComponent.new(show_close_button: false) do %>
|
||||
<%= render Settings::NostrEditMediaServersComponent.new(
|
||||
media_list_event: @media_list_event
|
||||
) %>
|
||||
<% end %>
|
||||
</div>
|
||||
@@ -0,0 +1,60 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Settings
|
||||
class NostrMediaServerStatusComponent < ViewComponent::Base
|
||||
def initialize(media_list_event:, server_url: Setting.nostr_blossom_server_url)
|
||||
@media_list_event = media_list_event
|
||||
@server_url = server_url
|
||||
@server_host = server_host(server_url)
|
||||
@statuses = []
|
||||
|
||||
if media_list_event.present?
|
||||
@statuses.push({
|
||||
text: "You have a media server list configured",
|
||||
icon_name: "check-circle",
|
||||
icon_color: "emerald-500"
|
||||
})
|
||||
|
||||
if @server_url.present?
|
||||
if normalized_server_urls(media_list_event).include?(NostrManagerService.normalize_url(@server_url))
|
||||
@statuses.push({
|
||||
text: "The <strong>#{@server_host}</strong> media server is part of your list",
|
||||
icon_name: "check-circle",
|
||||
icon_color: "emerald-500"
|
||||
})
|
||||
else
|
||||
@statuses.push({
|
||||
text: "<strong>#{@server_host}</strong> is missing from your media server list",
|
||||
icon_name: "alert-octagon",
|
||||
icon_color: "amber-500"
|
||||
})
|
||||
end
|
||||
end
|
||||
else
|
||||
@statuses.push({
|
||||
text: "We could not find a media server list for your public key",
|
||||
icon_name: "alert-octagon",
|
||||
icon_color: "amber-500"
|
||||
})
|
||||
end
|
||||
|
||||
@button_text = (media_list_event.present? ? "Edit media servers" : "Set up media servers")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def server_host(url)
|
||||
URI.parse(url).host
|
||||
rescue URI::InvalidURIError
|
||||
nil
|
||||
end
|
||||
|
||||
def server_urls(event)
|
||||
event["tags"].select { |t| t.is_a?(Array) && t[0] == "server" }.map { |t| t[1] }
|
||||
end
|
||||
|
||||
def normalized_server_urls(event)
|
||||
server_urls(event).map { |url| NostrManagerService.normalize_url(url) }
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,8 @@
|
||||
<% @statuses.each do |status| %>
|
||||
<%= render StatusTextComponent.new(
|
||||
text: status[:text],
|
||||
icon_name: status[:icon_name],
|
||||
icon_color: status[:icon_color]
|
||||
) %>
|
||||
<% end %>
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Settings
|
||||
class NostrProfileStatusComponent < ViewComponent::Base
|
||||
def initialize(profile_event:, user_address:)
|
||||
@statuses = []
|
||||
|
||||
if profile_event.present?
|
||||
profile = JSON.parse(profile_event["content"])
|
||||
|
||||
@statuses.push({
|
||||
text: "You have a public Nostr profile",
|
||||
icon_name: "check-circle",
|
||||
icon_color: "emerald-500"
|
||||
})
|
||||
|
||||
if profile["nip05"].present? && profile["nip05"] == user_address
|
||||
@statuses.push({
|
||||
text: "Your profile's Nostr address is set to <strong>#{ user_address }</strong>",
|
||||
icon_name: "check-circle",
|
||||
icon_color: "emerald-500"
|
||||
})
|
||||
else
|
||||
@statuses.push({
|
||||
text: "Your profile's Nostr address is not set to <strong>#{ user_address }</strong> yet",
|
||||
icon_name: "alert-octagon",
|
||||
icon_color: "amber-500"
|
||||
})
|
||||
end
|
||||
|
||||
if profile["lud16"].present? && profile["lud16"] == user_address
|
||||
@statuses.push({
|
||||
text: "Your profile's Lightning address is set to <strong>#{ user_address }</strong>",
|
||||
icon_name: "check-circle",
|
||||
icon_color: "emerald-500"
|
||||
})
|
||||
else
|
||||
@statuses.push({
|
||||
text: "Your profile's Lightning address is not set to <strong>#{ user_address }</strong> yet",
|
||||
icon_name: "alert-octagon",
|
||||
icon_color: "amber-500"
|
||||
})
|
||||
end
|
||||
else
|
||||
@statuses.push({
|
||||
text: "We could not find a profile for your public key",
|
||||
icon_name: "alert-octagon",
|
||||
icon_color: "amber-500"
|
||||
})
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,18 @@
|
||||
<% @statuses.each do |status| %>
|
||||
<%= render StatusTextComponent.new(
|
||||
text: status[:text],
|
||||
icon_name: status[:icon_name],
|
||||
icon_color: status[:icon_color]
|
||||
) %>
|
||||
<% end %>
|
||||
|
||||
<div class="mt-8" data-controller="modal" data-action="keydown.esc->modal#close">
|
||||
<button data-action="click->modal#open" class="btn-md btn-blue w-full sm:w-auto">
|
||||
<%= @button_text %>
|
||||
</button>
|
||||
<%= render ModalComponent.new(show_close_button: false) do %>
|
||||
<%= render Settings::NostrEditRelaysComponent.new(
|
||||
nip65_event: @nip65_event
|
||||
) %>
|
||||
<% end %>
|
||||
</div>
|
||||
@@ -0,0 +1,60 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Settings
|
||||
class NostrRelayStatusComponent < ViewComponent::Base
|
||||
def initialize(nip65_event:, relay_url: Setting.nostr_relay_url)
|
||||
@nip65_event = nip65_event
|
||||
@relay_url = relay_url
|
||||
@relay_host = relay_host(relay_url)
|
||||
@statuses = []
|
||||
|
||||
if nip65_event.present?
|
||||
@statuses.push({
|
||||
text: "You have a relay list configured",
|
||||
icon_name: "check-circle",
|
||||
icon_color: "emerald-500"
|
||||
})
|
||||
|
||||
if @relay_url.present?
|
||||
if normalized_relay_urls(nip65_event).include?(NostrManagerService.normalize_url(@relay_url))
|
||||
@statuses.push({
|
||||
text: "The <strong>#{@relay_host}</strong> relay is part of your relay list",
|
||||
icon_name: "check-circle",
|
||||
icon_color: "emerald-500"
|
||||
})
|
||||
else
|
||||
@statuses.push({
|
||||
text: "<strong>#{@relay_host}</strong> is missing from your relay list",
|
||||
icon_name: "alert-octagon",
|
||||
icon_color: "amber-500"
|
||||
})
|
||||
end
|
||||
end
|
||||
else
|
||||
@statuses.push({
|
||||
text: "We could not find a relay list for your public key",
|
||||
icon_name: "alert-octagon",
|
||||
icon_color: "amber-500"
|
||||
})
|
||||
end
|
||||
|
||||
@button_text = (nip65_event.present? ? "Edit relays" : "Set up relays")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def relay_host(url)
|
||||
URI.parse(url).host
|
||||
rescue URI::InvalidURIError
|
||||
nil
|
||||
end
|
||||
|
||||
def relay_urls(nip65_event)
|
||||
nip65_event["tags"].select { |t| t.is_a?(Array) && t[0] == "r" }.map { |t| t[1] }
|
||||
end
|
||||
|
||||
def normalized_relay_urls(nip65_event)
|
||||
relay_urls(nip65_event).map { |url| NostrManagerService.normalize_url(url) }
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,8 @@
|
||||
<p class="flex gap-x-4 items-center">
|
||||
<span class="inline-block h-6 w-6 grow-0 text-<%= @icon_color %>">
|
||||
<%= render "icons/#{@icon_name}" %>
|
||||
</span>
|
||||
<span>
|
||||
<%= raw @text %>
|
||||
</span>
|
||||
</p>
|
||||
@@ -0,0 +1,7 @@
|
||||
class StatusTextComponent < ViewComponent::Base
|
||||
def initialize(text:, icon_name:, icon_color:)
|
||||
@text = text
|
||||
@icon_name = icon_name
|
||||
@icon_color = icon_color
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,96 @@
|
||||
module Settings
|
||||
class NostrEventsController < ApplicationController
|
||||
before_action :authenticate_user!
|
||||
|
||||
ALLOWED_KINDS = [
|
||||
NostrManagerService::PROFILE_KIND,
|
||||
NostrManagerService::RELAY_LIST_KIND,
|
||||
NostrManagerService::MEDIA_SERVER_LIST_KIND
|
||||
].freeze
|
||||
|
||||
MAX_CONTENT_BYTES = 10_000
|
||||
MAX_TAGS = 100
|
||||
MAX_TAG_BYTES = 512
|
||||
CLOCK_SKEW = 5.minutes
|
||||
RATE_LIMIT = 10
|
||||
RATE_WINDOW = 5.minutes
|
||||
|
||||
def create
|
||||
return render_error("This account has no Nostr public key", :forbidden) if current_user.nostr_pubkey.blank?
|
||||
return render_error("Too many publish attempts. Please try again later.", :too_many_requests) if rate_limited?
|
||||
|
||||
event = Nostr::Event.new(**event_params)
|
||||
return render_error("Invalid event", :unprocessable_entity) unless valid_event?(event)
|
||||
|
||||
NostrPublishUserEventJob.perform_later(event: event.to_h.transform_keys(&:to_s))
|
||||
clear_metadata_cache
|
||||
|
||||
render json: { ok: true }
|
||||
rescue ActionController::ParameterMissing, ArgumentError, TypeError
|
||||
render_error("Invalid event", :unprocessable_entity)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def event_params
|
||||
raw = params.require(:signed_event)
|
||||
{
|
||||
id: raw[:id],
|
||||
pubkey: raw[:pubkey],
|
||||
created_at: raw[:created_at],
|
||||
kind: raw[:kind],
|
||||
tags: raw[:tags],
|
||||
content: raw[:content],
|
||||
sig: raw[:sig]
|
||||
}
|
||||
end
|
||||
|
||||
def valid_event?(event)
|
||||
return false unless event.pubkey == current_user.nostr_pubkey
|
||||
return false unless event.created_at.is_a?(Integer) && event.kind.is_a?(Integer)
|
||||
return false unless NostrManager::VerifySignedEvent.call(
|
||||
event: event, allowed_kinds: ALLOWED_KINDS
|
||||
)
|
||||
return false unless fresh?(event)
|
||||
|
||||
within_size_limits?(event)
|
||||
end
|
||||
|
||||
def fresh?(event)
|
||||
now = Time.current.to_i
|
||||
(now - CLOCK_SKEW.to_i) <= event.created_at &&
|
||||
event.created_at <= (now + CLOCK_SKEW.to_i)
|
||||
end
|
||||
|
||||
def within_size_limits?(event)
|
||||
tags = Array(event.tags)
|
||||
return false if tags.size > MAX_TAGS
|
||||
return false if event.content.to_s.bytesize > MAX_CONTENT_BYTES
|
||||
|
||||
tags.all? do |tag|
|
||||
tag.is_a?(Array) &&
|
||||
tag.all? { |value| value.is_a?(String) } &&
|
||||
tag.sum(&:bytesize) <= MAX_TAG_BYTES
|
||||
end
|
||||
end
|
||||
|
||||
def rate_limited?
|
||||
key = "nostr_publish:#{current_user.id}"
|
||||
count = Rails.cache.read(key).to_i
|
||||
return true if count >= RATE_LIMIT
|
||||
|
||||
Rails.cache.write(key, count + 1, expires_in: RATE_WINDOW)
|
||||
false
|
||||
end
|
||||
|
||||
def clear_metadata_cache
|
||||
NostrManagerService.metadata_cache_keys(current_user.id).each do |key|
|
||||
Rails.cache.delete(key)
|
||||
end
|
||||
end
|
||||
|
||||
def render_error(message, status)
|
||||
render json: { error: message }, status: status
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -4,8 +4,13 @@ require "bcrypt"
|
||||
class SettingsController < ApplicationController
|
||||
before_action :authenticate_user!
|
||||
before_action :set_main_nav_section
|
||||
before_action :set_settings_section, only: [:show, :update, :update_email, :reset_email_password]
|
||||
before_action :set_user, only: [:show, :update, :update_email, :reset_email_password]
|
||||
before_action :set_settings_section, only: [
|
||||
:show, :update, :update_email, :reset_email_password
|
||||
]
|
||||
before_action :set_user, only: [
|
||||
:show, :update, :update_email, :reset_email_password,
|
||||
:fetch_nostr_metadata
|
||||
]
|
||||
|
||||
def index
|
||||
redirect_to setting_path(:profile)
|
||||
@@ -143,12 +148,86 @@ class SettingsController < ApplicationController
|
||||
}
|
||||
end
|
||||
|
||||
def fetch_nostr_metadata
|
||||
return render plain: "no pubkey", status: :bad_request if @user.nostr_pubkey.blank?
|
||||
|
||||
case params[:step]
|
||||
when "relays"
|
||||
nip65_event = NostrManager::DiscoverUserEvent.call(
|
||||
pubkey: @user.nostr_pubkey, kind: NostrManagerService::RELAY_LIST_KIND,
|
||||
relays: discovery_relay_urls
|
||||
)
|
||||
write_relays = nip65_event ? extract_write_relays(nip65_event) : []
|
||||
|
||||
if nip65_event && write_relays.any? && stale?(nip65_event)
|
||||
auth_event = NostrManager::DiscoverUserEvent.call(
|
||||
pubkey: @user.nostr_pubkey, kind: NostrManagerService::RELAY_LIST_KIND,
|
||||
relays: write_relays
|
||||
)
|
||||
nip65_event = auth_event if auth_event
|
||||
write_relays = extract_write_relays(nip65_event) if auth_event
|
||||
end
|
||||
|
||||
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", event_id: nip65_event&.dig("id") }
|
||||
|
||||
when "profile"
|
||||
write_relays = Rails.cache.read(nostr_metadata_cache_key("write_relays")) || []
|
||||
relays = write_relays.any? ? write_relays : discovery_relay_urls
|
||||
profile = NostrManager::DiscoverUserEvent.call(
|
||||
pubkey: @user.nostr_pubkey, kind: NostrManagerService::PROFILE_KIND, relays: relays
|
||||
)
|
||||
Rails.cache.write(nostr_metadata_cache_key("profile"), profile, expires_in: 5.minutes)
|
||||
render json: { next: "blossom", event_id: profile&.dig("id") }
|
||||
|
||||
when "blossom"
|
||||
write_relays = Rails.cache.read(nostr_metadata_cache_key("write_relays")) || []
|
||||
relays = write_relays.any? ? write_relays : discovery_relay_urls
|
||||
media_list = NostrManager::DiscoverUserEvent.call(
|
||||
pubkey: @user.nostr_pubkey, kind: NostrManagerService::MEDIA_SERVER_LIST_KIND,
|
||||
relays: relays
|
||||
)
|
||||
Rails.cache.write(nostr_metadata_cache_key("blossom"), media_list, expires_in: 5.minutes)
|
||||
render json: { next: "render", event_id: media_list&.dig("id") }
|
||||
|
||||
when "render", nil
|
||||
@nip65_event = Rails.cache.read(nostr_metadata_cache_key("nip65"))
|
||||
@profile = Rails.cache.read(nostr_metadata_cache_key("profile"))
|
||||
@media_list = Rails.cache.read(nostr_metadata_cache_key("blossom"))
|
||||
render partial: "nostr_metadata", formats: :html
|
||||
|
||||
else
|
||||
render plain: "invalid step", status: :bad_request
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_main_nav_section
|
||||
@current_section = :settings
|
||||
end
|
||||
|
||||
def extract_write_relays(nip65_event)
|
||||
NostrManager::RelayUrlValidator.filter(
|
||||
nip65_event["tags"]
|
||||
.select { |t| t.is_a?(Array) && t[0] == "r" && t[2] != "read" }
|
||||
.map { |t| t[1] }
|
||||
)
|
||||
end
|
||||
|
||||
def nostr_metadata_cache_key(suffix)
|
||||
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
|
||||
|
||||
def set_settings_section
|
||||
@settings_section = params[:section]
|
||||
allowed_sections = [
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
import { isAdded, setAddedClasses } from "lib/added_badge"
|
||||
|
||||
const AMBER_CLASSES = [
|
||||
"border-amber-400", "ring-1", "ring-amber-400",
|
||||
"focus:border-amber-400", "focus:ring-amber-400"
|
||||
]
|
||||
|
||||
const ADDED_BADGE_HTML = `
|
||||
<span class="rounded-full bg-emerald-100 px-2 py-0.5 text-xs font-semibold text-emerald-800">
|
||||
added
|
||||
</span>
|
||||
`.trim()
|
||||
|
||||
export default class extends Controller {
|
||||
static targets = [ "input", "badge", "suggestion" ]
|
||||
static values = { addedValue: String }
|
||||
|
||||
apply (event) {
|
||||
event.preventDefault()
|
||||
const value = event.params.value ?? this.addedValueValue
|
||||
|
||||
if (this.hasInputTarget && value !== undefined) {
|
||||
this.inputTarget.value = value
|
||||
this.checkAdded()
|
||||
}
|
||||
}
|
||||
|
||||
checkAdded () {
|
||||
if (!this.hasInputTarget) return
|
||||
|
||||
const addedValue = this.hasAddedValueValue ? this.addedValueValue : null
|
||||
if (!addedValue) return
|
||||
|
||||
const added = isAdded(this.inputTarget, addedValue)
|
||||
setAddedClasses(this.inputTarget, added)
|
||||
|
||||
if (added) {
|
||||
this.inputTarget.classList.remove(...AMBER_CLASSES)
|
||||
|
||||
if (this.hasBadgeTarget) {
|
||||
this.badgeTarget.innerHTML = ADDED_BADGE_HTML
|
||||
this.badgeTarget.classList.remove("hidden")
|
||||
}
|
||||
} else if (this.hasBadgeTarget) {
|
||||
this.badgeTarget.classList.add("hidden")
|
||||
}
|
||||
|
||||
if (this.hasSuggestionTarget) {
|
||||
this.suggestionTarget.classList.toggle("hidden", added)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
|
||||
const REQUEST_TIMEOUT = 60000
|
||||
const REFRESH_ATTEMPTS = 5
|
||||
const REFRESH_DELAY = 2000
|
||||
const STEP_FOR_KIND = { 10002: "relays", 0: "profile", 10063: "blossom" }
|
||||
const MESSAGES = {
|
||||
relays: "Looking up your relay list",
|
||||
profile: "Fetching your profile",
|
||||
blossom: "Fetching your media server list"
|
||||
}
|
||||
const WAITING_MESSAGE = "Waiting for your changes to appear"
|
||||
|
||||
export default class extends Controller {
|
||||
static targets = [ "status", "loading", "content", "retry" ]
|
||||
static values = { url: String }
|
||||
|
||||
connect () {
|
||||
this.runStep("relays")
|
||||
}
|
||||
|
||||
refresh (event) {
|
||||
const detail = event.detail || {}
|
||||
|
||||
this.contentTarget.classList.add("hidden")
|
||||
this.contentTarget.innerHTML = ""
|
||||
this.loadingTarget.classList.remove("hidden")
|
||||
this.runStep("relays", {
|
||||
message: "Saved. Updating",
|
||||
expectedKind: detail.kind,
|
||||
expectedId: detail.eventId,
|
||||
attempts: 0
|
||||
})
|
||||
}
|
||||
|
||||
retry () {
|
||||
this.runStep("relays")
|
||||
}
|
||||
|
||||
async runStep (step, options = {}) {
|
||||
this.hideRetry()
|
||||
|
||||
const message = options.message || MESSAGES[step]
|
||||
if (message) {
|
||||
this.statusTarget.textContent = message
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await this.request(step)
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status}`)
|
||||
}
|
||||
|
||||
if (step === "render") {
|
||||
const html = await res.text()
|
||||
this.loadingTarget.classList.add("hidden")
|
||||
this.contentTarget.classList.remove("hidden")
|
||||
this.contentTarget.innerHTML = html
|
||||
} else {
|
||||
const data = await res.json()
|
||||
|
||||
if (this.awaitingUpdate(step, data, options)) {
|
||||
const attempts = (options.attempts || 0) + 1
|
||||
setTimeout(
|
||||
() => this.runStep(step, { ...options, message: WAITING_MESSAGE, attempts }),
|
||||
REFRESH_DELAY
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (data.next) {
|
||||
this.runStep(data.next, { ...options, message: null })
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Nostr metadata fetch failed:", error.message)
|
||||
this.statusTarget.textContent = "Something went wrong. You can try again."
|
||||
this.showRetry()
|
||||
}
|
||||
}
|
||||
|
||||
async request (step) {
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT)
|
||||
|
||||
const headers = (step === "render")
|
||||
? { "Accept": "text/html" }
|
||||
: { "Accept": "application/json" }
|
||||
|
||||
try {
|
||||
return await fetch(`${this.urlValue}?step=${step}`, {
|
||||
headers,
|
||||
signal: controller.signal
|
||||
})
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
|
||||
awaitingUpdate (step, data, options) {
|
||||
return step === (STEP_FOR_KIND[options.expectedKind] || "relays") &&
|
||||
Boolean(options.expectedId) &&
|
||||
data.event_id !== options.expectedId &&
|
||||
(options.attempts || 0) < REFRESH_ATTEMPTS
|
||||
}
|
||||
|
||||
showRetry () {
|
||||
if (this.hasRetryTarget) this.retryTarget.classList.remove("hidden")
|
||||
}
|
||||
|
||||
hideRetry () {
|
||||
if (this.hasRetryTarget) this.retryTarget.classList.add("hidden")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
import { signAndPublish, hasNostrExtension } from "lib/nostr_publish"
|
||||
|
||||
const PROFILE_KIND = 0
|
||||
const ADDRESS_PATTERN = /^[^@\s]+@[^@\s]+\.[^@\s]+$/
|
||||
|
||||
export default class extends Controller {
|
||||
static targets = [ "error", "submit" ]
|
||||
static values = { profile: { type: Object, default: {} }, handle: String }
|
||||
|
||||
async save (event) {
|
||||
event.preventDefault()
|
||||
this.clearError()
|
||||
|
||||
const displayName = this.field("display_name")
|
||||
const nip05 = this.field("nip05_address")
|
||||
const lud16 = this.field("lud16_address")
|
||||
|
||||
if (nip05 && !ADDRESS_PATTERN.test(nip05)) {
|
||||
this.showError("Please enter a valid NIP-05 address, e.g. name@example.com.")
|
||||
return
|
||||
}
|
||||
if (lud16 && !ADDRESS_PATTERN.test(lud16)) {
|
||||
this.showError("Please enter a valid Lightning address, e.g. name@example.com.")
|
||||
return
|
||||
}
|
||||
if (!hasNostrExtension()) {
|
||||
this.showError("No Nostr extension (NIP-07) found.")
|
||||
return
|
||||
}
|
||||
|
||||
this.setBusy(true)
|
||||
|
||||
try {
|
||||
const signedEvent = await signAndPublish({
|
||||
kind: PROFILE_KIND,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
tags: [],
|
||||
content: JSON.stringify(this.content(displayName, nip05, lud16))
|
||||
})
|
||||
this.element.dispatchEvent(new CustomEvent("nostr:publish", {
|
||||
bubbles: true,
|
||||
detail: { kind: PROFILE_KIND, eventId: signedEvent.id }
|
||||
}))
|
||||
} catch (error) {
|
||||
this.showError(error.message)
|
||||
} finally {
|
||||
this.setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
content (displayName, nip05, lud16) {
|
||||
const content = { ...(this.profileValue || {}) }
|
||||
|
||||
this.assign(content, "display_name", displayName)
|
||||
delete content.displayName
|
||||
this.assign(content, "nip05", nip05)
|
||||
this.assign(content, "lud16", lud16)
|
||||
|
||||
if (!content.name && this.handleValue) {
|
||||
content.name = this.handleValue
|
||||
}
|
||||
|
||||
return content
|
||||
}
|
||||
|
||||
assign (content, key, value) {
|
||||
if (value) {
|
||||
content[key] = value
|
||||
} else {
|
||||
delete content[key]
|
||||
}
|
||||
}
|
||||
|
||||
field (name) {
|
||||
const input = this.element.querySelector(`[name='user[${name}]']`)
|
||||
return input ? input.value.trim() : ""
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
import { signAndPublish, hasNostrExtension } from "lib/nostr_publish"
|
||||
import { updateAddedBadge } from "lib/added_badge"
|
||||
|
||||
export default class extends Controller {
|
||||
static targets = [ "list", "template", "addedBadge", "error", "submit" ]
|
||||
static values = {
|
||||
kind: Number,
|
||||
tag: String,
|
||||
markers: Boolean,
|
||||
pattern: String,
|
||||
emptyMessage: String,
|
||||
invalidMessage: String
|
||||
}
|
||||
|
||||
add (event) {
|
||||
event.preventDefault()
|
||||
const row = this.templateTarget.content.cloneNode(true)
|
||||
this.listTarget.appendChild(row)
|
||||
this.clearError()
|
||||
}
|
||||
|
||||
remove (event) {
|
||||
event.preventDefault()
|
||||
event.target.closest("li").remove()
|
||||
this.clearError()
|
||||
}
|
||||
|
||||
checkAdded (event) {
|
||||
const input = event.target
|
||||
const badge = input.closest(".relative")
|
||||
?.querySelector("[data-url-list-editor-target='addedBadge']")
|
||||
|
||||
updateAddedBadge(input, badge, input.dataset.addedValue)
|
||||
}
|
||||
|
||||
async save (event) {
|
||||
event.preventDefault()
|
||||
this.clearError()
|
||||
|
||||
const rows = this.rows()
|
||||
|
||||
if (rows.length === 0) {
|
||||
this.showError(this.emptyMessageValue || "Please add at least one entry.")
|
||||
return
|
||||
}
|
||||
if (this.patternValue && !rows.every((row) => this.valid(row.url))) {
|
||||
this.showError(this.invalidMessageValue || "Please check the URLs.")
|
||||
return
|
||||
}
|
||||
if (!hasNostrExtension()) {
|
||||
this.showError("No Nostr extension (NIP-07) found.")
|
||||
return
|
||||
}
|
||||
|
||||
this.setBusy(true)
|
||||
|
||||
try {
|
||||
const signedEvent = await signAndPublish({
|
||||
kind: this.kindValue,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
tags: rows.map((row) => this.tag(row)),
|
||||
content: ""
|
||||
})
|
||||
this.element.dispatchEvent(new CustomEvent("nostr:publish", {
|
||||
bubbles: true,
|
||||
detail: { kind: this.kindValue, eventId: signedEvent.id }
|
||||
}))
|
||||
} catch (error) {
|
||||
this.showError(error.message)
|
||||
} finally {
|
||||
this.setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
rows () {
|
||||
const seen = new Set()
|
||||
|
||||
return Array.from(this.listTarget.querySelectorAll("li"))
|
||||
.map((row) => {
|
||||
const input = row.querySelector("input[name$='_urls[]']")
|
||||
const select = row.querySelector("select[name$='_markers[]']")
|
||||
|
||||
return {
|
||||
url: input ? input.value.trim() : "",
|
||||
marker: select ? select.value : ""
|
||||
}
|
||||
})
|
||||
.filter((row) => {
|
||||
if (row.url.length === 0) return false
|
||||
|
||||
const key = this.normalize(row.url)
|
||||
if (seen.has(key)) return false
|
||||
|
||||
seen.add(key)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
tag (row) {
|
||||
if (this.markersValue && row.marker) {
|
||||
return [this.tagValue, row.url, row.marker]
|
||||
}
|
||||
|
||||
return [this.tagValue, row.url]
|
||||
}
|
||||
|
||||
valid (url) {
|
||||
return new RegExp(this.patternValue, "i").test(url)
|
||||
}
|
||||
|
||||
normalize (url) {
|
||||
return url.replace(/\/+$/, "").toLowerCase()
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
export const ADDED_CLASSES = [
|
||||
"border-emerald-500", "ring-1", "ring-emerald-500",
|
||||
"focus:border-emerald-500", "focus:ring-emerald-500",
|
||||
"bg-emerald-50/20"
|
||||
]
|
||||
|
||||
export function isAdded (input, addedValue) {
|
||||
return Boolean(addedValue) && input.value.trim() === addedValue.trim()
|
||||
}
|
||||
|
||||
export function setAddedClasses (input, added) {
|
||||
if (added) {
|
||||
input.classList.add(...ADDED_CLASSES)
|
||||
} else {
|
||||
input.classList.remove(...ADDED_CLASSES)
|
||||
}
|
||||
}
|
||||
|
||||
export function updateAddedBadge (input, badge, addedValue) {
|
||||
if (!addedValue) return false
|
||||
|
||||
const added = isAdded(input, addedValue)
|
||||
setAddedClasses(input, added)
|
||||
|
||||
if (badge) {
|
||||
badge.classList.toggle("hidden", !added)
|
||||
}
|
||||
|
||||
return added
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
const DEFAULT_URL = "/settings/nostr_publish"
|
||||
|
||||
export function hasNostrExtension () {
|
||||
return Boolean(window.nostr && window.nostr.signEvent)
|
||||
}
|
||||
|
||||
export async function signAndPublish (eventTemplate, { url = DEFAULT_URL } = {}) {
|
||||
if (!hasNostrExtension()) {
|
||||
throw new Error("No Nostr extension (NIP-07) found")
|
||||
}
|
||||
|
||||
const signedEvent = await window.nostr.signEvent(eventTemplate)
|
||||
await publish(signedEvent, { url })
|
||||
return signedEvent
|
||||
}
|
||||
|
||||
export async function publish (signedEvent, { url = DEFAULT_URL } = {}) {
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: {
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/json",
|
||||
"X-CSRF-Token": csrfToken()
|
||||
},
|
||||
body: JSON.stringify({ signed_event: signedEvent })
|
||||
})
|
||||
|
||||
const data = await response.json().catch(() => ({}))
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || `Publishing failed (HTTP ${response.status})`)
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
function csrfToken () {
|
||||
return document.head.querySelector('meta[name="csrf-token"]')?.getAttribute("content")
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
class NostrPublishUserEventJob < ApplicationJob
|
||||
queue_as :nostr
|
||||
|
||||
def perform(event:)
|
||||
NostrManager::PublishUserEvent.call(event: event)
|
||||
end
|
||||
end
|
||||
@@ -16,10 +16,31 @@ module Settings
|
||||
default: ENV["NOSTR_PUBLIC_KEY_PRIMARY_DOMAIN"].presence
|
||||
|
||||
field :nostr_relay_url, type: :string,
|
||||
default: ENV["NOSTR_RELAY_URL"].presence
|
||||
default: ENV["NOSTR_RELAY_URL"].presence,
|
||||
validates: { format: {
|
||||
with: %r{\Awss?://.+},
|
||||
allow_blank: true,
|
||||
message: "must be a ws:// or wss:// URL"
|
||||
} }
|
||||
|
||||
field :nostr_blossom_server_url, type: :string,
|
||||
default: ENV["NOSTR_BLOSSOM_SERVER_URL"].presence,
|
||||
validates: { format: {
|
||||
with: %r{\Ahttps?://.+},
|
||||
allow_blank: true,
|
||||
message: "must be an http:// or https:// URL"
|
||||
} }
|
||||
|
||||
field :nostr_zaps_relay_limit, type: :integer,
|
||||
default: 12
|
||||
|
||||
field :nostr_discovery_relays, type: :array, default: %w[
|
||||
wss://nostr.kosmos.org
|
||||
wss://nos.lol
|
||||
wss://relay.snort.social
|
||||
wss://relay.primal.net
|
||||
wss://relay.damus.io
|
||||
]
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,19 @@
|
||||
module NostrManager
|
||||
class DiscoverUserEvent < NostrManagerService
|
||||
def initialize(pubkey:, kind:, relays: nil)
|
||||
@pubkey = pubkey
|
||||
@kind = kind
|
||||
@relays = relays.present? ? relays : Setting.nostr_discovery_relays
|
||||
end
|
||||
|
||||
def call
|
||||
filter = Nostr::Filter.new(
|
||||
authors: [@pubkey],
|
||||
kinds: [@kind],
|
||||
limit: 1,
|
||||
)
|
||||
|
||||
NostrManager::FetchLatestEvent.call(relays: @relays, filter: filter)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,67 @@
|
||||
module NostrManager
|
||||
class FetchEvent < NostrManagerService
|
||||
TIMEOUT = 5
|
||||
|
||||
def initialize(filter:, relay_url:)
|
||||
@filter = filter
|
||||
@relay = new_relay(relay_url)
|
||||
@client = Nostr::Client.new
|
||||
end
|
||||
|
||||
def call
|
||||
filter, client, relay = @filter, @client, @relay
|
||||
event = nil
|
||||
done = false
|
||||
errored = false
|
||||
mutex = Mutex.new
|
||||
received_event = ConditionVariable.new
|
||||
log_prefix = "[nostr][#{@relay.name}]"
|
||||
|
||||
thread = Thread.new do
|
||||
client.on :connect do
|
||||
client.subscribe(filter: filter)
|
||||
end
|
||||
|
||||
client.on :error do |e|
|
||||
Rails.logger.info "#{log_prefix} Error: #{e}"
|
||||
mutex.synchronize do
|
||||
errored = true
|
||||
received_event.signal
|
||||
end
|
||||
end
|
||||
|
||||
client.on :message do |m|
|
||||
msg = JSON.parse(m) rescue nil
|
||||
if msg && msg[0] == "EVENT" && msg[2]
|
||||
Rails.logger.debug "#{log_prefix} Event received: #{msg[2]["id"]}"
|
||||
mutex.synchronize do
|
||||
event = msg[2]
|
||||
received_event.signal
|
||||
end
|
||||
elsif msg && msg[0] == "EOSE"
|
||||
mutex.synchronize do
|
||||
done = true
|
||||
received_event.signal
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
client.connect relay
|
||||
end
|
||||
|
||||
begin
|
||||
mutex.synchronize do
|
||||
received_event.wait(mutex, TIMEOUT) if event.nil? && !done && !errored
|
||||
end
|
||||
|
||||
if event.nil? && !done && !errored
|
||||
Rails.logger.debug "#{log_prefix} Timeout: No event received within #{TIMEOUT} seconds"
|
||||
end
|
||||
ensure
|
||||
thread.exit
|
||||
end
|
||||
|
||||
event
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,45 @@
|
||||
module NostrManager
|
||||
class FetchLatestEvent < NostrManagerService
|
||||
TIMEOUT = 20
|
||||
|
||||
def initialize(relays:, filter:, max_events: 2)
|
||||
@relays = relays
|
||||
@filter = filter
|
||||
@max_events = max_events
|
||||
end
|
||||
|
||||
def call
|
||||
events = []
|
||||
deadline = monotonic_now + TIMEOUT
|
||||
|
||||
@relays.each do |url|
|
||||
if monotonic_now >= deadline
|
||||
Rails.logger.debug "[nostr] Timeout after #{TIMEOUT}s, found #{events.size} events"
|
||||
break
|
||||
end
|
||||
|
||||
event = fetch(url)
|
||||
next if event.blank?
|
||||
next if events.any? { |e| e["id"] == event["id"] }
|
||||
|
||||
events << event
|
||||
break if events.size >= @max_events
|
||||
end
|
||||
|
||||
events.max_by { |e| e["created_at"] }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def fetch(url)
|
||||
NostrManager::FetchEvent.call(filter: @filter, relay_url: url)
|
||||
rescue StandardError => e
|
||||
Rails.logger.info "[nostr] Error fetching from #{url}: #{e.class}: #{e.message}"
|
||||
nil
|
||||
end
|
||||
|
||||
def monotonic_now
|
||||
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,8 +1,9 @@
|
||||
module NostrManager
|
||||
class PublishEvent < NostrManagerService
|
||||
TIMEOUT = 10
|
||||
|
||||
def initialize(event:, relay_url:)
|
||||
relay_name = URI.parse(relay_url).host
|
||||
@relay = Nostr::Relay.new(url: relay_url, name: relay_name)
|
||||
@relay_url = relay_url
|
||||
|
||||
if event.is_a?(Nostr::Event)
|
||||
@event = event
|
||||
@@ -14,37 +15,55 @@ module NostrManager
|
||||
end
|
||||
|
||||
def call
|
||||
client, relay, event = @client, @relay, @event
|
||||
relay = build_relay
|
||||
return if relay.nil?
|
||||
|
||||
client, event = @client, @event
|
||||
log_prefix = "[nostr][#{relay.name}]"
|
||||
|
||||
thread = Thread.new do
|
||||
client.on :connect do
|
||||
puts "#{log_prefix} Publishing #{event.id}..."
|
||||
Rails.logger.debug "#{log_prefix} Publishing #{event.id}..."
|
||||
client.publish event
|
||||
end
|
||||
|
||||
client.on :error do |e|
|
||||
puts "#{log_prefix} Error: #{e}"
|
||||
puts "#{log_prefix} Closing thread..."
|
||||
Rails.logger.debug "#{log_prefix} Error: #{e}"
|
||||
Rails.logger.debug "#{log_prefix} Closing thread..."
|
||||
thread.exit
|
||||
end
|
||||
|
||||
client.on :message do |m|
|
||||
puts "#{log_prefix} Message: #{m}"
|
||||
Rails.logger.debug "#{log_prefix} Message: #{m}"
|
||||
msg = JSON.parse(m) rescue []
|
||||
if msg[0] == "OK" && msg[1] == event.id && msg[2]
|
||||
puts "#{log_prefix} Event published. Closing thread..."
|
||||
Rails.logger.debug "#{log_prefix} Event published. Closing thread..."
|
||||
else
|
||||
puts "#{log_prefix} Unexpected message from relay. Closing thread..."
|
||||
Rails.logger.debug "#{log_prefix} Unexpected message from relay. Closing thread..."
|
||||
end
|
||||
thread.exit
|
||||
end
|
||||
|
||||
puts "#{log_prefix} Connecting to #{relay.url}..."
|
||||
Rails.logger.debug "#{log_prefix} Connecting to #{relay.url}..."
|
||||
client.connect relay
|
||||
end
|
||||
|
||||
thread.join
|
||||
if thread.join(TIMEOUT).nil?
|
||||
Rails.logger.debug "#{log_prefix} Timeout: no relay response within #{TIMEOUT}s"
|
||||
end
|
||||
|
||||
thread.exit
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def build_relay
|
||||
return nil if @relay_url.blank?
|
||||
|
||||
new_relay(@relay_url)
|
||||
rescue URI::InvalidURIError
|
||||
Rails.logger.debug "[nostr] Invalid relay URL: #{@relay_url.inspect}"
|
||||
nil
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,49 @@
|
||||
module NostrManager
|
||||
class PublishUserEvent < NostrManagerService
|
||||
def initialize(event:)
|
||||
@event = event.is_a?(Nostr::Event) ? event : Nostr::Event.new(**event.symbolize_keys)
|
||||
end
|
||||
|
||||
def call
|
||||
relays.each do |relay_url|
|
||||
NostrManager::PublishEvent.call(event: @event, relay_url: relay_url)
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def relays
|
||||
urls = []
|
||||
urls << Setting.nostr_relay_url
|
||||
urls.concat(RelayUrlValidator.filter(user_relays).take(MAX_RELAY_LIST_SIZE))
|
||||
urls.reject(&:blank?).uniq
|
||||
end
|
||||
|
||||
def user_relays
|
||||
case @event.kind
|
||||
when RELAY_LIST_KIND
|
||||
relay_tag_urls(@event.tags)
|
||||
when PROFILE_KIND, MEDIA_SERVER_LIST_KIND
|
||||
write_relays
|
||||
else
|
||||
[]
|
||||
end
|
||||
end
|
||||
|
||||
def write_relays
|
||||
relay_list = DiscoverUserEvent.call(pubkey: @event.pubkey, kind: RELAY_LIST_KIND)
|
||||
return [] unless relay_list
|
||||
|
||||
relay_tag_urls(relay_list["tags"], exclude_read: true)
|
||||
end
|
||||
|
||||
def relay_tag_urls(tags, exclude_read: false)
|
||||
Array(tags).select do |tag|
|
||||
next false unless tag.is_a?(Array) && tag[0] == "r"
|
||||
next false if exclude_read && tag[2] == "read"
|
||||
|
||||
true
|
||||
end.map { |tag| tag[1] }
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -6,7 +6,8 @@ module NostrManager
|
||||
|
||||
def call
|
||||
tags = parse_tags(@zap.request_event.tags)
|
||||
relays = tags[:relays].take(Setting.nostr_zaps_relay_limit)
|
||||
relays = NostrManager::RelayUrlValidator.filter(tags[:relays])
|
||||
.take(Setting.nostr_zaps_relay_limit)
|
||||
|
||||
if Setting.nostr_relay_url.present?
|
||||
relays << Setting.nostr_relay_url
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
require "ipaddr"
|
||||
require "resolv"
|
||||
|
||||
module NostrManager
|
||||
class RelayUrlValidator
|
||||
ALLOWED_SCHEMES = %w[ws wss].freeze
|
||||
|
||||
def self.valid?(url)
|
||||
new(url).valid?
|
||||
end
|
||||
|
||||
def self.filter(urls)
|
||||
Array(urls).select { |url| valid?(url) }
|
||||
end
|
||||
|
||||
def initialize(url)
|
||||
@url = url.to_s
|
||||
end
|
||||
|
||||
def valid?
|
||||
return false if @url.blank?
|
||||
|
||||
uri = URI.parse(@url)
|
||||
return false unless ALLOWED_SCHEMES.include?(uri.scheme)
|
||||
return false if uri.host.blank?
|
||||
|
||||
!private_host?(uri.host)
|
||||
rescue URI::InvalidURIError
|
||||
false
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def private_host?(host)
|
||||
host = host.delete_prefix("[").delete_suffix("]").downcase
|
||||
return true if host == "localhost" || host.end_with?(".localhost")
|
||||
|
||||
literal = begin
|
||||
IPAddr.new(host)
|
||||
rescue IPAddr::InvalidAddressError
|
||||
nil
|
||||
end
|
||||
return private_address?(literal) if literal
|
||||
|
||||
addresses = Resolv.getaddresses(host)
|
||||
return false if addresses.empty?
|
||||
|
||||
addresses.any? { |address| private_address?(address) }
|
||||
rescue Resolv::ResolvError, Resolv::ResolvTimeout
|
||||
false
|
||||
end
|
||||
|
||||
def private_address?(address)
|
||||
ip = address.is_a?(IPAddr) ? address : IPAddr.new(address)
|
||||
ip = ip.native
|
||||
ip.loopback? || ip.private? || ip.link_local?
|
||||
rescue IPAddr::InvalidAddressError
|
||||
false
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,8 +1,29 @@
|
||||
require "nostr"
|
||||
|
||||
class NostrManagerService < ApplicationService
|
||||
PROFILE_KIND = 0
|
||||
RELAY_LIST_KIND = 10002
|
||||
MEDIA_SERVER_LIST_KIND = 10063
|
||||
|
||||
METADATA_CACHE_SUFFIXES = %w[nip65 write_relays profile blossom].freeze
|
||||
|
||||
MAX_RELAY_LIST_SIZE = 10
|
||||
|
||||
def self.metadata_cache_key(user_id, suffix)
|
||||
"nostr_metadata:#{user_id}:#{suffix}"
|
||||
end
|
||||
|
||||
def self.metadata_cache_keys(user_id)
|
||||
METADATA_CACHE_SUFFIXES.map { |suffix| metadata_cache_key(user_id, suffix) }
|
||||
end
|
||||
|
||||
def self.normalize_url(url)
|
||||
url.to_s.strip.chomp("/").downcase
|
||||
end
|
||||
|
||||
def parse_tags(tags)
|
||||
out = {}
|
||||
# TODO support more than 1 item for each tag type
|
||||
tags.each do |tag|
|
||||
out[tag[0].to_sym] = tag[1, tag.length]
|
||||
end
|
||||
@@ -19,4 +40,8 @@ class NostrManagerService < ApplicationService
|
||||
def site_user
|
||||
Nostr::User.new(keypair: site_keypair)
|
||||
end
|
||||
|
||||
def new_relay(url)
|
||||
Nostr::Relay.new(url: url, name: URI.parse(url).host)
|
||||
end
|
||||
end
|
||||
@@ -29,15 +29,35 @@
|
||||
title: "Relay URL",
|
||||
description: "Websockets URL of a relay associated with #{Setting.primary_domain}"
|
||||
) %>
|
||||
<%= render FormElements::FieldsetResettableSettingComponent.new(
|
||||
key: :nostr_blossom_server_url,
|
||||
title: "Blossom server URL",
|
||||
description: "HTTP URL of the Blossom media server to add to users' server lists during onboarding"
|
||||
) %>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h3>Zaps</h3>
|
||||
<ul role="list">
|
||||
<%= render FormElements::FieldsetResettableSettingComponent.new(
|
||||
key: :nostr_zaps_relay_limit,
|
||||
title: "Relay limit",
|
||||
description: "The maximum number of relays to publish zap receipts to"
|
||||
description: "The maximum number of sender-defined relays to try to publish zap receipts to"
|
||||
) %>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h3>Onboarding</h3>
|
||||
<ul role="list">
|
||||
<%= render FormElements::FieldsetComponent.new(
|
||||
title: "Discovery relays",
|
||||
description: "Used to discover a user's published relay list and/or profile"
|
||||
) do %>
|
||||
<%= f.text_area :nostr_discovery_relays,
|
||||
value: Setting.nostr_discovery_relays.join("\n"),
|
||||
class: "h-44 w-80" %>
|
||||
<% end %>
|
||||
</ul>
|
||||
<% end %>
|
||||
@@ -1,47 +1,46 @@
|
||||
<section>
|
||||
<h3>Nostr</h3>
|
||||
<h4 class="mb-0">Public Key</h4>
|
||||
<div data-controller="settings--nostr-pubkey"
|
||||
data-settings--nostr-pubkey-user-address-value="<%= current_user.address %>"
|
||||
data-settings--nostr-pubkey-site-value="<%= Setting.accounts_domain %>"
|
||||
data-settings--nostr-pubkey-shared-secret-value="<%= session[:shared_secret] %>"
|
||||
data-settings--nostr-pubkey-pubkey-hex-value="<%= current_user.nostr_pubkey %>">
|
||||
|
||||
<p class="<%= current_user.nostr_pubkey.present? ? '' : 'hidden' %> mt-2 flex gap-1">
|
||||
<div data-controller="settings--nostr-pubkey"
|
||||
data-settings--nostr-pubkey-user-address-value="<%= current_user.address %>"
|
||||
data-settings--nostr-pubkey-site-value="<%= Setting.accounts_domain %>"
|
||||
data-settings--nostr-pubkey-shared-secret-value="<%= session[:shared_secret] %>"
|
||||
data-settings--nostr-pubkey-pubkey-hex-value="<%= current_user.nostr_pubkey %>">
|
||||
<section class="mb-8 sm:mb-12">
|
||||
<h3>Nostr</h3>
|
||||
<h4 class="mb-0">
|
||||
Public Key
|
||||
</h4>
|
||||
<p class="<%= current_user.nostr_pubkey.present? ? '' : 'hidden' %> mt-2 flex gap-x-1">
|
||||
<input type="text" value="<%= current_user.nostr_pubkey_bech32 %>" disabled
|
||||
data-settings--nostr-pubkey-target="pubkeyBech32Input"
|
||||
name="nostr_public_key" class="relative grow" />
|
||||
name="nostr_public_key" class="w-full" />
|
||||
<%= link_to nostr_pubkey_settings_path,
|
||||
class: 'btn-md btn-outline text-red-700 relative shrink-0',
|
||||
class: 'btn-md btn-outline relative grow-0 shrink-0 text-red-700',
|
||||
data: { turbo_method: :delete, turbo_confirm: 'Are you sure?' } do %>
|
||||
Remove
|
||||
<% end %>
|
||||
</p>
|
||||
|
||||
<% if current_user.nostr_pubkey.present? %>
|
||||
<div class="rounded-md bg-blue-50 p-4">
|
||||
<div class="flex">
|
||||
<div class="flex-shrink-0">
|
||||
<svg class="h-5 w-5 text-blue-400" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
|
||||
<path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z" clip-rule="evenodd" />
|
||||
</svg>
|
||||
</div>
|
||||
<div class="ml-3 flex-1">
|
||||
<p class="text-sm text-blue-800">
|
||||
Your user address <strong><%= current_user.address %></strong> is
|
||||
also a Nostr address now. Use your favorite Nostr app, or for
|
||||
example <a href="http://metadata.nostr.com" target="_blank"
|
||||
class="underline">metadata.nostr.com</a>, to add this
|
||||
<strong>NIP-05</strong> address to your public profile.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- <div> -->
|
||||
<!-- Pubkey present -->
|
||||
<!-- </div> -->
|
||||
<% else %>
|
||||
<p class="my-4">
|
||||
If you use any apps on the Nostr network, you can verify your public key
|
||||
with us in order to enable Nostr-specific features for your account.
|
||||
Verify your Nostr public key with us in order to enable Nostr-specific
|
||||
features for your account:
|
||||
</p>
|
||||
<ul class="list-disc list-inside">
|
||||
<li>Log in with Nostr (no password needed)</li>
|
||||
<li>Verified Nostr address</li>
|
||||
<% if Setting.lndhub_enabled? %>
|
||||
<li>Receive zaps in your Lightning account</li>
|
||||
<% end %>
|
||||
<% if Setting.nostr_relay_url.present? %>
|
||||
<li>Publish notes and other stuff on our Nostr relay</li>
|
||||
<% end %>
|
||||
<% if Setting.nostr_blossom_server_url.present? %>
|
||||
<li>Publish media files on our Nostr media server</li>
|
||||
<% end %>
|
||||
</ul>
|
||||
<% end %>
|
||||
|
||||
<div data-settings--nostr-pubkey-target="noExtension"
|
||||
@@ -58,8 +57,8 @@
|
||||
</h3>
|
||||
<div class="mt-2 mb-0 text-sm text-blue-800">
|
||||
<p>
|
||||
We recommend Alby, which you can also use for your Lightning
|
||||
Wallet.
|
||||
We recommend Alby, which you can also use a wallet for your
|
||||
Lightning account.
|
||||
</p>
|
||||
</div>
|
||||
<div class="mt-4">
|
||||
@@ -86,5 +85,26 @@
|
||||
</button>
|
||||
</p>
|
||||
<% end %>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<% if current_user.nostr_pubkey.present? %>
|
||||
<div data-controller="nostr-metadata"
|
||||
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>
|
||||
<h3>Just a moment...</h3>
|
||||
<p data-nostr-metadata-target="status"
|
||||
class="text-gray-500 animate-pulse">Loading</p>
|
||||
<button type="button"
|
||||
data-nostr-metadata-target="retry"
|
||||
data-action="click->nostr-metadata#retry"
|
||||
class="btn-md btn-blue mt-4 hidden">
|
||||
Try again
|
||||
</button>
|
||||
</div>
|
||||
<div data-nostr-metadata-target="content" class="hidden"></div>
|
||||
</div>
|
||||
<% end %>
|
||||
</div>
|
||||
@@ -0,0 +1,32 @@
|
||||
<section class="">
|
||||
<h3>Relays</h3>
|
||||
<%= render Settings::NostrRelayStatusComponent.new(
|
||||
nip65_event: @nip65_event
|
||||
) %>
|
||||
</section>
|
||||
|
||||
<section class="">
|
||||
<h3>Profile</h3>
|
||||
<%= render Settings::NostrProfileStatusComponent.new(
|
||||
profile_event: @profile,
|
||||
user_address: current_user.address
|
||||
) %>
|
||||
<div class="mt-8" data-controller="modal" data-action="keydown.esc->modal#close">
|
||||
<button data-action="click->modal#open" class="btn-md btn-blue w-full sm:w-auto">
|
||||
Edit profile
|
||||
</button>
|
||||
<%= render ModalComponent.new(show_close_button: false) do %>
|
||||
<%= render Settings::NostrEditProfileComponent.new(
|
||||
user: current_user,
|
||||
profile_event: @profile
|
||||
) %>
|
||||
<% end %>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="mb-8 sm:mb-12">
|
||||
<h3>Media servers</h3>
|
||||
<%= render Settings::NostrMediaServerStatusComponent.new(
|
||||
media_list_event: @media_list
|
||||
) %>
|
||||
</section>
|
||||
@@ -19,18 +19,18 @@
|
||||
active: @settings_section.to_s == "email"
|
||||
) %>
|
||||
<% end %>
|
||||
<% if Setting.lndhub_enabled %>
|
||||
<%= render SidenavLinkComponent.new(
|
||||
name: "Lightning", path: setting_path(:lightning), icon: "zap",
|
||||
active: @settings_section.to_s == "lightning"
|
||||
) %>
|
||||
<% end %>
|
||||
<% if Setting.remotestorage_enabled? %>
|
||||
<%= render SidenavLinkComponent.new(
|
||||
name: "Storage", path: setting_path(:remotestorage), icon: "remotestorage",
|
||||
active: @settings_section.to_s == "remotestorage"
|
||||
) %>
|
||||
<% end %>
|
||||
<% if Setting.lndhub_enabled %>
|
||||
<%= render SidenavLinkComponent.new(
|
||||
name: "Lightning", path: setting_path(:lightning), icon: "zap",
|
||||
active: @settings_section.to_s == "lightning"
|
||||
) %>
|
||||
<% end %>
|
||||
<% if Setting.nostr_enabled %>
|
||||
<%= render SidenavLinkComponent.new(
|
||||
name: "Nostr", path: setting_path(:nostr), icon: "nostrich-head",
|
||||
|
||||
@@ -24,7 +24,7 @@ Rails.application.configure do
|
||||
else
|
||||
config.action_controller.perform_caching = false
|
||||
|
||||
config.cache_store = :null_store
|
||||
config.cache_store = :memory_store
|
||||
end
|
||||
|
||||
# Don't care if the mailer can't send.
|
||||
|
||||
@@ -7,4 +7,5 @@ pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
|
||||
pin "turbo_stream_animations"
|
||||
pin "local_time"
|
||||
pin_all_from "app/javascript/controllers", under: "controllers"
|
||||
pin_all_from "app/javascript/lib", under: "lib"
|
||||
pin "tailwindcss-stimulus-components" # @4.0.3
|
||||
@@ -65,6 +65,8 @@ Rails.application.routes.draw do
|
||||
post 'reset_email_password'
|
||||
post 'set_nostr_pubkey'
|
||||
delete 'nostr_pubkey', to: 'settings#remove_nostr_pubkey'
|
||||
get 'fetch_nostr_metadata', as: 'nostr_metadata'
|
||||
post 'nostr_publish', to: 'settings/nostr_events#create', as: :nostr_publish
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -60,4 +60,38 @@ it to your local strfry for example:
|
||||
|
||||
nak req -i 0fb010192685b86b0810b3de3706fbbf3b8c1db30b14533094a2b9700c820cdc nostr.kosmos.org | nak event ws://localhost:4777
|
||||
|
||||
## User onboarding
|
||||
|
||||
The account settings page lets users publish their own Nostr data:
|
||||
|
||||
* **Profile** (kind `0`) — display name, NIP-05 address and Lightning address. Edited fields are
|
||||
merged into the existing profile JSON, so unknown keys (`about`, `picture`, …) are preserved.
|
||||
* **Relay list** (NIP-65, kind `10002`) — the site relay is pre-included; entries can be marked
|
||||
read-only or write-only.
|
||||
* **Media server list** (Blossom, kind `10063`) — the configured Blossom server is pre-included.
|
||||
|
||||
Events are signed in the browser with a NIP-07 extension and sent to the app, which verifies them
|
||||
(`NostrManager::VerifySignedEvent` recomputes the event id from the body before checking the
|
||||
signature) and publishes them to the site relay and the user's relays. Reads — discovering an
|
||||
existing profile, relay list or media server list — happen server-side.
|
||||
|
||||
Relevant settings (admin → Services → Nostr):
|
||||
|
||||
* **Relay URL** — the site's relay, pre-included in user relay lists.
|
||||
* **Blossom server URL** — the site's media server, pre-included in user media server lists.
|
||||
* **Discovery relays** — used to look up a user's published events.
|
||||
|
||||
### Known limitations
|
||||
|
||||
* Relays that require NIP-42 authentication are not supported: the `nostr` gem's client cannot
|
||||
answer `AUTH`.
|
||||
* A new relay list is published to the new list plus the site relay, so relays that were *removed*
|
||||
from the list do not receive the update.
|
||||
* Relay URL validation (ws/wss only, no loopback/private/link-local hosts) has a DNS-rebinding
|
||||
time-of-check/time-of-use gap between validation and connection.
|
||||
* The relay editor rejects non-`ws`/`wss` URLs, so an existing list containing e.g. `http://`
|
||||
entries cannot be saved unchanged.
|
||||
* Metadata discovery is sequential (relays → profile → media server list) and can take a while on
|
||||
slow relays.
|
||||
|
||||
[1]: https://github.com/hoytech/strfry
|
||||
@@ -0,0 +1,22 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe FormElements::FieldsetComponent, type: :component do
|
||||
it "renders a div with flex gap-x-1 for vertical positioning" do
|
||||
rendered = render_inline(described_class.new(title: "Username")) do
|
||||
"<input type='text' name='username' />".html_safe
|
||||
end
|
||||
|
||||
expect(rendered.css("label.block > div.flex.gap-x-1")).to be_present
|
||||
expect(rendered.css("label.block > p.flex")).not_to be_present
|
||||
end
|
||||
|
||||
it "renders a div for horizontal positioning" do
|
||||
rendered = render_inline(described_class.new(positioning: :horizontal, title: "Enable notifications")) do
|
||||
"<input type='checkbox' />".html_safe
|
||||
end
|
||||
|
||||
expect(rendered.css("label.block > div.relative")).to be_present
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,87 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe Settings::NostrEditMediaServersComponent, type: :component do
|
||||
before do
|
||||
allow(Setting).to receive(:nostr_blossom_server_url).and_return("https://blossom.example.com")
|
||||
end
|
||||
|
||||
it "wires the form to the media server list editor" do
|
||||
rendered = render_inline(described_class.new(media_list_event: nil))
|
||||
|
||||
form = rendered.css("form").first
|
||||
expect(form["data-controller"]).to eq("url-list-editor")
|
||||
expect(form["data-action"]).to include("submit->url-list-editor#save")
|
||||
expect(form["data-url-list-editor-kind-value"]).to eq("10063")
|
||||
expect(form["data-url-list-editor-tag-value"]).to eq("server")
|
||||
expect(form["data-url-list-editor-markers-value"]).to eq("false")
|
||||
expect(form["data-url-list-editor-pattern-value"]).to eq("^https?://")
|
||||
|
||||
expect(rendered.css("[data-url-list-editor-target='error']")).to be_present
|
||||
expect(rendered.css("[data-url-list-editor-target='submit']")).to be_present
|
||||
end
|
||||
|
||||
describe "when user has no media server list" do
|
||||
it "prepends the site media server marked as added" do
|
||||
rendered = render_inline(described_class.new(media_list_event: nil))
|
||||
|
||||
list = rendered.css("[data-url-list-editor-target='list']").first
|
||||
inputs = list.css("input[name='server_urls[]']").map { |el| el["value"] }
|
||||
expect(inputs).to eq(["https://blossom.example.com"])
|
||||
|
||||
badges = rendered.css("span.rounded-full").select { |el| el.text.strip == "added" }
|
||||
expect(badges.size).to eq(1)
|
||||
end
|
||||
end
|
||||
|
||||
describe "when user has an existing media server list without the site server" do
|
||||
let(:media_list_event) do
|
||||
{
|
||||
"kind" => 10063,
|
||||
"tags" => [["server", "https://cdn.example.com"]]
|
||||
}
|
||||
end
|
||||
|
||||
it "prepends the site server as added, preserving existing servers" do
|
||||
rendered = render_inline(described_class.new(media_list_event: media_list_event))
|
||||
|
||||
list = rendered.css("[data-url-list-editor-target='list']").first
|
||||
inputs = list.css("input[name='server_urls[]']").map { |el| el["value"] }
|
||||
expect(inputs).to eq(["https://blossom.example.com", "https://cdn.example.com"])
|
||||
|
||||
badges = rendered.css("span.rounded-full").select { |el| el.text.strip == "added" }
|
||||
expect(badges.size).to eq(1)
|
||||
end
|
||||
end
|
||||
|
||||
describe "when user already has the site server" do
|
||||
let(:media_list_event) do
|
||||
{
|
||||
"kind" => 10063,
|
||||
"tags" => [
|
||||
["server", "https://blossom.example.com"],
|
||||
["server", "https://cdn.example.com"]
|
||||
]
|
||||
}
|
||||
end
|
||||
|
||||
it "renders servers without any added badges" do
|
||||
rendered = render_inline(described_class.new(media_list_event: media_list_event))
|
||||
|
||||
badges = rendered.css("span.rounded-full").select { |el| el.text.strip == "added" }
|
||||
expect(badges).to be_empty
|
||||
end
|
||||
end
|
||||
|
||||
describe "when no site media server is configured" do
|
||||
before { allow(Setting).to receive(:nostr_blossom_server_url).and_return(nil) }
|
||||
|
||||
it "renders an empty list" do
|
||||
rendered = render_inline(described_class.new(media_list_event: nil))
|
||||
|
||||
list = rendered.css("[data-url-list-editor-target='list']").first
|
||||
expect(list.css("input[name='server_urls[]']")).to be_empty
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,138 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe Settings::NostrEditProfileComponent, type: :component do
|
||||
let(:user) { build(:user, cn: "alice") }
|
||||
|
||||
before do
|
||||
allow(user).to receive(:address).and_return("alice@kosmos.org")
|
||||
allow(user).to receive(:display_name).and_return("Alice Wonderland")
|
||||
end
|
||||
|
||||
it "wires the form to the profile editor" do
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: nil))
|
||||
|
||||
form = rendered.css("form").first
|
||||
expect(form["data-controller"]).to eq("nostr-profile-editor")
|
||||
expect(form["data-action"]).to include("submit->nostr-profile-editor#save")
|
||||
expect(form["data-nostr-profile-editor-handle-value"]).to eq("alice")
|
||||
expect(JSON.parse(form["data-nostr-profile-editor-profile-value"])).to eq({})
|
||||
|
||||
expect(rendered.css("[data-nostr-profile-editor-target='error']")).to be_present
|
||||
expect(rendered.css("[data-nostr-profile-editor-target='submit']")).to be_present
|
||||
end
|
||||
|
||||
it "passes the existing profile to the editor so unknown keys survive" do
|
||||
profile_event = {
|
||||
"content" => { "about" => "hi", "nip05" => "alice@kosmos.org" }.to_json
|
||||
}
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: profile_event))
|
||||
|
||||
form = rendered.css("form").first
|
||||
profile = JSON.parse(form["data-nostr-profile-editor-profile-value"])
|
||||
expect(profile).to eq("about" => "hi", "nip05" => "alice@kosmos.org")
|
||||
end
|
||||
|
||||
describe "image URL sanitization" do
|
||||
it "ignores non-http(s) banner and picture URLs" do
|
||||
profile_event = {
|
||||
"content" => {
|
||||
"banner" => "javascript:alert(1)",
|
||||
"picture" => "ftp://example.com/x.png"
|
||||
}.to_json
|
||||
}
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: profile_event))
|
||||
|
||||
expect(rendered.css("img")).to be_empty
|
||||
expect(rendered.css("header").first["style"]).to be_blank
|
||||
end
|
||||
|
||||
it "renders http(s) banner and picture URLs" do
|
||||
profile_event = {
|
||||
"content" => {
|
||||
"banner" => "https://example.com/b.png",
|
||||
"picture" => "https://example.com/p.png"
|
||||
}.to_json
|
||||
}
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: profile_event))
|
||||
|
||||
expect(rendered.css("img").first["src"]).to eq("https://example.com/p.png")
|
||||
expect(rendered.css("header").first["style"]).to include("https://example.com/b.png")
|
||||
end
|
||||
end
|
||||
|
||||
describe "when profile event is missing or fields are empty" do
|
||||
it "prefills NIP-05 and Lightning addresses with user address and marks them as added" do
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: nil))
|
||||
|
||||
nip05_input = rendered.css("input[name='user[nip05_address]']").first
|
||||
expect(nip05_input["value"]).to eq("alice@kosmos.org")
|
||||
expect(nip05_input["class"]).to include("border-emerald-500")
|
||||
expect(nip05_input["data-action"]).to include("input->field-suggestion#checkAdded")
|
||||
|
||||
lud16_input = rendered.css("input[name='user[lud16_address]']").first
|
||||
expect(lud16_input["value"]).to eq("alice@kosmos.org")
|
||||
expect(lud16_input["class"]).to include("border-emerald-500")
|
||||
expect(lud16_input["data-action"]).to include("input->field-suggestion#checkAdded")
|
||||
|
||||
badges = rendered.css("span.rounded-full").select { |el| el.text.strip == "added" }
|
||||
expect(badges.size).to eq(2)
|
||||
end
|
||||
end
|
||||
|
||||
describe "when profile has different NIP-05 and Lightning addresses" do
|
||||
let(:profile_event) do
|
||||
{
|
||||
"content" => {
|
||||
"nip05" => "alice@other.org",
|
||||
"lud16" => "alice@getalby.com",
|
||||
"display_name" => "Alice External"
|
||||
}.to_json
|
||||
}
|
||||
end
|
||||
|
||||
it "shows current values with different badges and suggestion strips" do
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: profile_event))
|
||||
|
||||
nip05_input = rendered.css("input[name='user[nip05_address]']").first
|
||||
expect(nip05_input["value"]).to eq("alice@other.org")
|
||||
expect(nip05_input["class"]).to include("border-amber-400")
|
||||
|
||||
lud16_input = rendered.css("input[name='user[lud16_address]']").first
|
||||
expect(lud16_input["value"]).to eq("alice@getalby.com")
|
||||
expect(lud16_input["class"]).to include("border-amber-400")
|
||||
|
||||
different_badges = rendered.css("span.rounded-full").select { |el| el.text.strip == "different" }
|
||||
expect(different_badges.size).to eq(2)
|
||||
|
||||
suggestion_buttons = rendered.css("button[data-action='click->field-suggestion#apply']")
|
||||
expect(suggestion_buttons.size).to eq(2)
|
||||
expect(suggestion_buttons.first["data-field-suggestion-value-param"]).to eq("alice@kosmos.org")
|
||||
end
|
||||
end
|
||||
|
||||
describe "when profile addresses match user address" do
|
||||
let(:profile_event) do
|
||||
{
|
||||
"content" => {
|
||||
"nip05" => "alice@kosmos.org",
|
||||
"lud16" => "alice@kosmos.org",
|
||||
"display_name" => "Alice Wonderland"
|
||||
}.to_json
|
||||
}
|
||||
end
|
||||
|
||||
it "renders standard inputs without added or different badges" do
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: profile_event))
|
||||
|
||||
nip05_input = rendered.css("input[name='user[nip05_address]']").first
|
||||
expect(nip05_input["value"]).to eq("alice@kosmos.org")
|
||||
expect(nip05_input["class"]).not_to include("border-emerald-500")
|
||||
expect(nip05_input["class"]).not_to include("border-amber-400")
|
||||
|
||||
badges = rendered.css("span.rounded-full").select { |el| %w[added different].include?(el.text.strip) }
|
||||
expect(badges).to be_empty
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,105 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe Settings::NostrEditRelaysComponent, type: :component do
|
||||
before do
|
||||
allow(Setting).to receive(:nostr_relay_url).and_return("wss://nostr.kosmos.org")
|
||||
allow(Setting).to receive(:nostr_discovery_relays).and_return([
|
||||
"wss://nos.lol",
|
||||
"wss://relay.damus.io"
|
||||
])
|
||||
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("url-list-editor")
|
||||
expect(form["data-action"]).to include("submit->url-list-editor#save")
|
||||
expect(form["data-url-list-editor-kind-value"]).to eq("10002")
|
||||
expect(form["data-url-list-editor-tag-value"]).to eq("r")
|
||||
expect(form["data-url-list-editor-markers-value"]).to eq("true")
|
||||
expect(form["data-url-list-editor-pattern-value"]).to eq("^wss?://")
|
||||
|
||||
expect(rendered.css("[data-url-list-editor-target='error']")).to be_present
|
||||
expect(rendered.css("[data-url-list-editor-target='submit']")).to be_present
|
||||
end
|
||||
|
||||
describe "when user has no relay list (nip65_event is nil)" 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))
|
||||
|
||||
list = rendered.css("[data-url-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(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
|
||||
|
||||
describe "when user has an existing relay list without site relay" do
|
||||
let(:nip65_event) do
|
||||
{
|
||||
"kind" => 10002,
|
||||
"tags" => [
|
||||
["r", "wss://nos.lol"],
|
||||
["r", "wss://relay.damus.io", "read"]
|
||||
]
|
||||
}
|
||||
end
|
||||
|
||||
it "prepends the site relay marked as added, while existing relays are not added" do
|
||||
rendered = render_inline(described_class.new(nip65_event: nip65_event))
|
||||
|
||||
relay_inputs = rendered.css("input[name='relay_urls[]']").map { |el| el["value"] }
|
||||
expect(relay_inputs.first).to eq("wss://nostr.kosmos.org")
|
||||
|
||||
badges = rendered.css("span.rounded-full").select { |el| el.text.strip == "added" }
|
||||
expect(badges.size).to eq(1)
|
||||
|
||||
site_input = rendered.css("input[value='wss://nostr.kosmos.org']").first
|
||||
expect(site_input["class"]).to include("border-emerald-500")
|
||||
expect(site_input["data-added-value"]).to eq("wss://nostr.kosmos.org")
|
||||
expect(site_input["data-action"]).to include("input->url-list-editor#checkAdded")
|
||||
|
||||
other_input = rendered.css("input[value='wss://nos.lol']").first
|
||||
expect(other_input["class"]).not_to include("border-emerald-500")
|
||||
expect(other_input["data-added-value"]).to be_nil
|
||||
|
||||
select = rendered.css("select[name='relay_markers[]']").first
|
||||
expect(select["class"]).to include("w-36")
|
||||
end
|
||||
end
|
||||
|
||||
describe "when user already has site relay in their relay list" do
|
||||
let(:nip65_event) do
|
||||
{
|
||||
"kind" => 10002,
|
||||
"tags" => [
|
||||
["r", "wss://nostr.kosmos.org"],
|
||||
["r", "wss://nos.lol"]
|
||||
]
|
||||
}
|
||||
end
|
||||
|
||||
it "renders relays without any added badges" do
|
||||
rendered = render_inline(described_class.new(nip65_event: nip65_event))
|
||||
|
||||
badges = rendered.css("span.rounded-full").select { |el| el.text.strip == "added" }
|
||||
expect(badges).to be_empty
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,53 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe Settings::NostrMediaServerStatusComponent, type: :component do
|
||||
let(:server_url) { "https://blossom.example.com" }
|
||||
|
||||
def render_status(media_list_event:)
|
||||
render_inline(
|
||||
described_class.new(media_list_event: media_list_event, server_url: server_url)
|
||||
)
|
||||
end
|
||||
|
||||
describe "without a media server list" do
|
||||
it "reports that no list was found and offers setup" do
|
||||
rendered = render_status(media_list_event: nil)
|
||||
|
||||
expect(rendered.text).to include("We could not find a media server list")
|
||||
expect(rendered.text).to include("Set up media servers")
|
||||
end
|
||||
end
|
||||
|
||||
describe "with the site server in the list" do
|
||||
let(:media_list_event) { { "tags" => [["server", server_url]] } }
|
||||
|
||||
it "reports that the site server is part of the list" do
|
||||
rendered = render_status(media_list_event: media_list_event)
|
||||
|
||||
expect(rendered.text).to include("is part of your list")
|
||||
expect(rendered.text).to include("Edit media servers")
|
||||
end
|
||||
end
|
||||
|
||||
describe "without the site server in the list" do
|
||||
let(:media_list_event) { { "tags" => [["server", "https://cdn.example.com"]] } }
|
||||
|
||||
it "reports that the site server is missing" do
|
||||
rendered = render_status(media_list_event: media_list_event)
|
||||
|
||||
expect(rendered.text).to include("is missing from your media server list")
|
||||
end
|
||||
end
|
||||
|
||||
describe "with a normalized variant of the site server in the list" do
|
||||
let(:media_list_event) { { "tags" => [["server", "HTTPS://Blossom.Example.com/"]] } }
|
||||
|
||||
it "still reports it as part of the list" do
|
||||
rendered = render_status(media_list_event: media_list_event)
|
||||
|
||||
expect(rendered.text).to include("is part of your list")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,51 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe Settings::NostrRelayStatusComponent, type: :component do
|
||||
let(:relay_url) { "wss://nostr.kosmos.org" }
|
||||
|
||||
def render_status(nip65_event:)
|
||||
render_inline(described_class.new(nip65_event: nip65_event, relay_url: relay_url))
|
||||
end
|
||||
|
||||
describe "without a relay list" do
|
||||
it "reports that no list was found and offers setup" do
|
||||
rendered = render_status(nip65_event: nil)
|
||||
|
||||
expect(rendered.text).to include("We could not find a relay list")
|
||||
expect(rendered.text).to include("Set up relays")
|
||||
end
|
||||
end
|
||||
|
||||
describe "with the site relay in the list" do
|
||||
let(:nip65_event) { { "tags" => [["r", relay_url]] } }
|
||||
|
||||
it "reports that the site relay is part of the list" do
|
||||
rendered = render_status(nip65_event: nip65_event)
|
||||
|
||||
expect(rendered.text).to include("is part of your relay list")
|
||||
expect(rendered.text).to include("Edit relays")
|
||||
end
|
||||
end
|
||||
|
||||
describe "without the site relay in the list" do
|
||||
let(:nip65_event) { { "tags" => [["r", "wss://other.example.com"]] } }
|
||||
|
||||
it "reports that the site relay is missing" do
|
||||
rendered = render_status(nip65_event: nip65_event)
|
||||
|
||||
expect(rendered.text).to include("is missing from your relay list")
|
||||
end
|
||||
end
|
||||
|
||||
describe "with a normalized variant of the site relay in the list" do
|
||||
let(:nip65_event) { { "tags" => [["r", "WSS://Nostr.Kosmos.org/"]] } }
|
||||
|
||||
it "still reports it as part of the list" do
|
||||
rendered = render_status(nip65_event: nip65_event)
|
||||
|
||||
expect(rendered.text).to include("is part of your relay list")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,225 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe "Settings::NostrEvents", type: :request do
|
||||
let(:user) { create :user, cn: 'mark', ou: 'kosmos.org' }
|
||||
let(:pubkey) { Setting.nostr_public_key }
|
||||
let(:keypair) do
|
||||
Nostr::KeyPair.new(
|
||||
private_key: Nostr::PrivateKey.new(Setting.nostr_private_key),
|
||||
public_key: Nostr::PublicKey.new(Setting.nostr_public_key)
|
||||
)
|
||||
end
|
||||
let(:nostr_user) { Nostr::User.new(keypair: keypair) }
|
||||
|
||||
before do
|
||||
login_as user, :scope => :user
|
||||
|
||||
allow_any_instance_of(User).to receive(:dn)
|
||||
.and_return("cn=#{user.cn},ou=kosmos.org,cn=users,dc=kosmos,dc=org")
|
||||
allow_any_instance_of(User).to receive(:nostr_pubkey).and_return(pubkey)
|
||||
end
|
||||
|
||||
def signed_event(kind: 0, content: "{}", tags: [], created_at: Time.current.to_i)
|
||||
nostr_user.create_event(
|
||||
kind: kind, content: content, created_at: created_at, tags: tags
|
||||
)
|
||||
end
|
||||
|
||||
def post_signed_event(event)
|
||||
post nostr_publish_settings_path,
|
||||
params: { signed_event: event.to_h }.to_json,
|
||||
headers: {
|
||||
"CONTENT_TYPE" => "application/json",
|
||||
"HTTP_ACCEPT" => "application/json"
|
||||
}
|
||||
end
|
||||
|
||||
describe "POST /settings/nostr_publish" do
|
||||
it "enqueues a publish job and reports success" do
|
||||
expect(NostrPublishUserEventJob).to receive(:perform_later)
|
||||
.with(event: hash_including("kind" => 0))
|
||||
|
||||
post_signed_event(signed_event)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(JSON.parse(response.body)).to eq("ok" => true)
|
||||
end
|
||||
|
||||
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"],
|
||||
["r", "wss://read.example.com", "read"],
|
||||
["r", "wss://write.example.com", "write"]
|
||||
]
|
||||
)
|
||||
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
|
||||
|
||||
it "accepts a media server list event" do
|
||||
event = signed_event(
|
||||
kind: NostrManagerService::MEDIA_SERVER_LIST_KIND,
|
||||
tags: [["server", "https://blossom.example.com"]]
|
||||
)
|
||||
expect(NostrPublishUserEventJob).to receive(:perform_later) do |args|
|
||||
expect(args[:event]["kind"]).to eq(NostrManagerService::MEDIA_SERVER_LIST_KIND)
|
||||
expect(args[:event]["tags"]).to eq([["server", "https://blossom.example.com"]])
|
||||
end
|
||||
|
||||
post_signed_event(event)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
end
|
||||
|
||||
context "when the account has no public key" do
|
||||
before { allow_any_instance_of(User).to receive(:nostr_pubkey).and_return(nil) }
|
||||
|
||||
it "is forbidden" do
|
||||
expect(NostrPublishUserEventJob).not_to receive(:perform_later)
|
||||
|
||||
post_signed_event(signed_event)
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
end
|
||||
end
|
||||
|
||||
context "when the event was signed by a different key" do
|
||||
it "is rejected" do
|
||||
event = signed_event
|
||||
forged = Nostr::Event.new(**event.to_h.merge(pubkey: "0" * 64))
|
||||
expect(NostrPublishUserEventJob).not_to receive(:perform_later)
|
||||
|
||||
post_signed_event(forged)
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
end
|
||||
|
||||
context "with a forged event body" do
|
||||
it "is rejected" do
|
||||
event = signed_event(content: "original")
|
||||
forged = Nostr::Event.new(**event.to_h.merge(content: "injected"))
|
||||
expect(NostrPublishUserEventJob).not_to receive(:perform_later)
|
||||
|
||||
post_signed_event(forged)
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
end
|
||||
|
||||
context "with a disallowed kind" do
|
||||
it "is rejected" do
|
||||
expect(NostrPublishUserEventJob).not_to receive(:perform_later)
|
||||
|
||||
post_signed_event(signed_event(kind: 1))
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
end
|
||||
|
||||
context "with a stale event" do
|
||||
it "is rejected" do
|
||||
expect(NostrPublishUserEventJob).not_to receive(:perform_later)
|
||||
|
||||
post_signed_event(signed_event(created_at: 1.hour.ago.to_i))
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
end
|
||||
|
||||
context "with a far-future event" do
|
||||
it "is rejected" do
|
||||
expect(NostrPublishUserEventJob).not_to receive(:perform_later)
|
||||
|
||||
post_signed_event(signed_event(created_at: 1.hour.from_now.to_i))
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
end
|
||||
|
||||
context "with oversized content" do
|
||||
it "is rejected" do
|
||||
expect(NostrPublishUserEventJob).not_to receive(:perform_later)
|
||||
|
||||
post_signed_event(signed_event(content: "x" * 10_001))
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
end
|
||||
|
||||
context "with malformed parameters" do
|
||||
it "returns 422 instead of raising" do
|
||||
post nostr_publish_settings_path,
|
||||
params: { foo: "bar" }.to_json,
|
||||
headers: {
|
||||
"CONTENT_TYPE" => "application/json",
|
||||
"HTTP_ACCEPT" => "application/json"
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
|
||||
it "returns 422 when signed_event is not an object" do
|
||||
post nostr_publish_settings_path,
|
||||
params: { signed_event: "nope" }.to_json,
|
||||
headers: {
|
||||
"CONTENT_TYPE" => "application/json",
|
||||
"HTTP_ACCEPT" => "application/json"
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
end
|
||||
|
||||
context "with a non-array tag" do
|
||||
it "is rejected" do
|
||||
expect(NostrPublishUserEventJob).not_to receive(:perform_later)
|
||||
|
||||
post_signed_event(signed_event(tags: ["not-an-array"]))
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
end
|
||||
|
||||
context "when rate limited" do
|
||||
before do
|
||||
allow(Rails).to receive(:cache).and_return(ActiveSupport::Cache::MemoryStore.new)
|
||||
end
|
||||
|
||||
it "rejects after too many attempts" do
|
||||
Settings::NostrEventsController::RATE_LIMIT.times do
|
||||
post_signed_event(signed_event)
|
||||
end
|
||||
|
||||
post_signed_event(signed_event)
|
||||
|
||||
expect(response).to have_http_status(:too_many_requests)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -151,4 +151,138 @@ RSpec.describe "Settings", type: :request do
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe "GET /settings/fetch_nostr_metadata" 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
|
||||
before do
|
||||
allow_any_instance_of(User).to receive(:nostr_pubkey).and_return(nil)
|
||||
end
|
||||
|
||||
it "returns a bad request status" do
|
||||
get nostr_metadata_settings_path,
|
||||
headers: { "HTTP_ACCEPT" => "application/json" }
|
||||
|
||||
expect(response).to have_http_status(:bad_request)
|
||||
end
|
||||
end
|
||||
|
||||
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,
|
||||
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", "event_id" => nil)
|
||||
end
|
||||
|
||||
context "with a stale relay list" do
|
||||
let(:stale_event) do
|
||||
{
|
||||
"id" => "old",
|
||||
"created_at" => 2.hours.ago.to_i,
|
||||
"tags" => [
|
||||
["r", "wss://write.example.com"],
|
||||
["r", "wss://read.example.com", "read"],
|
||||
["r", "ws://10.0.0.1"]
|
||||
]
|
||||
}
|
||||
end
|
||||
|
||||
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,
|
||||
relays: discovery_relays)
|
||||
.and_return(stale_event)
|
||||
expect(NostrManager::DiscoverUserEvent).to receive(:call)
|
||||
.with(pubkey: "abc123", kind: NostrManagerService::RELAY_LIST_KIND,
|
||||
relays: ["wss://write.example.com"])
|
||||
.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", "event_id" => "old")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context "when a discovery relay fails" do
|
||||
it "returns an empty result instead of raising" do
|
||||
allow(NostrManager::FetchEvent).to receive(:call)
|
||||
.and_raise(Timeout::Error, "execution expired")
|
||||
|
||||
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", "event_id" => nil)
|
||||
end
|
||||
end
|
||||
|
||||
context "with step=profile" do
|
||||
it "discovers the profile and asks for the media server list next" do
|
||||
expect(NostrManager::DiscoverUserEvent).to receive(:call)
|
||||
.with(pubkey: "abc123", kind: NostrManagerService::PROFILE_KIND,
|
||||
relays: discovery_relays)
|
||||
.and_return(nil)
|
||||
|
||||
get nostr_metadata_settings_path(step: "profile"),
|
||||
headers: { "HTTP_ACCEPT" => "application/json" }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(JSON.parse(response.body)).to eq("next" => "blossom", "event_id" => nil)
|
||||
end
|
||||
end
|
||||
|
||||
context "with step=blossom" do
|
||||
it "discovers the media server list and asks to render next" do
|
||||
expect(NostrManager::DiscoverUserEvent).to receive(:call)
|
||||
.with(pubkey: "abc123", kind: NostrManagerService::MEDIA_SERVER_LIST_KIND,
|
||||
relays: discovery_relays)
|
||||
.and_return(nil)
|
||||
|
||||
get nostr_metadata_settings_path(step: "blossom"),
|
||||
headers: { "HTTP_ACCEPT" => "application/json" }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(JSON.parse(response.body)).to eq("next" => "render", "event_id" => nil)
|
||||
end
|
||||
end
|
||||
|
||||
context "with step=render" do
|
||||
it "renders the metadata partial" do
|
||||
get nostr_metadata_settings_path(step: "render"),
|
||||
headers: { "HTTP_ACCEPT" => "text/html" }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
end
|
||||
end
|
||||
|
||||
context "with an unknown step" do
|
||||
it "returns a bad request status" do
|
||||
get nostr_metadata_settings_path(step: "bogus"),
|
||||
headers: { "HTTP_ACCEPT" => "application/json" }
|
||||
|
||||
expect(response).to have_http_status(:bad_request)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,40 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe NostrManager::DiscoverUserEvent, type: :model do
|
||||
before do
|
||||
allow(Setting).to receive(:nostr_discovery_relays)
|
||||
.and_return(["wss://discovery.example.com"])
|
||||
end
|
||||
|
||||
describe "without explicit relays" do
|
||||
it "queries the discovery relays for the requested kind" do
|
||||
expect(NostrManager::FetchLatestEvent).to receive(:call) do |args|
|
||||
expect(args[:relays]).to eq(["wss://discovery.example.com"])
|
||||
expect(args[:filter].authors).to eq(["abc123"])
|
||||
expect(args[:filter].kinds).to eq([NostrManagerService::RELAY_LIST_KIND])
|
||||
expect(args[:filter].limit).to eq(1)
|
||||
"event"
|
||||
end
|
||||
|
||||
result = described_class.call(
|
||||
pubkey: "abc123", kind: NostrManagerService::RELAY_LIST_KIND
|
||||
)
|
||||
expect(result).to eq("event")
|
||||
end
|
||||
end
|
||||
|
||||
describe "with explicit relays" do
|
||||
it "queries the given relays instead of the discovery relays" do
|
||||
expect(NostrManager::FetchLatestEvent).to receive(:call) do |args|
|
||||
expect(args[:relays]).to eq(["wss://write.example.com"])
|
||||
expect(args[:filter].kinds).to eq([NostrManagerService::PROFILE_KIND])
|
||||
nil
|
||||
end
|
||||
|
||||
described_class.call(
|
||||
pubkey: "abc123", kind: NostrManagerService::PROFILE_KIND,
|
||||
relays: ["wss://write.example.com"]
|
||||
)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,97 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe NostrManager::FetchLatestEvent, type: :model do
|
||||
let(:filter) { Nostr::Filter.new(authors: ["pubkey"], kinds: [0], limit: 1) }
|
||||
let(:event_v1) { { "id" => "aaa", "created_at" => 1000, "content" => "v1" } }
|
||||
let(:event_v2) { { "id" => "bbb", "created_at" => 2000, "content" => "v2" } }
|
||||
|
||||
describe "with no events found" do
|
||||
it "returns nil" do
|
||||
allow(NostrManager::FetchEvent).to receive(:call).and_return(nil)
|
||||
|
||||
result = described_class.call(relays: ["wss://a", "wss://b"], filter: filter)
|
||||
expect(result).to be_nil
|
||||
end
|
||||
end
|
||||
|
||||
describe "with all relays failing" do
|
||||
it "returns nil instead of raising" do
|
||||
allow(NostrManager::FetchEvent).to receive(:call).and_raise(Timeout::Error)
|
||||
|
||||
result = described_class.call(relays: ["wss://a", "wss://b"], filter: filter)
|
||||
expect(result).to be_nil
|
||||
end
|
||||
end
|
||||
|
||||
describe "with event on 1 relay only" do
|
||||
it "returns the event" do
|
||||
allow(NostrManager::FetchEvent).to receive(:call) do |args|
|
||||
case args[:relay_url]
|
||||
when "wss://a" then event_v1
|
||||
else nil
|
||||
end
|
||||
end
|
||||
|
||||
result = described_class.call(
|
||||
relays: ["wss://a", "wss://b", "wss://c"], filter: filter
|
||||
)
|
||||
expect(result).to eq(event_v1)
|
||||
end
|
||||
end
|
||||
|
||||
describe "with events on 2 relays, different versions" do
|
||||
it "returns the latest event (max created_at)" do
|
||||
allow(NostrManager::FetchEvent).to receive(:call) do |args|
|
||||
case args[:relay_url]
|
||||
when "wss://a" then event_v1
|
||||
when "wss://b" then event_v2
|
||||
end
|
||||
end
|
||||
|
||||
result = described_class.call(relays: ["wss://a", "wss://b"], filter: filter)
|
||||
expect(result).to eq(event_v2)
|
||||
end
|
||||
end
|
||||
|
||||
describe "with duplicate events (same ID) on 2 relays" do
|
||||
it "returns the single event without double-counting" do
|
||||
allow(NostrManager::FetchEvent).to receive(:call).and_return(event_v1)
|
||||
|
||||
result = described_class.call(relays: ["wss://a", "wss://b"], filter: filter)
|
||||
expect(result).to eq(event_v1)
|
||||
end
|
||||
end
|
||||
|
||||
describe "with timeout after finding 1 event" do
|
||||
it "still returns the found event" do
|
||||
allow(NostrManager::FetchEvent).to receive(:call) do |args|
|
||||
case args[:relay_url]
|
||||
when "wss://a" then event_v1
|
||||
when "wss://b" then raise Timeout::Error
|
||||
end
|
||||
end
|
||||
|
||||
result = described_class.call(relays: ["wss://a", "wss://b"], filter: filter)
|
||||
expect(result).to eq(event_v1)
|
||||
end
|
||||
end
|
||||
|
||||
describe "with max_events reached" do
|
||||
it "stops querying further relays" do
|
||||
call_count = 0
|
||||
allow(NostrManager::FetchEvent).to receive(:call) do |args|
|
||||
call_count += 1
|
||||
raise "should not query wss://c" if args[:relay_url] == "wss://c"
|
||||
case args[:relay_url]
|
||||
when "wss://a" then event_v1
|
||||
when "wss://b" then event_v2
|
||||
end
|
||||
end
|
||||
|
||||
described_class.call(
|
||||
relays: ["wss://a", "wss://b", "wss://c"], filter: filter
|
||||
)
|
||||
expect(call_count).to eq(2)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,20 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe NostrManager::PublishEvent, type: :model do
|
||||
let(:event) do
|
||||
Nostr::Event.new(
|
||||
id: "b" * 64, pubkey: "a" * 64, sig: "c" * 128,
|
||||
created_at: Time.current.to_i, kind: 0, content: "{}", tags: []
|
||||
)
|
||||
end
|
||||
|
||||
it "does not raise on a malformed relay URL" do
|
||||
expect { described_class.call(event: event, relay_url: "not a url") }
|
||||
.not_to raise_error
|
||||
end
|
||||
|
||||
it "does not raise on a blank relay URL" do
|
||||
expect { described_class.call(event: event, relay_url: "") }
|
||||
.not_to raise_error
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,123 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe NostrManager::PublishUserEvent, type: :model do
|
||||
let(:pubkey) { Setting.nostr_public_key }
|
||||
let(:keypair) do
|
||||
Nostr::KeyPair.new(
|
||||
private_key: Nostr::PrivateKey.new(Setting.nostr_private_key),
|
||||
public_key: Nostr::PublicKey.new(Setting.nostr_public_key)
|
||||
)
|
||||
end
|
||||
let(:nostr_user) { Nostr::User.new(keypair: keypair) }
|
||||
|
||||
before do
|
||||
Setting.nostr_relay_url = "wss://site.example.com"
|
||||
end
|
||||
|
||||
def build_event(kind:, tags: [])
|
||||
nostr_user.create_event(
|
||||
kind: kind, content: "{}", created_at: Time.current.to_i, tags: tags
|
||||
)
|
||||
end
|
||||
|
||||
describe "for a relay list event (kind 10002)" do
|
||||
let(:relay_list) do
|
||||
build_event(kind: NostrManagerService::RELAY_LIST_KIND, tags: [
|
||||
["r", "wss://write.example.com"],
|
||||
["r", "wss://read.example.com", "read"]
|
||||
])
|
||||
end
|
||||
|
||||
it "publishes to the site relay and every relay in the list" do
|
||||
expect(NostrManager::PublishEvent).to receive(:call)
|
||||
.with(event: relay_list, relay_url: "wss://site.example.com")
|
||||
expect(NostrManager::PublishEvent).to receive(:call)
|
||||
.with(event: relay_list, relay_url: "wss://write.example.com")
|
||||
expect(NostrManager::PublishEvent).to receive(:call)
|
||||
.with(event: relay_list, relay_url: "wss://read.example.com")
|
||||
|
||||
described_class.call(event: relay_list)
|
||||
end
|
||||
|
||||
it "skips unsafe relay URLs" do
|
||||
list = build_event(kind: NostrManagerService::RELAY_LIST_KIND, tags: [
|
||||
["r", "ws://127.0.0.1:7777"],
|
||||
["r", "wss://write.example.com"]
|
||||
])
|
||||
|
||||
expect(NostrManager::PublishEvent).to receive(:call).once
|
||||
.with(event: list, relay_url: "wss://site.example.com")
|
||||
expect(NostrManager::PublishEvent).to receive(:call).once
|
||||
.with(event: list, relay_url: "wss://write.example.com")
|
||||
|
||||
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
|
||||
let(:profile) { build_event(kind: NostrManagerService::PROFILE_KIND) }
|
||||
let(:relay_list) do
|
||||
{
|
||||
"tags" => [
|
||||
["r", "wss://write.example.com"],
|
||||
["r", "wss://read.example.com", "read"],
|
||||
["r", "ws://10.0.0.1"]
|
||||
]
|
||||
}
|
||||
end
|
||||
|
||||
before do
|
||||
allow(NostrManager::DiscoverUserEvent).to receive(:call)
|
||||
.with(pubkey: pubkey, kind: NostrManagerService::RELAY_LIST_KIND)
|
||||
.and_return(relay_list)
|
||||
end
|
||||
|
||||
it "publishes to the site relay and the user's write relays only" do
|
||||
expect(NostrManager::PublishEvent).to receive(:call)
|
||||
.with(event: profile, relay_url: "wss://site.example.com")
|
||||
expect(NostrManager::PublishEvent).to receive(:call)
|
||||
.with(event: profile, relay_url: "wss://write.example.com")
|
||||
expect(NostrManager::PublishEvent).not_to receive(:call)
|
||||
.with(event: profile, relay_url: "wss://read.example.com")
|
||||
|
||||
described_class.call(event: profile)
|
||||
end
|
||||
end
|
||||
|
||||
describe "when the site relay is not configured" do
|
||||
before { Setting.nostr_relay_url = "" }
|
||||
|
||||
it "publishes to the user's relays only" do
|
||||
list = build_event(kind: NostrManagerService::RELAY_LIST_KIND, tags: [
|
||||
["r", "wss://write.example.com"]
|
||||
])
|
||||
|
||||
expect(NostrManager::PublishEvent).to receive(:call).once
|
||||
.with(event: list, relay_url: "wss://write.example.com")
|
||||
|
||||
described_class.call(event: list)
|
||||
end
|
||||
end
|
||||
|
||||
describe "with a plain hash event" do
|
||||
it "accepts a serialized event" do
|
||||
list = build_event(kind: NostrManagerService::RELAY_LIST_KIND, tags: [
|
||||
["r", "wss://write.example.com"]
|
||||
])
|
||||
|
||||
expect(NostrManager::PublishEvent).to receive(:call).twice
|
||||
|
||||
described_class.call(event: list.to_h.transform_keys(&:to_s))
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -16,6 +16,23 @@ RSpec.describe NostrManager::PublishZapReceipt, type: :model do
|
||||
described_class.call(zap: zap)
|
||||
end
|
||||
|
||||
context "with an unsafe relay in the list" do
|
||||
before do
|
||||
relays = zap.request["tags"].find { |t| t.first == "relays" }
|
||||
relays << "ws://127.0.0.1:6379"
|
||||
relays << "ws://[::ffff:169.254.1.1]"
|
||||
end
|
||||
|
||||
it "does not publish to unsafe relays" do
|
||||
expect(NostrPublishEventJob).to receive(:perform_later)
|
||||
.with(hash_including(relay_url: "wss://nostr.kosmos.org")).and_return(true)
|
||||
expect(NostrPublishEventJob).to receive(:perform_later)
|
||||
.with(hash_including(relay_url: "wss://relay.example.com")).and_return(true)
|
||||
|
||||
described_class.call(zap: zap)
|
||||
end
|
||||
end
|
||||
|
||||
context "with a long relay list" do
|
||||
before do
|
||||
relays = zap.request["tags"].find { |t| t.first == "relays" }
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe NostrManager::RelayUrlValidator, type: :model do
|
||||
describe ".valid?" do
|
||||
it "accepts websocket URLs with public hosts" do
|
||||
expect(described_class.valid?("wss://relay.example.com")).to be(true)
|
||||
expect(described_class.valid?("ws://relay.example.com:7777")).to be(true)
|
||||
end
|
||||
|
||||
it "rejects non-websocket schemes" do
|
||||
expect(described_class.valid?("http://relay.example.com")).to be(false)
|
||||
expect(described_class.valid?("https://relay.example.com")).to be(false)
|
||||
expect(described_class.valid?("ftp://relay.example.com")).to be(false)
|
||||
end
|
||||
|
||||
it "rejects loopback hosts" do
|
||||
expect(described_class.valid?("ws://127.0.0.1:7777")).to be(false)
|
||||
expect(described_class.valid?("ws://localhost:7777")).to be(false)
|
||||
expect(described_class.valid?("ws://[::1]:7777")).to be(false)
|
||||
end
|
||||
|
||||
it "rejects private and link-local addresses" do
|
||||
expect(described_class.valid?("ws://10.0.0.1")).to be(false)
|
||||
expect(described_class.valid?("ws://192.168.1.5")).to be(false)
|
||||
expect(described_class.valid?("ws://172.16.0.1")).to be(false)
|
||||
expect(described_class.valid?("ws://169.254.1.1")).to be(false)
|
||||
end
|
||||
|
||||
it "rejects IPv4-mapped and IPv4-compatible IPv6 addresses" do
|
||||
expect(described_class.valid?("ws://[::ffff:127.0.0.1]:7777")).to be(false)
|
||||
expect(described_class.valid?("ws://[::ffff:169.254.1.1]")).to be(false)
|
||||
expect(described_class.valid?("ws://[::ffff:10.0.0.1]")).to be(false)
|
||||
expect(described_class.valid?("ws://[::0a00:1]")).to be(false)
|
||||
end
|
||||
|
||||
it "rejects blank and malformed URLs" do
|
||||
expect(described_class.valid?("")).to be(false)
|
||||
expect(described_class.valid?(nil)).to be(false)
|
||||
expect(described_class.valid?("not a url")).to be(false)
|
||||
expect(described_class.valid?("wss://")).to be(false)
|
||||
end
|
||||
end
|
||||
|
||||
describe ".filter" do
|
||||
it "keeps only valid relay URLs" do
|
||||
urls = [
|
||||
"wss://relay.example.com",
|
||||
"ws://127.0.0.1:7777",
|
||||
"http://internal.example.com",
|
||||
nil
|
||||
]
|
||||
|
||||
expect(described_class.filter(urls)).to eq(["wss://relay.example.com"])
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in new issue
Block a user