Keep Nostr Connect listeners alive only while polling

Stop abandoned listeners after 60s without polling, re-enqueue from status polls with a throttle, and add a Start over action for stuck sessions.
This commit is contained in:
raucao committed 2026-11-27 15:43:01 +04:00
1 parent e7d1a5b2e2
commit 102009c6ba
11 files changed
+205 -33

No files matched your search

@@ -5,6 +5,7 @@ module Users
STATUS_RATE_LIMIT = 240
STATUS_RATE_WINDOW = 5.minutes
MAX_PENDING = 20
LISTENER_ENQUEUE_THROTTLE = 5.seconds
def show
unless Setting.nostr_enabled? && NostrSignerSession.encryption_available?
@@ -76,6 +77,8 @@ module Users
return render json: { status: "expired", error: signer_session.error }
end
ensure_listener(signer_session) if signer_session.pending?
if signer_session.verified?
sign_in_user(signer_session)
elsif signer_session.connected? && signer_session.user.present?
@@ -92,8 +95,27 @@ module Users
end
end
def restart
existing = NostrSignerSession.find_by_token(session[:nostr_connect_token])
existing.expire! if existing && (existing.pending? || existing.verified?)
session.delete(:nostr_connect_token)
redirect_to nostr_connect_path
end
private
def ensure_listener(signer_session)
started_at = signer_session.listener_started_at
return if started_at.present? && started_at > NostrConnectListenerJob::LISTENER_STALE_AFTER.ago
key = "nostr_listener_enqueued:#{signer_session.id}"
return if Rails.cache.read(key)
Rails.cache.write(key, true, expires_in: LISTENER_ENQUEUE_THROTTLE)
NostrConnectListenerJob.perform_later(signer_session.id)
end
def find_or_create_session
existing = NostrSignerSession.find_by_token(session[:nostr_connect_token])
+16 -3
View File
@@ -1,17 +1,30 @@
class NostrConnectListenerJob < ApplicationJob
queue_as :nostr_connect
LISTENER_STALE_AFTER = 5.minutes
def perform(session_id)
session = NostrSignerSession.find_by(id: session_id)
return if session.nil? || !session.pending?
return if session.listener_started_at.present? && session.listener_started_at > 1.minute.ago
session.update_column(:listener_started_at, Time.current)
started_at = Time.current
claimed = NostrSignerSession
.where(id: session_id)
.where("listener_started_at IS NULL OR listener_started_at < ?", LISTENER_STALE_AFTER.ago)
.update_all(listener_started_at: started_at)
return if claimed.zero?
NostrManager::RemoteSigner::ListenForConnection.call(session: session)
rescue StandardError => e
Rails.logger.warn("[nostr][signer] listener job failed: #{e.class}: #{e.message}")
fresh_session = NostrSignerSession.find_by(id: session_id)
fresh_session&.fail!("Could not connect to your signer. Please try again.") unless
fresh_session.nil? || fresh_session.verified? || fresh_session.connected?
ensure
if started_at
NostrSignerSession
.where(id: session_id, listener_started_at: started_at)
.update_all(listener_started_at: nil)
end
end
end
end
+13 -2
View File
@@ -12,6 +12,7 @@ module NostrManager
Result = Struct.new(:url, :message, keyword_init: true)
class TimeoutError < StandardError; end
class CancelledError < StandardError; end
DEFAULT_TIMEOUT = 30
DEFAULT_CONNECT_TIMEOUT = 5
@@ -90,14 +91,24 @@ module NostrManager
true
end
def wait_for(timeout: 10)
def wait_for(timeout: 10, tick: nil, on_tick: nil)
deadline = monotonic_now + timeout
loop do
remaining = deadline - monotonic_now
raise TimeoutError, "timed out waiting for a relay message" if remaining <= 0
result = @task.with_timeout(remaining) { @inbox.dequeue }
slice = tick ? [remaining, tick].min : remaining
result =
begin
@task.with_timeout(slice) { @inbox.dequeue }
rescue Async::TimeoutError
if on_tick && !on_tick.call
raise CancelledError, "listener no longer wanted"
end
next
end
return result if yield(result)
end
rescue Async::TimeoutError
@@ -5,6 +5,7 @@ module NostrManager
module RemoteSigner
class Client
HEX_KEY = /\A[0-9a-f]{64}\z/
LIVENESS_TICK = 5
attr_reader :remote_signer_pubkey
@@ -23,12 +24,13 @@ module NostrManager
)
end
def connect_bunker(remote_signer_pubkey:, secret:, perms:, metadata:, timeout: 30)
def connect_bunker(remote_signer_pubkey:, secret:, perms:, metadata:, timeout: 30, on_tick: nil)
@remote_signer_pubkey = remote_signer_pubkey
result = request(
"connect",
[remote_signer_pubkey, secret, perms, metadata.to_json],
timeout: timeout
timeout: timeout,
on_tick: on_tick
)
accepted = result == "ack" || (secret.present? && result == secret)
@@ -37,10 +39,10 @@ module NostrManager
result
end
def await_nostrconnect(secret:, timeout: 120)
def await_nostrconnect(secret:, timeout: 120, on_tick: nil)
raise ArgumentError, "a connection secret is required" if secret.blank?
payload, event = wait_for_payload(timeout: timeout, require_remote_signer: false) do |candidate, _event|
payload, event = wait_for_payload(timeout: timeout, require_remote_signer: false, on_tick: on_tick) do |candidate, _event|
candidate["result"] == secret && candidate["error"].blank?
end
@@ -48,8 +50,8 @@ module NostrManager
payload["result"]
end
def get_public_key(timeout: 30)
result = request("get_public_key", [], timeout: timeout)
def get_public_key(timeout: 30, on_tick: nil)
result = request("get_public_key", [], timeout: timeout, on_tick: on_tick)
unless result.is_a?(String) && result.match?(HEX_KEY)
raise RequestError, "The remote signer returned an invalid public key"
@@ -58,27 +60,28 @@ module NostrManager
result
end
def sign_event(template, timeout: 90, on_auth_url: nil)
result = request("sign_event", [template.to_json], timeout: timeout, on_auth_url: on_auth_url)
def sign_event(template, timeout: 90, on_auth_url: nil, on_tick: nil)
result = request("sign_event", [template.to_json], timeout: timeout,
on_auth_url: on_auth_url, on_tick: on_tick)
parse_signed_event(result)
end
def ping(timeout: 10)
request("ping", [], timeout: timeout)
def ping(timeout: 10, on_tick: nil)
request("ping", [], timeout: timeout, on_tick: on_tick)
end
def logout(timeout: 10)
request("logout", [], timeout: timeout)
def logout(timeout: 10, on_tick: nil)
request("logout", [], timeout: timeout, on_tick: on_tick)
end
def request(method, params, timeout:, on_auth_url: nil)
def request(method, params, timeout:, on_auth_url: nil, on_tick: nil)
raise RequestError, "The remote signer is not known yet" if @remote_signer_pubkey.blank?
request_id = SecureRandom.hex(16)
event = build_event(id: request_id, method: method, params: params)
@pool.publish(event)
response, = wait_for_payload(timeout: timeout) do |candidate, _event|
response, = wait_for_payload(timeout: timeout, on_tick: on_tick) do |candidate, _event|
next false unless candidate["id"] == request_id
if candidate["result"] == "auth_url" && candidate["error"].to_s.start_with?("https://")
@@ -111,10 +114,10 @@ module NostrManager
)
end
def wait_for_payload(timeout:, require_remote_signer: true)
def wait_for_payload(timeout:, require_remote_signer: true, on_tick: nil)
match = nil
@pool.wait_for(timeout: timeout) do |result|
@pool.wait_for(timeout: timeout, tick: (on_tick ? LIVENESS_TICK : nil), on_tick: on_tick) do |result|
pair = parse_event(result.message, require_remote_signer: require_remote_signer)
next false if pair.nil?
@@ -1,6 +1,8 @@
module NostrManager
module RemoteSigner
class ListenForConnection < ApplicationService
LISTENER_POLL_GRACE = 60.seconds
def initialize(session:)
@session = session
end
@@ -10,6 +12,7 @@ module NostrManager
return if @session.nil? || !@session.pending?
timeout = [(@session.expires_at - Time.current).to_i, 1].max
on_tick = method(:listener_still_wanted?)
NostrManager::Relay::Pool.with(
relays: @session.relays,
@@ -37,17 +40,19 @@ module NostrManager
secret: @session.secret,
perms: PERMS,
metadata: client_metadata,
timeout: 30
timeout: 30,
on_tick: on_tick
)
else
client.await_nostrconnect(secret: @session.secret, timeout: timeout)
client.await_nostrconnect(secret: @session.secret, timeout: timeout, on_tick: on_tick)
end
user_pubkey = client.get_public_key
user_pubkey = client.get_public_key(on_tick: on_tick)
signed_auth = client.sign_event(
auth_template,
timeout: 90,
on_auth_url: ->(url) { @session.update!(auth_url: url) }
on_auth_url: ->(url) { @session.update!(auth_url: url) },
on_tick: on_tick
)
verify_auth_event!(signed_auth, user_pubkey)
@@ -56,6 +61,7 @@ module NostrManager
user_pubkey: user_pubkey
)
end
rescue NostrManager::Relay::Pool::CancelledError
rescue NostrManager::Relay::Pool::TimeoutError
fresh_session&.expire!
rescue UnsupportedTransportError, NostrManager::Nip44::UnsupportedTransportError => e
@@ -69,6 +75,14 @@ module NostrManager
private
def listener_still_wanted?
fresh = NostrSignerSession.find_by(id: @session.id)
return false if fresh.nil? || !fresh.pending?
last_seen = fresh.last_status_poll_at || fresh.created_at
last_seen > LISTENER_POLL_GRACE.ago
end
def fresh_session
NostrSignerSession.find_by(id: @session.id)
end
+6 -4
View File
@@ -1,7 +1,7 @@
<%= render HeaderCompactComponent.new(title: "Log in") %>
<%= render MainCompactComponent.new do %>
<h2 class="mb-2 text-xl font-bold text-gray-900">Remote signer</h2>
<h2 class="mb-2 text-xl font-bold text-gray-900">Nostr Connect</h2>
<p class="mb-6 text-gray-600">
Open your Nostr signer app on this device, or scan the QR code or copy the
@@ -16,7 +16,9 @@
show_disconnect: false
) %>
<p class="mt-8 text-sm">
<div class="mt-8 flex items-center justify-between gap-4 text-sm">
<%= link_to "Back to login", new_user_session_path, class: "text-gray-500 underline" %>
</p>
<% end %>
<%= button_to "Start over", restart_nostr_connect_path, method: :post,
form_class: "inline", class: "text-gray-500 underline" %>
</div>
<% end %>
+1
View File
@@ -9,6 +9,7 @@ Rails.application.routes.draw do
get 'users/nostr_connect', to: 'users/nostr_connects#show', as: :nostr_connect
post 'users/nostr_connect', to: 'users/nostr_connects#create'
get 'users/nostr_connect/status', to: 'users/nostr_connects#status', as: :nostr_connect_status
post 'users/nostr_connect/restart', to: 'users/nostr_connects#restart', as: :restart_nostr_connect
post 'users/nostr_continue', to: 'users/nostr_continues#create', as: :nostr_continue
get 'users/nostr_continue', to: 'users/nostr_continues#show', as: :nostr_continue_page
+9 -1
View File
@@ -21,7 +21,7 @@ RSpec.describe NostrConnectListenerJob, type: :job do
described_class.perform_now(session.id)
expect(session.reload.listener_started_at).to be_present
expect(session.reload.listener_started_at).to be_nil
end
it "skips sessions that are no longer pending" do
@@ -40,6 +40,14 @@ RSpec.describe NostrConnectListenerJob, type: :job do
described_class.perform_now(session.id)
end
it "reclaims a listener slot that has gone stale" do
session = build_session
session.update_column(:listener_started_at, (described_class::LISTENER_STALE_AFTER + 1.minute).ago)
expect(NostrManager::RemoteSigner::ListenForConnection).to receive(:call).with(session: session)
described_class.perform_now(session.id)
end
it "marks the session failed when the listener raises" do
session = build_session
allow(NostrManager::RemoteSigner::ListenForConnection).to receive(:call)
+43 -2
View File
@@ -37,8 +37,8 @@ RSpec.describe "Users::NostrConnects", type: :request do
html = Nokogiri::HTML(response.body)
expect(html.at_css("h1").text.strip).to eq("Log in")
expect(html.at_css("h2").text.strip).to eq("Remote signer")
expect(html.css("h4").map { |node| node.text.strip }).not_to include("Remote signer")
expect(html.at_css("h2").text.strip).to eq("Nostr Connect")
expect(html.css("h4").map { |node| node.text.strip }).not_to include("Nostr Connect")
open_link = html.css("a[data-action='nostr-signer-connect#openSigner']").first
expect(open_link["href"]).to start_with("nostrconnect://")
@@ -94,6 +94,47 @@ RSpec.describe "Users::NostrConnects", type: :request do
expect(JSON.parse(response.body)["status"]).to eq("expired")
expect(signer_session.reload).to be_expired
end
it "re-enqueues a listener when none is running" do
get nostr_connect_path
NostrSignerSession.last.update_column(:listener_started_at, nil)
clear_enqueued_jobs
expect do
get nostr_connect_status_path, as: :json
end.to have_enqueued_job(NostrConnectListenerJob)
end
it "does not enqueue another listener while one is active" do
get nostr_connect_path
NostrSignerSession.last.update_column(:listener_started_at, Time.current)
clear_enqueued_jobs
expect do
get nostr_connect_status_path, as: :json
end.not_to have_enqueued_job(NostrConnectListenerJob)
end
end
describe "POST /users/nostr_connect/restart" do
it "expires the current pending session and starts a new one" do
get nostr_connect_path
old_session = NostrSignerSession.last
expect do
post restart_nostr_connect_path
end.not_to change(NostrSignerSession, :count)
expect(response).to redirect_to(nostr_connect_path)
expect(old_session.reload).to be_expired
expect do
follow_redirect!
end.to change(NostrSignerSession, :count).by(1)
expect(response).to have_http_status(:ok)
expect(NostrSignerSession.last.id).not_to eq(old_session.id)
end
end
describe "POST /users/nostr_connect with a bunker URI" do
@@ -48,6 +48,59 @@ RSpec.describe NostrManager::RemoteSigner::ListenForConnection, type: :model do
)
end
describe "listener liveness" do
it "keeps listening while the browser is polling" do
session = build_session
session.update!(last_status_poll_at: Time.current)
service = described_class.new(session: session)
expect(service.send(:listener_still_wanted?)).to be(true)
end
it "keeps listening before the first status poll" do
session = build_session
session.update_columns(last_status_poll_at: nil, created_at: Time.current)
service = described_class.new(session: session)
expect(service.send(:listener_still_wanted?)).to be(true)
end
it "stops when the page never polls" do
session = build_session
session.update_columns(last_status_poll_at: nil, created_at: 2.minutes.ago)
service = described_class.new(session: session)
expect(service.send(:listener_still_wanted?)).to be(false)
end
it "stops when the browser stops polling" do
session = build_session
session.update!(last_status_poll_at: 2.minutes.ago)
service = described_class.new(session: session)
expect(service.send(:listener_still_wanted?)).to be(false)
end
it "stops when the session is no longer pending" do
session = build_session
session.update!(status: "verified")
service = described_class.new(session: session)
expect(service.send(:listener_still_wanted?)).to be(false)
end
it "returns quietly when the listener is cancelled" do
session = build_session
session.update!(last_status_poll_at: 2.minutes.ago)
pool = build_pool(session)
stub_pool(pool)
described_class.call(session: session)
expect(session.reload).to be_pending
end
end
it "verifies a client-initiated connection" do
session = build_session
pool = build_pool(session)
+5 -1
View File
@@ -64,11 +64,15 @@ class FakeSignerPool
@queue << Result.new(url: "fake", message: ["EVENT", SUBSCRIPTION_ID, event_hash])
end
def wait_for(timeout:)
def wait_for(timeout:, tick: nil, on_tick: nil)
while (result = @queue.shift)
return result if yield(result)
end
if on_tick && !on_tick.call
raise NostrManager::Relay::Pool::CancelledError, "fake listener cancelled"
end
raise NostrManager::Relay::Pool::TimeoutError, "fake pool is empty"
end