Add NIP-46 remote signer services and jobs
This commit is contained in:
27 files changed
+1404
-28
No files matched your search
+1
-1
@@ -5,7 +5,7 @@
|
||||
# SECRET_KEY_BASE=
|
||||
|
||||
# Generate these using `rails db:encryption:init`
|
||||
# (Optional, needed for LndHub integration)
|
||||
# Required for LNDHub integration and NIP-46 remote signing.
|
||||
# ENCRYPTION_PRIMARY_KEY=
|
||||
# ENCRYPTION_KEY_DERIVATION_SALT=
|
||||
|
||||
|
||||
@@ -8,10 +8,6 @@ module Settings
|
||||
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
|
||||
|
||||
@@ -57,9 +53,9 @@ module Settings
|
||||
"kind #{event.kind} not allowed"
|
||||
elsif !NostrManager::VerifySignedEvent.call(event: event)
|
||||
"invalid id or signature"
|
||||
elsif !fresh?(event)
|
||||
elsif !NostrManager::EventLimits.fresh?(event)
|
||||
"stale created_at"
|
||||
elsif !within_size_limits?(event)
|
||||
elsif !NostrManager::EventLimits.within_size_limits?(event)
|
||||
"content or tags too large"
|
||||
end
|
||||
|
||||
@@ -73,24 +69,6 @@ module Settings
|
||||
reason
|
||||
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
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
class NostrConnectListenerJob < ApplicationJob
|
||||
queue_as :nostr_connect
|
||||
|
||||
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)
|
||||
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?
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,16 @@
|
||||
class NostrSignEventJob < ApplicationJob
|
||||
queue_as :nostr_rpc
|
||||
|
||||
def perform(request_id)
|
||||
request = NostrSignRequest.find_by(id: request_id)
|
||||
return if request.nil? || !request.pending?
|
||||
|
||||
signed = NostrManager::RemoteSigner::SignEvent.call(request: request)
|
||||
request.sign!(signed)
|
||||
rescue NostrManager::RemoteSigner::Error => e
|
||||
NostrSignRequest.find_by(id: request_id)&.fail!(e.message)
|
||||
rescue StandardError => e
|
||||
Rails.logger.warn("[nostr][signer] signing job failed: #{e.class}: #{e.message}")
|
||||
NostrSignRequest.find_by(id: request_id)&.fail!("Could not sign the event. Please try again.")
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,15 @@
|
||||
class NostrSignerCleanupJob < ApplicationJob
|
||||
queue_as :default
|
||||
|
||||
def perform
|
||||
NostrSignerSession
|
||||
.where(status: %w[pending failed])
|
||||
.where("expires_at < ?", Time.current)
|
||||
.delete_all
|
||||
|
||||
NostrSignRequest
|
||||
.where(status: %w[pending signed failed])
|
||||
.where("expires_at < ?", Time.current)
|
||||
.delete_all
|
||||
end
|
||||
end
|
||||
@@ -31,6 +31,10 @@ module Settings
|
||||
message: "must be an http:// or https:// URL"
|
||||
} }
|
||||
|
||||
field :nostr_signer_relays, type: :array, default: %w[
|
||||
wss://nostr.kosmos.org
|
||||
]
|
||||
|
||||
field :nostr_zaps_relay_limit, type: :integer,
|
||||
default: 12
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
module NostrManager
|
||||
class EventLimits
|
||||
MAX_CONTENT_BYTES = 10_000
|
||||
MAX_TAGS = 100
|
||||
MAX_TAG_BYTES = 512
|
||||
CLOCK_SKEW = 5.minutes
|
||||
|
||||
def self.fresh?(event)
|
||||
now = Time.current.to_i
|
||||
created_at = event.created_at
|
||||
|
||||
created_at.is_a?(Integer) &&
|
||||
(now - CLOCK_SKEW.to_i) <= created_at &&
|
||||
created_at <= (now + CLOCK_SKEW.to_i)
|
||||
end
|
||||
|
||||
def self.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 self.valid?(event)
|
||||
fresh?(event) && within_size_limits?(event)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -13,6 +13,13 @@ module NostrManager
|
||||
Array(urls).select { |url| valid?(url) }
|
||||
end
|
||||
|
||||
# Stricter check for user-supplied relay URLs (e.g. bunker:// URIs).
|
||||
# Fails closed on DNS errors, allows ws:// only outside production, and
|
||||
# rejects any host that resolves to a private/loopback/link-local address.
|
||||
def self.strict_valid?(url)
|
||||
new(url).strict_valid?
|
||||
end
|
||||
|
||||
def initialize(url)
|
||||
@url = url.to_s
|
||||
end
|
||||
@@ -29,6 +36,22 @@ module NostrManager
|
||||
false
|
||||
end
|
||||
|
||||
def strict_valid?
|
||||
return false if @url.blank?
|
||||
|
||||
uri = URI.parse(@url)
|
||||
return false unless ALLOWED_SCHEMES.include?(uri.scheme)
|
||||
return false if uri.host.blank?
|
||||
return false if uri.scheme == "ws" && Rails.env.production?
|
||||
|
||||
addresses = Resolv.getaddresses(uri.host)
|
||||
return false if addresses.empty?
|
||||
|
||||
addresses.none? { |address| private_address?(address) }
|
||||
rescue URI::InvalidURIError, Resolv::ResolvError, Resolv::ResolvTimeout
|
||||
false
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def private_host?(host)
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
module NostrManager
|
||||
module RemoteSigner
|
||||
KIND = 24133
|
||||
AUTH_KIND = 22242
|
||||
ALLOWED_SIGN_KINDS = [0, 10002, 10063, 24242].freeze
|
||||
PERMS = %w[
|
||||
sign_event:0
|
||||
sign_event:10002
|
||||
sign_event:10063
|
||||
sign_event:22242
|
||||
sign_event:24242
|
||||
].join(",")
|
||||
|
||||
class Error < StandardError; end
|
||||
class RequestError < Error; end
|
||||
class UnsupportedTransportError < Error; end
|
||||
|
||||
class AuthRequired < Error
|
||||
attr_reader :url
|
||||
|
||||
def initialize(url)
|
||||
@url = url
|
||||
super("Authentication required: #{url}")
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,198 @@
|
||||
require "json"
|
||||
require "securerandom"
|
||||
|
||||
module NostrManager
|
||||
module RemoteSigner
|
||||
class Client
|
||||
HEX_KEY = /\A[0-9a-f]{64}\z/
|
||||
|
||||
attr_reader :remote_signer_pubkey
|
||||
|
||||
def initialize(pool:, client_private_key:, client_public_key:, remote_signer_pubkey: nil,
|
||||
logger: Rails.logger)
|
||||
@pool = pool
|
||||
@client_private_key = client_private_key
|
||||
@client_public_key = client_public_key
|
||||
@remote_signer_pubkey = remote_signer_pubkey
|
||||
@logger = logger
|
||||
@user = Nostr::User.new(
|
||||
keypair: Nostr::KeyPair.new(
|
||||
private_key: Nostr::PrivateKey.new(client_private_key),
|
||||
public_key: Nostr::PublicKey.new(client_public_key)
|
||||
)
|
||||
)
|
||||
end
|
||||
|
||||
def connect_bunker(remote_signer_pubkey:, secret:, perms:, metadata:, timeout: 30)
|
||||
@remote_signer_pubkey = remote_signer_pubkey
|
||||
result = request(
|
||||
"connect",
|
||||
[remote_signer_pubkey, secret, perms, metadata.to_json],
|
||||
timeout: timeout
|
||||
)
|
||||
|
||||
accepted = result == "ack" || (secret.present? && result == secret)
|
||||
raise RequestError, "The remote signer rejected the connection" unless accepted
|
||||
|
||||
result
|
||||
end
|
||||
|
||||
def await_nostrconnect(secret:, timeout: 120)
|
||||
raise ArgumentError, "a connection secret is required" if secret.blank?
|
||||
|
||||
payload, event = wait_for_payload(timeout: timeout, require_remote_signer: false) do |candidate, _event|
|
||||
candidate["result"] == secret && candidate["error"].blank?
|
||||
end
|
||||
|
||||
@remote_signer_pubkey = event["pubkey"]
|
||||
payload["result"]
|
||||
end
|
||||
|
||||
def get_public_key(timeout: 30)
|
||||
result = request("get_public_key", [], timeout: timeout)
|
||||
|
||||
unless result.is_a?(String) && result.match?(HEX_KEY)
|
||||
raise RequestError, "The remote signer returned an invalid public key"
|
||||
end
|
||||
|
||||
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)
|
||||
parse_signed_event(result)
|
||||
end
|
||||
|
||||
def ping(timeout: 10)
|
||||
request("ping", [], timeout: timeout)
|
||||
end
|
||||
|
||||
def request(method, params, timeout:, on_auth_url: 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|
|
||||
next false unless candidate["id"] == request_id
|
||||
|
||||
if candidate["result"] == "auth_url" && candidate["error"].to_s.start_with?("https://")
|
||||
on_auth_url&.call(candidate["error"])
|
||||
next false
|
||||
end
|
||||
|
||||
true
|
||||
end
|
||||
|
||||
raise RequestError, response["error"].to_s if response["error"].present?
|
||||
|
||||
response["result"]
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def build_event(id:, method:, params:)
|
||||
payload = { id: id, method: method, params: params }
|
||||
content = NostrManager::Nip44.encrypt(
|
||||
payload.to_json,
|
||||
@client_private_key,
|
||||
@remote_signer_pubkey
|
||||
)
|
||||
|
||||
@user.create_event(
|
||||
kind: KIND,
|
||||
tags: [["p", @remote_signer_pubkey]],
|
||||
content: content
|
||||
)
|
||||
end
|
||||
|
||||
def wait_for_payload(timeout:, require_remote_signer: true)
|
||||
match = nil
|
||||
|
||||
@pool.wait_for(timeout: timeout) do |result|
|
||||
pair = parse_event(result.message, require_remote_signer: require_remote_signer)
|
||||
next false if pair.nil?
|
||||
|
||||
payload, event = pair
|
||||
if yield(payload, event)
|
||||
match = pair
|
||||
true
|
||||
else
|
||||
false
|
||||
end
|
||||
end
|
||||
|
||||
match || raise(RequestError, "The remote signer did not respond")
|
||||
rescue NostrManager::Relay::Pool::TimeoutError
|
||||
raise RequestError, "The remote signer did not respond"
|
||||
end
|
||||
|
||||
def parse_event(message, require_remote_signer:)
|
||||
@logger.debug "[nostr][signer] relay message #{message.is_a?(Array) ? message[0] : message.class}"
|
||||
return nil unless message.is_a?(Array) && message[0] == "EVENT"
|
||||
|
||||
event = message[2]
|
||||
return nil unless event.is_a?(Hash) && event["kind"] == KIND
|
||||
return nil unless fresh?(event)
|
||||
return nil unless p_tagged?(event)
|
||||
return nil if require_remote_signer && @remote_signer_pubkey.present? &&
|
||||
event["pubkey"] != @remote_signer_pubkey
|
||||
return nil unless valid_signature?(event)
|
||||
|
||||
payload = decrypt_payload(event)
|
||||
return nil unless payload.is_a?(Hash)
|
||||
|
||||
[payload, event]
|
||||
rescue NostrManager::Nip44::UnsupportedTransportError
|
||||
raise UnsupportedTransportError,
|
||||
"This signer uses the old NIP-04 transport, which is not supported. Please update your signer."
|
||||
rescue NostrManager::Nip44::Error, JSON::ParserError => e
|
||||
@logger.info "[nostr][signer] could not decrypt relay message: #{e.class}: #{e.message}"
|
||||
nil
|
||||
end
|
||||
|
||||
def fresh?(event)
|
||||
created_at = event["created_at"]
|
||||
return false unless created_at.is_a?(Integer)
|
||||
|
||||
(Time.current.to_i - created_at).between?(-5.minutes.to_i, 15.minutes.to_i)
|
||||
end
|
||||
|
||||
def p_tagged?(event)
|
||||
Array(event["tags"]).any? do |tag|
|
||||
tag.is_a?(Array) && tag[0] == "p" && tag[1] == @client_public_key
|
||||
end
|
||||
end
|
||||
|
||||
def valid_signature?(event)
|
||||
NostrManager::VerifySignedEvent.call(event: Nostr::Event.new(**event.symbolize_keys))
|
||||
rescue StandardError
|
||||
false
|
||||
end
|
||||
|
||||
def decrypt_payload(event)
|
||||
json = NostrManager::Nip44.decrypt(
|
||||
event["content"],
|
||||
@client_private_key,
|
||||
event["pubkey"]
|
||||
)
|
||||
|
||||
JSON.parse(json)
|
||||
end
|
||||
|
||||
def parse_signed_event(result)
|
||||
data = result.is_a?(String) ? JSON.parse(result) : result
|
||||
raise RequestError, "The remote signer returned an invalid event" unless data.is_a?(Hash)
|
||||
|
||||
event = Nostr::Event.new(**data.symbolize_keys)
|
||||
raise RequestError, "The remote signer returned an invalid event" unless
|
||||
NostrManager::VerifySignedEvent.call(event: event)
|
||||
|
||||
event
|
||||
rescue JSON::ParserError, ArgumentError, TypeError
|
||||
raise RequestError, "The remote signer returned an invalid event"
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,68 @@
|
||||
require "securerandom"
|
||||
|
||||
module NostrManager
|
||||
module RemoteSigner
|
||||
class CreateSession < ApplicationService
|
||||
DEFAULT_RELAYS = %w[wss://nostr.kosmos.org].freeze
|
||||
|
||||
def initialize(flow:, user: nil, relays: nil, connection_method: "nostrconnect",
|
||||
remote_signer_pubkey: nil, secret: nil, challenge: nil)
|
||||
@flow = flow
|
||||
@user = user
|
||||
@relays = relays
|
||||
@connection_method = connection_method
|
||||
@remote_signer_pubkey = remote_signer_pubkey
|
||||
@secret = secret
|
||||
@challenge = challenge
|
||||
end
|
||||
|
||||
def call
|
||||
raise Error, "Remote signing requires encryption keys to be configured" unless
|
||||
NostrSignerSession.encryption_available?
|
||||
|
||||
keypair = Nostr::Keygen.new.generate_key_pair
|
||||
session = NostrSignerSession.new(
|
||||
user: @user,
|
||||
client_private_key: keypair.private_key.to_s,
|
||||
client_public_key: keypair.public_key.to_s,
|
||||
secret: connection_secret,
|
||||
challenge: @challenge.presence || SecureRandom.urlsafe_base64(24),
|
||||
relays: resolve_relays,
|
||||
encryption: "nip44",
|
||||
connection_method: @connection_method,
|
||||
remote_signer_pubkey: @remote_signer_pubkey,
|
||||
flow: @flow,
|
||||
status: "pending",
|
||||
expires_at: NostrSignerSession::CONNECT_TTL.from_now
|
||||
)
|
||||
|
||||
NostrSignerSession.transaction do
|
||||
if @user
|
||||
NostrSignerSession.where(user: @user, status: %w[pending verified connected]).delete_all
|
||||
end
|
||||
session.save!
|
||||
end
|
||||
|
||||
session
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def connection_secret
|
||||
return SecureRandom.urlsafe_base64(24) if @connection_method == "nostrconnect"
|
||||
|
||||
@secret.presence
|
||||
end
|
||||
|
||||
def resolve_relays
|
||||
list = Array(@relays.presence || Setting.nostr_signer_relays)
|
||||
.map { |relay| relay.to_s.strip }
|
||||
.reject(&:blank?)
|
||||
.uniq
|
||||
.select { |relay| relay.match?(%r{\Awss?://}) }
|
||||
|
||||
list.presence || DEFAULT_RELAYS
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,105 @@
|
||||
module NostrManager
|
||||
module RemoteSigner
|
||||
class ListenForConnection < ApplicationService
|
||||
def initialize(session:)
|
||||
@session = session
|
||||
end
|
||||
|
||||
def call
|
||||
@session = NostrSignerSession.find_by(id: @session.id)
|
||||
return if @session.nil? || !@session.pending?
|
||||
|
||||
timeout = [(@session.expires_at - Time.current).to_i, 1].max
|
||||
|
||||
NostrManager::Relay::Pool.with(
|
||||
relays: @session.relays,
|
||||
timeout: timeout,
|
||||
connect_timeout: 10
|
||||
) do |pool|
|
||||
pool.subscribe(
|
||||
Nostr::Filter.new(
|
||||
kinds: [KIND],
|
||||
p: [@session.client_public_key],
|
||||
since: @session.created_at.to_i - 60
|
||||
)
|
||||
)
|
||||
|
||||
client = Client.new(
|
||||
pool: pool,
|
||||
client_private_key: @session.client_private_key,
|
||||
client_public_key: @session.client_public_key,
|
||||
remote_signer_pubkey: @session.remote_signer_pubkey
|
||||
)
|
||||
|
||||
if @session.bunker?
|
||||
client.connect_bunker(
|
||||
remote_signer_pubkey: @session.remote_signer_pubkey,
|
||||
secret: @session.secret,
|
||||
perms: PERMS,
|
||||
metadata: client_metadata,
|
||||
timeout: 30
|
||||
)
|
||||
else
|
||||
client.await_nostrconnect(secret: @session.secret, timeout: timeout)
|
||||
end
|
||||
|
||||
user_pubkey = client.get_public_key
|
||||
signed_auth = client.sign_event(
|
||||
auth_template,
|
||||
timeout: 90,
|
||||
on_auth_url: ->(url) { @session.update!(auth_url: url) }
|
||||
)
|
||||
|
||||
verify_auth_event!(signed_auth, user_pubkey)
|
||||
fresh_session&.complete_connection!(
|
||||
remote_signer_pubkey: client.remote_signer_pubkey,
|
||||
user_pubkey: user_pubkey
|
||||
)
|
||||
end
|
||||
rescue NostrManager::Relay::Pool::TimeoutError
|
||||
fresh_session&.expire!
|
||||
rescue UnsupportedTransportError, NostrManager::Nip44::UnsupportedTransportError => e
|
||||
fresh_session&.fail!(e.message)
|
||||
rescue Error => e
|
||||
fresh_session&.fail!(e.message)
|
||||
rescue StandardError => e
|
||||
Rails.logger.warn("[nostr][signer] connection failed: #{e.class}: #{e.message}")
|
||||
fresh_session&.fail!("Could not connect to your signer. Please try again.")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def fresh_session
|
||||
NostrSignerSession.find_by(id: @session.id)
|
||||
end
|
||||
|
||||
def auth_template
|
||||
{
|
||||
kind: AUTH_KIND,
|
||||
created_at: Time.current.to_i,
|
||||
tags: [
|
||||
["site", Setting.accounts_domain.to_s],
|
||||
["challenge", @session.challenge]
|
||||
],
|
||||
content: ""
|
||||
}
|
||||
end
|
||||
|
||||
def client_metadata
|
||||
domain = Setting.accounts_domain.to_s
|
||||
metadata = { name: domain } if domain.present?
|
||||
metadata[:url] = "https://#{domain}" if domain.present?
|
||||
metadata || {}
|
||||
end
|
||||
|
||||
def verify_auth_event!(event, user_pubkey)
|
||||
valid = event.pubkey == user_pubkey &&
|
||||
NostrManager::VerifySignedEvent.call(event: event) &&
|
||||
NostrManager::VerifyAuth.call(event: event, challenge: @session.challenge) &&
|
||||
NostrManager::EventLimits.fresh?(event)
|
||||
|
||||
raise Error, "The remote signer returned an invalid authentication event" unless valid
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,44 @@
|
||||
module NostrManager
|
||||
module RemoteSigner
|
||||
class ParseBunkerUri < ApplicationService
|
||||
HEX_KEY = /\A[0-9a-f]{64}\z/
|
||||
|
||||
def initialize(uri:)
|
||||
@uri = uri
|
||||
end
|
||||
|
||||
def call
|
||||
parsed = URI.parse(@uri.to_s.strip)
|
||||
raise Error, "Invalid bunker URI" unless parsed.scheme == "bunker"
|
||||
|
||||
remote_signer_pubkey = parsed.host.to_s.downcase
|
||||
raise Error, "Invalid bunker URI" unless remote_signer_pubkey.match?(HEX_KEY)
|
||||
|
||||
params = URI.decode_www_form(parsed.query.to_s)
|
||||
relays = params
|
||||
.select { |key, _value| key == "relay" }
|
||||
.map { |_key, value| value.to_s.strip }
|
||||
.reject(&:blank?)
|
||||
.uniq
|
||||
|
||||
raise Error, "The bunker URI does not include a relay" if relays.empty?
|
||||
|
||||
relays.each do |relay|
|
||||
unless NostrManager::RelayUrlValidator.strict_valid?(relay)
|
||||
raise Error, "The bunker URI contains an invalid relay URL"
|
||||
end
|
||||
end
|
||||
|
||||
secret = params.find { |key, _value| key == "secret" }&.last.presence
|
||||
|
||||
{
|
||||
remote_signer_pubkey: remote_signer_pubkey,
|
||||
relays: relays,
|
||||
secret: secret
|
||||
}
|
||||
rescue URI::InvalidURIError
|
||||
raise Error, "Invalid bunker URI"
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,84 @@
|
||||
module NostrManager
|
||||
module RemoteSigner
|
||||
class SignEvent < ApplicationService
|
||||
def initialize(request:)
|
||||
@request = request
|
||||
end
|
||||
|
||||
def call
|
||||
raise Error, "Remote signing is not configured" unless NostrSignerSession.encryption_available?
|
||||
|
||||
session = NostrSignerSession
|
||||
.where(user: @request.user, status: %w[verified connected])
|
||||
.order(updated_at: :desc)
|
||||
.first
|
||||
raise Error, "No remote signer is connected" if session.nil?
|
||||
|
||||
template = @request.template.symbolize_keys
|
||||
template[:created_at] ||= Time.current.to_i
|
||||
|
||||
signed = NostrManager::Relay::Pool.with(
|
||||
relays: session.relays,
|
||||
timeout: 90,
|
||||
connect_timeout: 10
|
||||
) do |pool|
|
||||
pool.subscribe(
|
||||
Nostr::Filter.new(
|
||||
kinds: [KIND],
|
||||
p: [session.client_public_key],
|
||||
since: Time.current.to_i - 60
|
||||
)
|
||||
)
|
||||
|
||||
client = Client.new(
|
||||
pool: pool,
|
||||
client_private_key: session.client_private_key,
|
||||
client_public_key: session.client_public_key,
|
||||
remote_signer_pubkey: session.remote_signer_pubkey
|
||||
)
|
||||
|
||||
client.sign_event(template, timeout: 80)
|
||||
end
|
||||
|
||||
validate!(signed, template, session)
|
||||
session.update(last_used_at: Time.current)
|
||||
signed
|
||||
rescue NostrManager::Relay::Pool::TimeoutError
|
||||
raise Error, "Your signer did not respond. Check that it is online and try again."
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def validate!(event, template, session)
|
||||
unless NostrManager::VerifySignedEvent.call(event: event)
|
||||
raise Error, "The signer returned an invalid event"
|
||||
end
|
||||
|
||||
unless event.pubkey == session.user_pubkey
|
||||
raise Error, "The signer returned an event for a different public key"
|
||||
end
|
||||
|
||||
if @request.user.nostr_pubkey.present? && event.pubkey != @request.user.nostr_pubkey
|
||||
raise Error, "The signer does not match the public key on your account"
|
||||
end
|
||||
|
||||
unless event.kind == @request.kind &&
|
||||
event.tags == template[:tags] &&
|
||||
event.content == template[:content]
|
||||
raise Error, "The signer returned a different event than requested"
|
||||
end
|
||||
|
||||
requested_at = template[:created_at].to_i
|
||||
unless (requested_at - 300) <= event.created_at &&
|
||||
event.created_at <= (requested_at + 300)
|
||||
raise Error, "The signer returned a stale event"
|
||||
end
|
||||
|
||||
if event.kind == 24242
|
||||
verbs = Array(event.tags).select { |tag| tag[0] == "t" }.map { |tag| tag[1] }
|
||||
raise Error, "The signer returned an invalid upload authorization" unless verbs.include?("upload")
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,9 +1,22 @@
|
||||
if ENV["SENTRY_DSN"].present?
|
||||
sensitive_key = /secret|private_key|bunker_uri|token/i
|
||||
|
||||
Sentry.init do |config|
|
||||
config.dsn = ENV["SENTRY_DSN"]
|
||||
config.breadcrumbs_logger = [:active_support_logger, :http_logger]
|
||||
config.send_default_pii = false
|
||||
config.traces_sampler = lambda do |context|
|
||||
true
|
||||
end
|
||||
config.before_send = lambda do |event, _hint|
|
||||
[event.request&.data, event.extra].each do |data|
|
||||
next unless data.is_a?(Hash)
|
||||
|
||||
data.each_key do |key|
|
||||
data[key] = "[FILTERED]" if key.to_s.match?(sensitive_key)
|
||||
end
|
||||
end
|
||||
event
|
||||
end
|
||||
end
|
||||
end
|
||||
+9
-3
@@ -3,19 +3,25 @@ default: &default
|
||||
- polling_interval: 1
|
||||
batch_size: 500
|
||||
workers:
|
||||
- queues: "*"
|
||||
- queues: [default, nostr]
|
||||
threads: 3
|
||||
processes: <%= ENV.fetch("JOB_CONCURRENCY", 1) %>
|
||||
polling_interval: 0.1
|
||||
- queues: [nostr_connect, nostr_rpc]
|
||||
threads: 4
|
||||
processes: 1
|
||||
polling_interval: 0.1
|
||||
|
||||
development:
|
||||
<<: *default
|
||||
workers:
|
||||
- queues: "*"
|
||||
- queues: [default, nostr]
|
||||
threads: 1
|
||||
- queues: [nostr_connect, nostr_rpc]
|
||||
threads: 2
|
||||
|
||||
test:
|
||||
<<: *default
|
||||
|
||||
production:
|
||||
<<: *default
|
||||
<<: *default
|
||||
@@ -9,7 +9,15 @@
|
||||
# priority: 2
|
||||
# schedule: at 5am every day
|
||||
|
||||
development:
|
||||
cleanup_nostr_signer_sessions:
|
||||
class: NostrSignerCleanupJob
|
||||
schedule: every 15 minutes
|
||||
|
||||
production:
|
||||
purge_rs_authorization_codes:
|
||||
class: PurgeRsAuthorizationCodesJob
|
||||
schedule: every hour
|
||||
cleanup_nostr_signer_sessions:
|
||||
class: NostrSignerCleanupJob
|
||||
schedule: every hour
|
||||
@@ -60,6 +60,7 @@ services:
|
||||
environment:
|
||||
RAILS_ENV: development
|
||||
SOLID_QUEUE_IN_PUMA: true
|
||||
DB_POOL: 10
|
||||
LAUNCHY_DRY_RUN: true
|
||||
BROWSER: /dev/null
|
||||
ENCRYPTION_PRIMARY_KEY: YhNLBgCFMAzw5dV3gISxnGrhNDMQwRdn
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe NostrConnectListenerJob, type: :job do
|
||||
let(:user) { create :user }
|
||||
|
||||
before do
|
||||
allow(Setting).to receive(:nostr_signer_relays).and_return(["wss://relay.example.com"])
|
||||
end
|
||||
|
||||
def build_session(**overrides)
|
||||
NostrManager::RemoteSigner::CreateSession.call(
|
||||
flow: "settings",
|
||||
user: user,
|
||||
**overrides
|
||||
)
|
||||
end
|
||||
|
||||
it "runs the listener for a pending session" do
|
||||
session = build_session
|
||||
expect(NostrManager::RemoteSigner::ListenForConnection).to receive(:call).with(session: session)
|
||||
|
||||
described_class.perform_now(session.id)
|
||||
|
||||
expect(session.reload.listener_started_at).to be_present
|
||||
end
|
||||
|
||||
it "skips sessions that are no longer pending" do
|
||||
session = build_session
|
||||
session.update!(status: "verified")
|
||||
expect(NostrManager::RemoteSigner::ListenForConnection).not_to receive(:call)
|
||||
|
||||
described_class.perform_now(session.id)
|
||||
end
|
||||
|
||||
it "skips a duplicate listener that started less than a minute ago" do
|
||||
session = build_session
|
||||
session.update_column(:listener_started_at, 30.seconds.ago)
|
||||
expect(NostrManager::RemoteSigner::ListenForConnection).not_to receive(:call)
|
||||
|
||||
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)
|
||||
.and_raise(StandardError, "boom")
|
||||
|
||||
described_class.perform_now(session.id)
|
||||
|
||||
expect(session.reload).to be_failed
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,53 @@
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe NostrSignEventJob, type: :job do
|
||||
let(:user) { create :user }
|
||||
let(:template) do
|
||||
{
|
||||
"kind" => 0,
|
||||
"content" => "{}",
|
||||
"tags" => [],
|
||||
"created_at" => Time.current.to_i
|
||||
}
|
||||
end
|
||||
|
||||
def build_request
|
||||
NostrSignRequest.create!(
|
||||
user: user,
|
||||
kind: 0,
|
||||
template: template,
|
||||
status: "pending",
|
||||
expires_at: 2.minutes.from_now
|
||||
)
|
||||
end
|
||||
|
||||
it "stores the signed event" do
|
||||
request = build_request
|
||||
signed = Nostr::User.new.create_event(kind: 0, content: "{}", tags: [])
|
||||
allow(NostrManager::RemoteSigner::SignEvent).to receive(:call).with(request: request).and_return(signed)
|
||||
|
||||
described_class.perform_now(request.id)
|
||||
|
||||
expect(request.reload.status).to eq("signed")
|
||||
expect(request.signed_event["id"]).to eq(signed.id)
|
||||
end
|
||||
|
||||
it "stores a user-safe error" do
|
||||
request = build_request
|
||||
allow(NostrManager::RemoteSigner::SignEvent).to receive(:call)
|
||||
.and_raise(NostrManager::RemoteSigner::Error, "Your signer did not respond.")
|
||||
|
||||
described_class.perform_now(request.id)
|
||||
|
||||
expect(request.reload.status).to eq("failed")
|
||||
expect(request.error).to eq("Your signer did not respond.")
|
||||
end
|
||||
|
||||
it "ignores requests that already finished" do
|
||||
request = build_request
|
||||
request.update!(status: "signed", signed_event: { "id" => "abc" })
|
||||
expect(NostrManager::RemoteSigner::SignEvent).not_to receive(:call)
|
||||
|
||||
described_class.perform_now(request.id)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,34 @@
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe NostrSignerCleanupJob, type: :job do
|
||||
let(:user) { create :user }
|
||||
|
||||
it "removes expired pending sessions and requests" do
|
||||
allow(Setting).to receive(:nostr_signer_relays).and_return(["wss://relay.example.com"])
|
||||
|
||||
session = NostrManager::RemoteSigner::CreateSession.call(flow: "settings", user: user)
|
||||
session.update_columns(expires_at: 1.minute.ago)
|
||||
|
||||
request = NostrSignRequest.create!(
|
||||
user: user,
|
||||
kind: 0,
|
||||
template: { "kind" => 0, "content" => "{}", "tags" => [], "created_at" => Time.current.to_i },
|
||||
status: "pending",
|
||||
expires_at: 1.minute.ago
|
||||
)
|
||||
|
||||
described_class.perform_now
|
||||
|
||||
expect(NostrSignerSession.exists?(session.id)).to be(false)
|
||||
expect(NostrSignRequest.exists?(request.id)).to be(false)
|
||||
end
|
||||
|
||||
it "keeps active sessions" do
|
||||
allow(Setting).to receive(:nostr_signer_relays).and_return(["wss://relay.example.com"])
|
||||
session = NostrManager::RemoteSigner::CreateSession.call(flow: "settings", user: user)
|
||||
|
||||
described_class.perform_now
|
||||
|
||||
expect(NostrSignerSession.exists?(session.id)).to be(true)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,147 @@
|
||||
require "rails_helper"
|
||||
require "support/fake_signer_pool"
|
||||
|
||||
RSpec.describe NostrManager::RemoteSigner::Client, type: :model do
|
||||
let(:client_keypair) { Nostr::Keygen.new.generate_key_pair }
|
||||
let(:signer_private_key) { SecureRandom.hex(32) }
|
||||
let(:user_private_key) { SecureRandom.hex(32) }
|
||||
|
||||
let(:pool) do
|
||||
FakeSignerPool.new(
|
||||
client_public_key: client_keypair.public_key.to_s,
|
||||
signer_private_key: signer_private_key,
|
||||
user_private_key: user_private_key
|
||||
)
|
||||
end
|
||||
|
||||
let(:client) do
|
||||
described_class.new(
|
||||
pool: pool,
|
||||
client_private_key: client_keypair.private_key.to_s,
|
||||
client_public_key: client_keypair.public_key.to_s
|
||||
)
|
||||
end
|
||||
|
||||
describe "#await_nostrconnect" do
|
||||
it "accepts the matching secret and learns the remote signer pubkey" do
|
||||
pool.enqueue_connect_response("shared-secret")
|
||||
|
||||
expect(client.await_nostrconnect(secret: "shared-secret", timeout: 1)).to eq("shared-secret")
|
||||
expect(client.remote_signer_pubkey).to eq(pool.signer_pubkey)
|
||||
end
|
||||
|
||||
it "ignores responses with the wrong secret" do
|
||||
pool.enqueue_connect_response("wrong-secret")
|
||||
|
||||
expect do
|
||||
client.await_nostrconnect(secret: "expected-secret", timeout: 0.1)
|
||||
end.to raise_error(NostrManager::RemoteSigner::RequestError)
|
||||
end
|
||||
end
|
||||
|
||||
describe "#connect_bunker" do
|
||||
it "accepts an ack" do
|
||||
client = described_class.new(
|
||||
pool: pool,
|
||||
client_private_key: client_keypair.private_key.to_s,
|
||||
client_public_key: client_keypair.public_key.to_s,
|
||||
remote_signer_pubkey: pool.signer_pubkey
|
||||
)
|
||||
|
||||
result = client.connect_bunker(
|
||||
remote_signer_pubkey: pool.signer_pubkey,
|
||||
secret: nil,
|
||||
perms: NostrManager::RemoteSigner::PERMS,
|
||||
metadata: {}
|
||||
)
|
||||
|
||||
expect(result).to eq("ack")
|
||||
end
|
||||
end
|
||||
|
||||
describe "#get_public_key" do
|
||||
before do
|
||||
pool.enqueue_connect_response("shared-secret")
|
||||
client.await_nostrconnect(secret: "shared-secret", timeout: 1)
|
||||
end
|
||||
|
||||
it "returns the user pubkey" do
|
||||
expect(client.get_public_key).to eq(pool.user_pubkey)
|
||||
end
|
||||
end
|
||||
|
||||
describe "#sign_event" do
|
||||
before do
|
||||
pool.enqueue_connect_response("shared-secret")
|
||||
client.await_nostrconnect(secret: "shared-secret", timeout: 1)
|
||||
end
|
||||
|
||||
it "returns a valid signed event" do
|
||||
template = {
|
||||
kind: 0,
|
||||
content: '{"name":"jimmy"}',
|
||||
tags: [],
|
||||
created_at: Time.current.to_i
|
||||
}
|
||||
|
||||
signed = client.sign_event(template)
|
||||
|
||||
expect(signed.pubkey).to eq(pool.user_pubkey)
|
||||
expect(signed.kind).to eq(0)
|
||||
expect(signed.content).to eq(template[:content])
|
||||
expect(signed.verify_signature).to be(true)
|
||||
end
|
||||
|
||||
it "surfaces an auth_url challenge" do
|
||||
pool = FakeSignerPool.new(
|
||||
client_public_key: client_keypair.public_key.to_s,
|
||||
signer_private_key: signer_private_key,
|
||||
user_private_key: user_private_key,
|
||||
auth_url: "https://signer.example/auth"
|
||||
)
|
||||
pool.enqueue_connect_response("shared-secret")
|
||||
|
||||
client = described_class.new(
|
||||
pool: pool,
|
||||
client_private_key: client_keypair.private_key.to_s,
|
||||
client_public_key: client_keypair.public_key.to_s
|
||||
)
|
||||
client.await_nostrconnect(secret: "shared-secret", timeout: 1)
|
||||
|
||||
urls = []
|
||||
signed = client.sign_event(
|
||||
{ kind: 0, content: "{}", tags: [], created_at: Time.current.to_i },
|
||||
on_auth_url: ->(url) { urls << url }
|
||||
)
|
||||
|
||||
expect(urls).to eq(["https://signer.example/auth"])
|
||||
expect(signed.kind).to eq(0)
|
||||
end
|
||||
end
|
||||
|
||||
describe "transport errors" do
|
||||
before do
|
||||
pool.enqueue_connect_response("shared-secret")
|
||||
client.await_nostrconnect(secret: "shared-secret", timeout: 1)
|
||||
end
|
||||
|
||||
it "raises a clear error for NIP-04 payloads" do
|
||||
signer = Nostr::User.new(
|
||||
keypair: Nostr::Keygen.new.get_key_pair_from_private_key(
|
||||
Nostr::PrivateKey.new(signer_private_key)
|
||||
)
|
||||
)
|
||||
event = signer.create_event(
|
||||
kind: NostrManager::RemoteSigner::KIND,
|
||||
tags: [["p", client_keypair.public_key.to_s]],
|
||||
content: "abc?iv=def"
|
||||
)
|
||||
|
||||
pool.enqueue_raw_event(event.to_h.stringify_keys)
|
||||
|
||||
expect do
|
||||
client.get_public_key
|
||||
end.to raise_error(NostrManager::RemoteSigner::UnsupportedTransportError)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,54 @@
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe NostrManager::RemoteSigner::CreateSession, type: :model do
|
||||
let(:user) { create :user }
|
||||
|
||||
before do
|
||||
allow(Setting).to receive(:nostr_signer_relays).and_return(["wss://relay.example.com"])
|
||||
end
|
||||
|
||||
it "creates a pending nostrconnect session" do
|
||||
session = described_class.call(flow: "settings", user: user)
|
||||
|
||||
expect(session).to be_persisted
|
||||
expect(session.status).to eq("pending")
|
||||
expect(session.flow).to eq("settings")
|
||||
expect(session.connection_method).to eq("nostrconnect")
|
||||
expect(session.client_public_key).to match(/\A[0-9a-f]{64}\z/)
|
||||
expect(session.secret).to be_present
|
||||
expect(session.relays).to eq(["wss://relay.example.com"])
|
||||
expect(session.token).to be_present
|
||||
end
|
||||
|
||||
it "creates a bunker session with the supplied values" do
|
||||
remote = SecureRandom.hex(32)
|
||||
|
||||
session = described_class.call(
|
||||
flow: "settings",
|
||||
user: user,
|
||||
relays: ["wss://relay.example.com"],
|
||||
connection_method: "bunker",
|
||||
remote_signer_pubkey: remote,
|
||||
secret: nil
|
||||
)
|
||||
|
||||
expect(session).to be_bunker
|
||||
expect(session.remote_signer_pubkey).to eq(remote)
|
||||
expect(session.secret).to be_nil
|
||||
end
|
||||
|
||||
it "replaces an existing active session for the user" do
|
||||
old_session = described_class.call(flow: "settings", user: user)
|
||||
new_session = described_class.call(flow: "settings", user: user)
|
||||
|
||||
expect(NostrSignerSession.exists?(old_session.id)).to be(false)
|
||||
expect(NostrSignerSession.exists?(new_session.id)).to be(true)
|
||||
end
|
||||
|
||||
it "creates anonymous login sessions" do
|
||||
session = described_class.call(flow: "login")
|
||||
|
||||
expect(session.user).to be_nil
|
||||
expect(session.flow).to eq("login")
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,103 @@
|
||||
require "rails_helper"
|
||||
require "support/fake_signer_pool"
|
||||
|
||||
RSpec.describe NostrManager::RemoteSigner::ListenForConnection, type: :model do
|
||||
let(:user) { create :user }
|
||||
let(:signer_private_key) { SecureRandom.hex(32) }
|
||||
let(:user_private_key) { SecureRandom.hex(32) }
|
||||
let(:domain) { "accounts.example.com" }
|
||||
|
||||
before do
|
||||
allow(Setting).to receive(:nostr_signer_relays).and_return(["wss://relay.example.com"])
|
||||
allow(Setting).to receive(:accounts_domain).and_return(domain)
|
||||
end
|
||||
|
||||
def stub_pool(pool)
|
||||
allow(NostrManager::Relay::Pool).to receive(:with) do |relays:, timeout:, connect_timeout:, &block|
|
||||
block.call(pool)
|
||||
end
|
||||
end
|
||||
|
||||
def build_session(**overrides)
|
||||
NostrManager::RemoteSigner::CreateSession.call(
|
||||
flow: "settings",
|
||||
user: user,
|
||||
**overrides
|
||||
)
|
||||
end
|
||||
|
||||
def build_pool(session, **options)
|
||||
FakeSignerPool.new(
|
||||
client_public_key: session.client_public_key,
|
||||
signer_private_key: signer_private_key,
|
||||
user_private_key: user_private_key,
|
||||
**options
|
||||
)
|
||||
end
|
||||
|
||||
it "verifies a client-initiated connection" do
|
||||
session = build_session
|
||||
pool = build_pool(session)
|
||||
pool.enqueue_connect_response(session.secret)
|
||||
stub_pool(pool)
|
||||
|
||||
described_class.call(session: session)
|
||||
|
||||
session.reload
|
||||
expect(session).to be_verified
|
||||
expect(session.user_pubkey).to eq(pool.user_pubkey)
|
||||
expect(session.remote_signer_pubkey).to eq(pool.signer_pubkey)
|
||||
end
|
||||
|
||||
it "verifies a bunker connection" do
|
||||
session = build_session(connection_method: "bunker", remote_signer_pubkey: nil)
|
||||
|
||||
pool = FakeSignerPool.new(
|
||||
client_public_key: session.client_public_key,
|
||||
signer_private_key: signer_private_key,
|
||||
user_private_key: user_private_key
|
||||
)
|
||||
session.update!(connection_method: "bunker", remote_signer_pubkey: pool.signer_pubkey)
|
||||
stub_pool(pool)
|
||||
|
||||
described_class.call(session: session)
|
||||
|
||||
expect(session.reload).to be_verified
|
||||
expect(session.user_pubkey).to eq(pool.user_pubkey)
|
||||
end
|
||||
|
||||
it "records an auth_url challenge" do
|
||||
session = build_session
|
||||
pool = build_pool(session, auth_url: "https://signer.example/auth")
|
||||
pool.enqueue_connect_response(session.secret)
|
||||
stub_pool(pool)
|
||||
|
||||
described_class.call(session: session)
|
||||
|
||||
expect(session.reload.auth_url).to eq("https://signer.example/auth")
|
||||
expect(session).to be_verified
|
||||
end
|
||||
|
||||
it "fails clearly for NIP-04 signers" do
|
||||
session = build_session
|
||||
pool = build_pool(session)
|
||||
signer = Nostr::User.new(
|
||||
keypair: Nostr::Keygen.new.get_key_pair_from_private_key(
|
||||
Nostr::PrivateKey.new(signer_private_key)
|
||||
)
|
||||
)
|
||||
event = signer.create_event(
|
||||
kind: NostrManager::RemoteSigner::KIND,
|
||||
tags: [["p", session.client_public_key]],
|
||||
content: "abc?iv=def"
|
||||
)
|
||||
pool.enqueue_raw_event(event.to_h.stringify_keys)
|
||||
stub_pool(pool)
|
||||
|
||||
described_class.call(session: session)
|
||||
|
||||
session.reload
|
||||
expect(session).to be_failed
|
||||
expect(session.error).to include("NIP-04")
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,55 @@
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe NostrManager::RemoteSigner::ParseBunkerUri, type: :model do
|
||||
let(:pubkey) { SecureRandom.hex(32) }
|
||||
|
||||
before do
|
||||
allow(NostrManager::RelayUrlValidator).to receive(:strict_valid?).and_return(true)
|
||||
end
|
||||
|
||||
it "parses a bunker URI with a secret" do
|
||||
result = described_class.call(
|
||||
uri: "bunker://#{pubkey}?relay=wss%3A%2F%2Frelay.example.com&secret=abc"
|
||||
)
|
||||
|
||||
expect(result).to eq(
|
||||
remote_signer_pubkey: pubkey,
|
||||
relays: ["wss://relay.example.com"],
|
||||
secret: "abc"
|
||||
)
|
||||
end
|
||||
|
||||
it "accepts a bunker URI without a secret" do
|
||||
result = described_class.call(
|
||||
uri: "bunker://#{pubkey}?relay=wss%3A%2F%2Frelay.example.com"
|
||||
)
|
||||
|
||||
expect(result[:secret]).to be_nil
|
||||
end
|
||||
|
||||
it "rejects invalid schemes" do
|
||||
expect do
|
||||
described_class.call(uri: "https://#{pubkey}?relay=wss%3A%2F%2Frelay.example.com")
|
||||
end.to raise_error(NostrManager::RemoteSigner::Error)
|
||||
end
|
||||
|
||||
it "rejects invalid pubkeys" do
|
||||
expect do
|
||||
described_class.call(uri: "bunker://not-a-key?relay=wss%3A%2F%2Frelay.example.com")
|
||||
end.to raise_error(NostrManager::RemoteSigner::Error)
|
||||
end
|
||||
|
||||
it "rejects URIs without relays" do
|
||||
expect do
|
||||
described_class.call(uri: "bunker://#{pubkey}")
|
||||
end.to raise_error(NostrManager::RemoteSigner::Error)
|
||||
end
|
||||
|
||||
it "rejects relay URLs that fail strict validation" do
|
||||
allow(NostrManager::RelayUrlValidator).to receive(:strict_valid?).and_return(false)
|
||||
|
||||
expect do
|
||||
described_class.call(uri: "bunker://#{pubkey}?relay=ws%3A%2F%2F127.0.0.1%3A7777")
|
||||
end.to raise_error(NostrManager::RemoteSigner::Error)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,107 @@
|
||||
require "rails_helper"
|
||||
require "support/fake_signer_pool"
|
||||
|
||||
RSpec.describe NostrManager::RemoteSigner::SignEvent, type: :model do
|
||||
let(:user) { create :user }
|
||||
let(:signer_private_key) { SecureRandom.hex(32) }
|
||||
let(:user_private_key) { SecureRandom.hex(32) }
|
||||
let(:template) do
|
||||
{
|
||||
"kind" => 0,
|
||||
"content" => '{"name":"jimmy"}',
|
||||
"tags" => [],
|
||||
"created_at" => Time.current.to_i
|
||||
}
|
||||
end
|
||||
|
||||
before do
|
||||
allow(Setting).to receive(:nostr_signer_relays).and_return(["wss://relay.example.com"])
|
||||
allow_any_instance_of(User).to receive(:nostr_pubkey).and_return(nil)
|
||||
end
|
||||
|
||||
def build_session
|
||||
NostrManager::RemoteSigner::CreateSession.call(flow: "settings", user: user)
|
||||
end
|
||||
|
||||
def build_pool(session, user_key: user_private_key, sign_event_override: nil)
|
||||
FakeSignerPool.new(
|
||||
client_public_key: session.client_public_key,
|
||||
signer_private_key: signer_private_key,
|
||||
user_private_key: user_key,
|
||||
sign_event_override: sign_event_override
|
||||
)
|
||||
end
|
||||
|
||||
def stub_pool(pool)
|
||||
allow(NostrManager::Relay::Pool).to receive(:with) do |relays:, timeout:, connect_timeout:, &block|
|
||||
block.call(pool)
|
||||
end
|
||||
end
|
||||
|
||||
def build_request(template)
|
||||
NostrSignRequest.create!(
|
||||
user: user,
|
||||
kind: template["kind"],
|
||||
template: template,
|
||||
status: "pending",
|
||||
expires_at: 2.minutes.from_now
|
||||
)
|
||||
end
|
||||
|
||||
it "signs the requested template" do
|
||||
session = build_session
|
||||
pool = build_pool(session)
|
||||
session.complete_connection!(
|
||||
remote_signer_pubkey: pool.signer_pubkey,
|
||||
user_pubkey: pool.user_pubkey
|
||||
)
|
||||
stub_pool(pool)
|
||||
|
||||
signed = described_class.call(request: build_request(template))
|
||||
|
||||
expect(signed.pubkey).to eq(pool.user_pubkey)
|
||||
expect(signed.kind).to eq(0)
|
||||
expect(signed.content).to eq(template["content"])
|
||||
expect(signed.verify_signature).to be(true)
|
||||
end
|
||||
|
||||
it "rejects an event signed by a different key" do
|
||||
session = build_session
|
||||
other_user_private_key = SecureRandom.hex(32)
|
||||
pool = build_pool(session)
|
||||
session.complete_connection!(
|
||||
remote_signer_pubkey: pool.signer_pubkey,
|
||||
user_pubkey: pool.user_pubkey
|
||||
)
|
||||
other_pool = build_pool(session, user_key: other_user_private_key)
|
||||
stub_pool(other_pool)
|
||||
|
||||
expect do
|
||||
described_class.call(request: build_request(template))
|
||||
end.to raise_error(NostrManager::RemoteSigner::Error, /different public key/)
|
||||
end
|
||||
|
||||
it "rejects an event with different content" do
|
||||
session = build_session
|
||||
pool = build_pool(session)
|
||||
session.complete_connection!(
|
||||
remote_signer_pubkey: pool.signer_pubkey,
|
||||
user_pubkey: pool.user_pubkey
|
||||
)
|
||||
user_private = Nostr::PrivateKey.new(user_private_key)
|
||||
user = Nostr::User.new(keypair: Nostr::Keygen.new.get_key_pair_from_private_key(user_private))
|
||||
override = lambda do |signed_template|
|
||||
user.create_event(
|
||||
kind: signed_template["kind"],
|
||||
content: "different",
|
||||
created_at: signed_template["created_at"],
|
||||
tags: signed_template["tags"]
|
||||
)
|
||||
end
|
||||
stub_pool(build_pool(session, sign_event_override: override))
|
||||
|
||||
expect do
|
||||
described_class.call(request: build_request(template))
|
||||
end.to raise_error(NostrManager::RemoteSigner::Error, /different event/)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,131 @@
|
||||
require "json"
|
||||
|
||||
# In-memory stand-in for NostrManager::Relay::Pool that also plays the role of
|
||||
# the remote signer. It decrypts requests and returns signed NIP-46 responses
|
||||
# without any network I/O.
|
||||
class FakeSignerPool
|
||||
Result = NostrManager::Relay::Pool::Result
|
||||
SUBSCRIPTION_ID = "fake-sub"
|
||||
|
||||
attr_reader :published
|
||||
|
||||
def initialize(client_public_key:, signer_private_key:, user_private_key:,
|
||||
connect_result: "ack", auth_url: nil, sign_event_override: nil)
|
||||
@client_public_key = client_public_key
|
||||
@signer_private_key = signer_private_key
|
||||
@user_private_key = user_private_key
|
||||
@connect_result = connect_result
|
||||
@auth_url = auth_url
|
||||
@sign_event_override = sign_event_override
|
||||
@queue = []
|
||||
@published = []
|
||||
|
||||
@signer = Nostr::User.new(
|
||||
keypair: Nostr::Keygen.new.get_key_pair_from_private_key(
|
||||
Nostr::PrivateKey.new(signer_private_key)
|
||||
)
|
||||
)
|
||||
@user = Nostr::User.new(
|
||||
keypair: Nostr::Keygen.new.get_key_pair_from_private_key(
|
||||
Nostr::PrivateKey.new(user_private_key)
|
||||
)
|
||||
)
|
||||
end
|
||||
|
||||
def signer_pubkey
|
||||
@signer.keypair.public_key.to_s
|
||||
end
|
||||
|
||||
def user_pubkey
|
||||
@user.keypair.public_key.to_s
|
||||
end
|
||||
|
||||
def subscribe(_filter, **)
|
||||
SUBSCRIPTION_ID
|
||||
end
|
||||
|
||||
def unsubscribe(*)
|
||||
end
|
||||
|
||||
def publish(event)
|
||||
@published << event
|
||||
payload = JSON.parse(
|
||||
NostrManager::Nip44.decrypt(event.content, @signer_private_key, event.pubkey)
|
||||
)
|
||||
|
||||
enqueue_response(payload["id"], handle(payload))
|
||||
end
|
||||
|
||||
def enqueue_connect_response(secret)
|
||||
enqueue_response(nil, secret)
|
||||
end
|
||||
|
||||
def enqueue_raw_event(event_hash)
|
||||
@queue << Result.new(url: "fake", message: ["EVENT", SUBSCRIPTION_ID, event_hash])
|
||||
end
|
||||
|
||||
def wait_for(timeout:)
|
||||
while (result = @queue.shift)
|
||||
return result if yield(result)
|
||||
end
|
||||
|
||||
raise NostrManager::Relay::Pool::TimeoutError, "fake pool is empty"
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def handle(payload)
|
||||
case payload["method"]
|
||||
when "connect"
|
||||
@connect_result
|
||||
when "get_public_key"
|
||||
user_pubkey
|
||||
when "ping"
|
||||
"pong"
|
||||
when "sign_event"
|
||||
template = JSON.parse(payload["params"].first)
|
||||
signed =
|
||||
if @sign_event_override
|
||||
@sign_event_override.call(template)
|
||||
else
|
||||
@user.create_event(
|
||||
kind: template["kind"],
|
||||
content: template["content"],
|
||||
created_at: template["created_at"],
|
||||
tags: template["tags"]
|
||||
)
|
||||
end
|
||||
|
||||
signed.to_h.stringify_keys.to_json
|
||||
else
|
||||
raise "Unknown method: #{payload["method"]}"
|
||||
end
|
||||
end
|
||||
|
||||
def enqueue_response(request_id, result)
|
||||
if @auth_url && request_id
|
||||
@queue << build_result(request_id, "auth_url", @auth_url)
|
||||
end
|
||||
|
||||
@queue << build_result(request_id, result)
|
||||
end
|
||||
|
||||
def build_result(request_id, result, error = nil)
|
||||
payload = { id: request_id, result: result }
|
||||
payload[:error] = error if error
|
||||
|
||||
content = NostrManager::Nip44.encrypt(
|
||||
payload.to_json,
|
||||
@signer_private_key,
|
||||
@client_public_key
|
||||
)
|
||||
|
||||
event = @signer.create_event(
|
||||
kind: NostrManager::RemoteSigner::KIND,
|
||||
tags: [["p", @client_public_key]],
|
||||
content: content
|
||||
)
|
||||
|
||||
Result.new(url: "fake", message: ["EVENT", SUBSCRIPTION_ID, event.to_h.stringify_keys])
|
||||
end
|
||||
end
|
||||
Reference in new issue
Block a user