Add server-side publishing for user-signed Nostr events
This commit is contained in:
17 files changed
+700
-17
No files matched your search
@@ -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
|
||||
@@ -151,8 +151,6 @@ class SettingsController < ApplicationController
|
||||
def fetch_nostr_metadata
|
||||
return render plain: "no pubkey", status: :bad_request if @user.nostr_pubkey.blank?
|
||||
|
||||
cache_key = "nostr_metadata:#{@user.id}"
|
||||
|
||||
case params[:step]
|
||||
when "relays"
|
||||
nip65_event = NostrManager::DiscoverUserEvent.call(
|
||||
@@ -169,22 +167,22 @@ class SettingsController < ApplicationController
|
||||
write_relays = extract_write_relays(nip65_event) if auth_event
|
||||
end
|
||||
|
||||
Rails.cache.write("#{cache_key}:nip65", nip65_event, expires_in: 5.minutes)
|
||||
Rails.cache.write("#{cache_key}:write_relays", write_relays, expires_in: 5.minutes)
|
||||
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" }
|
||||
|
||||
when "profile"
|
||||
write_relays = Rails.cache.read("#{cache_key}:write_relays") || []
|
||||
write_relays = Rails.cache.read(nostr_metadata_cache_key("write_relays")) || []
|
||||
relays = write_relays.any? ? write_relays : nil
|
||||
profile = NostrManager::DiscoverUserEvent.call(
|
||||
pubkey: @user.nostr_pubkey, kind: NostrManagerService::PROFILE_KIND, relays: relays
|
||||
)
|
||||
Rails.cache.write("#{cache_key}:profile", profile, expires_in: 5.minutes)
|
||||
Rails.cache.write(nostr_metadata_cache_key("profile"), profile, expires_in: 5.minutes)
|
||||
render json: { next: "render" }
|
||||
|
||||
when "render", nil
|
||||
@nip65_event = Rails.cache.read("#{cache_key}:nip65")
|
||||
@profile = Rails.cache.read("#{cache_key}:profile")
|
||||
@nip65_event = Rails.cache.read(nostr_metadata_cache_key("nip65"))
|
||||
@profile = Rails.cache.read(nostr_metadata_cache_key("profile"))
|
||||
render partial: "nostr_metadata", formats: :html
|
||||
|
||||
else
|
||||
@@ -199,9 +197,15 @@ class SettingsController < ApplicationController
|
||||
end
|
||||
|
||||
def extract_write_relays(nip65_event)
|
||||
nip65_event["tags"]
|
||||
.select { |t| t[0] == "r" && t[2] != "read" }
|
||||
.map { |t| t[1] }
|
||||
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 stale?(event, threshold = 30.minutes)
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
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)
|
||||
return publish(signedEvent, { url })
|
||||
}
|
||||
|
||||
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
|
||||
@@ -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,7 +15,10 @@ 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
|
||||
@@ -44,7 +48,24 @@ module NostrManager
|
||||
client.connect relay
|
||||
end
|
||||
|
||||
thread.join
|
||||
begin
|
||||
Timeout.timeout(TIMEOUT) { thread.join }
|
||||
rescue Timeout::Error
|
||||
Rails.logger.debug "#{log_prefix} Timeout: no relay response within #{TIMEOUT}s"
|
||||
ensure
|
||||
thread.exit
|
||||
end
|
||||
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))
|
||||
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
|
||||
@@ -5,6 +5,16 @@ class NostrManagerService < ApplicationService
|
||||
RELAY_LIST_KIND = 10002
|
||||
MEDIA_SERVER_LIST_KIND = 10063
|
||||
|
||||
METADATA_CACHE_SUFFIXES = %w[nip65 write_relays profile].freeze
|
||||
|
||||
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 parse_tags(tags)
|
||||
out = {}
|
||||
# TODO support more than 1 item for each tag type
|
||||
|
||||
@@ -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
|
||||
@@ -66,6 +66,7 @@ Rails.application.routes.draw do
|
||||
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
|
||||
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
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" do
|
||||
event = signed_event(
|
||||
kind: NostrManagerService::RELAY_LIST_KIND,
|
||||
tags: [["r", "wss://relay.example.com"]]
|
||||
)
|
||||
expect(NostrPublishUserEventJob).to receive(:perform_later)
|
||||
|
||||
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
|
||||
@@ -191,7 +191,8 @@ RSpec.describe "Settings", type: :request do
|
||||
"created_at" => 2.hours.ago.to_i,
|
||||
"tags" => [
|
||||
["r", "wss://write.example.com"],
|
||||
["r", "wss://read.example.com", "read"]
|
||||
["r", "wss://read.example.com", "read"],
|
||||
["r", "ws://10.0.0.1"]
|
||||
]
|
||||
}
|
||||
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,113 @@
|
||||
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
|
||||
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