Merge pull request 'Add NIP-46 remote signer support' (#275) from feature/nostr-remote_signing into master
CI / Test (push) Successful in 1m48s
CI / Test (push) Successful in 1m48s
Reviewed-on: #275
This commit was merged in pull request #275.
This commit is contained in:
107 files changed
+7244
-161
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=
|
||||
|
||||
|
||||
@@ -46,6 +46,10 @@ gem 'kramdown'
|
||||
gem 'kramdown-parser-gfm'
|
||||
gem 'device_detector'
|
||||
|
||||
# Async I/O for relay WebSockets
|
||||
gem 'async', '~> 2.46'
|
||||
gem 'async-websocket', '~> 0.30'
|
||||
|
||||
# HTTP requests
|
||||
gem 'faraday'
|
||||
gem 'down'
|
||||
|
||||
@@ -80,6 +80,26 @@ GEM
|
||||
addressable (2.8.7)
|
||||
public_suffix (>= 2.0.2, < 7.0)
|
||||
ast (2.4.3)
|
||||
async (2.46.0)
|
||||
console (~> 1.29)
|
||||
fiber-annotation
|
||||
io-event (~> 1.21)
|
||||
async-http (0.105.0)
|
||||
async (>= 2.35.1)
|
||||
async-pool (~> 0.12)
|
||||
io-endpoint (~> 0.18)
|
||||
io-stream (~> 0.14)
|
||||
protocol-http (~> 0.72)
|
||||
protocol-http1 (~> 0.41)
|
||||
protocol-http2 (~> 0.28)
|
||||
protocol-url (~> 0.2)
|
||||
async-pool (0.12.0)
|
||||
async (>= 2.0)
|
||||
async-websocket (0.30.2)
|
||||
async-http (~> 0.76)
|
||||
protocol-http (~> 0.34)
|
||||
protocol-rack (~> 0.7)
|
||||
protocol-websocket (~> 0.17)
|
||||
aws-eventstream (1.3.2)
|
||||
aws-partitions (1.1092.0)
|
||||
aws-sdk-core (3.222.2)
|
||||
@@ -123,6 +143,10 @@ GEM
|
||||
chunky_png (1.4.0)
|
||||
concurrent-ruby (1.3.8)
|
||||
connection_pool (3.0.2)
|
||||
console (1.38.0)
|
||||
fiber-annotation
|
||||
fiber-local (~> 1.1)
|
||||
json
|
||||
crack (1.0.0)
|
||||
bigdecimal
|
||||
rexml
|
||||
@@ -189,6 +213,10 @@ GEM
|
||||
ffi (1.17.2)
|
||||
ffi (1.17.2-arm64-darwin)
|
||||
ffi (1.17.2-x86_64-linux-gnu)
|
||||
fiber-annotation (0.2.0)
|
||||
fiber-local (1.1.0)
|
||||
fiber-storage
|
||||
fiber-storage (1.0.1)
|
||||
flipper (1.3.4)
|
||||
concurrent-ruby (< 2)
|
||||
flipper-active_record (1.3.4)
|
||||
@@ -219,6 +247,11 @@ GEM
|
||||
activesupport (>= 6.0.0)
|
||||
railties (>= 6.0.0)
|
||||
io-console (0.9.2)
|
||||
io-endpoint (0.19.0)
|
||||
openssl (>= 3.3.0)
|
||||
io-event (1.22.3)
|
||||
io-stream (0.14.0)
|
||||
openssl (>= 3.3)
|
||||
irb (1.18.0)
|
||||
pp (>= 0.6.0)
|
||||
prism (>= 1.3.0)
|
||||
@@ -313,6 +346,7 @@ GEM
|
||||
faye-websocket (~> 0.11)
|
||||
json (~> 2.6)
|
||||
observer (0.1.2)
|
||||
openssl (4.0.2)
|
||||
orm_adapter (0.5.0)
|
||||
ostruct (0.6.1)
|
||||
pagy (6.5.0)
|
||||
@@ -329,6 +363,21 @@ GEM
|
||||
actionpack (>= 7.0.0)
|
||||
activesupport (>= 7.0.0)
|
||||
rack
|
||||
protocol-hpack (1.5.1)
|
||||
protocol-http (0.72.1)
|
||||
protocol-http1 (0.41.1)
|
||||
protocol-http (~> 0.68)
|
||||
protocol-http2 (0.29.2)
|
||||
protocol-hpack (~> 1.4)
|
||||
protocol-http (~> 0.62)
|
||||
protocol-rack (0.23.0)
|
||||
console (~> 1.0)
|
||||
io-stream (>= 0.10)
|
||||
protocol-http (~> 0.58)
|
||||
rack (>= 1.0)
|
||||
protocol-url (0.19.0)
|
||||
protocol-websocket (0.21.3)
|
||||
protocol-http (~> 0.2)
|
||||
psych (5.4.0)
|
||||
date
|
||||
stringio
|
||||
@@ -539,6 +588,8 @@ PLATFORMS
|
||||
|
||||
DEPENDENCIES
|
||||
aasm
|
||||
async (~> 2.46)
|
||||
async-websocket (~> 0.30)
|
||||
aws-sdk-s3
|
||||
bcrypt (~> 3.1)
|
||||
capybara
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<!-- Modal Background -->
|
||||
<div class="hidden fixed inset-0 bg-black bg-opacity-80 overflow-y-auto flex items-center justify-center"
|
||||
data-modal-target="background"
|
||||
data-action="click->modal#closeBackground"
|
||||
<% if @dismissible %>data-action="click->modal#closeBackground"<% end %>
|
||||
data-transition-enter="transition-all ease-in-out duration-100"
|
||||
data-transition-enter-from="bg-opacity-0"
|
||||
data-transition-enter-to="bg-opacity-80"
|
||||
@@ -13,9 +13,10 @@
|
||||
<!-- Modal Container -->
|
||||
<div data-modal-target="container"
|
||||
class="relative m-4 max-h-screen w-auto max-w-full
|
||||
hidden animate-scale-in fixed inset-0 overflow-y-auto flex items-center justify-center">
|
||||
hidden animate-scale-in fixed inset-0 overflow-y-auto flex items-center justify-center"
|
||||
role="dialog" aria-modal="true" tabindex="-1">
|
||||
<!-- Modal Card -->
|
||||
<div class="m-1 bg-white rounded shadow">
|
||||
<div class="m-1 bg-white rounded shadow <%= @card_class %>">
|
||||
<div class="p-8">
|
||||
<%= content %>
|
||||
<% if @show_close_button %>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
class ModalComponent < ViewComponent::Base
|
||||
def initialize(show_close_button: true)
|
||||
def initialize(show_close_button: true, dismissible: true, card_class: nil)
|
||||
@show_close_button = show_close_button
|
||||
@dismissible = dismissible
|
||||
@card_class = card_class
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,72 @@
|
||||
<div data-controller="modal nostr-login"
|
||||
data-nostr-login-site-value="<%= @site %>"
|
||||
data-nostr-login-shared-secret-value="<%= @shared_secret %>"
|
||||
data-action="keydown.esc->modal#close turbo:before-cache@document->nostr-login#closeModal"
|
||||
class="<%= "hidden" unless remote_signer_available? %>">
|
||||
<div class="relative my-6">
|
||||
<div class="absolute inset-0 flex items-center" aria-hidden="true">
|
||||
<div class="w-full border-t border-gray-200"></div>
|
||||
</div>
|
||||
<div class="relative flex justify-center">
|
||||
<span class="bg-white px-2 text-sm text-gray-500 italic">or</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="button"
|
||||
class="btn-md btn-gray w-full text-purple-600"
|
||||
data-action="click->modal#open">
|
||||
Log in with Nostr
|
||||
</button>
|
||||
|
||||
<%= render ModalComponent.new(show_close_button: false, card_class: "w-96 max-w-[85vw]") do %>
|
||||
<h2 class="mb-1 text-xl font-bold text-gray-900">Log in with Nostr</h2>
|
||||
<p class="mb-6 text-gray-600">
|
||||
This only works if your account already has a key linked.
|
||||
</p>
|
||||
|
||||
<div class="space-y-3">
|
||||
<button type="button"
|
||||
class="group flex w-full items-start gap-3 rounded-lg border border-gray-200 p-4 text-left transition-colors hover:border-purple-300 hover:bg-purple-50/50 disabled:cursor-not-allowed disabled:border-gray-200 disabled:hover:border-gray-200 disabled:hover:bg-gray-50"
|
||||
data-nostr-login-target="extensionOption"
|
||||
data-action="nostr-login#login"
|
||||
disabled>
|
||||
<span class="mt-0.5 rounded-md bg-purple-50 p-2 text-purple-600 group-disabled:bg-gray-100 group-disabled:text-gray-500">
|
||||
<%= render partial: "icons/globe", locals: { custom_class: "h-5 w-5" } %>
|
||||
</span>
|
||||
<span class="min-w-0">
|
||||
<span class="block font-bold text-gray-900 group-disabled:text-gray-500">Browser extension</span>
|
||||
<span class="mt-2 hidden block text-sm text-gray-600 group-disabled:text-gray-500"
|
||||
data-nostr-login-target="extensionDescription">
|
||||
Use a Nostr-signing browser extension, like Alby or nos2x
|
||||
</span>
|
||||
<span class="mt-2 block text-sm text-gray-600 group-disabled:text-gray-500"
|
||||
data-nostr-login-target="extensionUnavailable">
|
||||
No browser extension detected. Install a Nostr signer like Alby to use this option.
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<% if remote_signer_available? %>
|
||||
<%= link_to @connect_path,
|
||||
class: "group flex w-full items-start gap-3 rounded-lg border border-gray-200 p-4 text-left no-underline transition-colors hover:border-purple-300 hover:bg-purple-50/50 hover:no-underline" do %>
|
||||
<span class="mt-0.5 rounded-md bg-purple-50 p-2 text-purple-600">
|
||||
<%= render partial: "icons/key", locals: { custom_class: "h-5 w-5" } %>
|
||||
</span>
|
||||
<span class="min-w-0">
|
||||
<span class="block font-bold text-gray-900">Nostr Connect</span>
|
||||
<span class="mt-2 block text-sm text-gray-600">
|
||||
Use a mobile or desktop signer app, like Amber or Regent
|
||||
</span>
|
||||
</span>
|
||||
<% end %>
|
||||
<% end %>
|
||||
</div>
|
||||
|
||||
<div class="mt-6 text-center">
|
||||
<button type="button" class="text-sm text-gray-500 underline"
|
||||
data-action="click->modal#close:prevent">
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
<% end %>
|
||||
</div>
|
||||
@@ -0,0 +1,19 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class NostrLoginComponent < ViewComponent::Base
|
||||
def initialize(nostr_available:, remembered_user:, site:, shared_secret:, connect_path:)
|
||||
@nostr_available = nostr_available
|
||||
@remembered_user = remembered_user
|
||||
@site = site
|
||||
@shared_secret = shared_secret
|
||||
@connect_path = connect_path
|
||||
end
|
||||
|
||||
def render?
|
||||
@nostr_available
|
||||
end
|
||||
|
||||
def remote_signer_available?
|
||||
@nostr_available && @remembered_user.nil?
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,165 @@
|
||||
<%= content_tag(@collapsible ? :details : :section, class: section_class) do %>
|
||||
<% if @title.present? %>
|
||||
<% if @collapsible %>
|
||||
<summary class="<%= title_class %>"><%= @title %><% if show_connected_dot? %><span class="ml-2 inline-block h-2 w-2 rounded-full bg-emerald-500 align-middle" aria-hidden="true"></span><% end %></summary>
|
||||
<% else %>
|
||||
<h4 class="<%= title_class %>"><%= @title %></h4>
|
||||
<% end %>
|
||||
<% end %>
|
||||
|
||||
<% if @description.present? %>
|
||||
<p class="mt-2 <%= text_class %> text-gray-600"><%= @description %></p>
|
||||
<% end %>
|
||||
|
||||
<% if @active_session.present? %>
|
||||
<div class="mt-4 rounded-md bg-emerald-50 p-4 text-sm text-emerald-800">
|
||||
<div class="flex w-full flex-col gap-1 sm:flex-row sm:items-baseline sm:justify-between sm:gap-4">
|
||||
<p class="mb-0 font-bold">Connected via remote signer</p>
|
||||
<% if @active_session.verified_at.present? %>
|
||||
<p class="mb-0 text-xs sm:whitespace-nowrap">
|
||||
since <%= connected_at_tag(@active_session.verified_at) %>
|
||||
</p>
|
||||
<% end %>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<% if @show_disconnect && @destroy_url.present? %>
|
||||
<div class="mt-4">
|
||||
<%= button_to "Disconnect remote signer", @destroy_url, method: :delete,
|
||||
class: "btn-md btn-outline text-red-700" %>
|
||||
</div>
|
||||
<% end %>
|
||||
<% elsif @pending_session.present? %>
|
||||
<div data-controller="nostr-signer-connect"
|
||||
data-nostr-signer-connect-status-url-value="<%= @status_url %>"
|
||||
data-nostr-signer-connect-replace-url-value="<%= @replace_url %>"
|
||||
data-nostr-signer-connect-destroy-url-value="<%= @destroy_url %>"
|
||||
data-nostr-signer-connect-section-url-value="<%= @section_url %>">
|
||||
<% unless @pending_session.bunker? %>
|
||||
<div data-nostr-signer-connect-target="details">
|
||||
<div class="<%= @title.present? ? "mt-4" : "" %> hidden justify-center sm:flex"
|
||||
data-nostr-signer-connect-target="qr">
|
||||
<div class="<%= qr_wrapper_class %> rounded-lg bg-white p-3">
|
||||
<%= qr_svg %>
|
||||
</div>
|
||||
</div>
|
||||
<p class="mt-2 sm:hidden" data-nostr-signer-connect-target="qrToggle">
|
||||
<button type="button" class="text-sm text-gray-600 underline"
|
||||
data-action="nostr-signer-connect#showQr">
|
||||
Show QR code
|
||||
</button>
|
||||
</p>
|
||||
|
||||
<p data-controller="clipboard" class="mt-3 flex gap-1">
|
||||
<input type="text" readonly value="<%= @pending_session.nostrconnect_uri %>"
|
||||
class="grow <%= input_class %>" data-clipboard-target="source" />
|
||||
<button type="button" class="btn-md btn-icon btn-outline shrink-0"
|
||||
data-clipboard-target="trigger" data-action="clipboard#copy"
|
||||
title="Copy to clipboard">
|
||||
<span class="content-initial">
|
||||
<%= render partial: "icons/copy", locals: { custom_class: "text-blue-600 h-4 w-4 inline" } %>
|
||||
</span>
|
||||
<span class="content-active hidden">
|
||||
<%= render partial: "icons/check", locals: { custom_class: "text-blue-600 h-4 w-4 inline" } %>
|
||||
</span>
|
||||
</button>
|
||||
</p>
|
||||
|
||||
<p class="mt-2 sm:hidden">
|
||||
<a href="<%= @pending_session.nostrconnect_uri %>"
|
||||
class="btn-md btn-blue w-full text-center"
|
||||
data-action="nostr-signer-connect#openSigner">
|
||||
Open with signer app
|
||||
</a>
|
||||
</p>
|
||||
<p class="mt-2 hidden sm:block">
|
||||
<a href="<%= @pending_session.nostrconnect_uri %>"
|
||||
class="<%= action_button_class %>"
|
||||
data-action="nostr-signer-connect#openSigner">
|
||||
Open with signer app
|
||||
</a>
|
||||
</p>
|
||||
<p class="mt-2 hidden <%= text_class %> text-amber-800"
|
||||
data-nostr-signer-connect-target="signerHint">
|
||||
Didn’t open your signer app? Scan the QR code or copy the connection link.
|
||||
</p>
|
||||
</div>
|
||||
<% end %>
|
||||
|
||||
<p class="mt-4 <%= text_class %> text-gray-600" data-nostr-signer-connect-target="status"></p>
|
||||
|
||||
<p class="mt-2 hidden <%= text_class %>" data-nostr-signer-connect-target="authWrapper">
|
||||
<a href="#" target="_blank" rel="noopener noreferrer"
|
||||
class="text-blue-700 underline"
|
||||
data-nostr-signer-connect-target="authLink">
|
||||
Authenticate with your signer
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<p class="mt-2 hidden <%= text_class %> text-red-700" data-nostr-signer-connect-target="error"></p>
|
||||
|
||||
<% if @replace_url.present? %>
|
||||
<div class="mt-4 hidden rounded-md border border-amber-300 bg-amber-50 p-4"
|
||||
data-nostr-signer-connect-target="replace">
|
||||
<p class="mb-2 font-bold text-amber-900">
|
||||
This account already has a Nostr public key
|
||||
</p>
|
||||
<p class="mb-1 <%= text_class %> text-amber-900">Existing key:</p>
|
||||
<p class="mb-3 break-all font-mono text-sm text-amber-900"
|
||||
data-nostr-signer-connect-target="replaceExisting"></p>
|
||||
<p class="mb-1 <%= text_class %> text-amber-900">Your signer's key:</p>
|
||||
<p class="mb-3 break-all font-mono text-sm text-amber-900"
|
||||
data-nostr-signer-connect-target="replaceSigner"></p>
|
||||
<p class="mb-3 <%= text_class %> text-amber-900">
|
||||
Connecting this signer would replace the existing key. Your signer
|
||||
must use the account key to sign.
|
||||
</p>
|
||||
<button type="button" class="<%= action_button_class %>"
|
||||
data-action="nostr-signer-connect#replace">
|
||||
Replace existing key
|
||||
</button>
|
||||
<button type="button" class="mt-2 <%= cancel_button_class %>"
|
||||
data-action="nostr-signer-connect#cancel">
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
<% end %>
|
||||
|
||||
<div class="mt-4 hidden" data-nostr-signer-connect-target="retry">
|
||||
<%= button_to "Try again", @create_url, method: :post, class: action_button_class,
|
||||
form: button_form_options %>
|
||||
</div>
|
||||
|
||||
<details class="mt-4">
|
||||
<summary class="cursor-pointer text-gray-600">Prefer a bunker:// URI?</summary>
|
||||
<%= form_with url: @create_url, method: :post, class: "mt-3" do %>
|
||||
<p>
|
||||
<%= text_field_tag :bunker_uri, nil,
|
||||
placeholder: "bunker://…",
|
||||
class: "w-full",
|
||||
autocomplete: "off" %>
|
||||
</p>
|
||||
<p class="mt-2">
|
||||
<%= submit_tag "Connect bunker", class: action_button_class %>
|
||||
</p>
|
||||
<% end %>
|
||||
</details>
|
||||
|
||||
<% if @show_disconnect && @destroy_url.present? %>
|
||||
<div class="mt-4">
|
||||
<%= button_to "Cancel", @destroy_url, method: :delete,
|
||||
class: cancel_button_class, form: button_form_options %>
|
||||
</div>
|
||||
<% end %>
|
||||
</div>
|
||||
<% else %>
|
||||
<p class="mt-3">
|
||||
Use a mobile or desktop signer app, like Amber or Regent
|
||||
</p>
|
||||
|
||||
<div class="mt-4">
|
||||
<%= button_to "Connect a signer app", @create_url, method: :post,
|
||||
class: "btn-md btn-gray w-full sm:w-auto" %>
|
||||
</div>
|
||||
<% end %>
|
||||
<% end %>
|
||||
@@ -0,0 +1,84 @@
|
||||
require "rqrcode"
|
||||
|
||||
class NostrSignerConnectComponent < ViewComponent::Base
|
||||
def initialize(pending_session: nil, active_session: nil, create_url:, destroy_url: nil,
|
||||
status_url: nil, replace_url: nil, title: "Nostr Connect", description: nil,
|
||||
show_disconnect: true, modal: false, collapsible: false, flush: false,
|
||||
section_url: nil)
|
||||
@pending_session = pending_session
|
||||
@active_session = active_session
|
||||
@create_url = create_url
|
||||
@destroy_url = destroy_url
|
||||
@status_url = status_url
|
||||
@replace_url = replace_url
|
||||
@title = title
|
||||
@description = description
|
||||
@show_disconnect = show_disconnect
|
||||
@modal = modal
|
||||
@collapsible = collapsible
|
||||
@flush = flush
|
||||
@section_url = section_url
|
||||
end
|
||||
|
||||
def section_class
|
||||
return "" if @modal || @flush || @title.blank?
|
||||
|
||||
"mt-8"
|
||||
end
|
||||
|
||||
def title_class
|
||||
return "mb-1 text-xl font-bold" if @modal
|
||||
return "cursor-pointer font-bold leading-6" if @collapsible
|
||||
|
||||
"mb-0"
|
||||
end
|
||||
|
||||
def show_connected_dot?
|
||||
@collapsible && @active_session.present?
|
||||
end
|
||||
|
||||
def text_class
|
||||
"text-base"
|
||||
end
|
||||
|
||||
def input_class
|
||||
"text-sm font-mono"
|
||||
end
|
||||
|
||||
def qr_wrapper_class
|
||||
@modal ? "w-[264px] max-w-full" : "w-[232px] max-w-full"
|
||||
end
|
||||
|
||||
def action_button_class
|
||||
@modal ? "btn-md btn-gray w-full" : "btn-md btn-gray"
|
||||
end
|
||||
|
||||
def cancel_button_class
|
||||
@modal ? "btn-md btn-outline text-gray-700 w-full" : "btn-md btn-outline text-gray-700"
|
||||
end
|
||||
|
||||
def button_form_options
|
||||
@modal ? { class: "w-full" } : {}
|
||||
end
|
||||
|
||||
def qr_svg
|
||||
RQRCode::QRCode.new(@pending_session.nostrconnect_uri).as_svg(
|
||||
color: "000",
|
||||
shape_rendering: "crispEdges",
|
||||
module_size: 4,
|
||||
viewbox: true,
|
||||
standalone: true,
|
||||
use_path: true,
|
||||
svg_attributes: { class: "block h-auto w-full" }
|
||||
).html_safe
|
||||
end
|
||||
|
||||
def connected_at_tag(time)
|
||||
fallback = time.utc.strftime("%-d %b %Y, %H:%M")
|
||||
|
||||
tag.time fallback,
|
||||
datetime: time.utc.iso8601,
|
||||
title: fallback,
|
||||
data: { local_time: "display" }
|
||||
end
|
||||
end
|
||||
@@ -1,5 +1,10 @@
|
||||
<div class="w-[72vw] md:w-[500px]">
|
||||
<h3 class="mb-6">Edit media servers</h3>
|
||||
<% if @media_list_event.blank? %>
|
||||
<p class="mb-4 text-gray-500">
|
||||
These are the servers that host the larger files you share — images, videos and other attachments that don't fit in a regular event. Here's a recommended server to start with:
|
||||
</p>
|
||||
<% end %>
|
||||
<%= form_with url: "#", local: true,
|
||||
html: { data: {
|
||||
controller: "url-list-editor",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<div class="w-[72vw] md:w-[640px] lg:w-[760px]"
|
||||
<div class="w-[72vw] md:w-[600px]"
|
||||
data-controller="nostr-image-upload"
|
||||
data-nostr-image-upload-store-url-value="<%= nostr_profile_images_settings_path %>"
|
||||
data-nostr-image-upload-picture-max-bytes-value="<%= BlossomManagerService.max_upload_bytes("picture") %>"
|
||||
@@ -18,11 +18,11 @@
|
||||
:'nostr-profile-editor-flush-url-value' => nostr_media_settings_path
|
||||
}
|
||||
}) do |f| %>
|
||||
<header class="absolute z-10 h-36 sm:h-44 inset-x-1 top-1 rounded-t
|
||||
<header class="-mx-8 -mt-8 relative aspect-[11/4] sm:aspect-[4/1] rounded-t
|
||||
bg-cover bg-center bg-gray-50"
|
||||
style="<%= "background-image: url('#{banner_url}');" if banner_url %>"
|
||||
data-nostr-profile-editor-target="bannerPreview">
|
||||
<div class="inline-block z-20 size-28 sm:size-32 ml-4 mt-16 sm:mt-20">
|
||||
<div class="absolute -bottom-14 left-4 z-20 size-28 sm:-bottom-16 sm:size-32">
|
||||
<%= tag.img src: picture_url.presence,
|
||||
class: "inline-block size-28 sm:size-32 rounded-full border-2 border-white #{'hidden' unless picture_url}",
|
||||
data: { :'nostr-profile-editor-target' => "picturePreview" } %>
|
||||
@@ -48,11 +48,31 @@
|
||||
</div>
|
||||
<% end %>
|
||||
</header>
|
||||
<main class="mt-44 sm:mt-52">
|
||||
<main class="pt-20 sm:pt-24">
|
||||
<div class="grid grid-cols-1 gap-y-6 md:grid-cols-2 md:gap-x-8">
|
||||
<div>
|
||||
<%= render FormElements::FieldsetComponent.new(tag: "div", title: "Display name") do %>
|
||||
<%= f.text_field :display_name, value: @display_name, class: "w-full" %>
|
||||
<% if @display_name_added %>
|
||||
<div class="w-full flex flex-col" data-controller="field-suggestion"
|
||||
data-field-suggestion-added-value-value="<%= @user.display_name %>">
|
||||
<div class="relative">
|
||||
<%= f.text_field :display_name, value: @display_name,
|
||||
data: {
|
||||
:'field-suggestion-target' => "input",
|
||||
action: "input->field-suggestion#checkAdded"
|
||||
},
|
||||
class: "w-full pr-16 border-emerald-500 ring-1 ring-emerald-500 focus:border-emerald-500 focus:ring-emerald-500 bg-emerald-50/20" %>
|
||||
<span class="absolute inset-y-0 right-2.5 flex items-center pointer-events-none"
|
||||
data-field-suggestion-target="badge">
|
||||
<span class="rounded-full bg-emerald-100 px-2 py-0.5 text-xs font-semibold text-emerald-800">
|
||||
added
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<% else %>
|
||||
<%= f.text_field :display_name, value: @display_name, class: "w-full" %>
|
||||
<% end %>
|
||||
<% end %>
|
||||
<%= render FormElements::FieldsetComponent.new(tag: "div", title: "About") do %>
|
||||
<%= f.text_area :about, value: @about, rows: 3, class: "w-full" %>
|
||||
|
||||
@@ -17,9 +17,11 @@ module Settings
|
||||
@profile = JSON.parse(profile_event["content"]) rescue {}
|
||||
end
|
||||
|
||||
@display_name = NostrManagerService::DISPLAY_NAME_KEYS
|
||||
@profile_display_name = NostrManagerService::DISPLAY_NAME_KEYS
|
||||
.map { |key| @profile[key] }
|
||||
.find(&:present?) || @user.display_name
|
||||
.find(&:present?)
|
||||
@display_name = @profile_display_name || @user.display_name
|
||||
@display_name_added = @profile_display_name.blank? && @user.display_name.present?
|
||||
|
||||
@about = @profile["about"] if @profile["about"].is_a?(String)
|
||||
@website = @profile["website"] if @profile["website"].is_a?(String)
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
<div class="w-[72vw] md:w-[500px]">
|
||||
<h3 class="mb-6">Edit relays</h3>
|
||||
<% if @nip65_event.blank? %>
|
||||
<p class="mb-4 text-gray-500">
|
||||
These are the servers that your Nostr apps will publish to. Here's a recommended list to start with:
|
||||
</p>
|
||||
<% end %>
|
||||
<%= form_with url: "#", local: true,
|
||||
html: { data: {
|
||||
controller: "url-list-editor",
|
||||
|
||||
@@ -14,7 +14,7 @@ module Settings
|
||||
normalized_site_relay = NostrManagerService.normalize_url(site_relay)
|
||||
|
||||
if @nip65_event.blank?
|
||||
relays = Setting.nostr_discovery_relays.map { |url| { url: url, marker: nil, added: false } }
|
||||
relays = Setting.nostr_discovery_relays.map { |url| { url: url, marker: nil, added: true } }
|
||||
if site_relay.present?
|
||||
relays.reject! { |r| NostrManagerService.normalize_url(r[:url]) == normalized_site_relay }
|
||||
relays.unshift({ url: site_relay, marker: nil, added: true })
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
class ApplicationController < ActionController::Base
|
||||
include NostrRememberable
|
||||
|
||||
rescue_from DeviseLdapAuthenticatable::LdapException do |exception|
|
||||
render :text => exception, :status => 500
|
||||
end
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
module NostrRememberable
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
REMEMBER_COOKIE = :nostr_remember
|
||||
REMEMBER_TTL = 1.year
|
||||
|
||||
def remember_nostr_account(user, session_record: nil)
|
||||
return if user.nil?
|
||||
|
||||
session_record ||= NostrSignerSession
|
||||
.where(user: user, status: "connected")
|
||||
.order(updated_at: :desc)
|
||||
.first
|
||||
|
||||
return unless session_record&.connected? && session_record.user_id == user.id
|
||||
return unless NostrSignerSession.encryption_available?
|
||||
|
||||
token = session_record.remember!
|
||||
|
||||
cookies.signed[REMEMBER_COOKIE] = {
|
||||
value: token,
|
||||
expires: REMEMBER_TTL.from_now,
|
||||
httponly: true,
|
||||
secure: Rails.env.production?,
|
||||
same_site: :lax
|
||||
}
|
||||
end
|
||||
|
||||
def resolve_remembered_nostr_account
|
||||
return nil unless Setting.nostr_enabled? && NostrSignerSession.encryption_available?
|
||||
|
||||
raw = cookies.signed[REMEMBER_COOKIE]
|
||||
return nil if raw.blank?
|
||||
|
||||
record = NostrSignerSession.find_by_remember_token(raw)
|
||||
|
||||
unless record&.continuable?
|
||||
forget_nostr_account
|
||||
return nil
|
||||
end
|
||||
|
||||
record
|
||||
end
|
||||
|
||||
def remembered_nostr_session_any_status
|
||||
raw = cookies.signed[REMEMBER_COOKIE]
|
||||
return nil if raw.blank?
|
||||
|
||||
NostrSignerSession.find_by_remember_token(raw)
|
||||
end
|
||||
|
||||
def forget_nostr_account
|
||||
cookies.delete(REMEMBER_COOKIE)
|
||||
session.delete(:nostr_reauth_token)
|
||||
end
|
||||
end
|
||||
@@ -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,118 @@
|
||||
module Settings
|
||||
class NostrSignaturesController < ApplicationController
|
||||
before_action :authenticate_user!
|
||||
|
||||
MAX_BODY_BYTES = 100_000
|
||||
RATE_LIMIT = 20
|
||||
RATE_WINDOW = 5.minutes
|
||||
|
||||
def create
|
||||
return render_error("Remote signing is not configured", :service_unavailable) unless
|
||||
NostrSignerSession.encryption_available?
|
||||
return render_error("This account has no Nostr public key", :forbidden) if
|
||||
current_user.nostr_pubkey.blank?
|
||||
return render_error("No remote signer is connected", :forbidden) if active_signer_session.nil?
|
||||
return render_error("Too many signing requests. Please try again later.", :too_many_requests) if
|
||||
rate_limited?
|
||||
return render_error("Request is too large", :payload_too_large) if
|
||||
request.content_length.to_i > MAX_BODY_BYTES
|
||||
|
||||
template = build_template
|
||||
sign_request = current_user.nostr_sign_requests.create!(
|
||||
kind: template["kind"],
|
||||
template: template,
|
||||
purpose: "sign",
|
||||
status: "pending",
|
||||
expires_at: NostrSignRequest::TTL.from_now
|
||||
)
|
||||
|
||||
NostrSignEventJob.perform_later(sign_request.id)
|
||||
|
||||
render json: { token: sign_request.token, status: "pending" }
|
||||
rescue ActionController::ParameterMissing, ArgumentError, TypeError, JSON::ParserError => e
|
||||
render_error("Invalid event: #{e.message}", :unprocessable_entity)
|
||||
end
|
||||
|
||||
def show
|
||||
sign_request = current_user.nostr_sign_requests.sign.find_by(token: params[:token])
|
||||
return render_error("Unknown signing request", :not_found) if sign_request.nil?
|
||||
|
||||
case sign_request.status
|
||||
when "signed"
|
||||
render json: { status: "signed", signed_event: sign_request.signed_event }
|
||||
when "failed"
|
||||
render json: { status: "failed", error: sign_request.error }, status: :unprocessable_entity
|
||||
when "expired"
|
||||
render json: { status: "expired", error: sign_request.error }, status: :gone
|
||||
else
|
||||
if sign_request.expires_at < Time.current
|
||||
sign_request.expire!
|
||||
render json: { status: "expired", error: sign_request.error }, status: :gone
|
||||
else
|
||||
render json: { status: "pending" }
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def active_signer_session
|
||||
@active_signer_session ||= NostrSignerSession
|
||||
.where(user: current_user, status: %w[verified connected])
|
||||
.order(updated_at: :desc)
|
||||
.first
|
||||
end
|
||||
|
||||
def build_template
|
||||
raw = params.require(:event)
|
||||
raw = raw.to_unsafe_h if raw.respond_to?(:to_unsafe_h)
|
||||
raw = raw.symbolize_keys
|
||||
|
||||
kind = Integer(raw[:kind])
|
||||
content = raw[:content].to_s
|
||||
created_at = Integer(raw[:created_at] || Time.current.to_i)
|
||||
tags = Array(raw[:tags]).map { |tag| Array(tag).map(&:to_s) }
|
||||
|
||||
allowed_kinds = NostrManager::RemoteSigner::ALLOWED_SIGN_KINDS
|
||||
raise ArgumentError, "kind #{kind} is not allowed" unless allowed_kinds.include?(kind)
|
||||
|
||||
event = Nostr::Event.new(
|
||||
pubkey: current_user.nostr_pubkey.presence || "0" * 64,
|
||||
kind: kind,
|
||||
content: content,
|
||||
created_at: created_at,
|
||||
tags: tags
|
||||
)
|
||||
|
||||
raise ArgumentError, "stale created_at" unless NostrManager::EventLimits.fresh?(event)
|
||||
unless NostrManager::EventLimits.within_size_limits?(event)
|
||||
raise ArgumentError, "content or tags too large"
|
||||
end
|
||||
|
||||
if kind == 24242
|
||||
verbs = tags.select { |tag| tag[0] == "t" }.map { |tag| tag[1] }
|
||||
raise ArgumentError, "invalid upload authorization" unless verbs.include?("upload")
|
||||
end
|
||||
|
||||
{
|
||||
"kind" => kind,
|
||||
"content" => content,
|
||||
"created_at" => created_at,
|
||||
"tags" => tags
|
||||
}
|
||||
end
|
||||
|
||||
def rate_limited?
|
||||
key = "nostr_sign:#{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 render_error(message, status)
|
||||
render json: { error: message }, status: status
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,202 @@
|
||||
module Settings
|
||||
class NostrSignersController < ApplicationController
|
||||
before_action :authenticate_user!
|
||||
|
||||
RATE_LIMIT = 8
|
||||
RATE_WINDOW = 10.minutes
|
||||
STATUS_RATE_LIMIT = 240
|
||||
STATUS_RATE_WINDOW = 5.minutes
|
||||
MAX_PENDING = 20
|
||||
|
||||
def create
|
||||
return render_error("Nostr is not enabled", :forbidden) unless Setting.nostr_enabled?
|
||||
return render_error("Remote signing is not configured", :service_unavailable) unless
|
||||
NostrSignerSession.encryption_available?
|
||||
return render_error("Too many connection attempts. Please try again later.", :too_many_requests) if
|
||||
rate_limited?
|
||||
return render_error("Too many pending connections. Please try again later.", :too_many_requests) if
|
||||
pending_connections_exceeded?
|
||||
|
||||
signer_session =
|
||||
if params[:bunker_uri].present?
|
||||
parsed = NostrManager::RemoteSigner::ParseBunkerUri.call(uri: params[:bunker_uri])
|
||||
NostrManager::RemoteSigner::CreateSession.call(
|
||||
flow: "settings",
|
||||
user: current_user,
|
||||
relays: parsed[:relays],
|
||||
connection_method: "bunker",
|
||||
remote_signer_pubkey: parsed[:remote_signer_pubkey],
|
||||
secret: parsed[:secret]
|
||||
)
|
||||
else
|
||||
NostrManager::RemoteSigner::CreateSession.call(flow: "settings", user: current_user)
|
||||
end
|
||||
|
||||
session[:nostr_signer_token] = signer_session.token
|
||||
NostrConnectListenerJob.perform_later(signer_session.id)
|
||||
|
||||
respond_to do |format|
|
||||
format.html { redirect_to setting_path(:nostr) }
|
||||
format.turbo_stream do
|
||||
@pending_signer_session = signer_session
|
||||
render turbo_stream: turbo_stream.replace("nostr-signer-section", partial: "settings/nostr_signer")
|
||||
end
|
||||
format.json do
|
||||
render json: {
|
||||
token: signer_session.token,
|
||||
uri: signer_session.nostrconnect_uri,
|
||||
expires_at: signer_session.expires_at
|
||||
}
|
||||
end
|
||||
end
|
||||
rescue NostrManager::RemoteSigner::Error => e
|
||||
render_error(e.message, :unprocessable_entity)
|
||||
end
|
||||
|
||||
def status
|
||||
return render_error("Too many status requests. Please try again later.", :too_many_requests) if
|
||||
status_rate_limited?
|
||||
|
||||
signer_session = NostrSignerSession.find_by_token(params[:token])
|
||||
return render_error("Unknown connection", :not_found) if signer_session.nil? ||
|
||||
signer_session.user_id != current_user.id
|
||||
|
||||
signer_session.update_column(:last_status_poll_at, Time.current)
|
||||
|
||||
if signer_session.status == "pending" && signer_session.expires_at < Time.current
|
||||
signer_session.expire!
|
||||
return render json: { status: "expired", error: signer_session.error }
|
||||
end
|
||||
|
||||
if signer_session.verified? || signer_session.connected?
|
||||
connect_account!(signer_session)
|
||||
elsif signer_session.disconnecting?
|
||||
render json: { status: "disconnected", error: "Remote signer disconnected." }
|
||||
elsif signer_session.failed? || signer_session.expired?
|
||||
render json: { status: signer_session.status, error: signer_session.error }
|
||||
else
|
||||
render json: { status: "pending", auth_url: signer_session.auth_url }
|
||||
end
|
||||
end
|
||||
|
||||
def section
|
||||
respond_to do |format|
|
||||
format.turbo_stream do
|
||||
render turbo_stream: turbo_stream.replace("nostr-signer-section", partial: "settings/nostr_signer")
|
||||
end
|
||||
format.html { redirect_to setting_path(:nostr) }
|
||||
end
|
||||
end
|
||||
|
||||
def replace
|
||||
signer_session = NostrSignerSession.find_by_token(params[:token])
|
||||
return render_error("Unknown connection", :not_found) if signer_session.nil? ||
|
||||
signer_session.user_id != current_user.id
|
||||
|
||||
unless signer_session.verified? || signer_session.connected?
|
||||
return render_error("This connection can no longer be confirmed. Please try again.",
|
||||
:unprocessable_entity)
|
||||
end
|
||||
|
||||
connect_account!(signer_session, replace: true)
|
||||
end
|
||||
|
||||
def destroy
|
||||
NostrManager::RemoteSigner::DisconnectSessions.call(
|
||||
sessions: current_user.nostr_signer_sessions.where(status: %w[pending verified connected])
|
||||
)
|
||||
|
||||
forget_nostr_account
|
||||
session.delete(:nostr_signer_token)
|
||||
|
||||
respond_to do |format|
|
||||
format.html { redirect_to setting_path(:nostr) }
|
||||
format.json { render json: { ok: true } }
|
||||
format.turbo_stream do
|
||||
if current_user.nostr_pubkey.present?
|
||||
render turbo_stream: turbo_stream.replace("nostr-signer-section", partial: "settings/nostr_signer")
|
||||
else
|
||||
redirect_to setting_path(:nostr)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def connect_account!(signer_session, replace: false)
|
||||
conflict = nil
|
||||
|
||||
signer_session.with_lock do
|
||||
next if signer_session.consumed_at.present?
|
||||
|
||||
other_user = LdapManager::FetchUserByNostrKey.call(pubkey: signer_session.user_pubkey)
|
||||
|
||||
if other_user.present? && other_user != current_user
|
||||
conflict = :other_account
|
||||
else
|
||||
current_pubkey = current_user.nostr_pubkey
|
||||
|
||||
if !replace && current_pubkey.present? && current_pubkey != signer_session.user_pubkey
|
||||
conflict = :existing_key
|
||||
else
|
||||
unless current_pubkey.present? && current_pubkey == signer_session.user_pubkey
|
||||
LdapManager::SetNostrKey.call(user: current_user, pubkey: signer_session.user_pubkey)
|
||||
end
|
||||
|
||||
signer_session.update!(status: "connected", consumed_at: Time.current)
|
||||
remember_nostr_account(current_user, session_record: signer_session)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
case conflict
|
||||
when :other_account
|
||||
render_error("Public key already in use for a different account", :unprocessable_entity)
|
||||
when :existing_key
|
||||
render json: {
|
||||
status: "replace_required",
|
||||
existing_npub: current_user.nostr_pubkey_bech32,
|
||||
signer_npub: signer_session.user_pubkey_bech32
|
||||
}
|
||||
else
|
||||
session.delete(:nostr_signer_token)
|
||||
render json: { status: "connected", npub: signer_session.user_pubkey_bech32 }
|
||||
end
|
||||
end
|
||||
|
||||
def rate_limited?
|
||||
key = "nostr_signer:#{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 status_rate_limited?
|
||||
key = "nostr_signer_status:#{current_user.id}"
|
||||
count = Rails.cache.read(key).to_i
|
||||
return true if count >= STATUS_RATE_LIMIT
|
||||
|
||||
Rails.cache.write(key, count + 1, expires_in: STATUS_RATE_WINDOW)
|
||||
false
|
||||
end
|
||||
|
||||
def pending_connections_exceeded?
|
||||
NostrSignerSession
|
||||
.where(status: "pending")
|
||||
.where("expires_at > ?", Time.current)
|
||||
.count >= MAX_PENDING
|
||||
end
|
||||
|
||||
def render_error(message, status)
|
||||
respond_to do |format|
|
||||
format.html do
|
||||
redirect_to setting_path(:nostr), flash: { alert: message }
|
||||
end
|
||||
format.json { render json: { error: message }, status: status }
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -23,6 +23,13 @@ class SettingsController < ApplicationController
|
||||
@user.preferences[:lightning_notify_zap_received] != "disabled"
|
||||
when "nostr"
|
||||
session[:shared_secret] ||= SecureRandom.base64(12)
|
||||
@pending_signer_session = NostrSignerSession.find_by_token(session[:nostr_signer_token])
|
||||
|
||||
if @pending_signer_session &&
|
||||
(@pending_signer_session.user_id != current_user.id ||
|
||||
!(@pending_signer_session.pending? || @pending_signer_session.verified?))
|
||||
@pending_signer_session = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -131,7 +138,16 @@ class SettingsController < ApplicationController
|
||||
http_status :unprocessable_entity and return
|
||||
end
|
||||
|
||||
LdapManager::UpdateNostrKey.call(dn: current_user.dn, pubkey: signed_event.pubkey)
|
||||
current_pubkey = current_user.nostr_pubkey
|
||||
|
||||
if current_pubkey.present? && current_pubkey != signed_event.pubkey &&
|
||||
params[:replace].to_s != "true"
|
||||
flash[:alert] = "This account already has a different Nostr public key. " \
|
||||
"Remove it first or confirm the replacement."
|
||||
http_status :unprocessable_entity and return
|
||||
end
|
||||
|
||||
LdapManager::SetNostrKey.call(user: current_user, pubkey: signed_event.pubkey)
|
||||
session[:shared_secret] = nil
|
||||
|
||||
flash[:success] = "Public key verification successful"
|
||||
@@ -141,7 +157,11 @@ class SettingsController < ApplicationController
|
||||
# DELETE /settings/nostr_pubkey
|
||||
def remove_nostr_pubkey
|
||||
# TODO require current pubkey or password to delete
|
||||
LdapManager::UpdateNostrKey.call(dn: current_user.dn, pubkey: nil)
|
||||
LdapManager::SetNostrKey.call(user: current_user, pubkey: nil)
|
||||
NostrManager::RemoteSigner::DisconnectSessions.call(
|
||||
sessions: current_user.nostr_signer_sessions.where(status: %w[pending verified connected])
|
||||
)
|
||||
forget_nostr_account
|
||||
|
||||
redirect_to setting_path(:nostr), flash: {
|
||||
success: 'Public key removed from account'
|
||||
@@ -179,9 +199,14 @@ class SettingsController < ApplicationController
|
||||
pubkey: @user.nostr_pubkey, kind: NostrManagerService::PROFILE_KIND, relays: relays
|
||||
)
|
||||
Rails.cache.write(nostr_metadata_cache_key("profile"), profile, expires_in: 5.minutes)
|
||||
render json: { next: "blossom", event_id: profile&.dig("id") }
|
||||
render json: {
|
||||
next: Setting.nostr_media_servers_enabled? ? "blossom" : "render",
|
||||
event_id: profile&.dig("id")
|
||||
}
|
||||
|
||||
when "blossom"
|
||||
return render json: { next: "render" } unless Setting.nostr_media_servers_enabled?
|
||||
|
||||
write_relays = Rails.cache.read(nostr_metadata_cache_key("write_relays")) || []
|
||||
relays = write_relays.any? ? write_relays : discovery_relay_urls
|
||||
media_list = NostrManager::DiscoverUserEvent.call(
|
||||
@@ -194,7 +219,7 @@ class SettingsController < ApplicationController
|
||||
when "render", nil
|
||||
@nip65_event = Rails.cache.read(nostr_metadata_cache_key("nip65"))
|
||||
@profile = Rails.cache.read(nostr_metadata_cache_key("profile"))
|
||||
@media_list = Rails.cache.read(nostr_metadata_cache_key("blossom"))
|
||||
@media_list = Rails.cache.read(nostr_metadata_cache_key("blossom")) if Setting.nostr_media_servers_enabled?
|
||||
render partial: "nostr_metadata", formats: :html
|
||||
|
||||
else
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
module Users
|
||||
class NostrConnectsController < ApplicationController
|
||||
RATE_LIMIT = 10
|
||||
RATE_WINDOW = 10.minutes
|
||||
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?
|
||||
redirect_to new_user_session_path, alert: "Nostr login is not available right now."
|
||||
return
|
||||
end
|
||||
|
||||
@signer_session = find_or_create_session
|
||||
|
||||
if @signer_session.nil?
|
||||
redirect_to new_user_session_path,
|
||||
alert: "Too many connection attempts. Please try again later."
|
||||
else
|
||||
session[:nostr_connect_token] = @signer_session.token
|
||||
end
|
||||
end
|
||||
|
||||
def create
|
||||
unless Setting.nostr_enabled? && NostrSignerSession.encryption_available?
|
||||
redirect_to new_user_session_path, alert: "Nostr login is not available right now."
|
||||
return
|
||||
end
|
||||
|
||||
if rate_limited?
|
||||
redirect_to new_user_session_path,
|
||||
alert: "Too many connection attempts. Please try again later."
|
||||
return
|
||||
end
|
||||
|
||||
if pending_connections_exceeded?
|
||||
redirect_to new_user_session_path,
|
||||
alert: "Too many pending connections. Please try again later."
|
||||
return
|
||||
end
|
||||
|
||||
parsed = NostrManager::RemoteSigner::ParseBunkerUri.call(uri: params[:bunker_uri])
|
||||
signer_session = NostrManager::RemoteSigner::CreateSession.call(
|
||||
flow: "login",
|
||||
relays: parsed[:relays],
|
||||
connection_method: "bunker",
|
||||
remote_signer_pubkey: parsed[:remote_signer_pubkey],
|
||||
secret: parsed[:secret]
|
||||
)
|
||||
|
||||
session[:nostr_connect_token] = signer_session.token
|
||||
NostrConnectListenerJob.perform_later(signer_session.id)
|
||||
|
||||
redirect_to nostr_connect_path
|
||||
rescue NostrManager::RemoteSigner::Error => e
|
||||
redirect_to nostr_connect_path, alert: e.message
|
||||
end
|
||||
|
||||
def status
|
||||
if status_rate_limited?
|
||||
return render json: { error: "Too many status requests. Please try again later." },
|
||||
status: :too_many_requests
|
||||
end
|
||||
|
||||
signer_session = NostrSignerSession.find_by_token(session[:nostr_connect_token])
|
||||
|
||||
unless signer_session&.flow == "login"
|
||||
return render json: { status: "failed", error: "Unknown connection" }, status: :not_found
|
||||
end
|
||||
|
||||
signer_session.update_column(:last_status_poll_at, Time.current)
|
||||
|
||||
if signer_session.status == "pending" && signer_session.expires_at < Time.current
|
||||
signer_session.expire!
|
||||
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?
|
||||
sign_in(:user, signer_session.user)
|
||||
session.delete(:nostr_connect_token)
|
||||
render json: {
|
||||
status: "connected",
|
||||
redirect_url: after_sign_in_path_for(signer_session.user)
|
||||
}
|
||||
elsif signer_session.failed? || signer_session.expired?
|
||||
render json: { status: signer_session.status, error: signer_session.error }
|
||||
else
|
||||
render json: { status: "pending", auth_url: signer_session.auth_url }
|
||||
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])
|
||||
|
||||
if existing && existing.flow == "login" && (existing.pending? || existing.verified?)
|
||||
return existing
|
||||
end
|
||||
|
||||
return nil if pending_connections_exceeded?
|
||||
|
||||
NostrManager::RemoteSigner::CreateSession.call(flow: "login").tap do |signer_session|
|
||||
NostrConnectListenerJob.perform_later(signer_session.id)
|
||||
end
|
||||
end
|
||||
|
||||
def sign_in_user(signer_session)
|
||||
user = LdapManager::FetchUserByNostrKey.call(pubkey: signer_session.user_pubkey)
|
||||
|
||||
if user.nil?
|
||||
signer_session.fail!("No account is linked to this public key. Add it in your settings first.")
|
||||
return render json: { status: "failed", error: signer_session.error }, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
signer_session.with_lock do
|
||||
next if signer_session.consumed_at.present?
|
||||
|
||||
NostrSignerSession
|
||||
.where(user: user, status: %w[pending verified connected])
|
||||
.where.not(id: signer_session.id)
|
||||
.delete_all
|
||||
|
||||
signer_session.update!(
|
||||
user: user,
|
||||
status: "connected",
|
||||
consumed_at: Time.current
|
||||
)
|
||||
remember_nostr_account(user, session_record: signer_session)
|
||||
end
|
||||
|
||||
sign_in(:user, user)
|
||||
session.delete(:nostr_connect_token)
|
||||
|
||||
render json: {
|
||||
status: "connected",
|
||||
redirect_url: after_sign_in_path_for(user)
|
||||
}
|
||||
end
|
||||
|
||||
def rate_limited?
|
||||
key = "nostr_connect_ip:#{request.remote_ip}"
|
||||
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 status_rate_limited?
|
||||
key = "nostr_connect_status_ip:#{request.remote_ip}"
|
||||
count = Rails.cache.read(key).to_i
|
||||
return true if count >= STATUS_RATE_LIMIT
|
||||
|
||||
Rails.cache.write(key, count + 1, expires_in: STATUS_RATE_WINDOW)
|
||||
false
|
||||
end
|
||||
|
||||
def pending_connections_exceeded?
|
||||
NostrSignerSession
|
||||
.where(status: "pending")
|
||||
.where("expires_at > ?", Time.current)
|
||||
.count >= MAX_PENDING
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,254 @@
|
||||
module Users
|
||||
class NostrContinuesController < ApplicationController
|
||||
CREATE_IP_LIMIT = 10
|
||||
CREATE_IP_WINDOW = 10.minutes
|
||||
CREATE_USER_LIMIT = 5
|
||||
CREATE_USER_WINDOW = 5.minutes
|
||||
STATUS_LIMIT = 240
|
||||
STATUS_WINDOW = 5.minutes
|
||||
DIFFERENT_LIMIT = 10
|
||||
DIFFERENT_WINDOW = 10.minutes
|
||||
|
||||
before_action :redirect_signed_in_user, only: [:create, :show]
|
||||
before_action :require_nostr_available
|
||||
|
||||
def create
|
||||
remembered = resolve_remembered_nostr_account
|
||||
return render_error("No saved remote signer connection", :forbidden) if remembered.nil?
|
||||
|
||||
if rate_limited?("nostr_continue_create_ip:#{request.remote_ip}", CREATE_IP_LIMIT, CREATE_IP_WINDOW) ||
|
||||
rate_limited?("nostr_continue_create_user:#{remembered.user_id}", CREATE_USER_LIMIT, CREATE_USER_WINDOW)
|
||||
return render_error("Too many login attempts. Please try again later.", :too_many_requests)
|
||||
end
|
||||
|
||||
if remembered.user.nostr_pubkey != remembered.user_pubkey
|
||||
forget_nostr_account
|
||||
return render_error(
|
||||
"Your account's public key no longer matches this remote signer. Please reconnect it.",
|
||||
:unprocessable_entity
|
||||
)
|
||||
end
|
||||
|
||||
invalidate_previous_requests(remembered.user)
|
||||
|
||||
challenge = SecureRandom.urlsafe_base64(24)
|
||||
template = {
|
||||
"kind" => 22242,
|
||||
"content" => "",
|
||||
"created_at" => Time.current.to_i,
|
||||
"tags" => [
|
||||
["site", Setting.accounts_domain.to_s],
|
||||
["challenge", challenge]
|
||||
]
|
||||
}
|
||||
|
||||
sign_request = remembered.user.nostr_sign_requests.create!(
|
||||
kind: 22242,
|
||||
template: template,
|
||||
purpose: "reauth",
|
||||
status: "pending",
|
||||
expires_at: NostrSignRequest::TTL.from_now
|
||||
)
|
||||
|
||||
session[:nostr_reauth_token] = sign_request.token
|
||||
NostrSignEventJob.perform_later(sign_request.id)
|
||||
|
||||
redirect_to nostr_continue_page_path
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
render_error("Could not start the login request: #{e.message}", :unprocessable_entity)
|
||||
end
|
||||
|
||||
def show
|
||||
@remembered = resolve_remembered_nostr_account
|
||||
@sign_request = current_reauth_request
|
||||
|
||||
if @remembered.nil? || @sign_request.nil?
|
||||
redirect_to new_user_session_path,
|
||||
alert: "Your saved login expired. Please connect your signer again."
|
||||
return
|
||||
end
|
||||
|
||||
@nostr_remembered_user = @remembered.user
|
||||
end
|
||||
|
||||
def status
|
||||
remembered = resolve_remembered_nostr_account
|
||||
sign_request = current_reauth_request
|
||||
|
||||
if remembered.nil? || sign_request.nil? || sign_request.user_id != remembered.user_id
|
||||
session.delete(:nostr_reauth_token)
|
||||
return render json: { status: "expired", error: "Your login request expired. Please try again." },
|
||||
status: :gone
|
||||
end
|
||||
|
||||
if rate_limited?("nostr_continue_status_ip:#{request.remote_ip}", STATUS_LIMIT, STATUS_WINDOW)
|
||||
return render json: { error: "Too many status requests. Please try again later." },
|
||||
status: :too_many_requests
|
||||
end
|
||||
|
||||
if sign_request.consumed?
|
||||
if user_signed_in? && current_user.id == sign_request.user_id
|
||||
return render json: {
|
||||
status: "connected",
|
||||
redirect_url: after_sign_in_path_for(current_user)
|
||||
}
|
||||
end
|
||||
|
||||
session.delete(:nostr_reauth_token)
|
||||
return render json: { status: "expired", error: "Your login request expired. Please try again." },
|
||||
status: :gone
|
||||
end
|
||||
|
||||
case sign_request.status
|
||||
when "signed"
|
||||
if sign_request.expires_at < Time.current
|
||||
sign_request.expire!
|
||||
session.delete(:nostr_reauth_token)
|
||||
render json: { status: "expired", error: sign_request.error }, status: :gone
|
||||
else
|
||||
complete_sign_in(remembered, sign_request)
|
||||
end
|
||||
when "failed", "expired"
|
||||
session.delete(:nostr_reauth_token)
|
||||
render json: { status: sign_request.status, error: sign_request.error }, status: :unprocessable_entity
|
||||
else
|
||||
if sign_request.expires_at < Time.current
|
||||
sign_request.expire!
|
||||
session.delete(:nostr_reauth_token)
|
||||
render json: { status: "expired", error: sign_request.error }, status: :gone
|
||||
else
|
||||
render json: { status: "pending" }
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def different_account
|
||||
if rate_limited?("nostr_continue_different_ip:#{request.remote_ip}", DIFFERENT_LIMIT, DIFFERENT_WINDOW)
|
||||
return render_error("Too many requests. Please try again later.", :too_many_requests)
|
||||
end
|
||||
|
||||
sign_out(current_user) if user_signed_in?
|
||||
|
||||
record = remembered_nostr_session_any_status
|
||||
disconnect_remembered_session(record)
|
||||
|
||||
forget_nostr_account
|
||||
session.delete(:nostr_connect_token)
|
||||
|
||||
redirect_to nostr_connect_path
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def redirect_signed_in_user
|
||||
return unless user_signed_in?
|
||||
|
||||
redirect_to after_sign_in_path_for(current_user), notice: "You are already logged in."
|
||||
end
|
||||
|
||||
def complete_sign_in(remembered, sign_request)
|
||||
user = remembered.user
|
||||
failure = nil
|
||||
|
||||
sign_request.with_lock do
|
||||
if sign_request.consumed?
|
||||
next
|
||||
end
|
||||
|
||||
unless valid_auth_event?(sign_request, remembered)
|
||||
failure = "Login verification failed"
|
||||
sign_request.fail!(failure)
|
||||
next
|
||||
end
|
||||
|
||||
sign_request.consume!
|
||||
sign_in(:user, user)
|
||||
remember_nostr_account(user, session_record: remembered)
|
||||
session.delete(:nostr_reauth_token)
|
||||
end
|
||||
|
||||
if failure
|
||||
render json: { status: "failed", error: failure }, status: :unprocessable_entity
|
||||
else
|
||||
render json: {
|
||||
status: "connected",
|
||||
redirect_url: after_sign_in_path_for(user)
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
def valid_auth_event?(sign_request, remembered)
|
||||
return false unless sign_request.kind == 22242
|
||||
return false if sign_request.signed_event.blank?
|
||||
|
||||
template = sign_request.template.symbolize_keys
|
||||
tags = Array(template[:tags])
|
||||
challenge = tags.find { |tag| tag[0] == "challenge" }&.[](1)
|
||||
return false if challenge.blank?
|
||||
|
||||
event = Nostr::Event.new(**sign_request.signed_event.symbolize_keys)
|
||||
|
||||
event.kind == 22242 &&
|
||||
event.pubkey == remembered.user_pubkey &&
|
||||
remembered.user.nostr_pubkey == event.pubkey &&
|
||||
NostrManager::VerifySignedEvent.call(event: event) &&
|
||||
NostrManager::VerifyAuth.call(event: event, challenge: challenge) &&
|
||||
NostrManager::EventLimits.fresh?(event)
|
||||
rescue StandardError
|
||||
false
|
||||
end
|
||||
|
||||
def disconnect_remembered_session(record)
|
||||
NostrManager::RemoteSigner::DisconnectSessions.call(sessions: [record])
|
||||
end
|
||||
|
||||
def current_reauth_request
|
||||
token = session[:nostr_reauth_token]
|
||||
return nil if token.blank?
|
||||
|
||||
NostrSignRequest.find_by(token: token, purpose: "reauth")
|
||||
end
|
||||
|
||||
def invalidate_previous_requests(user)
|
||||
NostrSignRequest
|
||||
.where(user: user, purpose: "reauth", status: "pending")
|
||||
.update_all(
|
||||
status: "expired",
|
||||
error: "A new login request replaced this one.",
|
||||
updated_at: Time.current
|
||||
)
|
||||
end
|
||||
|
||||
def require_nostr_available
|
||||
return if Setting.nostr_enabled? && NostrSignerSession.encryption_available?
|
||||
|
||||
respond_to do |format|
|
||||
format.html do
|
||||
redirect_to new_user_session_path,
|
||||
alert: "Nostr Connect login is not available right now."
|
||||
end
|
||||
format.json do
|
||||
render json: { status: "failed", error: "Nostr Connect login is not available right now." },
|
||||
status: :service_unavailable
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def rate_limited?(key, limit, window)
|
||||
count = Rails.cache.read(key).to_i
|
||||
return true if count >= limit
|
||||
|
||||
Rails.cache.write(key, count + 1, expires_in: window)
|
||||
false
|
||||
end
|
||||
|
||||
def render_error(message, status)
|
||||
session.delete(:nostr_reauth_token)
|
||||
|
||||
respond_to do |format|
|
||||
format.html { redirect_to new_user_session_path, alert: message }
|
||||
format.json { render json: { status: "failed", error: message }, status: status }
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -6,7 +6,21 @@ class Users::SessionsController < Devise::SessionsController
|
||||
# GET /resource/sign_in
|
||||
def new
|
||||
session[:shared_secret] = SecureRandom.base64(12)
|
||||
super
|
||||
@nostr_remembered_session = resolve_remembered_nostr_account
|
||||
@nostr_remembered_user = @nostr_remembered_session&.user
|
||||
|
||||
if @nostr_remembered_session &&
|
||||
@nostr_remembered_user.nostr_pubkey != @nostr_remembered_session.user_pubkey
|
||||
forget_nostr_account
|
||||
@nostr_remembered_session = nil
|
||||
@nostr_remembered_user = nil
|
||||
end
|
||||
|
||||
if @nostr_remembered_user.present? && params[:password].blank?
|
||||
render :continue_as
|
||||
else
|
||||
super
|
||||
end
|
||||
end
|
||||
|
||||
# POST /resource/sign_in
|
||||
@@ -15,9 +29,10 @@ class Users::SessionsController < Devise::SessionsController
|
||||
# end
|
||||
|
||||
# DELETE /resource/sign_out
|
||||
# def destroy
|
||||
# super
|
||||
# end
|
||||
def destroy
|
||||
session.delete(:nostr_reauth_token)
|
||||
super
|
||||
end
|
||||
|
||||
# POST /users/nostr_login
|
||||
def nostr_login
|
||||
|
||||
@@ -21,6 +21,30 @@ module ApplicationHelper
|
||||
}).to_html
|
||||
end
|
||||
|
||||
def active_nostr_signer_session
|
||||
return nil unless user_signed_in?
|
||||
return nil unless NostrSignerSession.encryption_available?
|
||||
|
||||
return @active_nostr_signer_session if defined?(@active_nostr_signer_session)
|
||||
|
||||
session = current_user.nostr_signer_sessions
|
||||
.where(status: %w[verified connected])
|
||||
.order(updated_at: :desc)
|
||||
.first
|
||||
|
||||
@active_nostr_signer_session =
|
||||
if session && (current_user.nostr_pubkey.blank? ||
|
||||
session.user_pubkey != current_user.nostr_pubkey)
|
||||
nil
|
||||
else
|
||||
session
|
||||
end
|
||||
end
|
||||
|
||||
def nostr_remote_signer_available?
|
||||
Setting.nostr_enabled? && NostrSignerSession.encryption_available?
|
||||
end
|
||||
|
||||
def image_url_for(attachment)
|
||||
return s3_image_url(attachment) if Setting.s3_enabled?
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
|
||||
const POLL_INTERVAL = 1500
|
||||
const MAX_ATTEMPTS = 120
|
||||
|
||||
export default class extends Controller {
|
||||
static targets = [ "status", "error" ]
|
||||
static values = { statusUrl: String }
|
||||
|
||||
connect () {
|
||||
this.attempts = 0
|
||||
this.stopped = false
|
||||
this.poll()
|
||||
}
|
||||
|
||||
disconnect () {
|
||||
this.stopped = true
|
||||
clearTimeout(this.timer)
|
||||
}
|
||||
|
||||
async poll () {
|
||||
if (this.stopped) return
|
||||
|
||||
this.attempts += 1
|
||||
|
||||
try {
|
||||
const response = await fetch(this.statusUrlValue, {
|
||||
credentials: "include",
|
||||
headers: { "Accept": "application/json" }
|
||||
})
|
||||
const data = await response.json().catch(() => ({}))
|
||||
|
||||
if (data.status === "connected") {
|
||||
this.statusTarget.textContent = "Signed in. Redirecting…"
|
||||
window.location.href = data.redirect_url || "/"
|
||||
return
|
||||
}
|
||||
|
||||
if (!response.ok || data.status === "failed" || data.status === "expired") {
|
||||
this.showError(data.error || "Login failed. Please try again.")
|
||||
return
|
||||
}
|
||||
|
||||
if (this.attempts >= MAX_ATTEMPTS) {
|
||||
this.showError("Timed out waiting for your signer. Please try again.")
|
||||
return
|
||||
}
|
||||
|
||||
this.timer = setTimeout(() => this.poll(), POLL_INTERVAL)
|
||||
} catch (error) {
|
||||
if (this.attempts >= MAX_ATTEMPTS) {
|
||||
this.showError(error.message)
|
||||
return
|
||||
}
|
||||
|
||||
this.timer = setTimeout(() => this.poll(), POLL_INTERVAL)
|
||||
}
|
||||
}
|
||||
|
||||
showError (message) {
|
||||
this.errorTarget.textContent = message
|
||||
this.errorTarget.classList.remove("hidden")
|
||||
}
|
||||
}
|
||||
@@ -3,18 +3,35 @@ import { csrfToken } from "lib/csrf"
|
||||
|
||||
// Connects to data-controller="nostr-login"
|
||||
export default class extends Controller {
|
||||
static targets = [ "loginForm", "loginButton" ]
|
||||
static targets = [ "extensionOption", "extensionDescription", "extensionUnavailable" ]
|
||||
static values = { site: String, sharedSecret: String }
|
||||
|
||||
connect() {
|
||||
if (window.nostr) {
|
||||
this.loginButtonTarget.disabled = false
|
||||
this.loginFormTarget.classList.remove("hidden")
|
||||
const hasExtension = Boolean(window.nostr)
|
||||
|
||||
if (hasExtension) {
|
||||
this.element.classList.remove("hidden")
|
||||
}
|
||||
|
||||
if (this.hasExtensionOptionTarget) {
|
||||
this.extensionOptionTarget.disabled = !hasExtension
|
||||
}
|
||||
if (this.hasExtensionDescriptionTarget) {
|
||||
this.extensionDescriptionTarget.classList.toggle("hidden", !hasExtension)
|
||||
}
|
||||
if (this.hasExtensionUnavailableTarget) {
|
||||
this.extensionUnavailableTarget.classList.toggle("hidden", hasExtension)
|
||||
}
|
||||
}
|
||||
|
||||
closeModal() {
|
||||
this.element
|
||||
.querySelectorAll("[data-modal-target='background'], [data-modal-target='container']")
|
||||
.forEach((element) => element.classList.add("hidden"))
|
||||
}
|
||||
|
||||
async login () {
|
||||
this.loginButtonTarget.disabled = true
|
||||
if (this.hasExtensionOptionTarget) this.extensionOptionTarget.disabled = true
|
||||
|
||||
try {
|
||||
// Auth based on NIP-42
|
||||
@@ -43,7 +60,7 @@ export default class extends Controller {
|
||||
} catch (error) {
|
||||
console.warn('Unable to authenticate:', error.message)
|
||||
} finally {
|
||||
this.loginButtonTarget.disabled = false
|
||||
if (this.hasExtensionOptionTarget) this.extensionOptionTarget.disabled = false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
import { signAndPublish, hasNostrExtension } from "lib/nostr_publish"
|
||||
import { signAndPublish } from "lib/nostr_publish"
|
||||
import { canSign, signEvent } from "lib/nostr_signer"
|
||||
import { csrfToken } from "lib/csrf"
|
||||
|
||||
const PROFILE_KIND = 0
|
||||
@@ -43,8 +44,8 @@ export default class extends Controller {
|
||||
this.showError("Please enter a valid website URL, e.g. https://example.com.")
|
||||
return
|
||||
}
|
||||
if (!hasNostrExtension()) {
|
||||
this.showError("No Nostr extension (NIP-07) found.")
|
||||
if (!canSign()) {
|
||||
this.showError("No Nostr signer is available.")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -98,7 +99,7 @@ export default class extends Controller {
|
||||
if (fields.length === 0) return
|
||||
|
||||
const now = Math.floor(Date.now() / 1000)
|
||||
const signedEvent = await window.nostr.signEvent({
|
||||
const signedEvent = await signEvent({
|
||||
kind: AUTH_KIND,
|
||||
created_at: now,
|
||||
tags: [
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
import { csrfToken } from "lib/csrf"
|
||||
|
||||
const POLL_INTERVAL = 2000
|
||||
const MAX_ATTEMPTS = 160
|
||||
|
||||
export default class extends Controller {
|
||||
static targets = [ "status", "error", "authWrapper", "authLink", "details", "retry", "signerHint", "qr", "qrToggle", "replace", "replaceExisting", "replaceSigner" ]
|
||||
static values = { statusUrl: String, replaceUrl: String, destroyUrl: String, sectionUrl: String }
|
||||
|
||||
connect () {
|
||||
this.attempts = 0
|
||||
this.stopped = false
|
||||
this.poll()
|
||||
}
|
||||
|
||||
disconnect () {
|
||||
this.stopped = true
|
||||
clearTimeout(this.timer)
|
||||
}
|
||||
|
||||
async poll () {
|
||||
if (this.stopped) return
|
||||
|
||||
this.attempts += 1
|
||||
|
||||
try {
|
||||
const response = await fetch(this.statusUrlValue, {
|
||||
credentials: "include",
|
||||
headers: { "Accept": "application/json" }
|
||||
})
|
||||
const data = await response.json().catch(() => ({}))
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || `HTTP ${response.status}`)
|
||||
}
|
||||
|
||||
if (data.status === "connected") {
|
||||
this.finishConnection(data.redirect_url)
|
||||
return
|
||||
}
|
||||
|
||||
if (data.status === "replace_required") {
|
||||
this.showReplace(data.existing_npub, data.signer_npub)
|
||||
return
|
||||
}
|
||||
|
||||
if (data.status === "failed" || data.status === "expired" || data.status === "disconnected") {
|
||||
this.showTerminalError(data.error || "The connection failed. Please try again.")
|
||||
return
|
||||
}
|
||||
|
||||
this.showAuthUrl(data.auth_url)
|
||||
|
||||
if (this.attempts >= MAX_ATTEMPTS) {
|
||||
this.showTerminalError("Timed out waiting for your signer. Please try again.")
|
||||
return
|
||||
}
|
||||
|
||||
this.timer = setTimeout(() => this.poll(), POLL_INTERVAL)
|
||||
} catch (error) {
|
||||
this.showError(error.message)
|
||||
}
|
||||
}
|
||||
|
||||
openSigner () {
|
||||
if (!this.hasSignerHintTarget) return
|
||||
|
||||
this.signerHintTarget.classList.add("hidden")
|
||||
const attempt = this.launchAttempt = (this.launchAttempt || 0) + 1
|
||||
let launched = false
|
||||
let timer
|
||||
let onNavigateError
|
||||
|
||||
const finish = () => {
|
||||
clearTimeout(timer)
|
||||
document.removeEventListener("visibilitychange", onVisibility)
|
||||
window.removeEventListener("blur", onBlur)
|
||||
if (onNavigateError && "navigation" in window) {
|
||||
navigation.removeEventListener("navigateerror", onNavigateError)
|
||||
}
|
||||
}
|
||||
|
||||
const revealHint = () => {
|
||||
if (attempt !== this.launchAttempt || !this.hasSignerHintTarget) return
|
||||
this.signerHintTarget.classList.remove("hidden")
|
||||
}
|
||||
|
||||
const markLaunched = () => {
|
||||
launched = true
|
||||
finish()
|
||||
}
|
||||
|
||||
const onVisibility = () => {
|
||||
if (document.visibilityState === "hidden") markLaunched()
|
||||
}
|
||||
|
||||
const onBlur = () => markLaunched()
|
||||
|
||||
document.addEventListener("visibilitychange", onVisibility)
|
||||
window.addEventListener("blur", onBlur, { once: true })
|
||||
|
||||
if ("navigation" in window) {
|
||||
onNavigateError = (event) => {
|
||||
if (!event.destination?.url?.startsWith("nostrconnect:")) return
|
||||
finish()
|
||||
revealHint()
|
||||
}
|
||||
navigation.addEventListener("navigateerror", onNavigateError)
|
||||
}
|
||||
|
||||
timer = setTimeout(() => {
|
||||
if (launched || attempt !== this.launchAttempt) return
|
||||
finish()
|
||||
revealHint()
|
||||
}, 2000)
|
||||
}
|
||||
|
||||
showQr () {
|
||||
if (!this.hasQrTarget) return
|
||||
|
||||
this.qrTarget.classList.remove("hidden")
|
||||
this.qrTarget.classList.add("flex")
|
||||
if (this.hasQrToggleTarget) this.qrToggleTarget.classList.add("hidden")
|
||||
}
|
||||
|
||||
showReplace (existingNpub, signerNpub) {
|
||||
this.stopped = true
|
||||
clearTimeout(this.timer)
|
||||
|
||||
if (this.hasReplaceExistingTarget) {
|
||||
this.replaceExistingTarget.textContent = existingNpub || ""
|
||||
}
|
||||
if (this.hasReplaceSignerTarget) {
|
||||
this.replaceSignerTarget.textContent = signerNpub || ""
|
||||
}
|
||||
|
||||
this.statusTarget.classList.add("hidden")
|
||||
if (this.hasDetailsTarget) this.detailsTarget.classList.add("hidden")
|
||||
if (this.hasAuthWrapperTarget) this.authWrapperTarget.classList.add("hidden")
|
||||
if (this.hasReplaceTarget) this.replaceTarget.classList.remove("hidden")
|
||||
}
|
||||
|
||||
async replace () {
|
||||
if (!this.hasReplaceUrlValue || !this.replaceUrlValue) return
|
||||
|
||||
try {
|
||||
const response = await fetch(this.replaceUrlValue, {
|
||||
method: "POST", credentials: "include",
|
||||
headers: { "Accept": "application/json", "X-CSRF-Token": csrfToken() }
|
||||
})
|
||||
const data = await response.json().catch(() => ({}))
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || `HTTP ${response.status}`)
|
||||
}
|
||||
|
||||
if (data.status === "connected") {
|
||||
// Replacing links a different key, so the pubkey field, profile and
|
||||
// media server lists elsewhere on the page are stale — full reload.
|
||||
window.location.reload()
|
||||
return
|
||||
}
|
||||
|
||||
this.showError(data.error || "Could not replace the key. Please try again.")
|
||||
} catch (error) {
|
||||
this.showError(error.message)
|
||||
}
|
||||
}
|
||||
|
||||
async cancel () {
|
||||
try {
|
||||
if (this.hasDestroyUrlValue && this.destroyUrlValue) {
|
||||
await fetch(this.destroyUrlValue, {
|
||||
method: "DELETE", credentials: "include",
|
||||
headers: { "Accept": "application/json", "X-CSRF-Token": csrfToken() }
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
// Ignore; the section update below reflects whatever state the server is in.
|
||||
}
|
||||
|
||||
this.finishConnection()
|
||||
}
|
||||
|
||||
// After the connection is established (or cancelled), update just the signer
|
||||
// section so the page's Nostr metadata isn't re-fetched from relays. Falls
|
||||
// back to a full reload when there is no section to update (login flow) or
|
||||
// when the account had no key yet (the pubkey field and metadata need a fresh
|
||||
// page).
|
||||
finishConnection (redirectUrl) {
|
||||
if (!this.hasSectionUrlValue || !this.sectionUrlValue) {
|
||||
if (this.hasStatusTarget) this.statusTarget.textContent = "Connected. Redirecting…"
|
||||
window.location.href = redirectUrl || window.location.href
|
||||
return
|
||||
}
|
||||
|
||||
if (!this.hasAccountKey()) {
|
||||
window.location.reload()
|
||||
return
|
||||
}
|
||||
|
||||
if (this.hasStatusTarget) this.statusTarget.textContent = "Connected. Updating…"
|
||||
this.refreshSection()
|
||||
}
|
||||
|
||||
hasAccountKey () {
|
||||
return Boolean(document.querySelector('[data-controller~="nostr-metadata"]'))
|
||||
}
|
||||
|
||||
async refreshSection () {
|
||||
try {
|
||||
const response = await fetch(this.sectionUrlValue, {
|
||||
credentials: "include",
|
||||
headers: { "Accept": "text/vnd.turbo-stream.html" }
|
||||
})
|
||||
if (!response.ok || response.redirected) {
|
||||
window.location.reload()
|
||||
return
|
||||
}
|
||||
window.Turbo.renderStreamMessage(await response.text())
|
||||
} catch (error) {
|
||||
window.location.reload()
|
||||
}
|
||||
}
|
||||
|
||||
showAuthUrl (url) {
|
||||
if (!url) {
|
||||
this.authWrapperTarget.classList.add("hidden")
|
||||
return
|
||||
}
|
||||
|
||||
this.authLinkTarget.href = url
|
||||
this.authWrapperTarget.classList.remove("hidden")
|
||||
}
|
||||
|
||||
showError (message) {
|
||||
this.errorTarget.textContent = message
|
||||
this.errorTarget.classList.remove("hidden")
|
||||
}
|
||||
|
||||
showTerminalError (message) {
|
||||
this.showError(message)
|
||||
this.statusTarget.textContent = "Connection request ended."
|
||||
if (this.hasDetailsTarget) this.detailsTarget.classList.add("hidden")
|
||||
if (this.hasRetryTarget) this.retryTarget.classList.remove("hidden")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
|
||||
// Mirrors the signer section's connection state onto the document, so the
|
||||
// `data-remote-signer` flag stays correct when the section is replaced in place
|
||||
// (turbo stream) instead of via a full page load.
|
||||
export default class extends Controller {
|
||||
static values = { connected: Boolean }
|
||||
|
||||
connect () {
|
||||
document.documentElement.dataset.remoteSigner = this.connectedValue ? "true" : "false"
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { csrfToken } from "lib/csrf"
|
||||
|
||||
// Connects to data-controller="settings--nostr-pubkey"
|
||||
export default class extends Controller {
|
||||
static targets = [ "noExtension", "setPubkey", "pubkeyBech32Input" ]
|
||||
static targets = [ "setPubkey", "extensionDescription", "extensionUnavailable" ]
|
||||
static values = {
|
||||
userAddress: String,
|
||||
pubkeyHex: String,
|
||||
@@ -12,12 +12,16 @@ export default class extends Controller {
|
||||
}
|
||||
|
||||
connect () {
|
||||
if (window.nostr) {
|
||||
if (this.hasSetPubkeyTarget) {
|
||||
this.setPubkeyTarget.disabled = false
|
||||
}
|
||||
} else {
|
||||
this.noExtensionTarget.classList.remove("hidden")
|
||||
const hasExtension = Boolean(window.nostr)
|
||||
|
||||
if (this.hasSetPubkeyTarget) {
|
||||
this.setPubkeyTarget.disabled = !hasExtension
|
||||
}
|
||||
if (this.hasExtensionDescriptionTarget) {
|
||||
this.extensionDescriptionTarget.classList.toggle("hidden", !hasExtension)
|
||||
}
|
||||
if (this.hasExtensionUnavailableTarget) {
|
||||
this.extensionUnavailableTarget.classList.toggle("hidden", hasExtension)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
import { signAndPublish, hasNostrExtension } from "lib/nostr_publish"
|
||||
import { signAndPublish } from "lib/nostr_publish"
|
||||
import { canSign } from "lib/nostr_signer"
|
||||
import { updateAddedBadge } from "lib/added_badge"
|
||||
|
||||
export default class extends Controller {
|
||||
@@ -48,8 +49,8 @@ export default class extends Controller {
|
||||
this.showError(this.invalidMessageValue || "Please check the URLs.")
|
||||
return
|
||||
}
|
||||
if (!hasNostrExtension()) {
|
||||
this.showError("No Nostr extension (NIP-07) found.")
|
||||
if (!canSign()) {
|
||||
this.showError("No Nostr signer is available.")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -1,17 +1,14 @@
|
||||
import { csrfToken } from "lib/csrf"
|
||||
import { canSign, signEvent } from "lib/nostr_signer"
|
||||
|
||||
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")
|
||||
if (!canSign()) {
|
||||
throw new Error("No Nostr signer is available")
|
||||
}
|
||||
|
||||
const signedEvent = await window.nostr.signEvent(eventTemplate)
|
||||
const signedEvent = await signEvent(eventTemplate)
|
||||
await publish(signedEvent, { url })
|
||||
return signedEvent
|
||||
}
|
||||
@@ -35,4 +32,4 @@ export async function publish (signedEvent, { url = DEFAULT_URL } = {}) {
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { csrfToken } from "lib/csrf"
|
||||
|
||||
const SIGN_URL = "/settings/nostr_sign"
|
||||
const POLL_INTERVAL = 1500
|
||||
const MAX_ATTEMPTS = 120
|
||||
|
||||
export function hasNostrExtension () {
|
||||
return Boolean(window.nostr && window.nostr.signEvent)
|
||||
}
|
||||
|
||||
export function hasRemoteSigner () {
|
||||
return document.documentElement.dataset.remoteSigner === "true"
|
||||
}
|
||||
|
||||
export function preferredSigner () {
|
||||
if (hasRemoteSigner()) return "remote"
|
||||
if (hasNostrExtension()) return "extension"
|
||||
return null
|
||||
}
|
||||
|
||||
export function canSign () {
|
||||
return preferredSigner() !== null
|
||||
}
|
||||
|
||||
export async function signEvent (eventTemplate) {
|
||||
const signer = preferredSigner()
|
||||
|
||||
if (signer === "extension") {
|
||||
return window.nostr.signEvent(eventTemplate)
|
||||
}
|
||||
|
||||
if (signer === "remote") {
|
||||
const created = await postJSON(SIGN_URL, { event: eventTemplate })
|
||||
if (!created.token) {
|
||||
throw new Error(created.error || "Could not start the signing request")
|
||||
}
|
||||
|
||||
return await pollSignedEvent(created.token)
|
||||
}
|
||||
|
||||
throw new Error("No Nostr signer is available")
|
||||
}
|
||||
|
||||
async function pollSignedEvent (token) {
|
||||
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
|
||||
const response = await fetch(`${SIGN_URL}/${encodeURIComponent(token)}`, {
|
||||
credentials: "include",
|
||||
headers: { "Accept": "application/json" }
|
||||
})
|
||||
const data = await response.json().catch(() => ({}))
|
||||
|
||||
if (data.status === "signed") {
|
||||
return data.signed_event
|
||||
}
|
||||
if (data.status === "failed" || data.status === "expired" || response.status === 410) {
|
||||
throw new Error(data.error || "Signing failed")
|
||||
}
|
||||
|
||||
await sleep(POLL_INTERVAL)
|
||||
}
|
||||
|
||||
throw new Error("Timed out waiting for your signer")
|
||||
}
|
||||
|
||||
async function postJSON (url, body) {
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: {
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/json",
|
||||
"X-CSRF-Token": csrfToken()
|
||||
},
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
const data = await response.json().catch(() => ({}))
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || `HTTP ${response.status}`)
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
function sleep (ms) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
@@ -24,7 +24,10 @@ const localizeTimestamps = () => {
|
||||
const timestamp = new Date(value)
|
||||
|
||||
if (!Number.isNaN(timestamp.getTime())) {
|
||||
element.title = LOCAL_TIME_FORMAT.format(timestamp)
|
||||
const localTime = LOCAL_TIME_FORMAT.format(timestamp)
|
||||
|
||||
element.title = localTime
|
||||
if (element.dataset.localTime === "display") element.textContent = localTime
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +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?
|
||||
|
||||
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
|
||||
@@ -0,0 +1,12 @@
|
||||
class NostrLogoutJob < ApplicationJob
|
||||
queue_as :nostr_rpc
|
||||
|
||||
def perform(session_id)
|
||||
signer_session = NostrSignerSession.find_by(id: session_id)
|
||||
return if signer_session.nil?
|
||||
|
||||
NostrManager::RemoteSigner::Disconnect.call(session: signer_session)
|
||||
ensure
|
||||
NostrSignerSession.find_by(id: session_id)&.destroy!
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,34 @@
|
||||
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.with_lock do
|
||||
if request.pending?
|
||||
request.sign!(signed)
|
||||
elsif request.status == "pending"
|
||||
request.expire!
|
||||
end
|
||||
end
|
||||
rescue NostrManager::RemoteSigner::Error => e
|
||||
fail_request(request_id, e.message)
|
||||
rescue StandardError => e
|
||||
Rails.logger.warn("[nostr][signer] signing job failed: #{e.class}: #{e.message}")
|
||||
fail_request(request_id, "Could not sign the event. Please try again.")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def fail_request(request_id, message)
|
||||
request = NostrSignRequest.find_by(id: request_id)
|
||||
return if request.nil?
|
||||
|
||||
request.with_lock do
|
||||
request.fail!(message) if request.pending?
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,25 @@
|
||||
class NostrSignerCleanupJob < ApplicationJob
|
||||
queue_as :default
|
||||
|
||||
def perform
|
||||
NostrSignerSession
|
||||
.where(status: %w[pending failed])
|
||||
.where("expires_at < ?", Time.current)
|
||||
.delete_all
|
||||
|
||||
NostrSignerSession
|
||||
.where(status: "disconnecting")
|
||||
.where("updated_at < ?", 10.minutes.ago)
|
||||
.delete_all
|
||||
|
||||
NostrSignRequest
|
||||
.where(status: %w[pending failed])
|
||||
.where("expires_at < ?", Time.current)
|
||||
.delete_all
|
||||
|
||||
NostrSignRequest
|
||||
.where(status: "signed")
|
||||
.where("expires_at < ?", 10.minutes.ago)
|
||||
.delete_all
|
||||
end
|
||||
end
|
||||
@@ -31,15 +31,29 @@ module Settings
|
||||
message: "must be an http:// or https:// URL"
|
||||
} }
|
||||
|
||||
field :nostr_media_servers_enabled, type: :boolean,
|
||||
default: -> { self.nostr_blossom_server_url.present? }
|
||||
|
||||
field :nostr_signer_relays, type: :array, default: %w[
|
||||
wss://nostr.kosmos.org
|
||||
]
|
||||
|
||||
field :nostr_client_icon_url, type: :string,
|
||||
default: "https://assets.kosmos.org/img/app-icon-256px.png",
|
||||
validates: { format: {
|
||||
with: %r{\Ahttps?://.+},
|
||||
allow_blank: true,
|
||||
message: "must be an http:// or https:// URL"
|
||||
} }
|
||||
|
||||
field :nostr_zaps_relay_limit, type: :integer,
|
||||
default: 12
|
||||
|
||||
field :nostr_discovery_relays, type: :array, default: %w[
|
||||
wss://nostr.kosmos.org
|
||||
wss://nos.lol
|
||||
wss://relay.snort.social
|
||||
wss://relay.primal.net
|
||||
wss://relay.damus.io
|
||||
wss://relay.snort.social
|
||||
]
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
require "securerandom"
|
||||
|
||||
class NostrSignRequest < ApplicationRecord
|
||||
TTL = 2.minutes
|
||||
STATUSES = %w[pending signed failed expired].freeze
|
||||
PURPOSES = %w[sign reauth].freeze
|
||||
|
||||
belongs_to :user
|
||||
|
||||
serialize :template, coder: JSON
|
||||
serialize :signed_event, coder: JSON
|
||||
|
||||
validates :token, presence: true, uniqueness: true
|
||||
validates :kind, presence: true
|
||||
validates :template, presence: true
|
||||
validates :status, inclusion: { in: STATUSES }
|
||||
validates :purpose, inclusion: { in: PURPOSES }
|
||||
validates :expires_at, presence: true
|
||||
|
||||
scope :pending, -> { where(status: "pending") }
|
||||
scope :stale, -> { where("expires_at < ?", Time.current).where(status: "pending") }
|
||||
scope :sign, -> { where(purpose: "sign") }
|
||||
scope :reauth, -> { where(purpose: "reauth") }
|
||||
|
||||
before_validation :generate_token, on: :create
|
||||
|
||||
def self.generate_token
|
||||
SecureRandom.urlsafe_base64(32)
|
||||
end
|
||||
|
||||
def pending?
|
||||
status == "pending" && expires_at.present? && expires_at > Time.current
|
||||
end
|
||||
|
||||
def signed?
|
||||
status == "signed"
|
||||
end
|
||||
|
||||
def failed?
|
||||
status == "failed"
|
||||
end
|
||||
|
||||
def expired?
|
||||
status == "expired"
|
||||
end
|
||||
|
||||
def consumed?
|
||||
consumed_at.present?
|
||||
end
|
||||
|
||||
def consume!
|
||||
update!(consumed_at: Time.current)
|
||||
end
|
||||
|
||||
def sign!(event)
|
||||
update!(status: "signed", signed_event: event.to_h.stringify_keys, error: nil)
|
||||
end
|
||||
|
||||
def fail!(message)
|
||||
update(status: "failed", error: message)
|
||||
end
|
||||
|
||||
def expire!
|
||||
update(status: "expired", error: "The signing request expired. Please try again.")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def generate_token
|
||||
self.token ||= self.class.generate_token
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,179 @@
|
||||
require "digest"
|
||||
require "securerandom"
|
||||
|
||||
class NostrSignerSession < ApplicationRecord
|
||||
CONNECT_TTL = 5.minutes
|
||||
CONNECTED_TTL = 1.year
|
||||
FLOWS = %w[settings login].freeze
|
||||
STATUSES = %w[pending verified connected failed expired disconnecting].freeze
|
||||
CONNECTION_METHODS = %w[nostrconnect bunker].freeze
|
||||
HEX_KEY = /\A[0-9a-f]{64}\z/
|
||||
|
||||
belongs_to :user, optional: true
|
||||
|
||||
encrypts :client_private_key
|
||||
serialize :relays, coder: JSON
|
||||
|
||||
attr_accessor :token, :remember_token
|
||||
|
||||
before_validation :generate_token, on: :create
|
||||
|
||||
validates :client_private_key, presence: true
|
||||
validates :client_public_key, presence: true, format: { with: HEX_KEY }
|
||||
validates :challenge, presence: true
|
||||
validates :flow, inclusion: { in: FLOWS }
|
||||
validates :status, inclusion: { in: STATUSES }
|
||||
validates :connection_method, inclusion: { in: CONNECTION_METHODS }
|
||||
validates :token_digest, presence: true, uniqueness: true
|
||||
validates :remember_token_digest, uniqueness: true, allow_nil: true
|
||||
validates :expires_at, presence: true
|
||||
validates :remote_signer_pubkey, format: { with: HEX_KEY }, allow_blank: true
|
||||
validates :user_pubkey, format: { with: HEX_KEY }, allow_blank: true
|
||||
validate :relays_are_valid
|
||||
|
||||
scope :pending, -> { where(status: "pending") }
|
||||
scope :verified, -> { where(status: "verified") }
|
||||
scope :connected, -> { where(status: "connected") }
|
||||
scope :usable, lambda {
|
||||
where(status: %w[verified connected])
|
||||
.or(where(status: "pending").where("expires_at > ?", Time.current))
|
||||
}
|
||||
scope :stale, -> { where("expires_at < ?", Time.current).where(status: %w[pending failed]) }
|
||||
|
||||
def self.find_by_token(raw_token)
|
||||
return nil if raw_token.blank?
|
||||
|
||||
record = find_by(token_digest: Digest::SHA256.hexdigest(raw_token))
|
||||
record.token = raw_token if record
|
||||
record
|
||||
end
|
||||
|
||||
def self.find_by_remember_token(raw_token)
|
||||
return nil if raw_token.blank?
|
||||
|
||||
record = find_by(remember_token_digest: Digest::SHA256.hexdigest(raw_token))
|
||||
record.remember_token = raw_token if record
|
||||
record
|
||||
end
|
||||
|
||||
def self.encryption_available?
|
||||
ENV["ENCRYPTION_PRIMARY_KEY"].present? &&
|
||||
ENV["ENCRYPTION_KEY_DERIVATION_SALT"].present?
|
||||
end
|
||||
|
||||
def pending?
|
||||
status == "pending" && expires_at.present? && expires_at > Time.current
|
||||
end
|
||||
|
||||
def verified?
|
||||
status == "verified"
|
||||
end
|
||||
|
||||
def connected?
|
||||
status == "connected"
|
||||
end
|
||||
|
||||
def failed?
|
||||
status == "failed"
|
||||
end
|
||||
|
||||
def expired?
|
||||
status == "expired"
|
||||
end
|
||||
|
||||
def disconnecting?
|
||||
status == "disconnecting"
|
||||
end
|
||||
|
||||
def usable?
|
||||
verified? || connected? || pending?
|
||||
end
|
||||
|
||||
def continuable?
|
||||
connected? &&
|
||||
user.present? &&
|
||||
user_pubkey.present? &&
|
||||
expires_at.present? &&
|
||||
expires_at > Time.current
|
||||
end
|
||||
|
||||
def remember!
|
||||
raise "Only connected sessions can be remembered" unless connected?
|
||||
|
||||
self.remember_token = SecureRandom.urlsafe_base64(32)
|
||||
update!(
|
||||
remember_token_digest: Digest::SHA256.hexdigest(remember_token),
|
||||
remembered_at: Time.current
|
||||
)
|
||||
remember_token
|
||||
end
|
||||
|
||||
def clear_remember_token!
|
||||
update!(remember_token_digest: nil, remembered_at: nil)
|
||||
end
|
||||
|
||||
def bunker?
|
||||
connection_method == "bunker"
|
||||
end
|
||||
|
||||
def complete_connection!(remote_signer_pubkey:, user_pubkey:)
|
||||
update!(
|
||||
remote_signer_pubkey: remote_signer_pubkey,
|
||||
user_pubkey: user_pubkey,
|
||||
status: "verified",
|
||||
verified_at: Time.current,
|
||||
expires_at: CONNECTED_TTL.from_now,
|
||||
error: nil
|
||||
)
|
||||
end
|
||||
|
||||
def fail!(message)
|
||||
update(status: "failed", error: message)
|
||||
end
|
||||
|
||||
def expire!
|
||||
update(status: "expired", error: "The connection request expired. Please try again.")
|
||||
end
|
||||
|
||||
def client_keypair
|
||||
Nostr::KeyPair.new(
|
||||
private_key: Nostr::PrivateKey.new(client_private_key),
|
||||
public_key: Nostr::PublicKey.new(client_public_key)
|
||||
)
|
||||
end
|
||||
|
||||
def user_pubkey_bech32
|
||||
return nil if user_pubkey.blank?
|
||||
|
||||
Nostr::PublicKey.new(user_pubkey).to_bech32
|
||||
end
|
||||
|
||||
def nostrconnect_uri
|
||||
params = relays.map { |relay| ["relay", relay] }
|
||||
params << ["secret", secret] if secret.present?
|
||||
|
||||
NostrManager::RemoteSigner.client_metadata.each do |key, value|
|
||||
params << [key.to_s, value] if value.present?
|
||||
end
|
||||
|
||||
params << ["perms", NostrManager::RemoteSigner::PERMS]
|
||||
|
||||
"nostrconnect://#{client_public_key}?#{URI.encode_www_form(params)}"
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def generate_token
|
||||
return if token_digest.present?
|
||||
|
||||
self.token = SecureRandom.urlsafe_base64(32)
|
||||
self.token_digest = Digest::SHA256.hexdigest(token)
|
||||
end
|
||||
|
||||
def relays_are_valid
|
||||
list = Array(relays)
|
||||
if list.empty? || !list.all? { |relay| relay.is_a?(String) && relay.match?(%r{\Awss?://}) }
|
||||
errors.add(:relays, "must contain at least one ws:// or wss:// URL")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -35,6 +35,9 @@ class User < ApplicationRecord
|
||||
has_one_attached :nostr_picture
|
||||
has_one_attached :nostr_banner
|
||||
|
||||
has_many :nostr_signer_sessions, dependent: :destroy
|
||||
has_many :nostr_sign_requests, dependent: :destroy
|
||||
|
||||
#
|
||||
# Validations
|
||||
#
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
module LdapManager
|
||||
class SetNostrKey < LdapManagerService
|
||||
# Single entry point for changing an account's Nostr key. Every caller
|
||||
# (browser extension, remote signer connect/replace, removal) goes through
|
||||
# here so step-up authentication can be enforced in one place later.
|
||||
def initialize(user:, pubkey:)
|
||||
@user = user
|
||||
@pubkey = pubkey
|
||||
end
|
||||
|
||||
def call
|
||||
authorize!
|
||||
UpdateNostrKey.call(dn: @user.dn, pubkey: @pubkey)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def authorize!
|
||||
# Reserved for step-up authentication (password / 2FA) on key changes.
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -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
|
||||
@@ -0,0 +1,259 @@
|
||||
require "base64"
|
||||
require "openssl"
|
||||
require "securerandom"
|
||||
|
||||
module NostrManager
|
||||
# NIP-44 v2 encrypted payloads (secp256k1 ECDH + HKDF-SHA256 + ChaCha20 + HMAC-SHA256).
|
||||
class Nip44
|
||||
VERSION = 2
|
||||
SALT = "nip44-v2"
|
||||
MIN_PLAINTEXT_BYTES = 1
|
||||
MAX_PLAINTEXT_BYTES = 1_048_576
|
||||
MIN_PADDED_BYTES = 32
|
||||
EXTENDED_PREFIX_THRESHOLD = 65_536
|
||||
MIN_PAYLOAD_CHARS = 132
|
||||
MIN_DECODED_BYTES = 99
|
||||
|
||||
# secp256k1 field prime and group order (SEC 2, section 2.4.1).
|
||||
FIELD_PRIME = 0xFFFFFFFF_FFFFFFFF_FFFFFFFF_FFFFFFFF_FFFFFFFF_FFFFFFFF_FFFFFFFE_FFFFFC2F
|
||||
GROUP_ORDER = 0xFFFFFFFF_FFFFFFFF_FFFFFFFF_FFFFFFFE_BAAEDCE6_AF48A03B_BFD25E8C_D0364141
|
||||
SECP256K1_OID = "1.3.132.0.10"
|
||||
EC_PUBLIC_KEY_OID = "1.2.840.10045.2.1"
|
||||
GENERATOR_X_HEX = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
|
||||
|
||||
class Error < StandardError; end
|
||||
class DecryptionError < Error; end
|
||||
class UnsupportedTransportError < Error; end
|
||||
|
||||
def self.encrypt(plaintext, private_key_hex, public_key_hex, nonce: nil)
|
||||
new(private_key_hex, public_key_hex).encrypt(plaintext, nonce: nonce)
|
||||
end
|
||||
|
||||
def self.decrypt(payload, private_key_hex, public_key_hex)
|
||||
new(private_key_hex, public_key_hex).decrypt(payload)
|
||||
end
|
||||
|
||||
def self.available?
|
||||
return @available unless @available.nil?
|
||||
|
||||
@available =
|
||||
begin
|
||||
generated = OpenSSL::Cipher.new("chacha20")
|
||||
generated.encrypt
|
||||
generated.key = "0" * 32
|
||||
generated.iv = "0" * 16
|
||||
generated.update("test") + generated.final
|
||||
|
||||
shared = shared_x("0" * 63 + "1", GENERATOR_X_HEX)
|
||||
shared == [GENERATOR_X_HEX].pack("H*")
|
||||
rescue StandardError
|
||||
false
|
||||
end
|
||||
end
|
||||
|
||||
def self.conversation_key(private_key_hex, public_key_hex)
|
||||
conversation_key_for(private_key_hex, public_key_hex)
|
||||
end
|
||||
|
||||
def self.conversation_key_for(private_key_hex, public_key_hex)
|
||||
shared_x(private_key_hex, public_key_hex).then { |shared| hkdf_extract(SALT, shared) }
|
||||
end
|
||||
|
||||
def self.shared_x(private_key_hex, public_key_hex)
|
||||
validate_hex32!(private_key_hex, "private key")
|
||||
validate_hex32!(public_key_hex, "public key")
|
||||
|
||||
scalar = private_key_hex.to_i(16)
|
||||
raise Error, "private key out of range" if scalar.zero? || scalar >= GROUP_ORDER
|
||||
|
||||
x = public_key_hex.to_i(16)
|
||||
raise Error, "public key x out of range" if x.zero? || x >= FIELD_PRIME
|
||||
|
||||
theirs = OpenSSL::PKey.read(public_key_der([public_key_hex].pack("H*")))
|
||||
ours = OpenSSL::PKey.read(private_key_der([private_key_hex].pack("H*")))
|
||||
shared = ours.derive(theirs)
|
||||
raise Error, "unexpected ECDH output length" unless shared.bytesize == 32
|
||||
|
||||
shared
|
||||
rescue OpenSSL::OpenSSLError => e
|
||||
raise Error, "ECDH failed: #{e.message}"
|
||||
end
|
||||
|
||||
def self.hkdf_extract(salt, input_key_material)
|
||||
OpenSSL::HMAC.digest("SHA256", salt, input_key_material)
|
||||
end
|
||||
|
||||
def self.hkdf_expand(pseudo_random_key, info, length)
|
||||
output = +"".b
|
||||
block = +"".b
|
||||
counter = 1
|
||||
|
||||
while output.bytesize < length
|
||||
block = OpenSSL::HMAC.digest("SHA256", pseudo_random_key, block + info + [counter].pack("C"))
|
||||
output << block
|
||||
counter += 1
|
||||
end
|
||||
|
||||
output.byteslice(0, length)
|
||||
end
|
||||
|
||||
def self.public_key_der(x_bytes)
|
||||
OpenSSL::ASN1::Sequence.new(
|
||||
[
|
||||
OpenSSL::ASN1::Sequence.new(
|
||||
[OpenSSL::ASN1::ObjectId.new(EC_PUBLIC_KEY_OID), OpenSSL::ASN1::ObjectId.new(SECP256K1_OID)]
|
||||
),
|
||||
OpenSSL::ASN1::BitString.new("\x02".b + x_bytes)
|
||||
]
|
||||
).to_der
|
||||
end
|
||||
|
||||
def self.private_key_der(d_bytes)
|
||||
OpenSSL::ASN1::Sequence.new(
|
||||
[
|
||||
OpenSSL::ASN1::Integer.new(1),
|
||||
OpenSSL::ASN1::OctetString.new(d_bytes),
|
||||
OpenSSL::ASN1::ObjectId.new(SECP256K1_OID, 0, :EXPLICIT)
|
||||
]
|
||||
).to_der
|
||||
end
|
||||
|
||||
def self.validate_hex32!(value, label)
|
||||
return if value.is_a?(String) && value.match?(/\A[0-9a-fA-F]{64}\z/)
|
||||
|
||||
raise Error, "#{label} must be 64 hex characters"
|
||||
end
|
||||
|
||||
private_class_method :conversation_key_for,
|
||||
:public_key_der, :private_key_der, :validate_hex32!
|
||||
|
||||
def initialize(private_key_hex, public_key_hex)
|
||||
@private_key_hex = private_key_hex
|
||||
@public_key_hex = public_key_hex
|
||||
end
|
||||
|
||||
def encrypt(plaintext, nonce: nil)
|
||||
bytes = plaintext.to_s.dup.force_encoding(Encoding::BINARY)
|
||||
unless bytes.bytesize.between?(MIN_PLAINTEXT_BYTES, MAX_PLAINTEXT_BYTES)
|
||||
raise Error, "plaintext length must be between #{MIN_PLAINTEXT_BYTES} and #{MAX_PLAINTEXT_BYTES} bytes"
|
||||
end
|
||||
|
||||
nonce ||= SecureRandom.random_bytes(32)
|
||||
raise Error, "nonce must be 32 bytes" unless nonce.bytesize == 32
|
||||
chacha_key, chacha_nonce, hmac_key = derive_message_keys(nonce)
|
||||
ciphertext = chacha20(chacha_key, chacha_nonce, pad(bytes))
|
||||
mac = OpenSSL::HMAC.digest("SHA256", hmac_key, nonce + ciphertext)
|
||||
|
||||
Base64.strict_encode64([VERSION].pack("C") + nonce + ciphertext + mac)
|
||||
end
|
||||
|
||||
def decrypt(payload)
|
||||
raise UnsupportedTransportError, "NIP-04 payloads are not supported" if payload.to_s.include?("?iv=")
|
||||
raise DecryptionError, "payload is blank" if payload.nil? || payload.empty?
|
||||
raise DecryptionError, "payload uses an unsupported encoding" if payload.start_with?("#")
|
||||
raise DecryptionError, "payload is too short" if payload.length < MIN_PAYLOAD_CHARS
|
||||
|
||||
raw = decode_payload(payload)
|
||||
version = raw.getbyte(0)
|
||||
raise DecryptionError, "unsupported NIP-44 version: #{version}" unless version == VERSION
|
||||
|
||||
nonce = raw.byteslice(1, 32)
|
||||
mac = raw.byteslice(raw.bytesize - 32, 32)
|
||||
ciphertext = raw.byteslice(33, raw.bytesize - 33 - 32)
|
||||
raise DecryptionError, "ciphertext is too large" if ciphertext.bytesize > (MAX_PLAINTEXT_BYTES * 2) + 64
|
||||
|
||||
chacha_key, chacha_nonce, hmac_key = derive_message_keys(nonce)
|
||||
expected_mac = OpenSSL::HMAC.digest("SHA256", hmac_key, nonce + ciphertext)
|
||||
raise DecryptionError, "MAC verification failed" unless secure_compare(mac, expected_mac)
|
||||
|
||||
unpad(chacha20(chacha_key, chacha_nonce, ciphertext)).force_encoding(Encoding::UTF_8)
|
||||
end
|
||||
|
||||
def conversation_key
|
||||
@conversation_key ||= self.class.conversation_key(@private_key_hex, @public_key_hex)
|
||||
end
|
||||
|
||||
def derive_message_keys(nonce)
|
||||
raise DecryptionError, "nonce must be 32 bytes" unless nonce.is_a?(String) && nonce.bytesize == 32
|
||||
|
||||
keys = self.class.hkdf_expand(conversation_key, nonce, 76)
|
||||
[keys.byteslice(0, 32), keys.byteslice(32, 12), keys.byteslice(44, 32)]
|
||||
end
|
||||
|
||||
def calc_padded_len(length)
|
||||
return MIN_PADDED_BYTES if length <= MIN_PADDED_BYTES
|
||||
|
||||
next_power = 1 << (length - 1).bit_length
|
||||
chunk = next_power <= 256 ? 32 : next_power / 8
|
||||
(((length - 1) / chunk) + 1) * chunk
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def decode_payload(payload)
|
||||
raw = Base64.strict_decode64(payload)
|
||||
raise DecryptionError, "payload is too short" if raw.bytesize < MIN_DECODED_BYTES
|
||||
|
||||
raw
|
||||
rescue ArgumentError
|
||||
raise DecryptionError, "payload is not valid base64"
|
||||
end
|
||||
|
||||
def pad(bytes)
|
||||
length = bytes.bytesize
|
||||
padded_length = calc_padded_len(length)
|
||||
prefix =
|
||||
if length < EXTENDED_PREFIX_THRESHOLD
|
||||
[length].pack("n")
|
||||
else
|
||||
"\x00\x00".b + [length].pack("N")
|
||||
end
|
||||
|
||||
prefix + bytes + ("\x00".b * (padded_length - length))
|
||||
end
|
||||
|
||||
def unpad(padded)
|
||||
raise DecryptionError, "padded data is too short" if padded.bytesize < 2
|
||||
|
||||
first_two = padded.byteslice(0, 2).unpack1("n")
|
||||
if first_two.zero?
|
||||
raise DecryptionError, "extended padding prefix is truncated" if padded.bytesize < 6
|
||||
|
||||
length = padded.byteslice(2, 4).unpack1("N")
|
||||
prefix_length = 6
|
||||
raise DecryptionError, "invalid extended padding length" if length < EXTENDED_PREFIX_THRESHOLD
|
||||
else
|
||||
length = first_two
|
||||
prefix_length = 2
|
||||
raise DecryptionError, "invalid padding length" if length < MIN_PLAINTEXT_BYTES
|
||||
end
|
||||
|
||||
raise DecryptionError, "plaintext is too large" if length > MAX_PLAINTEXT_BYTES
|
||||
|
||||
plaintext = padded.byteslice(prefix_length, length)
|
||||
raise DecryptionError, "padded plaintext is truncated" unless plaintext&.bytesize == length
|
||||
|
||||
expected_total = prefix_length + calc_padded_len(length)
|
||||
raise DecryptionError, "padded length mismatch" unless padded.bytesize == expected_total
|
||||
|
||||
padding = padded.byteslice(prefix_length + length, padded.bytesize - prefix_length - length)
|
||||
raise DecryptionError, "invalid padding bytes" unless padding.bytes.all?(&:zero?)
|
||||
|
||||
plaintext
|
||||
end
|
||||
|
||||
def chacha20(key, nonce, data)
|
||||
cipher = OpenSSL::Cipher.new("chacha20")
|
||||
cipher.encrypt
|
||||
cipher.key = key
|
||||
cipher.iv = [0].pack("V") + nonce
|
||||
cipher.update(data) + cipher.final
|
||||
end
|
||||
|
||||
def secure_compare(left, right)
|
||||
return false unless left.bytesize == right.bytesize
|
||||
|
||||
OpenSSL.fixed_length_secure_compare(left, right)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,34 @@
|
||||
require "json"
|
||||
|
||||
module NostrManager
|
||||
module Relay
|
||||
class Connection
|
||||
attr_reader :url
|
||||
|
||||
def initialize(url:, socket:)
|
||||
@url = url
|
||||
@socket = socket
|
||||
end
|
||||
|
||||
def write_json(message)
|
||||
@socket.write(JSON.generate(message))
|
||||
@socket.flush
|
||||
end
|
||||
|
||||
def read_json
|
||||
message = @socket.read
|
||||
return nil if message.nil?
|
||||
|
||||
JSON.parse(message.to_str)
|
||||
rescue JSON::ParserError
|
||||
nil
|
||||
end
|
||||
|
||||
def close
|
||||
@socket.close
|
||||
rescue StandardError
|
||||
nil
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,176 @@
|
||||
require "async"
|
||||
require "async/http/endpoint"
|
||||
require "async/http/protocol/http11"
|
||||
require "async/queue"
|
||||
require "async/websocket/client"
|
||||
require "securerandom"
|
||||
|
||||
module NostrManager
|
||||
module Relay
|
||||
# Owns one async reactor and one websocket per relay for the duration of a block.
|
||||
class Pool
|
||||
Result = Struct.new(:url, :message, keyword_init: true)
|
||||
|
||||
class TimeoutError < StandardError; end
|
||||
class CancelledError < StandardError; end
|
||||
|
||||
DEFAULT_TIMEOUT = 30
|
||||
DEFAULT_CONNECT_TIMEOUT = 5
|
||||
|
||||
def self.with(relays:, timeout: DEFAULT_TIMEOUT, connect_timeout: DEFAULT_CONNECT_TIMEOUT,
|
||||
logger: Rails.logger, &block)
|
||||
Async do |task|
|
||||
pool = new(relays: relays, task: task, connect_timeout: connect_timeout, logger: logger)
|
||||
begin
|
||||
pool.start
|
||||
task.with_timeout(timeout) { block.call(pool) }
|
||||
ensure
|
||||
pool.close
|
||||
end
|
||||
end.wait
|
||||
rescue Async::TimeoutError
|
||||
raise TimeoutError, "relay operation timed out"
|
||||
end
|
||||
|
||||
def initialize(relays:, task:, connect_timeout: DEFAULT_CONNECT_TIMEOUT, logger: Rails.logger)
|
||||
@relays = Array(relays).map(&:to_s).reject(&:blank?).uniq
|
||||
@task = task
|
||||
@connect_timeout = connect_timeout
|
||||
@logger = logger
|
||||
@connections = {}
|
||||
@subscriptions = {}
|
||||
@inbox = Async::Queue.new
|
||||
@ready_connections = 0
|
||||
@closed = false
|
||||
end
|
||||
|
||||
def start
|
||||
raise ArgumentError, "at least one relay is required" if @relays.empty?
|
||||
|
||||
@tasks = @relays.map { |url| @task.async { run(url) } }
|
||||
self
|
||||
end
|
||||
|
||||
def subscribe(filter, id: SecureRandom.hex(8), wait: true, timeout: @connect_timeout)
|
||||
@subscriptions[id] = filter
|
||||
@connections.each_value { |connection| send_request(connection, ["REQ", id, filter.to_h]) }
|
||||
wait_for_subscription(id, timeout: timeout) if wait
|
||||
id
|
||||
end
|
||||
|
||||
def wait_for_subscription(id, timeout: @connect_timeout)
|
||||
deferred = []
|
||||
|
||||
wait_for(timeout: timeout) do |result|
|
||||
message = result.message
|
||||
if message.is_a?(Array) && message[0] == "EOSE" && message[1] == id
|
||||
true
|
||||
else
|
||||
deferred << result
|
||||
false
|
||||
end
|
||||
end
|
||||
|
||||
true
|
||||
rescue TimeoutError
|
||||
@logger.info "[nostr][relay] no EOSE for subscription #{id} within #{timeout}s"
|
||||
false
|
||||
ensure
|
||||
deferred.reverse_each { |result| @inbox.enqueue(result) } if deferred
|
||||
end
|
||||
|
||||
def unsubscribe(id)
|
||||
@subscriptions.delete(id)
|
||||
@connections.each_value { |connection| send_request(connection, ["CLOSE", id]) }
|
||||
end
|
||||
|
||||
def publish(event)
|
||||
wait_for_connection
|
||||
payload = ["EVENT", event.to_h.transform_keys(&:to_s)]
|
||||
@connections.each_value { |connection| send_request(connection, payload) }
|
||||
true
|
||||
end
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
raise TimeoutError, "timed out waiting for a relay message"
|
||||
end
|
||||
|
||||
def wait_for_connection(timeout: @connect_timeout)
|
||||
deadline = monotonic_now + timeout
|
||||
@task.sleep(0.01) while @ready_connections.zero? && monotonic_now < deadline
|
||||
|
||||
raise TimeoutError, "no relay connection became ready" if @ready_connections.zero?
|
||||
|
||||
true
|
||||
end
|
||||
|
||||
def close
|
||||
return if @closed
|
||||
|
||||
@closed = true
|
||||
@tasks&.each(&:stop)
|
||||
@connections.each_value(&:close)
|
||||
@connections.clear
|
||||
@subscriptions.clear
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def run(url)
|
||||
endpoint = Async::HTTP::Endpoint.parse(
|
||||
url,
|
||||
alpn_protocols: Async::HTTP::Protocol::HTTP11.names
|
||||
)
|
||||
|
||||
Async::WebSocket::Client.connect(endpoint) do |socket|
|
||||
connection = Connection.new(url: url, socket: socket)
|
||||
@connections[url] = connection
|
||||
@subscriptions.each { |id, filter| send_request(connection, ["REQ", id, filter.to_h]) }
|
||||
@ready_connections += 1
|
||||
|
||||
while (message = connection.read_json)
|
||||
@logger.debug "[nostr][relay] #{url} <- #{message[0]}"
|
||||
@inbox.enqueue(Result.new(url: url, message: message))
|
||||
end
|
||||
rescue StandardError => e
|
||||
@logger.info "[nostr][relay] #{url} error: #{e.class}: #{e.message}"
|
||||
ensure
|
||||
@connections.delete(url)
|
||||
end
|
||||
rescue StandardError => e
|
||||
@logger.info "[nostr][relay] #{url} connection failed: #{e.class}: #{e.message}"
|
||||
end
|
||||
|
||||
def send_request(connection, payload)
|
||||
connection.write_json(payload)
|
||||
rescue StandardError => e
|
||||
@logger.info "[nostr][relay] #{connection.url} write failed: #{e.class}: #{e.message}"
|
||||
@connections.delete(connection.url)
|
||||
end
|
||||
|
||||
def monotonic_now
|
||||
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
||||
end
|
||||
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,39 @@
|
||||
module NostrManager
|
||||
module RemoteSigner
|
||||
KIND = 24133
|
||||
AUTH_KIND = 22242
|
||||
ALLOWED_SIGN_KINDS = [0, 10002, 10063, 24242].freeze
|
||||
CLIENT_NAME = "Kosmos Accounts"
|
||||
PERMS = %w[
|
||||
sign_event:0
|
||||
sign_event:10002
|
||||
sign_event:10063
|
||||
sign_event:22242
|
||||
sign_event:24242
|
||||
].join(",")
|
||||
|
||||
def self.client_metadata
|
||||
domain = Setting.accounts_domain.to_s.chomp("/")
|
||||
return {} if domain.blank?
|
||||
|
||||
{
|
||||
name: CLIENT_NAME,
|
||||
url: "https://#{domain}",
|
||||
image: Setting.nostr_client_icon_url.presence
|
||||
}.compact
|
||||
end
|
||||
|
||||
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,205 @@
|
||||
require "json"
|
||||
require "securerandom"
|
||||
|
||||
module NostrManager
|
||||
module RemoteSigner
|
||||
class Client
|
||||
HEX_KEY = /\A[0-9a-f]{64}\z/
|
||||
LIVENESS_TICK = 5
|
||||
|
||||
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, on_tick: nil)
|
||||
@remote_signer_pubkey = remote_signer_pubkey
|
||||
result = request(
|
||||
"connect",
|
||||
[remote_signer_pubkey, secret, perms, metadata.to_json],
|
||||
timeout: timeout,
|
||||
on_tick: on_tick
|
||||
)
|
||||
|
||||
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, on_tick: nil)
|
||||
raise ArgumentError, "a connection secret is required" if secret.blank?
|
||||
|
||||
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
|
||||
|
||||
@remote_signer_pubkey = event["pubkey"]
|
||||
payload["result"]
|
||||
end
|
||||
|
||||
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"
|
||||
end
|
||||
|
||||
result
|
||||
end
|
||||
|
||||
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, on_tick: nil)
|
||||
request("ping", [], timeout: timeout, on_tick: on_tick)
|
||||
end
|
||||
|
||||
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, 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, 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://")
|
||||
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, on_tick: nil)
|
||||
match = nil
|
||||
|
||||
@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?
|
||||
|
||||
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,41 @@
|
||||
module NostrManager
|
||||
module RemoteSigner
|
||||
class Disconnect < ApplicationService
|
||||
def initialize(session:)
|
||||
@session = session
|
||||
end
|
||||
|
||||
def call
|
||||
return false if @session.remote_signer_pubkey.blank? || Array(@session.relays).empty?
|
||||
|
||||
NostrManager::Relay::Pool.with(
|
||||
relays: @session.relays,
|
||||
timeout: 20,
|
||||
connect_timeout: 5
|
||||
) 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.logout(timeout: 10)
|
||||
end
|
||||
|
||||
true
|
||||
rescue StandardError => e
|
||||
Rails.logger.info("[nostr][signer] logout failed: #{e.class}: #{e.message}")
|
||||
false
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,23 @@
|
||||
module NostrManager
|
||||
module RemoteSigner
|
||||
class DisconnectSessions < ApplicationService
|
||||
def initialize(sessions:)
|
||||
@sessions = sessions
|
||||
end
|
||||
|
||||
def call
|
||||
@sessions.each do |session|
|
||||
next if session.nil? || session.disconnecting?
|
||||
|
||||
if session.remote_signer_pubkey.present? && session.verified_at.present?
|
||||
session.update!(status: "disconnecting")
|
||||
session.clear_remember_token!
|
||||
NostrLogoutJob.perform_later(session.id)
|
||||
else
|
||||
session.destroy!
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,116 @@
|
||||
module NostrManager
|
||||
module RemoteSigner
|
||||
class ListenForConnection < ApplicationService
|
||||
LISTENER_POLL_GRACE = 60.seconds
|
||||
|
||||
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
|
||||
on_tick = method(:listener_still_wanted?)
|
||||
|
||||
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,
|
||||
on_tick: on_tick
|
||||
)
|
||||
else
|
||||
client.await_nostrconnect(secret: @session.secret, timeout: timeout, on_tick: on_tick)
|
||||
end
|
||||
|
||||
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_tick: on_tick
|
||||
)
|
||||
|
||||
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::CancelledError
|
||||
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 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
|
||||
|
||||
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
|
||||
NostrManager::RemoteSigner.client_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
|
||||
@@ -60,4 +60,24 @@
|
||||
class: "h-44 w-80" %>
|
||||
<% end %>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h3>Nostr Connect (NIP-46)</h3>
|
||||
<ul role="list">
|
||||
<%= render FormElements::FieldsetComponent.new(
|
||||
title: "Signer relays",
|
||||
description: "Relays used to exchange NIP-46 connection and signing messages. One URL per line."
|
||||
) do %>
|
||||
<%= f.text_area :nostr_signer_relays,
|
||||
value: Setting.nostr_signer_relays.join("\n"),
|
||||
class: "h-32 w-80" %>
|
||||
<% end %>
|
||||
<%= render FormElements::FieldsetResettableSettingComponent.new(
|
||||
key: :nostr_client_icon_url,
|
||||
title: "Client icon URL",
|
||||
description: "Small square image shown in Nostr Connect prompts"
|
||||
) %>
|
||||
</ul>
|
||||
</section>
|
||||
<% end %>
|
||||
@@ -0,0 +1,27 @@
|
||||
<%= render HeaderCompactComponent.new(title: "Log in") %>
|
||||
|
||||
<%= render MainCompactComponent.new do %>
|
||||
<h2 class="mb-2 text-xl font-bold text-gray-900">
|
||||
Continue as <%= @nostr_remembered_user.address %>
|
||||
</h2>
|
||||
<p class="mb-8 text-gray-600">
|
||||
Your remote signer is still connected on this device.
|
||||
</p>
|
||||
|
||||
<div class="flex flex-col gap-3">
|
||||
<%= button_to "Continue", nostr_continue_path,
|
||||
method: :post, class: "btn-md btn-blue w-full" %>
|
||||
<%= button_to "Log in as a different account", different_account_nostr_continue_path,
|
||||
method: :post, class: "btn-md btn-gray w-full",
|
||||
data: { turbo_confirm: "This will disconnect your remote signer from this account. Continue?" } %>
|
||||
</div>
|
||||
|
||||
<p class="mt-6 mb-0 text-sm text-gray-600">
|
||||
Logging out normally keeps this device remembered. Use “different account” to disconnect the remote signer.
|
||||
</p>
|
||||
|
||||
<p class="mt-6 mb-0 text-sm">
|
||||
<%= link_to "Use username and password", new_user_session_path(password: 1),
|
||||
class: "text-gray-500 underline" %>
|
||||
</p>
|
||||
<% end %>
|
||||
@@ -56,26 +56,18 @@
|
||||
</p>
|
||||
<% end %>
|
||||
|
||||
<div data-controller="nostr-login"
|
||||
data-nostr-login-target="loginForm"
|
||||
data-nostr-login-site-value="<%= Setting.accounts_domain %>"
|
||||
data-nostr-login-shared-secret-value="<%= session[:shared_secret] %>"
|
||||
class="hidden">
|
||||
<div class="relative my-6">
|
||||
<div class="absolute inset-0 flex items-center" aria-hidden="true">
|
||||
<div class="w-full border-t border-gray-200"></div>
|
||||
</div>
|
||||
<div class="relative flex justify-center">
|
||||
<span class="bg-white px-2 text-sm text-gray-500 italic">or</span>
|
||||
</div>
|
||||
</div>
|
||||
<p>
|
||||
<button disabled tabindex="5"
|
||||
class="w-full btn-md btn-gray text-purple-600"
|
||||
data-nostr-login-target="loginButton"
|
||||
data-action="nostr-login#login">
|
||||
Log in with Nostr
|
||||
</button>
|
||||
<%= render NostrLoginComponent.new(
|
||||
nostr_available: nostr_remote_signer_available?,
|
||||
remembered_user: @nostr_remembered_user,
|
||||
site: Setting.accounts_domain,
|
||||
shared_secret: session[:shared_secret],
|
||||
connect_path: nostr_connect_path
|
||||
) %>
|
||||
|
||||
<% if @nostr_remembered_user.present? %>
|
||||
<p class="mt-6 mb-0 text-sm">
|
||||
<%= link_to "Back to continue as #{@nostr_remembered_user.address}",
|
||||
new_user_session_path, class: "text-gray-500 underline" %>
|
||||
</p>
|
||||
</div>
|
||||
<% end %>
|
||||
<% end %>
|
||||
@@ -1,5 +1,5 @@
|
||||
<!DOCTYPE html>
|
||||
<html class="h-full">
|
||||
<html class="h-full" data-remote-signer="<%= active_nostr_signer_session.present? %>">
|
||||
<head>
|
||||
<title>Kosmos Accounts</title>
|
||||
<%= csrf_meta_tags %>
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
data-settings--nostr-pubkey-user-address-value="<%= current_user.address %>"
|
||||
data-settings--nostr-pubkey-site-value="<%= Setting.accounts_domain %>"
|
||||
data-settings--nostr-pubkey-shared-secret-value="<%= session[:shared_secret] %>"
|
||||
data-settings--nostr-pubkey-pubkey-hex-value="<%= current_user.nostr_pubkey %>">
|
||||
data-settings--nostr-pubkey-pubkey-hex-value="<%= current_user.nostr_pubkey %>"
|
||||
data-remote-signer="<%= active_nostr_signer_session.present? %>">
|
||||
<section class="mb-8 sm:mb-12">
|
||||
<h3>Nostr</h3>
|
||||
<h4 class="mb-0">
|
||||
@@ -10,11 +11,11 @@
|
||||
</h4>
|
||||
<p class="<%= current_user.nostr_pubkey.present? ? '' : 'hidden' %> mt-2 flex gap-x-1">
|
||||
<input type="text" value="<%= current_user.nostr_pubkey_bech32 %>" disabled
|
||||
data-settings--nostr-pubkey-target="pubkeyBech32Input"
|
||||
name="nostr_public_key" class="w-full" />
|
||||
<%= link_to nostr_pubkey_settings_path,
|
||||
class: 'btn-md btn-outline relative grow-0 shrink-0 text-red-700',
|
||||
data: { turbo_method: :delete, turbo_confirm: 'Are you sure?' } do %>
|
||||
class: 'btn-md btn-outline relative flex items-center justify-center grow-0 shrink-0 text-red-700',
|
||||
data: { turbo_method: :delete,
|
||||
turbo_confirm: 'Remove your Nostr public key? Any connected remote signer will be disconnected.' } do %>
|
||||
Remove
|
||||
<% end %>
|
||||
</p>
|
||||
@@ -37,54 +38,16 @@
|
||||
<% if Setting.nostr_relay_url.present? %>
|
||||
<li>Publish notes and other stuff on our Nostr relay</li>
|
||||
<% end %>
|
||||
<% if Setting.nostr_blossom_server_url.present? %>
|
||||
<% if Setting.nostr_media_servers_enabled? %>
|
||||
<li>Publish media files on our Nostr media server</li>
|
||||
<% end %>
|
||||
</ul>
|
||||
<% end %>
|
||||
|
||||
<div data-settings--nostr-pubkey-target="noExtension"
|
||||
class="hidden rounded-md bg-blue-50 p-4">
|
||||
<div class="flex">
|
||||
<div class="flex-shrink-0">
|
||||
<svg class="h-5 w-5 text-blue-400" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
|
||||
<path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z" clip-rule="evenodd" />
|
||||
</svg>
|
||||
</div>
|
||||
<div class="ml-3">
|
||||
<h3 class="mb-0 text-sm font-bold text-blue-800">
|
||||
No browser extension found
|
||||
</h3>
|
||||
<div class="mt-2 mb-0 text-sm text-blue-800">
|
||||
<p>
|
||||
We recommend Alby, which you can also use a wallet for your
|
||||
Lightning account.
|
||||
</p>
|
||||
</div>
|
||||
<div class="mt-4">
|
||||
<div class="-mx-2 -my-1.5 flex">
|
||||
<a href="https://getalby.com" target="_blank"
|
||||
class="rounded-md bg-blue-50 px-2 py-1.5 text-sm
|
||||
font-bold text-blue-800 hover:bg-blue-100
|
||||
focus:outline-none focus:ring-2 focus:ring-blue-600
|
||||
focus:ring-offset-2 focus:ring-offset-blue-50">
|
||||
Get Alby
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<% unless current_user.nostr_pubkey.present? %>
|
||||
<p class="mt-8">
|
||||
<button class="btn-md btn-gray w-full sm:w-auto" disabled
|
||||
data-settings--nostr-pubkey-target="setPubkey"
|
||||
data-action="settings--nostr-pubkey#setPubkey">
|
||||
Get public key from browser extension
|
||||
</button>
|
||||
<p class="text-gray-500">
|
||||
Choose how to connect:
|
||||
</p>
|
||||
<% end %>
|
||||
|
||||
<%= render "nostr_signer" %>
|
||||
</section>
|
||||
|
||||
<% if current_user.nostr_pubkey.present? %>
|
||||
@@ -92,8 +55,8 @@
|
||||
data-nostr-metadata-url-value="<%= nostr_metadata_settings_path %>"
|
||||
data-action="nostr:publish->nostr-metadata#refresh">
|
||||
<div data-nostr-metadata-target="loading"
|
||||
class="flex flex-col items-center justify-center py-16">
|
||||
<div class="mb-4 h-12 w-12"></div>
|
||||
class="flex flex-col items-center justify-center pt-0 pb-0">
|
||||
<%= image_tag "/img/illustrations/relay_constellation.svg", class: "mb-6 h-48 w-auto", alt: "" %>
|
||||
<h3>Just a moment...</h3>
|
||||
<p data-nostr-metadata-target="status"
|
||||
class="text-gray-500 animate-pulse">Loading</p>
|
||||
|
||||
@@ -24,9 +24,11 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<% if Setting.nostr_media_servers_enabled? %>
|
||||
<section class="mb-8 sm:mb-12">
|
||||
<h3>Media servers</h3>
|
||||
<%= render Settings::NostrMediaServerStatusComponent.new(
|
||||
media_list_event: @media_list
|
||||
) %>
|
||||
</section>
|
||||
<% end %>
|
||||
@@ -0,0 +1,65 @@
|
||||
<div id="nostr-signer-section"
|
||||
data-controller="nostr-signer-status"
|
||||
data-nostr-signer-status-connected-value="<%= active_nostr_signer_session.present? %>">
|
||||
<% if nostr_remote_signer_available? && @pending_signer_session.present? %>
|
||||
<div data-controller="modal"
|
||||
data-modal-open-value="true"
|
||||
data-action="turbo:load->modal#open">
|
||||
<%= render ModalComponent.new(
|
||||
show_close_button: false,
|
||||
dismissible: false,
|
||||
card_class: "w-96 max-w-[85vw]"
|
||||
) do %>
|
||||
<%= render NostrSignerConnectComponent.new(
|
||||
pending_session: @pending_signer_session,
|
||||
create_url: nostr_signer_settings_path,
|
||||
destroy_url: nostr_signer_settings_path,
|
||||
status_url: nostr_signer_status_settings_path(token: @pending_signer_session.token),
|
||||
replace_url: nostr_signer_replace_settings_path(token: @pending_signer_session.token),
|
||||
title: "Nostr Connect",
|
||||
modal: true,
|
||||
section_url: nostr_signer_section_settings_path
|
||||
) %>
|
||||
<% end %>
|
||||
</div>
|
||||
<% elsif current_user.nostr_pubkey.present? %>
|
||||
<% if nostr_remote_signer_available? %>
|
||||
<%= render NostrSignerConnectComponent.new(
|
||||
active_session: active_nostr_signer_session,
|
||||
create_url: nostr_signer_settings_path,
|
||||
destroy_url: nostr_signer_settings_path,
|
||||
collapsible: true
|
||||
) %>
|
||||
<% end %>
|
||||
<% else %>
|
||||
<div class="mt-8 flex flex-col gap-8 sm:flex-row">
|
||||
<div class="flex-1">
|
||||
<h4 class="mb-0">Browser extension</h4>
|
||||
<p class="mt-3 hidden" data-settings--nostr-pubkey-target="extensionDescription">
|
||||
Use a Nostr-signing browser extension, like Alby or nos2x
|
||||
</p>
|
||||
<p class="mt-3" data-settings--nostr-pubkey-target="extensionUnavailable">
|
||||
No browser extension detected. Install a Nostr signer like Alby to use this option.
|
||||
</p>
|
||||
<div class="mt-4">
|
||||
<button class="btn-md btn-gray w-full sm:w-auto" disabled
|
||||
data-settings--nostr-pubkey-target="setPubkey"
|
||||
data-action="settings--nostr-pubkey#setPubkey">
|
||||
Connect browser extension
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<% if nostr_remote_signer_available? %>
|
||||
<div class="flex-1">
|
||||
<%= render NostrSignerConnectComponent.new(
|
||||
active_session: active_nostr_signer_session,
|
||||
create_url: nostr_signer_settings_path,
|
||||
destroy_url: nostr_signer_settings_path,
|
||||
flush: true
|
||||
) %>
|
||||
</div>
|
||||
<% end %>
|
||||
</div>
|
||||
<% end %>
|
||||
</div>
|
||||
@@ -0,0 +1,24 @@
|
||||
<%= render HeaderCompactComponent.new(title: "Log in") %>
|
||||
|
||||
<%= render MainCompactComponent.new do %>
|
||||
<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
|
||||
connection URL to use a signer on another device.
|
||||
</p>
|
||||
|
||||
<%= render NostrSignerConnectComponent.new(
|
||||
pending_session: @signer_session,
|
||||
create_url: nostr_connect_path,
|
||||
status_url: nostr_connect_status_path,
|
||||
title: nil,
|
||||
show_disconnect: false
|
||||
) %>
|
||||
|
||||
<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" %>
|
||||
<%= button_to "Start over", restart_nostr_connect_path, method: :post,
|
||||
form_class: "inline", class: "text-gray-500 underline" %>
|
||||
</div>
|
||||
<% end %>
|
||||
@@ -0,0 +1,26 @@
|
||||
<%= render HeaderCompactComponent.new(title: "Log in") %>
|
||||
|
||||
<%= render MainCompactComponent.new do %>
|
||||
<div data-controller="nostr-continue"
|
||||
data-nostr-continue-status-url-value="<%= nostr_continue_status_path %>">
|
||||
<h2 class="mb-2 text-xl font-bold text-gray-900">
|
||||
Continue as <%= @nostr_remembered_user.address %>
|
||||
</h2>
|
||||
|
||||
<p class="text-gray-700" data-nostr-continue-target="status">
|
||||
Check your signer app to approve the login…
|
||||
</p>
|
||||
|
||||
<p class="mt-4 hidden text-sm text-red-700" data-nostr-continue-target="error"></p>
|
||||
|
||||
<div class="mt-8">
|
||||
<%= button_to "Use a different account", different_account_nostr_continue_path,
|
||||
method: :post, class: "btn-md btn-gray w-full",
|
||||
data: { turbo_confirm: "This will disconnect your remote signer from this account. Continue?" } %>
|
||||
</div>
|
||||
|
||||
<p class="mt-6 text-sm">
|
||||
<%= link_to "Back to login", new_user_session_path, class: "text-gray-500 underline" %>
|
||||
</p>
|
||||
</div>
|
||||
<% 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
|
||||
+20
-2
@@ -3,16 +3,34 @@ 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
|
||||
# NIP-46 signing round-trips block up to 90s, so keep them off the
|
||||
# long-blocking listener pool below.
|
||||
- queues: [nostr_rpc]
|
||||
threads: <%= ENV.fetch("NOSTR_RPC_THREADS", 4) %>
|
||||
processes: 1
|
||||
polling_interval: 0.1
|
||||
# NostrConnectListenerJob holds a worker thread for up to
|
||||
# NostrSignerSession::CONNECT_TTL (5 min) waiting on relay websockets
|
||||
# (it aborts within ~60s once the browser stops polling status). These
|
||||
# are IO-blocked, so scale with cheap threads rather than processes.
|
||||
- queues: [nostr_connect]
|
||||
threads: <%= ENV.fetch("NOSTR_CONNECT_THREADS", 24) %>
|
||||
processes: <%= ENV.fetch("NOSTR_CONNECT_CONCURRENCY", 1) %>
|
||||
polling_interval: 0.1
|
||||
|
||||
development:
|
||||
<<: *default
|
||||
workers:
|
||||
- queues: "*"
|
||||
- queues: [default, nostr]
|
||||
threads: 1
|
||||
- queues: [nostr_rpc]
|
||||
threads: 2
|
||||
- queues: [nostr_connect]
|
||||
threads: 4
|
||||
|
||||
test:
|
||||
<<: *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
|
||||
@@ -6,6 +6,16 @@ Rails.application.routes.draw do
|
||||
|
||||
devise_scope :user do
|
||||
post 'users/nostr_login', to: 'users/sessions#nostr_login'
|
||||
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
|
||||
get 'users/nostr_continue/status', to: 'users/nostr_continues#status', as: :nostr_continue_status
|
||||
post 'users/nostr_continue/different_account', to: 'users/nostr_continues#different_account',
|
||||
as: :different_account_nostr_continue
|
||||
end
|
||||
|
||||
get 'welcome', to: 'welcome#index'
|
||||
@@ -67,6 +77,13 @@ Rails.application.routes.draw do
|
||||
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
|
||||
post 'nostr_signer', to: 'settings/nostr_signers#create', as: :nostr_signer
|
||||
get 'nostr_signer/status', to: 'settings/nostr_signers#status', as: :nostr_signer_status
|
||||
get 'nostr_signer/section', to: 'settings/nostr_signers#section', as: :nostr_signer_section
|
||||
post 'nostr_signer/replace', to: 'settings/nostr_signers#replace', as: :nostr_signer_replace
|
||||
delete 'nostr_signer', to: 'settings/nostr_signers#destroy'
|
||||
post 'nostr_sign', to: 'settings/nostr_signatures#create', as: :nostr_sign
|
||||
get 'nostr_sign/:token', to: 'settings/nostr_signatures#show', as: :nostr_sign_status
|
||||
post 'nostr_media', to: 'settings/nostr_media#create', as: :nostr_media
|
||||
post 'nostr_profile_images', to: 'settings/nostr_profile_images#create', as: :nostr_profile_images
|
||||
get 'nostr_profile_images/:field', to: 'settings/nostr_profile_images#show', as: :nostr_profile_image
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
class CreateNostrSignerSessions < ActiveRecord::Migration[8.1]
|
||||
def change
|
||||
create_table :nostr_signer_sessions do |t|
|
||||
t.references :user, null: true, foreign_key: true
|
||||
t.string :token_digest, null: false
|
||||
t.text :client_private_key, null: false
|
||||
t.string :client_public_key, null: false
|
||||
t.string :secret
|
||||
t.string :challenge, null: false
|
||||
t.string :remote_signer_pubkey
|
||||
t.string :user_pubkey
|
||||
t.text :relays, null: false, default: [].to_json
|
||||
t.string :encryption, null: false, default: "nip44"
|
||||
t.string :connection_method, null: false, default: "nostrconnect"
|
||||
t.string :flow, null: false
|
||||
t.string :status, null: false, default: "pending"
|
||||
t.string :error
|
||||
t.string :auth_url
|
||||
t.datetime :listener_started_at
|
||||
t.datetime :last_status_poll_at
|
||||
t.datetime :consumed_at
|
||||
t.datetime :expires_at, null: false
|
||||
t.datetime :verified_at
|
||||
t.datetime :last_used_at
|
||||
|
||||
t.timestamps
|
||||
end
|
||||
|
||||
add_index :nostr_signer_sessions, :token_digest, unique: true
|
||||
add_index :nostr_signer_sessions, [:user_id, :status]
|
||||
add_index :nostr_signer_sessions, [:status, :expires_at]
|
||||
add_index :nostr_signer_sessions, :user_id, unique: true,
|
||||
where: "user_id IS NOT NULL AND status IN ('pending', 'verified', 'connected')",
|
||||
name: "index_nostr_signer_sessions_on_active_user"
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,20 @@
|
||||
class CreateNostrSignRequests < ActiveRecord::Migration[8.1]
|
||||
def change
|
||||
create_table :nostr_sign_requests do |t|
|
||||
t.references :user, null: false, foreign_key: true
|
||||
t.string :token, null: false
|
||||
t.integer :kind, null: false
|
||||
t.text :template, null: false
|
||||
t.text :signed_event
|
||||
t.string :status, null: false, default: "pending"
|
||||
t.string :error
|
||||
t.datetime :expires_at, null: false
|
||||
|
||||
t.timestamps
|
||||
end
|
||||
|
||||
add_index :nostr_sign_requests, :token, unique: true
|
||||
add_index :nostr_sign_requests, [:user_id, :status]
|
||||
add_index :nostr_sign_requests, [:status, :expires_at]
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,11 @@
|
||||
class AddNostrRememberTokens < ActiveRecord::Migration[8.1]
|
||||
def change
|
||||
add_column :nostr_signer_sessions, :remember_token_digest, :string
|
||||
add_column :nostr_signer_sessions, :remembered_at, :datetime
|
||||
add_index :nostr_signer_sessions, :remember_token_digest, unique: true
|
||||
|
||||
add_column :nostr_sign_requests, :purpose, :string, null: false, default: "sign"
|
||||
add_column :nostr_sign_requests, :consumed_at, :datetime
|
||||
add_index :nostr_sign_requests, [:user_id, :purpose, :status]
|
||||
end
|
||||
end
|
||||
+57
-1
@@ -10,7 +10,7 @@
|
||||
#
|
||||
# It's strongly recommended that you check this file into your version control system.
|
||||
|
||||
ActiveRecord::Schema[8.1].define(version: 2026_11_04_120000) do
|
||||
ActiveRecord::Schema[8.1].define(version: 2026_11_25_120000) do
|
||||
create_table "active_storage_attachments", force: :cascade do |t|
|
||||
t.bigint "blob_id", null: false
|
||||
t.datetime "created_at", null: false
|
||||
@@ -101,6 +101,60 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_04_120000) do
|
||||
t.index ["user_id"], name: "index_invitations_on_user_id"
|
||||
end
|
||||
|
||||
create_table "nostr_sign_requests", force: :cascade do |t|
|
||||
t.datetime "consumed_at"
|
||||
t.datetime "created_at", null: false
|
||||
t.string "error"
|
||||
t.datetime "expires_at", null: false
|
||||
t.integer "kind", null: false
|
||||
t.string "purpose", default: "sign", null: false
|
||||
t.text "signed_event"
|
||||
t.string "status", default: "pending", null: false
|
||||
t.text "template", null: false
|
||||
t.string "token", null: false
|
||||
t.datetime "updated_at", null: false
|
||||
t.integer "user_id", null: false
|
||||
t.index ["status", "expires_at"], name: "index_nostr_sign_requests_on_status_and_expires_at"
|
||||
t.index ["token"], name: "index_nostr_sign_requests_on_token", unique: true
|
||||
t.index ["user_id", "purpose", "status"], name: "index_nostr_sign_requests_on_user_id_and_purpose_and_status"
|
||||
t.index ["user_id", "status"], name: "index_nostr_sign_requests_on_user_id_and_status"
|
||||
t.index ["user_id"], name: "index_nostr_sign_requests_on_user_id"
|
||||
end
|
||||
|
||||
create_table "nostr_signer_sessions", force: :cascade do |t|
|
||||
t.string "auth_url"
|
||||
t.string "challenge", null: false
|
||||
t.text "client_private_key", null: false
|
||||
t.string "client_public_key", null: false
|
||||
t.string "connection_method", default: "nostrconnect", null: false
|
||||
t.datetime "consumed_at"
|
||||
t.datetime "created_at", null: false
|
||||
t.string "encryption", default: "nip44", null: false
|
||||
t.string "error"
|
||||
t.datetime "expires_at", null: false
|
||||
t.string "flow", null: false
|
||||
t.datetime "last_status_poll_at"
|
||||
t.datetime "last_used_at"
|
||||
t.datetime "listener_started_at"
|
||||
t.text "relays", default: "[]", null: false
|
||||
t.string "remember_token_digest"
|
||||
t.datetime "remembered_at"
|
||||
t.string "remote_signer_pubkey"
|
||||
t.string "secret"
|
||||
t.string "status", default: "pending", null: false
|
||||
t.string "token_digest", null: false
|
||||
t.datetime "updated_at", null: false
|
||||
t.integer "user_id"
|
||||
t.string "user_pubkey"
|
||||
t.datetime "verified_at"
|
||||
t.index ["remember_token_digest"], name: "index_nostr_signer_sessions_on_remember_token_digest", unique: true
|
||||
t.index ["status", "expires_at"], name: "index_nostr_signer_sessions_on_status_and_expires_at"
|
||||
t.index ["token_digest"], name: "index_nostr_signer_sessions_on_token_digest", unique: true
|
||||
t.index ["user_id", "status"], name: "index_nostr_signer_sessions_on_user_id_and_status"
|
||||
t.index ["user_id"], name: "index_nostr_signer_sessions_on_active_user", unique: true, where: "user_id IS NOT NULL AND status IN ('pending', 'verified', 'connected')"
|
||||
t.index ["user_id"], name: "index_nostr_signer_sessions_on_user_id"
|
||||
end
|
||||
|
||||
create_table "remote_storage_authorizations", force: :cascade do |t|
|
||||
t.string "app_name"
|
||||
t.string "client_id"
|
||||
@@ -182,6 +236,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_04_120000) do
|
||||
|
||||
add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id"
|
||||
add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id"
|
||||
add_foreign_key "nostr_sign_requests", "users"
|
||||
add_foreign_key "nostr_signer_sessions", "users"
|
||||
add_foreign_key "remote_storage_authorizations", "app_catalog_web_apps", column: "web_app_id"
|
||||
add_foreign_key "remote_storage_authorizations", "users"
|
||||
add_foreign_key "rs_authorization_codes", "users"
|
||||
|
||||
@@ -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,46 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="118" viewBox="0 10 200 118">
|
||||
<style>
|
||||
.query { stroke-dasharray: 13 100; stroke-dashoffset: 16; opacity: 0; animation: constellation-query 3.6s linear infinite; }
|
||||
.reply { stroke-dasharray: 18 100; stroke-dashoffset: 21; opacity: 0; animation: constellation-reply 3.6s linear infinite; }
|
||||
.relay-halo { transform-box: fill-box; transform-origin: center; animation: constellation-relay 3.6s ease-out infinite; }
|
||||
@keyframes constellation-query {
|
||||
0% { opacity: 0; stroke-dashoffset: 16; }
|
||||
6% { opacity: 1; }
|
||||
31% { opacity: 1; stroke-dashoffset: -100; }
|
||||
33%, 100% { opacity: 0; stroke-dashoffset: -116; }
|
||||
}
|
||||
@keyframes constellation-reply {
|
||||
0%, 34% { opacity: 0; stroke-dashoffset: 21; }
|
||||
41% { opacity: 1; }
|
||||
71% { opacity: 1; stroke-dashoffset: -100; }
|
||||
73%, 100% { opacity: 0; stroke-dashoffset: -121; }
|
||||
}
|
||||
@keyframes constellation-relay {
|
||||
0%, 24%, 55%, 100% { opacity: 0; transform: scale(.6); }
|
||||
33% { opacity: .9; transform: scale(1); }
|
||||
50% { opacity: 0; transform: scale(1.55); }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.query, .reply, .relay-halo { animation: none; }
|
||||
}
|
||||
</style>
|
||||
<g fill="none" stroke-linecap="round" stroke-linejoin="round">
|
||||
<ellipse cx="100" cy="68" rx="84" ry="47" transform="rotate(-15 100 68)" stroke="#eee9f8" stroke-dasharray="2 5"/>
|
||||
<path d="M28 86 51 37 132 21 171 53 153 106 74 117Z M51 37 74 117 M132 21 153 106 M28 86 153 106" stroke="#e0d6f2" stroke-width="1.15"/>
|
||||
<path d="M100 68 51 37 M100 68 171 53 M100 68 74 117" stroke="#c9b6e9" stroke-width="1.5"/>
|
||||
<path class="query" d="M100 68 51 37" pathLength="100" stroke="#8750ce" stroke-width="2.6"/>
|
||||
<path class="query" d="M100 68 171 53" pathLength="100" stroke="#8750ce" stroke-width="2.6" style="animation-delay:.16s"/>
|
||||
<path class="query" d="M100 68 74 117" pathLength="100" stroke="#8750ce" stroke-width="2.6" style="animation-delay:.32s"/>
|
||||
<path class="reply" d="M171 53 100 68" pathLength="100" stroke="#159a8c" stroke-width="3.2"/>
|
||||
<circle class="relay-halo" cx="171" cy="53" r="9" stroke="#159a8c" opacity="0"/>
|
||||
</g>
|
||||
<g fill="#fff" stroke="#ae96d3" stroke-width="1.65">
|
||||
<circle cx="28" cy="86" r="4.5"/><circle cx="51" cy="37" r="5.5"/>
|
||||
<circle cx="132" cy="21" r="4.5"/><circle cx="153" cy="106" r="5"/>
|
||||
<circle cx="74" cy="117" r="5"/>
|
||||
</g>
|
||||
<circle cx="171" cy="53" r="5.5" fill="#e0f8f3" stroke="#159a8c" stroke-width="1.65"/>
|
||||
<circle cx="100" cy="68" r="22" fill="#f1e9fc"/>
|
||||
<circle cx="100" cy="68" r="17.5" fill="#7844ba"/>
|
||||
<path d="M99 67 a4.4 4.4 0 1 0 -6.2 0 a4.4 4.4 0 0 0 6.2 0L106 74m-1.9-2 2.2-2.2m-4.3.1 2.1-2.1" fill="none" stroke="#fff" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.8 KiB |
@@ -0,0 +1,18 @@
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe ModalComponent, type: :component do
|
||||
it "dismisses on background click by default" do
|
||||
rendered = render_inline(described_class.new) { "Body" }
|
||||
|
||||
background = rendered.css("[data-modal-target='background']").first
|
||||
expect(background["data-action"]).to eq("click->modal#closeBackground")
|
||||
end
|
||||
|
||||
it "can disable background dismissal" do
|
||||
rendered = render_inline(described_class.new(dismissible: false, card_class: "w-80")) { "Body" }
|
||||
|
||||
background = rendered.css("[data-modal-target='background']").first
|
||||
expect(background["data-action"]).to be_nil
|
||||
expect(rendered.css(".w-80").any?).to be(true)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,81 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe NostrLoginComponent, type: :component do
|
||||
let(:base_args) do
|
||||
{
|
||||
nostr_available: true,
|
||||
remembered_user: nil,
|
||||
site: "accounts.example.com",
|
||||
shared_secret: "shared-secret",
|
||||
connect_path: "/users/nostr_connect"
|
||||
}
|
||||
end
|
||||
|
||||
def render_component(**overrides)
|
||||
render_inline(described_class.new(**base_args.merge(overrides)))
|
||||
end
|
||||
|
||||
it "renders one Nostr button and the login options modal" do
|
||||
rendered = render_component
|
||||
|
||||
expect(rendered.text).to include("Log in with Nostr")
|
||||
expect(rendered.text).to include("This only works if your account already has a key linked")
|
||||
expect(rendered.text).to include("Nostr Connect")
|
||||
expect(rendered.text).to include("Browser extension")
|
||||
expect(rendered.text).to include("Use a Nostr-signing browser extension")
|
||||
expect(rendered.text).to include("Use a mobile or desktop signer app, like Amber or Regent")
|
||||
expect(rendered.text).to include("Cancel")
|
||||
expect(rendered.css("a[href='/users/nostr_connect']").any?).to be(true)
|
||||
end
|
||||
|
||||
it "does not underline the Nostr Connect option on hover" do
|
||||
rendered = render_component
|
||||
|
||||
link = rendered.css("a[href='/users/nostr_connect']").first
|
||||
expect(link["class"]).to include("no-underline", "hover:no-underline")
|
||||
end
|
||||
|
||||
it "renders the extension option disabled with its description when no extension is detected" do
|
||||
rendered = render_component
|
||||
|
||||
extension = rendered.css("[data-nostr-login-target='extensionOption']").first
|
||||
expect(extension["class"]).not_to include("hidden")
|
||||
expect(extension["class"]).to include("disabled:cursor-not-allowed")
|
||||
expect(extension["class"]).not_to include("disabled:opacity-60")
|
||||
expect(extension["disabled"]).not_to be_nil
|
||||
|
||||
unavailable = rendered.css("[data-nostr-login-target='extensionUnavailable']").first
|
||||
expect(unavailable.text).to include("No browser extension detected")
|
||||
expect(unavailable["class"]).not_to include("hidden")
|
||||
|
||||
description = rendered.css("[data-nostr-login-target='extensionDescription']").first
|
||||
expect(description.text).to include("Use a Nostr-signing browser extension")
|
||||
expect(description["class"]).to include("hidden")
|
||||
end
|
||||
|
||||
it "wires the login action to the extension option button" do
|
||||
rendered = render_component
|
||||
|
||||
extension = rendered.css("[data-nostr-login-target='extensionOption']").first
|
||||
expect(extension.name).to eq("button")
|
||||
expect(extension["data-action"]).to eq("nostr-login#login")
|
||||
end
|
||||
|
||||
it "omits the Nostr Connect option when the user is remembered" do
|
||||
rendered = render_component(remembered_user: Object.new)
|
||||
|
||||
expect(rendered.text).not_to include("Nostr Connect")
|
||||
expect(rendered.text).to include("Browser extension")
|
||||
|
||||
wrapper = rendered.css("[data-controller='modal nostr-login']").first
|
||||
expect(wrapper["class"]).to include("hidden")
|
||||
end
|
||||
|
||||
it "renders nothing when Nostr is unavailable" do
|
||||
rendered = render_component(nostr_available: false)
|
||||
|
||||
expect(rendered.text.strip).to be_blank
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,247 @@
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe NostrSignerConnectComponent, type: :component do
|
||||
let(:verified_at) { Time.utc(2026, 11, 24, 12, 21) }
|
||||
let(:active_session) { instance_double(NostrSignerSession, verified_at: verified_at) }
|
||||
|
||||
it "renders the connected timestamp in a localizable time element" do
|
||||
rendered = render_inline(
|
||||
described_class.new(
|
||||
active_session: active_session,
|
||||
create_url: "/settings/nostr_signer",
|
||||
show_disconnect: false
|
||||
)
|
||||
)
|
||||
|
||||
time = rendered.css("time").first
|
||||
|
||||
expect(time["datetime"]).to eq("2026-11-24T12:21:00Z")
|
||||
expect(time["title"]).to eq("24 Nov 2026, 12:21")
|
||||
expect(time["data-local-time"]).to eq("display")
|
||||
expect(time.text).to eq("24 Nov 2026, 12:21")
|
||||
expect(rendered.text).to include("since 24 Nov 2026, 12:21")
|
||||
|
||||
status = rendered.css("div.flex").first
|
||||
expect(status["class"]).to include("flex-col", "sm:flex-row", "sm:justify-between")
|
||||
end
|
||||
|
||||
it "renders a small, scalable QR code" do
|
||||
pending_session = instance_double(
|
||||
NostrSignerSession,
|
||||
bunker?: false,
|
||||
nostrconnect_uri: "nostrconnect://#{SecureRandom.hex(32)}?relay=wss%3A%2F%2Frelay.example.com&secret=abc"
|
||||
)
|
||||
|
||||
rendered = render_inline(
|
||||
described_class.new(
|
||||
pending_session: pending_session,
|
||||
create_url: "/users/nostr_connect",
|
||||
status_url: "/users/nostr_connect/status",
|
||||
show_disconnect: false
|
||||
)
|
||||
)
|
||||
|
||||
svg = rendered.css("svg").first
|
||||
|
||||
expect(svg["viewBox"]).to be_present
|
||||
expect(svg["width"]).to be_nil
|
||||
expect(svg["height"]).to be_nil
|
||||
expect(svg["class"]).to include("w-full")
|
||||
|
||||
qr_wrapper = rendered.css("div.rounded-lg.bg-white").first
|
||||
expect(qr_wrapper["class"]).to include("w-[232px]", "max-w-full")
|
||||
|
||||
qr = rendered.css("[data-nostr-signer-connect-target='qr']").first
|
||||
expect(qr["class"]).to include("hidden", "sm:flex")
|
||||
expect(rendered.css("[data-nostr-signer-connect-target='qrToggle']").any?).to be(true)
|
||||
expect(rendered.css("[data-nostr-signer-connect-target='details']").any?).to be(true)
|
||||
expect(rendered.text).to include("Try again")
|
||||
|
||||
clipboard = rendered.css("[data-controller='clipboard']").first
|
||||
expect(clipboard.css("[data-clipboard-target='source']").any?).to be(true)
|
||||
expect(clipboard.css("[data-clipboard-target='trigger']").any?).to be(true)
|
||||
expect(clipboard.css("button.btn-icon.btn-outline").any?).to be(true)
|
||||
expect(rendered.text).not_to include("Copy connection URI")
|
||||
|
||||
open_links = rendered.css("a[data-action='nostr-signer-connect#openSigner']")
|
||||
expect(open_links.size).to eq(2)
|
||||
expect(open_links.first["href"]).to eq(pending_session.nostrconnect_uri)
|
||||
expect(open_links.first["class"]).to include("btn-blue", "w-full")
|
||||
expect(open_links.last["class"]).to include("btn-gray")
|
||||
expect(rendered.css("[data-nostr-signer-connect-target='signerHint']").any?).to be(true)
|
||||
|
||||
expect(rendered.css("p.text-sm")).to be_empty
|
||||
expect(rendered.css("button.btn-sm")).to be_empty
|
||||
expect(rendered.css("p.text-base").any?).to be(true)
|
||||
expect(rendered.css("button.btn-md").any?).to be(true)
|
||||
end
|
||||
|
||||
it "omits the section heading and its spacing when no title is given" do
|
||||
pending_session = instance_double(
|
||||
NostrSignerSession,
|
||||
bunker?: false,
|
||||
nostrconnect_uri: "nostrconnect://#{SecureRandom.hex(32)}?relay=wss%3A%2F%2Frelay.example.com&secret=abc"
|
||||
)
|
||||
|
||||
rendered = render_inline(
|
||||
described_class.new(
|
||||
pending_session: pending_session,
|
||||
create_url: "/users/nostr_connect",
|
||||
title: nil
|
||||
)
|
||||
)
|
||||
|
||||
expect(rendered.css("h4")).to be_empty
|
||||
expect(rendered.css("section").first["class"]).not_to include("mt-8")
|
||||
|
||||
qr = rendered.css("[data-nostr-signer-connect-target='qr']").first
|
||||
expect(qr["class"]).not_to include("mt-4")
|
||||
end
|
||||
|
||||
it "uses normal typography in modal mode" do
|
||||
pending_session = instance_double(
|
||||
NostrSignerSession,
|
||||
bunker?: false,
|
||||
nostrconnect_uri: "nostrconnect://#{SecureRandom.hex(32)}?relay=wss%3A%2F%2Frelay.example.com&secret=abc"
|
||||
)
|
||||
|
||||
rendered = render_inline(
|
||||
described_class.new(
|
||||
pending_session: pending_session,
|
||||
create_url: "/settings/nostr_signer",
|
||||
destroy_url: "/settings/nostr_signer",
|
||||
status_url: "/settings/nostr_signer/status",
|
||||
title: "Nostr Connect",
|
||||
modal: true
|
||||
)
|
||||
)
|
||||
|
||||
expect(rendered.text).to include("Nostr Connect")
|
||||
expect(rendered.text).to include("Cancel")
|
||||
expect(rendered.text).to include("Prefer a bunker:// URI?")
|
||||
expect(rendered.css("a[data-action='nostr-signer-connect#openSigner']").any?).to be(true)
|
||||
expect(rendered.css("p.text-base").any?).to be(true)
|
||||
expect(rendered.css("button.btn-md").any?).to be(true)
|
||||
expect(rendered.css("section.mt-8")).to be_empty
|
||||
expect(rendered.css("h4").first["class"]).to include("text-xl", "font-bold")
|
||||
|
||||
qr_wrapper = rendered.css("div.rounded-lg").first
|
||||
expect(qr_wrapper["class"]).to include("w-[264px]")
|
||||
expect(rendered.css("div.w-56")).to be_empty
|
||||
expect(rendered.css("button.w-full").size).to be >= 2
|
||||
expect(rendered.css("a.w-full").size).to be >= 2
|
||||
expect(rendered.css("form.w-full").size).to eq(2)
|
||||
|
||||
retry_node = rendered.css("[data-nostr-signer-connect-target='retry']").first
|
||||
expect(retry_node.name).to eq("div")
|
||||
expect(retry_node["class"]).to include("hidden")
|
||||
expect(retry_node["hidden"]).to be_nil
|
||||
end
|
||||
|
||||
it "keeps the inline connect button when no connection exists" do
|
||||
rendered = render_inline(described_class.new(create_url: "/settings/nostr_signer"))
|
||||
|
||||
expect(rendered.text).to include("Use a mobile or desktop signer app, like Amber or Regent")
|
||||
expect(rendered.text).to include("Connect a signer app")
|
||||
expect(rendered.text).not_to include("bunker:// URI?")
|
||||
|
||||
connect = rendered.css("button, input[type=submit]").find do |node|
|
||||
node.text.strip == "Connect a signer app" || node["value"] == "Connect a signer app"
|
||||
end
|
||||
expect(connect["class"]).to include("btn-gray")
|
||||
end
|
||||
|
||||
it "keeps its heading but drops the section margin when flush" do
|
||||
rendered = render_inline(
|
||||
described_class.new(create_url: "/settings/nostr_signer", flush: true)
|
||||
)
|
||||
|
||||
expect(rendered.css("section").first["class"]).not_to include("mt-8")
|
||||
expect(rendered.css("h4").first.text.strip).to eq("Nostr Connect")
|
||||
end
|
||||
|
||||
it "wraps the section in a closed details with a connected dot when collapsible" do
|
||||
rendered = render_inline(
|
||||
described_class.new(
|
||||
active_session: active_session,
|
||||
create_url: "/settings/nostr_signer",
|
||||
collapsible: true
|
||||
)
|
||||
)
|
||||
|
||||
details = rendered.css("details").first
|
||||
expect(details).to be_present
|
||||
expect(details["open"]).to be_nil
|
||||
expect(rendered.css("section")).to be_empty
|
||||
expect(rendered.css("h4")).to be_empty
|
||||
|
||||
summary = details.css("summary").first
|
||||
expect(summary.text).to include("Nostr Connect")
|
||||
expect(summary["class"]).to include("cursor-pointer")
|
||||
expect(summary.css("span.rounded-full.bg-emerald-500").any?).to be(true)
|
||||
end
|
||||
|
||||
it "omits the connected dot when collapsible without an active session" do
|
||||
rendered = render_inline(
|
||||
described_class.new(create_url: "/settings/nostr_signer", collapsible: true)
|
||||
)
|
||||
|
||||
expect(rendered.css("details[open]")).to be_empty
|
||||
expect(rendered.css("summary").first.text).to include("Nostr Connect")
|
||||
expect(rendered.css("span.rounded-full.bg-emerald-500")).to be_empty
|
||||
end
|
||||
|
||||
it "renders a hidden replace dialog when a replace URL is given" do
|
||||
pending_session = instance_double(
|
||||
NostrSignerSession,
|
||||
bunker?: false,
|
||||
nostrconnect_uri: "nostrconnect://#{SecureRandom.hex(32)}?relay=wss%3A%2F%2Frelay.example.com&secret=abc"
|
||||
)
|
||||
|
||||
rendered = render_inline(
|
||||
described_class.new(
|
||||
pending_session: pending_session,
|
||||
create_url: "/settings/nostr_signer",
|
||||
destroy_url: "/settings/nostr_signer",
|
||||
status_url: "/settings/nostr_signer/status",
|
||||
replace_url: "/settings/nostr_signer/replace",
|
||||
title: "Nostr Connect",
|
||||
modal: true
|
||||
)
|
||||
)
|
||||
|
||||
dialog = rendered.css("[data-nostr-signer-connect-target='replace']").first
|
||||
expect(dialog["class"]).to include("hidden")
|
||||
expect(dialog.css("[data-nostr-signer-connect-target='replaceExisting']").any?).to be(true)
|
||||
expect(dialog.css("[data-nostr-signer-connect-target='replaceSigner']").any?).to be(true)
|
||||
expect(dialog.text).to include("Replace existing key", "Cancel")
|
||||
|
||||
element = rendered.css("[data-controller='nostr-signer-connect']").first
|
||||
expect(element["data-nostr-signer-connect-replace-url-value"])
|
||||
.to eq("/settings/nostr_signer/replace")
|
||||
expect(element["data-nostr-signer-connect-destroy-url-value"])
|
||||
.to eq("/settings/nostr_signer")
|
||||
|
||||
expect(dialog.css("button[data-action='nostr-signer-connect#replace']").any?).to be(true)
|
||||
expect(dialog.css("button[data-action='nostr-signer-connect#cancel']").any?).to be(true)
|
||||
end
|
||||
|
||||
it "omits the replace dialog when no replace URL is given" do
|
||||
pending_session = instance_double(
|
||||
NostrSignerSession,
|
||||
bunker?: false,
|
||||
nostrconnect_uri: "nostrconnect://#{SecureRandom.hex(32)}?relay=wss%3A%2F%2Frelay.example.com&secret=abc"
|
||||
)
|
||||
|
||||
rendered = render_inline(
|
||||
described_class.new(
|
||||
pending_session: pending_session,
|
||||
create_url: "/users/nostr_connect",
|
||||
status_url: "/users/nostr_connect/status",
|
||||
show_disconnect: false
|
||||
)
|
||||
)
|
||||
|
||||
expect(rendered.css("[data-nostr-signer-connect-target='replace']").any?).to be(false)
|
||||
end
|
||||
end
|
||||
@@ -33,6 +33,13 @@ RSpec.describe Settings::NostrEditMediaServersComponent, type: :component do
|
||||
badges = rendered.css("span.rounded-full").select { |el| el.text.strip == "added" }
|
||||
expect(badges.size).to eq(1)
|
||||
end
|
||||
|
||||
it "shows a hint about the recommended list" do
|
||||
rendered = render_inline(described_class.new(media_list_event: nil))
|
||||
|
||||
hint = rendered.css("p").find { |el| el.text.include?("recommended server to start with") }
|
||||
expect(hint).to be_present
|
||||
end
|
||||
end
|
||||
|
||||
describe "when user has an existing media server list without the site server" do
|
||||
@@ -53,6 +60,13 @@ RSpec.describe Settings::NostrEditMediaServersComponent, type: :component do
|
||||
badges = rendered.css("span.rounded-full").select { |el| el.text.strip == "added" }
|
||||
expect(badges.size).to eq(1)
|
||||
end
|
||||
|
||||
it "does not show the hint" do
|
||||
rendered = render_inline(described_class.new(media_list_event: media_list_event))
|
||||
|
||||
hint = rendered.css("p").find { |el| el.text.include?("recommended server to start with") }
|
||||
expect(hint).to be_nil
|
||||
end
|
||||
end
|
||||
|
||||
describe "when user already has the site server" do
|
||||
|
||||
@@ -23,6 +23,25 @@ RSpec.describe Settings::NostrEditProfileComponent, type: :component do
|
||||
expect(rendered.css("[data-nostr-profile-editor-target='submit']")).to be_present
|
||||
end
|
||||
|
||||
it "uses the standard editor width and a responsive banner ratio" do
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: nil))
|
||||
|
||||
root = rendered.css("[data-controller='nostr-image-upload']").first
|
||||
expect(root["class"]).to include("md:w-[600px]")
|
||||
expect(root["class"]).not_to include("lg:w-[760px]")
|
||||
|
||||
header = rendered.css("header").first
|
||||
expect(header["class"]).to include("aspect-[11/4]", "sm:aspect-[4/1]")
|
||||
expect(header["class"]).not_to include("aspect-[3/1]", "h-36", "h-44")
|
||||
|
||||
avatar = header.css(".absolute").find { |node| node["class"].to_s.include?("size-28") }
|
||||
expect(avatar["class"]).to include("-bottom-14", "left-4")
|
||||
|
||||
main = rendered.css("main").first
|
||||
expect(main["class"]).to include("pt-20", "sm:pt-24")
|
||||
expect(main["class"]).not_to include("mt-44")
|
||||
end
|
||||
|
||||
it "passes the display-name key list to the editor" do
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: nil))
|
||||
|
||||
@@ -252,9 +271,14 @@ RSpec.describe Settings::NostrEditProfileComponent, type: :component do
|
||||
end
|
||||
|
||||
describe "when profile event is missing or fields are empty" do
|
||||
it "prefills NIP-05 and Lightning addresses with user address and marks them as added" do
|
||||
it "prefills the display name, NIP-05 and Lightning addresses and marks them as added" do
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: nil))
|
||||
|
||||
display_name_input = rendered.css("input[name='user[display_name]']").first
|
||||
expect(display_name_input["value"]).to eq("Alice Wonderland")
|
||||
expect(display_name_input["class"]).to include("border-emerald-500")
|
||||
expect(display_name_input["data-action"]).to include("input->field-suggestion#checkAdded")
|
||||
|
||||
nip05_input = rendered.css("input[name='user[nip05_address]']").first
|
||||
expect(nip05_input["value"]).to eq("alice@kosmos.org")
|
||||
expect(nip05_input["class"]).to include("border-emerald-500")
|
||||
@@ -266,7 +290,22 @@ RSpec.describe Settings::NostrEditProfileComponent, type: :component do
|
||||
expect(lud16_input["data-action"]).to include("input->field-suggestion#checkAdded")
|
||||
|
||||
badges = rendered.css("span.rounded-full").select { |el| el.text.strip == "added" }
|
||||
expect(badges.size).to eq(2)
|
||||
expect(badges.size).to eq(3)
|
||||
end
|
||||
|
||||
context "without an account display name" do
|
||||
before { allow(user).to receive(:display_name).and_return(nil) }
|
||||
|
||||
it "does not mark the display name as added" do
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: nil))
|
||||
|
||||
display_name_input = rendered.css("input[name='user[display_name]']").first
|
||||
expect(display_name_input["value"]).to be_blank
|
||||
expect(display_name_input["class"]).not_to include("border-emerald-500")
|
||||
|
||||
badges = rendered.css("span.rounded-full").select { |el| el.text.strip == "added" }
|
||||
expect(badges.size).to eq(2)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -284,6 +323,11 @@ RSpec.describe Settings::NostrEditProfileComponent, type: :component do
|
||||
it "shows current values with different badges and suggestion strips" do
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: profile_event))
|
||||
|
||||
display_name_input = rendered.css("input[name='user[display_name]']").first
|
||||
expect(display_name_input["value"]).to eq("Alice External")
|
||||
expect(display_name_input["class"]).not_to include("border-emerald-500")
|
||||
expect(display_name_input["class"]).not_to include("border-amber-400")
|
||||
|
||||
nip05_input = rendered.css("input[name='user[nip05_address]']").first
|
||||
expect(nip05_input["value"]).to eq("alice@other.org")
|
||||
expect(nip05_input["class"]).to include("border-amber-400")
|
||||
|
||||
@@ -27,7 +27,7 @@ RSpec.describe Settings::NostrEditRelaysComponent, type: :component do
|
||||
end
|
||||
|
||||
describe "when user has no relay list (nip65_event is nil)" do
|
||||
it "prepends the site relay as added and suggests discovery relays without a badge" do
|
||||
it "marks the site relay and every discovery relay as added" do
|
||||
rendered = render_inline(described_class.new(nip65_event: nil))
|
||||
|
||||
list = rendered.css("[data-url-list-editor-target='list']").first
|
||||
@@ -39,14 +39,21 @@ RSpec.describe Settings::NostrEditRelaysComponent, type: :component do
|
||||
])
|
||||
|
||||
badges = rendered.css("span.rounded-full").select { |el| el.text.strip == "added" }
|
||||
expect(badges.size).to eq(1)
|
||||
expect(badges.size).to eq(3)
|
||||
|
||||
site_input = rendered.css("input[value='wss://nostr.kosmos.org']").first
|
||||
expect(site_input["data-added-value"]).to eq("wss://nostr.kosmos.org")
|
||||
relay_inputs.each do |url|
|
||||
input = rendered.css("input[value='#{url}']").first
|
||||
expect(input["data-added-value"]).to eq(url)
|
||||
expect(input["class"]).to include("border-emerald-500")
|
||||
expect(input["data-action"]).to include("input->url-list-editor#checkAdded")
|
||||
end
|
||||
end
|
||||
|
||||
suggestion_input = rendered.css("input[value='wss://nos.lol']").first
|
||||
expect(suggestion_input["data-added-value"]).to be_nil
|
||||
expect(suggestion_input["class"]).not_to include("border-emerald-500")
|
||||
it "shows a hint recommending the default list" do
|
||||
rendered = render_inline(described_class.new(nip65_event: nil))
|
||||
|
||||
hint = rendered.css("p").find { |el| el.text.include?("recommended list to start with") }
|
||||
expect(hint).to be_present
|
||||
end
|
||||
end
|
||||
|
||||
@@ -82,6 +89,13 @@ RSpec.describe Settings::NostrEditRelaysComponent, type: :component do
|
||||
select = rendered.css("select[name='relay_markers[]']").first
|
||||
expect(select["class"]).to include("w-36")
|
||||
end
|
||||
|
||||
it "does not show the recommended-list hint" do
|
||||
rendered = render_inline(described_class.new(nip65_event: nip65_event))
|
||||
|
||||
hint = rendered.css("p").find { |el| el.text.include?("recommended list to start with") }
|
||||
expect(hint).to be_nil
|
||||
end
|
||||
end
|
||||
|
||||
describe "when user already has site relay in their relay list" do
|
||||
|
||||
@@ -14,10 +14,18 @@ RSpec.describe 'Nostr Settings', type: :feature do
|
||||
describe 'Adding a nostr pubkey' do
|
||||
scenario 'Without nostr browser extension available' do
|
||||
visit setting_path(:nostr)
|
||||
expect(page).to have_content("No browser extension found")
|
||||
expect(page).to have_css("h4", text: "Browser extension")
|
||||
expect(page).to have_content("No browser extension detected. Install a Nostr signer like Alby to use this option.")
|
||||
expect(page).to have_css('button[data-settings--nostr-pubkey-target=setPubkey]:disabled')
|
||||
end
|
||||
|
||||
scenario 'With a remote signer available' do
|
||||
visit setting_path(:nostr)
|
||||
expect(page).to have_css("h4", text: "Nostr Connect")
|
||||
expect(page).to have_content("Use a mobile or desktop signer app, like Amber or Regent")
|
||||
expect(page).to have_button("Connect a signer app")
|
||||
end
|
||||
|
||||
# scenario 'Successfully saving a key' do
|
||||
# Note: Needs a more complex JS testing setup (maybe poltergeist), not
|
||||
# worth it for now
|
||||
@@ -30,6 +38,13 @@ RSpec.describe 'Nostr Settings', type: :feature do
|
||||
.and_return("ce273cbfb0d4e3e06930773a337c1459e4849efd4cb4c751b906a561c98a6d09")
|
||||
end
|
||||
|
||||
scenario 'Collapses the Nostr Connect section' do
|
||||
visit setting_path(:nostr)
|
||||
|
||||
expect(page).to have_css("details > summary", text: "Nostr Connect")
|
||||
expect(page).not_to have_button("Connect a signer app")
|
||||
end
|
||||
|
||||
scenario 'Remove nostr pubkey from account' do
|
||||
visit setting_path(:nostr)
|
||||
expect(page).to have_field("nostr_public_key",
|
||||
|
||||
+648
@@ -0,0 +1,648 @@
|
||||
{
|
||||
"v2": {
|
||||
"valid": {
|
||||
"get_conversation_key": [
|
||||
{
|
||||
"sec1": "315e59ff51cb9209768cf7da80791ddcaae56ac9775eb25b6dee1234bc5d2268",
|
||||
"pub2": "c2f9d9948dc8c7c38321e4b85c8558872eafa0641cd269db76848a6073e69133",
|
||||
"conversation_key": "3dfef0ce2a4d80a25e7a328accf73448ef67096f65f79588e358d9a0eb9013f1"
|
||||
},
|
||||
{
|
||||
"sec1": "a1e37752c9fdc1273be53f68c5f74be7c8905728e8de75800b94262f9497c86e",
|
||||
"pub2": "03bb7947065dde12ba991ea045132581d0954f042c84e06d8c00066e23c1a800",
|
||||
"conversation_key": "4d14f36e81b8452128da64fe6f1eae873baae2f444b02c950b90e43553f2178b"
|
||||
},
|
||||
{
|
||||
"sec1": "98a5902fd67518a0c900f0fb62158f278f94a21d6f9d33d30cd3091195500311",
|
||||
"pub2": "aae65c15f98e5e677b5050de82e3aba47a6fe49b3dab7863cf35d9478ba9f7d1",
|
||||
"conversation_key": "9c00b769d5f54d02bf175b7284a1cbd28b6911b06cda6666b2243561ac96bad7"
|
||||
},
|
||||
{
|
||||
"sec1": "86ae5ac8034eb2542ce23ec2f84375655dab7f836836bbd3c54cefe9fdc9c19f",
|
||||
"pub2": "59f90272378089d73f1339710c02e2be6db584e9cdbe86eed3578f0c67c23585",
|
||||
"conversation_key": "19f934aafd3324e8415299b64df42049afaa051c71c98d0aa10e1081f2e3e2ba"
|
||||
},
|
||||
{
|
||||
"sec1": "2528c287fe822421bc0dc4c3615878eb98e8a8c31657616d08b29c00ce209e34",
|
||||
"pub2": "f66ea16104c01a1c532e03f166c5370a22a5505753005a566366097150c6df60",
|
||||
"conversation_key": "c833bbb292956c43366145326d53b955ffb5da4e4998a2d853611841903f5442"
|
||||
},
|
||||
{
|
||||
"sec1": "49808637b2d21129478041813aceb6f2c9d4929cd1303cdaf4fbdbd690905ff2",
|
||||
"pub2": "74d2aab13e97827ea21baf253ad7e39b974bb2498cc747cdb168582a11847b65",
|
||||
"conversation_key": "4bf304d3c8c4608864c0fe03890b90279328cd24a018ffa9eb8f8ccec06b505d"
|
||||
},
|
||||
{
|
||||
"sec1": "af67c382106242c5baabf856efdc0629cc1c5b4061f85b8ceaba52aa7e4b4082",
|
||||
"pub2": "bdaf0001d63e7ec994fad736eab178ee3c2d7cfc925ae29f37d19224486db57b",
|
||||
"conversation_key": "a3a575dd66d45e9379904047ebfb9a7873c471687d0535db00ef2daa24b391db"
|
||||
},
|
||||
{
|
||||
"sec1": "0e44e2d1db3c1717b05ffa0f08d102a09c554a1cbbf678ab158b259a44e682f1",
|
||||
"pub2": "1ffa76c5cc7a836af6914b840483726207cb750889753d7499fb8b76aa8fe0de",
|
||||
"conversation_key": "a39970a667b7f861f100e3827f4adbf6f464e2697686fe1a81aeda817d6b8bdf"
|
||||
},
|
||||
{
|
||||
"sec1": "5fc0070dbd0666dbddc21d788db04050b86ed8b456b080794c2a0c8e33287bb6",
|
||||
"pub2": "31990752f296dd22e146c9e6f152a269d84b241cc95bb3ff8ec341628a54caf0",
|
||||
"conversation_key": "72c21075f4b2349ce01a3e604e02a9ab9f07e35dd07eff746de348b4f3c6365e"
|
||||
},
|
||||
{
|
||||
"sec1": "1b7de0d64d9b12ddbb52ef217a3a7c47c4362ce7ea837d760dad58ab313cba64",
|
||||
"pub2": "24383541dd8083b93d144b431679d70ef4eec10c98fceef1eff08b1d81d4b065",
|
||||
"conversation_key": "dd152a76b44e63d1afd4dfff0785fa07b3e494a9e8401aba31ff925caeb8f5b1"
|
||||
},
|
||||
{
|
||||
"sec1": "df2f560e213ca5fb33b9ecde771c7c0cbd30f1cf43c2c24de54480069d9ab0af",
|
||||
"pub2": "eeea26e552fc8b5e377acaa03e47daa2d7b0c787fac1e0774c9504d9094c430e",
|
||||
"conversation_key": "770519e803b80f411c34aef59c3ca018608842ebf53909c48d35250bd9323af6"
|
||||
},
|
||||
{
|
||||
"sec1": "cffff919fcc07b8003fdc63bc8a00c0f5dc81022c1c927c62c597352190d95b9",
|
||||
"pub2": "eb5c3cca1a968e26684e5b0eb733aecfc844f95a09ac4e126a9e58a4e4902f92",
|
||||
"conversation_key": "46a14ee7e80e439ec75c66f04ad824b53a632b8409a29bbb7c192e43c00bb795"
|
||||
},
|
||||
{
|
||||
"sec1": "64ba5a685e443e881e9094647ddd32db14444bb21aa7986beeba3d1c4673ba0a",
|
||||
"pub2": "50e6a4339fac1f3bf86f2401dd797af43ad45bbf58e0801a7877a3984c77c3c4",
|
||||
"conversation_key": "968b9dbbfcede1664a4ca35a5d3379c064736e87aafbf0b5d114dff710b8a946"
|
||||
},
|
||||
{
|
||||
"sec1": "dd0c31ccce4ec8083f9b75dbf23cc2878e6d1b6baa17713841a2428f69dee91a",
|
||||
"pub2": "b483e84c1339812bed25be55cff959778dfc6edde97ccd9e3649f442472c091b",
|
||||
"conversation_key": "09024503c7bde07eb7865505891c1ea672bf2d9e25e18dd7a7cea6c69bf44b5d"
|
||||
},
|
||||
{
|
||||
"sec1": "af71313b0d95c41e968a172b33ba5ebd19d06cdf8a7a98df80ecf7af4f6f0358",
|
||||
"pub2": "2a5c25266695b461ee2af927a6c44a3c598b8095b0557e9bd7f787067435bc7c",
|
||||
"conversation_key": "fe5155b27c1c4b4e92a933edae23726a04802a7cc354a77ac273c85aa3c97a92"
|
||||
},
|
||||
{
|
||||
"sec1": "6636e8a389f75fe068a03b3edb3ea4a785e2768e3f73f48ffb1fc5e7cb7289dc",
|
||||
"pub2": "514eb2064224b6a5829ea21b6e8f7d3ea15ff8e70e8555010f649eb6e09aec70",
|
||||
"conversation_key": "ff7afacd4d1a6856d37ca5b546890e46e922b508639214991cf8048ddbe9745c"
|
||||
},
|
||||
{
|
||||
"sec1": "94b212f02a3cfb8ad147d52941d3f1dbe1753804458e6645af92c7b2ea791caa",
|
||||
"pub2": "f0cac333231367a04b652a77ab4f8d658b94e86b5a8a0c472c5c7b0d4c6a40cc",
|
||||
"conversation_key": "e292eaf873addfed0a457c6bd16c8effde33d6664265697f69f420ab16f6669b"
|
||||
},
|
||||
{
|
||||
"sec1": "aa61f9734e69ae88e5d4ced5aae881c96f0d7f16cca603d3bed9eec391136da6",
|
||||
"pub2": "4303e5360a884c360221de8606b72dd316da49a37fe51e17ada4f35f671620a6",
|
||||
"conversation_key": "8e7d44fd4767456df1fb61f134092a52fcd6836ebab3b00766e16732683ed848"
|
||||
},
|
||||
{
|
||||
"sec1": "5e914bdac54f3f8e2cba94ee898b33240019297b69e96e70c8a495943a72fc98",
|
||||
"pub2": "5bd097924f606695c59f18ff8fd53c174adbafaaa71b3c0b4144a3e0a474b198",
|
||||
"conversation_key": "f5a0aecf2984bf923c8cd5e7bb8be262d1a8353cb93959434b943a07cf5644bc"
|
||||
},
|
||||
{
|
||||
"sec1": "8b275067add6312ddee064bcdbeb9d17e88aa1df36f430b2cea5cc0413d8278a",
|
||||
"pub2": "65bbbfca819c90c7579f7a82b750a18c858db1afbec8f35b3c1e0e7b5588e9b8",
|
||||
"conversation_key": "2c565e7027eb46038c2263563d7af681697107e975e9914b799d425effd248d6"
|
||||
},
|
||||
{
|
||||
"sec1": "1ac848de312285f85e0f7ec208aac20142a1f453402af9b34ec2ec7a1f9c96fc",
|
||||
"pub2": "45f7318fe96034d23ee3ddc25b77f275cc1dd329664dd51b89f89c4963868e41",
|
||||
"conversation_key": "b56e970e5057a8fd929f8aad9248176b9af87819a708d9ddd56e41d1aec74088"
|
||||
},
|
||||
{
|
||||
"sec1": "295a1cf621de401783d29d0e89036aa1c62d13d9ad307161b4ceb535ba1b40e6",
|
||||
"pub2": "840115ddc7f1034d3b21d8e2103f6cb5ab0b63cf613f4ea6e61ae3d016715cdd",
|
||||
"conversation_key": "b4ee9c0b9b9fef88975773394f0a6f981ca016076143a1bb575b9ff46e804753"
|
||||
},
|
||||
{
|
||||
"sec1": "a28eed0fe977893856ab9667e06ace39f03abbcdb845c329a1981be438ba565d",
|
||||
"pub2": "b0f38b950a5013eba5ab4237f9ed29204a59f3625c71b7e210fec565edfa288c",
|
||||
"conversation_key": "9d3a802b45bc5aeeb3b303e8e18a92ddd353375710a31600d7f5fff8f3a7285b"
|
||||
},
|
||||
{
|
||||
"sec1": "7ab65af72a478c05f5c651bdc4876c74b63d20d04cdbf71741e46978797cd5a4",
|
||||
"pub2": "f1112159161b568a9cb8c9dd6430b526c4204bcc8ce07464b0845b04c041beda",
|
||||
"conversation_key": "943884cddaca5a3fef355e9e7f08a3019b0b66aa63ec90278b0f9fdb64821e79"
|
||||
},
|
||||
{
|
||||
"sec1": "95c79a7b75ba40f2229e85756884c138916f9d103fc8f18acc0877a7cceac9fe",
|
||||
"pub2": "cad76bcbd31ca7bbda184d20cc42f725ed0bb105b13580c41330e03023f0ffb3",
|
||||
"conversation_key": "81c0832a669eea13b4247c40be51ccfd15bb63fcd1bba5b4530ce0e2632f301b"
|
||||
},
|
||||
{
|
||||
"sec1": "baf55cc2febd4d980b4b393972dfc1acf49541e336b56d33d429bce44fa12ec9",
|
||||
"pub2": "0c31cf87fe565766089b64b39460ebbfdedd4a2bc8379be73ad3c0718c912e18",
|
||||
"conversation_key": "37e2344da9ecdf60ae2205d81e89d34b280b0a3f111171af7e4391ded93b8ea6"
|
||||
},
|
||||
{
|
||||
"sec1": "6eeec45acd2ed31693c5256026abf9f072f01c4abb61f51cf64e6956b6dc8907",
|
||||
"pub2": "e501b34ed11f13d816748c0369b0c728e540df3755bab59ed3327339e16ff828",
|
||||
"conversation_key": "afaa141b522ddb27bb880d768903a7f618bb8b6357728cae7fb03af639b946e6"
|
||||
},
|
||||
{
|
||||
"sec1": "261a076a9702af1647fb343c55b3f9a4f1096273002287df0015ba81ce5294df",
|
||||
"pub2": "b2777c863878893ae100fb740c8fab4bebd2bf7be78c761a75593670380a6112",
|
||||
"conversation_key": "76f8d2853de0734e51189ced523c09427c3e46338b9522cd6f74ef5e5b475c74"
|
||||
},
|
||||
{
|
||||
"sec1": "ed3ec71ca406552ea41faec53e19f44b8f90575eda4b7e96380f9cc73c26d6f3",
|
||||
"pub2": "86425951e61f94b62e20cae24184b42e8e17afcf55bafa58645efd0172624fae",
|
||||
"conversation_key": "f7ffc520a3a0e9e9b3c0967325c9bf12707f8e7a03f28b6cd69ae92cf33f7036"
|
||||
},
|
||||
{
|
||||
"sec1": "5a788fc43378d1303ac78639c59a58cb88b08b3859df33193e63a5a3801c722e",
|
||||
"pub2": "a8cba2f87657d229db69bee07850fd6f7a2ed070171a06d006ec3a8ac562cf70",
|
||||
"conversation_key": "7d705a27feeedf78b5c07283362f8e361760d3e9f78adab83e3ae5ce7aeb6409"
|
||||
},
|
||||
{
|
||||
"sec1": "63bffa986e382b0ac8ccc1aa93d18a7aa445116478be6f2453bad1f2d3af2344",
|
||||
"pub2": "b895c70a83e782c1cf84af558d1038e6b211c6f84ede60408f519a293201031d",
|
||||
"conversation_key": "3a3b8f00d4987fc6711d9be64d9c59cf9a709c6c6481c2cde404bcc7a28f174e"
|
||||
},
|
||||
{
|
||||
"sec1": "e4a8bcacbf445fd3721792b939ff58e691cdcba6a8ba67ac3467b45567a03e5c",
|
||||
"pub2": "b54053189e8c9252c6950059c783edb10675d06d20c7b342f73ec9fa6ed39c9d",
|
||||
"conversation_key": "7b3933b4ef8189d347169c7955589fc1cfc01da5239591a08a183ff6694c44ad"
|
||||
},
|
||||
{
|
||||
"sec1": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364139",
|
||||
"pub2": "0000000000000000000000000000000000000000000000000000000000000002",
|
||||
"conversation_key": "8b6392dbf2ec6a2b2d5b1477fc2be84d63ef254b667cadd31bd3f444c44ae6ba",
|
||||
"note": "sec1 = n-2, pub2: random, 0x02"
|
||||
},
|
||||
{
|
||||
"sec1": "0000000000000000000000000000000000000000000000000000000000000002",
|
||||
"pub2": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdeb",
|
||||
"conversation_key": "be234f46f60a250bef52a5ee34c758800c4ca8e5030bf4cc1a31d37ba2104d43",
|
||||
"note": "sec1 = 2, pub2: rand"
|
||||
},
|
||||
{
|
||||
"sec1": "0000000000000000000000000000000000000000000000000000000000000001",
|
||||
"pub2": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
|
||||
"conversation_key": "3b4610cb7189beb9cc29eb3716ecc6102f1247e8f3101a03a1787d8908aeb54e",
|
||||
"note": "sec1 == pub2"
|
||||
}
|
||||
],
|
||||
"get_message_keys": {
|
||||
"conversation_key": "a1a3d60f3470a8612633924e91febf96dc5366ce130f658b1f0fc652c20b3b54",
|
||||
"keys": [
|
||||
{
|
||||
"nonce": "e1e6f880560d6d149ed83dcc7e5861ee62a5ee051f7fde9975fe5d25d2a02d72",
|
||||
"chacha_key": "f145f3bed47cb70dbeaac07f3a3fe683e822b3715edb7c4fe310829014ce7d76",
|
||||
"chacha_nonce": "c4ad129bb01180c0933a160c",
|
||||
"hmac_key": "027c1db445f05e2eee864a0975b0ddef5b7110583c8c192de3732571ca5838c4"
|
||||
},
|
||||
{
|
||||
"nonce": "e1d6d28c46de60168b43d79dacc519698512ec35e8ccb12640fc8e9f26121101",
|
||||
"chacha_key": "e35b88f8d4a8f1606c5082f7a64b100e5d85fcdb2e62aeafbec03fb9e860ad92",
|
||||
"chacha_nonce": "22925e920cee4a50a478be90",
|
||||
"hmac_key": "46a7c55d4283cb0df1d5e29540be67abfe709e3b2e14b7bf9976e6df994ded30"
|
||||
},
|
||||
{
|
||||
"nonce": "cfc13bef512ac9c15951ab00030dfaf2626fdca638dedb35f2993a9eeb85d650",
|
||||
"chacha_key": "020783eb35fdf5b80ef8c75377f4e937efb26bcbad0e61b4190e39939860c4bf",
|
||||
"chacha_nonce": "d3594987af769a52904656ac",
|
||||
"hmac_key": "237ec0ccb6ebd53d179fa8fd319e092acff599ef174c1fdafd499ef2b8dee745"
|
||||
},
|
||||
{
|
||||
"nonce": "ea6eb84cac23c5c1607c334e8bdf66f7977a7e374052327ec28c6906cbe25967",
|
||||
"chacha_key": "ff68db24b34fa62c78ac5ffeeaf19533afaedf651fb6a08384e46787f6ce94be",
|
||||
"chacha_nonce": "50bb859aa2dde938cc49ec7a",
|
||||
"hmac_key": "06ff32e1f7b29753a727d7927b25c2dd175aca47751462d37a2039023ec6b5a6"
|
||||
},
|
||||
{
|
||||
"nonce": "8c2e1dd3792802f1f9f7842e0323e5d52ad7472daf360f26e15f97290173605d",
|
||||
"chacha_key": "2f9daeda8683fdeede81adac247c63cc7671fa817a1fd47352e95d9487989d8b",
|
||||
"chacha_nonce": "400224ba67fc2f1b76736916",
|
||||
"hmac_key": "465c05302aeeb514e41c13ed6405297e261048cfb75a6f851ffa5b445b746e4b"
|
||||
},
|
||||
{
|
||||
"nonce": "05c28bf3d834fa4af8143bf5201a856fa5fac1a3aee58f4c93a764fc2f722367",
|
||||
"chacha_key": "1e3d45777025a035be566d80fd580def73ed6f7c043faec2c8c1c690ad31c110",
|
||||
"chacha_nonce": "021905b1ea3afc17cb9bf96f",
|
||||
"hmac_key": "74a6e481a89dcd130aaeb21060d7ec97ad30f0007d2cae7b1b11256cc70dfb81"
|
||||
},
|
||||
{
|
||||
"nonce": "5e043fb153227866e75a06d60185851bc90273bfb93342f6632a728e18a07a17",
|
||||
"chacha_key": "1ea72c9293841e7737c71567d8120145a58991aaa1c436ef77bf7adb83f882f1",
|
||||
"chacha_nonce": "72f69a5a5f795465cee59da8",
|
||||
"hmac_key": "e9daa1a1e9a266ecaa14e970a84bce3fbbf329079bbccda626582b4e66a0d4c9"
|
||||
},
|
||||
{
|
||||
"nonce": "7be7338eaf06a87e274244847fe7a97f5c6a91f44adc18fcc3e411ad6f786dbf",
|
||||
"chacha_key": "881e7968a1f0c2c80742ee03cd49ea587e13f22699730f1075ade01931582bf6",
|
||||
"chacha_nonce": "6e69be92d61c04a276021565",
|
||||
"hmac_key": "901afe79e74b19967c8829af23617d7d0ffbf1b57190c096855c6a03523a971b"
|
||||
},
|
||||
{
|
||||
"nonce": "94571c8d590905bad7becd892832b472f2aa5212894b6ce96e5ba719c178d976",
|
||||
"chacha_key": "f80873dd48466cb12d46364a97b8705c01b9b4230cb3ec3415a6b9551dc42eef",
|
||||
"chacha_nonce": "3dda53569cfcb7fac1805c35",
|
||||
"hmac_key": "e9fc264345e2839a181affebc27d2f528756e66a5f87b04bf6c5f1997047051e"
|
||||
},
|
||||
{
|
||||
"nonce": "13a6ee974b1fd759135a2c2010e3cdda47081c78e771125e4f0c382f0284a8cb",
|
||||
"chacha_key": "bc5fb403b0bed0d84cf1db872b6522072aece00363178c98ad52178d805fca85",
|
||||
"chacha_nonce": "65064239186e50304cc0f156",
|
||||
"hmac_key": "e872d320dde4ed3487958a8e43b48aabd3ced92bc24bb8ff1ccb57b590d9701a"
|
||||
},
|
||||
{
|
||||
"nonce": "082fecdb85f358367b049b08be0e82627ae1d8edb0f27327ccb593aa2613b814",
|
||||
"chacha_key": "1fbdb1cf6f6ea816349baf697932b36107803de98fcd805ebe9849b8ad0e6a45",
|
||||
"chacha_nonce": "2e605e1d825a3eaeb613db9c",
|
||||
"hmac_key": "fae910f591cf3c7eb538c598583abad33bc0a03085a96ca4ea3a08baf17c0eec"
|
||||
},
|
||||
{
|
||||
"nonce": "4c19020c74932c30ec6b2d8cd0d5bb80bd0fc87da3d8b4859d2fb003810afd03",
|
||||
"chacha_key": "1ab9905a0189e01cda82f843d226a82a03c4f5b6dbea9b22eb9bc953ba1370d4",
|
||||
"chacha_nonce": "cbb2530ea653766e5a37a83a",
|
||||
"hmac_key": "267f68acac01ac7b34b675e36c2cef5e7b7a6b697214add62a491bedd6efc178"
|
||||
},
|
||||
{
|
||||
"nonce": "67723a3381497b149ce24814eddd10c4c41a1e37e75af161930e6b9601afd0ff",
|
||||
"chacha_key": "9ecbd25e7e2e6c97b8c27d376dcc8c5679da96578557e4e21dba3a7ef4e4ac07",
|
||||
"chacha_nonce": "ef649fcf335583e8d45e3c2e",
|
||||
"hmac_key": "04dbbd812fa8226fdb45924c521a62e3d40a9e2b5806c1501efdeba75b006bf1"
|
||||
},
|
||||
{
|
||||
"nonce": "42063fe80b093e8619b1610972b4c3ab9e76c14fd908e642cd4997cafb30f36c",
|
||||
"chacha_key": "211c66531bbcc0efcdd0130f9f1ebc12a769105eb39608994bcb188fa6a73a4a",
|
||||
"chacha_nonce": "67803605a7e5010d0f63f8c8",
|
||||
"hmac_key": "e840e4e8921b57647369d121c5a19310648105dbdd008200ebf0d3b668704ff8"
|
||||
},
|
||||
{
|
||||
"nonce": "b5ac382a4be7ac03b554fe5f3043577b47ea2cd7cfc7e9ca010b1ffbb5cf1a58",
|
||||
"chacha_key": "b3b5f14f10074244ee42a3837a54309f33981c7232a8b16921e815e1f7d1bb77",
|
||||
"chacha_nonce": "4e62a0073087ed808be62469",
|
||||
"hmac_key": "c8efa10230b5ea11633816c1230ca05fa602ace80a7598916d83bae3d3d2ccd7"
|
||||
},
|
||||
{
|
||||
"nonce": "e9d1eba47dd7e6c1532dc782ff63125db83042bb32841db7eeafd528f3ea7af9",
|
||||
"chacha_key": "54241f68dc2e50e1db79e892c7c7a471856beeb8d51b7f4d16f16ab0645d2f1a",
|
||||
"chacha_nonce": "a963ed7dc29b7b1046820a1d",
|
||||
"hmac_key": "aba215c8634530dc21c70ddb3b3ee4291e0fa5fa79be0f85863747bde281c8b2"
|
||||
},
|
||||
{
|
||||
"nonce": "a94ecf8efeee9d7068de730fad8daf96694acb70901d762de39fa8a5039c3c49",
|
||||
"chacha_key": "c0565e9e201d2381a2368d7ffe60f555223874610d3d91fbbdf3076f7b1374dd",
|
||||
"chacha_nonce": "329bb3024461e84b2e1c489b",
|
||||
"hmac_key": "ac42445491f092481ce4fa33b1f2274700032db64e3a15014fbe8c28550f2fec"
|
||||
},
|
||||
{
|
||||
"nonce": "533605ea214e70c25e9a22f792f4b78b9f83a18ab2103687c8a0075919eaaa53",
|
||||
"chacha_key": "ab35a5e1e54d693ff023db8500d8d4e79ad8878c744e0eaec691e96e141d2325",
|
||||
"chacha_nonce": "653d759042b85194d4d8c0a7",
|
||||
"hmac_key": "b43628e37ba3c31ce80576f0a1f26d3a7c9361d29bb227433b66f49d44f167ba"
|
||||
},
|
||||
{
|
||||
"nonce": "7f38df30ceea1577cb60b355b4f5567ff4130c49e84fed34d779b764a9cc184c",
|
||||
"chacha_key": "a37d7f211b84a551a127ff40908974eb78415395d4f6f40324428e850e8c42a3",
|
||||
"chacha_nonce": "b822e2c959df32b3cb772a7c",
|
||||
"hmac_key": "1ba31764f01f69b5c89ded2d7c95828e8052c55f5d36f1cd535510d61ba77420"
|
||||
},
|
||||
{
|
||||
"nonce": "11b37f9dbc4d0185d1c26d5f4ed98637d7c9701fffa65a65839fa4126573a4e5",
|
||||
"chacha_key": "964f38d3a31158a5bfd28481247b18dd6e44d69f30ba2a40f6120c6d21d8a6ba",
|
||||
"chacha_nonce": "5f72c5b87c590bcd0f93b305",
|
||||
"hmac_key": "2fc4553e7cedc47f29690439890f9f19c1077ef3e9eaeef473d0711e04448918"
|
||||
},
|
||||
{
|
||||
"nonce": "8be790aa483d4cdd843189f71f135b3ec7e31f381312c8fe9f177aab2a48eafa",
|
||||
"chacha_key": "95c8c74d633721a131316309cf6daf0804d59eaa90ea998fc35bac3d2fbb7a94",
|
||||
"chacha_nonce": "409a7654c0e4bf8c2c6489be",
|
||||
"hmac_key": "21bb0b06eb2b460f8ab075f497efa9a01c9cf9146f1e3986c3bf9da5689b6dc4"
|
||||
},
|
||||
{
|
||||
"nonce": "19fd2a718ea084827d6bd73f509229ddf856732108b59fc01819f611419fd140",
|
||||
"chacha_key": "cc6714b9f5616c66143424e1413d520dae03b1a4bd202b82b0a89b0727f5cdc8",
|
||||
"chacha_nonce": "1b7fd2534f015a8f795d8f32",
|
||||
"hmac_key": "2bef39c4ce5c3c59b817e86351373d1554c98bc131c7e461ed19d96cfd6399a0"
|
||||
},
|
||||
{
|
||||
"nonce": "3c2acd893952b2f6d07d8aea76f545ca45961a93fe5757f6a5a80811d5e0255d",
|
||||
"chacha_key": "c8de6c878cb469278d0af894bc181deb6194053f73da5014c2b5d2c8db6f2056",
|
||||
"chacha_nonce": "6ffe4f1971b904a1b1a81b99",
|
||||
"hmac_key": "df1cd69dd3646fca15594284744d4211d70e7d8472e545d276421fbb79559fd4"
|
||||
},
|
||||
{
|
||||
"nonce": "7dbea4cead9ac91d4137f1c0a6eebb6ba0d1fb2cc46d829fbc75f8d86aca6301",
|
||||
"chacha_key": "c8e030f6aa680c3d0b597da9c92bb77c21c4285dd620c5889f9beba7446446b0",
|
||||
"chacha_nonce": "a9b5a67d081d3b42e737d16f",
|
||||
"hmac_key": "355a85f551bc3cce9a14461aa60994742c9bbb1c81a59ca102dc64e61726ab8e"
|
||||
},
|
||||
{
|
||||
"nonce": "45422e676cdae5f1071d3647d7a5f1f5adafb832668a578228aa1155a491f2f3",
|
||||
"chacha_key": "758437245f03a88e2c6a32807edfabff51a91c81ca2f389b0b46f2c97119ea90",
|
||||
"chacha_nonce": "263830a065af33d9c6c5aa1f",
|
||||
"hmac_key": "7c581cf3489e2de203a95106bfc0de3d4032e9d5b92b2b61fb444acd99037e17"
|
||||
},
|
||||
{
|
||||
"nonce": "babc0c03fad24107ad60678751f5db2678041ff0d28671ede8d65bdf7aa407e9",
|
||||
"chacha_key": "bd68a28bd48d9ffa3602db72c75662ac2848a0047a313d2ae2d6bc1ac153d7e9",
|
||||
"chacha_nonce": "d0f9d2a1ace6c758f594ffdd",
|
||||
"hmac_key": "eb435e3a642adfc9d59813051606fc21f81641afd58ea6641e2f5a9f123bb50a"
|
||||
},
|
||||
{
|
||||
"nonce": "7a1b8aac37d0d20b160291fad124ab697cfca53f82e326d78fef89b4b0ea8f83",
|
||||
"chacha_key": "9e97875b651a1d30d17d086d1e846778b7faad6fcbc12e08b3365d700f62e4fe",
|
||||
"chacha_nonce": "ccdaad5b3b7645be430992eb",
|
||||
"hmac_key": "6f2f55cf35174d75752f63c06cc7cbc8441759b142999ed2d5a6d09d263e1fc4"
|
||||
},
|
||||
{
|
||||
"nonce": "8370e4e32d7e680a83862cab0da6136ef607014d043e64cdf5ecc0c4e20b3d9a",
|
||||
"chacha_key": "1472bed5d19db9c546106de946e0649cd83cc9d4a66b087a65906e348dcf92e2",
|
||||
"chacha_nonce": "ed02dece5fc3a186f123420b",
|
||||
"hmac_key": "7b3f7739f49d30c6205a46b174f984bb6a9fc38e5ccfacef2dac04fcbd3b184e"
|
||||
},
|
||||
{
|
||||
"nonce": "9f1c5e8a29cd5677513c2e3a816551d6833ee54991eb3f00d5b68096fc8f0183",
|
||||
"chacha_key": "5e1a7544e4d4dafe55941fcbdf326f19b0ca37fc49c4d47e9eec7fb68cde4975",
|
||||
"chacha_nonce": "7d9acb0fdc174e3c220f40de",
|
||||
"hmac_key": "e265ab116fbbb86b2aefc089a0986a0f5b77eda50c7410404ad3b4f3f385c7a7"
|
||||
},
|
||||
{
|
||||
"nonce": "c385aa1c37c2bfd5cc35fcdbdf601034d39195e1cabff664ceb2b787c15d0225",
|
||||
"chacha_key": "06bf4e60677a13e54c4a38ab824d2ef79da22b690da2b82d0aa3e39a14ca7bdd",
|
||||
"chacha_nonce": "26b450612ca5e905b937e147",
|
||||
"hmac_key": "22208152be2b1f5f75e6bfcc1f87763d48bb7a74da1be3d102096f257207f8b3"
|
||||
},
|
||||
{
|
||||
"nonce": "3ff73528f88a50f9d35c0ddba4560bacee5b0462d0f4cb6e91caf41847040ce4",
|
||||
"chacha_key": "850c8a17a23aa761d279d9901015b2bbdfdff00adbf6bc5cf22bd44d24ecabc9",
|
||||
"chacha_nonce": "4a296a1fb0048e5020d3b129",
|
||||
"hmac_key": "b1bf49a533c4da9b1d629b7ff30882e12d37d49c19abd7b01b7807d75ee13806"
|
||||
},
|
||||
{
|
||||
"nonce": "2dcf39b9d4c52f1cb9db2d516c43a7c6c3b8c401f6a4ac8f131a9e1059957036",
|
||||
"chacha_key": "17f8057e6156ba7cc5310d01eda8c40f9aa388f9fd1712deb9511f13ecc37d27",
|
||||
"chacha_nonce": "a8188daff807a1182200b39d",
|
||||
"hmac_key": "47b89da97f68d389867b5d8a2d7ba55715a30e3d88a3cc11f3646bc2af5580ef"
|
||||
}
|
||||
]
|
||||
},
|
||||
"calc_padded_len": [
|
||||
[16, 32],
|
||||
[32, 32],
|
||||
[33, 64],
|
||||
[37, 64],
|
||||
[45, 64],
|
||||
[49, 64],
|
||||
[64, 64],
|
||||
[65, 96],
|
||||
[100, 128],
|
||||
[111, 128],
|
||||
[200, 224],
|
||||
[250, 256],
|
||||
[320, 320],
|
||||
[383, 384],
|
||||
[384, 384],
|
||||
[400, 448],
|
||||
[500, 512],
|
||||
[512, 512],
|
||||
[515, 640],
|
||||
[700, 768],
|
||||
[800, 896],
|
||||
[900, 1024],
|
||||
[1020, 1024],
|
||||
[65536, 65536]
|
||||
],
|
||||
"encrypt_decrypt": [
|
||||
{
|
||||
"sec1": "0000000000000000000000000000000000000000000000000000000000000001",
|
||||
"sec2": "0000000000000000000000000000000000000000000000000000000000000002",
|
||||
"conversation_key": "c41c775356fd92eadc63ff5a0dc1da211b268cbea22316767095b2871ea1412d",
|
||||
"nonce": "0000000000000000000000000000000000000000000000000000000000000001",
|
||||
"plaintext": "a",
|
||||
"payload": "AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABee0G5VSK0/9YypIObAtDKfYEAjD35uVkHyB0F4DwrcNaCXlCWZKaArsGrY6M9wnuTMxWfp1RTN9Xga8no+kF5Vsb"
|
||||
},
|
||||
{
|
||||
"sec1": "0000000000000000000000000000000000000000000000000000000000000002",
|
||||
"sec2": "0000000000000000000000000000000000000000000000000000000000000001",
|
||||
"conversation_key": "c41c775356fd92eadc63ff5a0dc1da211b268cbea22316767095b2871ea1412d",
|
||||
"nonce": "f00000000000000000000000000000f00000000000000000000000000000000f",
|
||||
"plaintext": "🍕🫃",
|
||||
"payload": "AvAAAAAAAAAAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAPSKSK6is9ngkX2+cSq85Th16oRTISAOfhStnixqZziKMDvB0QQzgFZdjLTPicCJaV8nDITO+QfaQ61+KbWQIOO2Yj"
|
||||
},
|
||||
{
|
||||
"sec1": "5c0c523f52a5b6fad39ed2403092df8cebc36318b39383bca6c00808626fab3a",
|
||||
"sec2": "4b22aa260e4acb7021e32f38a6cdf4b673c6a277755bfce287e370c924dc936d",
|
||||
"conversation_key": "3e2b52a63be47d34fe0a80e34e73d436d6963bc8f39827f327057a9986c20a45",
|
||||
"nonce": "b635236c42db20f021bb8d1cdff5ca75dd1a0cc72ea742ad750f33010b24f73b",
|
||||
"plaintext": "表ポあA鷗ŒéB逍Üߪąñ丂㐀𠀀",
|
||||
"payload": "ArY1I2xC2yDwIbuNHN/1ynXdGgzHLqdCrXUPMwELJPc7s7JqlCMJBAIIjfkpHReBPXeoMCyuClwgbT419jUWU1PwaNl4FEQYKCDKVJz+97Mp3K+Q2YGa77B6gpxB/lr1QgoqpDf7wDVrDmOqGoiPjWDqy8KzLueKDcm9BVP8xeTJIxs="
|
||||
},
|
||||
{
|
||||
"sec1": "8f40e50a84a7462e2b8d24c28898ef1f23359fff50d8c509e6fb7ce06e142f9c",
|
||||
"sec2": "b9b0a1e9cc20100c5faa3bbe2777303d25950616c4c6a3fa2e3e046f936ec2ba",
|
||||
"conversation_key": "d5a2f879123145a4b291d767428870f5a8d9e5007193321795b40183d4ab8c2b",
|
||||
"nonce": "b20989adc3ddc41cd2c435952c0d59a91315d8c5218d5040573fc3749543acaf",
|
||||
"plaintext": "ability🤝的 ȺȾ",
|
||||
"payload": "ArIJia3D3cQc0sQ1lSwNWakTFdjFIY1QQFc/w3SVQ6yvbG2S0x4Yu86QGwPTy7mP3961I1XqB6SFFTzqDZZavhxoWMj7mEVGMQIsh2RLWI5EYQaQDIePSnXPlzf7CIt+voTD"
|
||||
},
|
||||
{
|
||||
"sec1": "875adb475056aec0b4809bd2db9aa00cff53a649e7b59d8edcbf4e6330b0995c",
|
||||
"sec2": "9c05781112d5b0a2a7148a222e50e0bd891d6b60c5483f03456e982185944aae",
|
||||
"conversation_key": "3b15c977e20bfe4b8482991274635edd94f366595b1a3d2993515705ca3cedb8",
|
||||
"nonce": "8d4442713eb9d4791175cb040d98d6fc5be8864d6ec2f89cf0895a2b2b72d1b1",
|
||||
"plaintext": "pepper👀їжак",
|
||||
"payload": "Ao1EQnE+udR5EXXLBA2Y1vxb6IZNbsL4nPCJWisrctGxY3AduCS+jTUgAAnfvKafkmpy15+i9YMwCdccisRa8SvzW671T2JO4LFSPX31K4kYUKelSAdSPwe9NwO6LhOsnoJ+"
|
||||
},
|
||||
{
|
||||
"sec1": "eba1687cab6a3101bfc68fd70f214aa4cc059e9ec1b79fdb9ad0a0a4e259829f",
|
||||
"sec2": "dff20d262bef9dfd94666548f556393085e6ea421c8af86e9d333fa8747e94b3",
|
||||
"conversation_key": "4f1538411098cf11c8af216836444787c462d47f97287f46cf7edb2c4915b8a5",
|
||||
"nonce": "2180b52ae645fcf9f5080d81b1f0b5d6f2cd77ff3c986882bb549158462f3407",
|
||||
"plaintext": "( ͡° ͜ʖ ͡°)",
|
||||
"payload": "AiGAtSrmRfz59QgNgbHwtdbyzXf/PJhogrtUkVhGLzQHv4qhKQwnFQ54OjVMgqCea/Vj0YqBSdhqNR777TJ4zIUk7R0fnizp6l1zwgzWv7+ee6u+0/89KIjY5q1wu6inyuiv"
|
||||
},
|
||||
{
|
||||
"sec1": "d5633530f5bcfebceb5584cfbbf718a30df0751b729dd9a789b9f30c0587d74e",
|
||||
"sec2": "b74e6a341fb134127272b795a08b59250e5fa45a82a2eb4095e4ce9ed5f5e214",
|
||||
"conversation_key": "75fe686d21a035f0c7cd70da64ba307936e5ca0b20710496a6b6b5f573377bdd",
|
||||
"nonce": "e4cd5f7ce4eea024bc71b17ad456a986a74ac426c2c62b0a15eb5c5c8f888b68",
|
||||
"plaintext": "مُنَاقَشَةُ سُبُلِ اِسْتِخْدَامِ اللُّغَةِ فِي النُّظُمِ الْقَائِمَةِ وَفِيم يَخُصَّ التَّطْبِيقَاتُ الْحاسُوبِيَّةُ،",
|
||||
"payload": "AuTNX3zk7qAkvHGxetRWqYanSsQmwsYrChXrXFyPiItoIBsWu1CB+sStla2M4VeANASHxM78i1CfHQQH1YbBy24Tng7emYW44ol6QkFD6D8Zq7QPl+8L1c47lx8RoODEQMvNCbOk5ffUV3/AhONHBXnffrI+0025c+uRGzfqpYki4lBqm9iYU+k3Tvjczq9wU0mkVDEaM34WiQi30MfkJdRbeeYaq6kNvGPunLb3xdjjs5DL720d61Flc5ZfoZm+CBhADy9D9XiVZYLKAlkijALJur9dATYKci6OBOoc2SJS2Clai5hOVzR0yVeyHRgRfH9aLSlWW5dXcUxTo7qqRjNf8W5+J4jF4gNQp5f5d0YA4vPAzjBwSP/5bGzNDslKfcAH"
|
||||
},
|
||||
{
|
||||
"sec1": "d5633530f5bcfebceb5584cfbbf718a30df0751b729dd9a789b9f30c0587d74e",
|
||||
"sec2": "b74e6a341fb134127272b795a08b59250e5fa45a82a2eb4095e4ce9ed5f5e214",
|
||||
"conversation_key": "75fe686d21a035f0c7cd70da64ba307936e5ca0b20710496a6b6b5f573377bdd",
|
||||
"nonce": "38d1ca0abef9e5f564e89761a86cee04574b6825d3ef2063b10ad75899e4b023",
|
||||
"plaintext": "الكل في المجمو عة (5)",
|
||||
"payload": "AjjRygq++eX1ZOiXYahs7gRXS2gl0+8gY7EK11iZ5LAjbOTrlfrxak5Lki42v2jMPpLSicy8eHjsWkkMtF0i925vOaKG/ZkMHh9ccQBdfTvgEGKzztedqDCAWb5TP1YwU1PsWaiiqG3+WgVvJiO4lUdMHXL7+zKKx8bgDtowzz4QAwI="
|
||||
},
|
||||
{
|
||||
"sec1": "d5633530f5bcfebceb5584cfbbf718a30df0751b729dd9a789b9f30c0587d74e",
|
||||
"sec2": "b74e6a341fb134127272b795a08b59250e5fa45a82a2eb4095e4ce9ed5f5e214",
|
||||
"conversation_key": "75fe686d21a035f0c7cd70da64ba307936e5ca0b20710496a6b6b5f573377bdd",
|
||||
"nonce": "4f1a31909f3483a9e69c8549a55bbc9af25fa5bbecf7bd32d9896f83ef2e12e0",
|
||||
"plaintext": "𝖑𝖆𝖟𝖞 社會科學院語學研究所",
|
||||
"payload": "Ak8aMZCfNIOp5pyFSaVbvJryX6W77Pe9MtmJb4PvLhLgh/TsxPLFSANcT67EC1t/qxjru5ZoADjKVEt2ejdx+xGvH49mcdfbc+l+L7gJtkH7GLKpE9pQNQWNHMAmj043PAXJZ++fiJObMRR2mye5VHEANzZWkZXMrXF7YjuG10S1pOU="
|
||||
},
|
||||
{
|
||||
"sec1": "d5633530f5bcfebceb5584cfbbf718a30df0751b729dd9a789b9f30c0587d74e",
|
||||
"sec2": "b74e6a341fb134127272b795a08b59250e5fa45a82a2eb4095e4ce9ed5f5e214",
|
||||
"conversation_key": "75fe686d21a035f0c7cd70da64ba307936e5ca0b20710496a6b6b5f573377bdd",
|
||||
"nonce": "a3e219242d85465e70adcd640b564b3feff57d2ef8745d5e7a0663b2dccceb54",
|
||||
"plaintext": "🙈 🙉 🙊 0️⃣ 1️⃣ 2️⃣ 3️⃣ 4️⃣ 5️⃣ 6️⃣ 7️⃣ 8️⃣ 9️⃣ 🔟 Powerلُلُصّبُلُلصّبُررً ॣ ॣh ॣ ॣ冗",
|
||||
"payload": "AqPiGSQthUZecK3NZAtWSz/v9X0u+HRdXnoGY7LczOtUf05aMF89q1FLwJvaFJYICZoMYgRJHFLwPiOHce7fuAc40kX0wXJvipyBJ9HzCOj7CgtnC1/cmPCHR3s5AIORmroBWglm1LiFMohv1FSPEbaBD51VXxJa4JyWpYhreSOEjn1wd0lMKC9b+osV2N2tpbs+rbpQem2tRen3sWflmCqjkG5VOVwRErCuXuPb5+hYwd8BoZbfCrsiAVLd7YT44dRtKNBx6rkabWfddKSLtreHLDysOhQUVOp/XkE7OzSkWl6sky0Hva6qJJ/V726hMlomvcLHjE41iKmW2CpcZfOedg=="
|
||||
}
|
||||
],
|
||||
"encrypt_decrypt_long_msg": [
|
||||
{
|
||||
"conversation_key": "8fc262099ce0d0bb9b89bac05bb9e04f9bc0090acc181fef6840ccee470371ed",
|
||||
"nonce": "326bcb2c943cd6bb717588c9e5a7e738edf6ed14ec5f5344caa6ef56f0b9cff7",
|
||||
"pattern": "x",
|
||||
"repeat": 65535,
|
||||
"plaintext_sha256": "09ab7495d3e61a76f0deb12cb0306f0696cbb17ffc12131368c7a939f12f56d3",
|
||||
"payload_sha256": "90714492225faba06310bff2f249ebdc2a5e609d65a629f1c87f2d4ffc55330a"
|
||||
},
|
||||
{
|
||||
"conversation_key": "56adbe3720339363ab9c3b8526ffce9fd77600927488bfc4b59f7a68ffe5eae0",
|
||||
"nonce": "ad68da81833c2a8ff609c3d2c0335fd44fe5954f85bb580c6a8d467aa9fc5dd0",
|
||||
"pattern": "!",
|
||||
"repeat": 65535,
|
||||
"plaintext_sha256": "6af297793b72ae092c422e552c3bb3cbc310da274bd1cf9e31023a7fe4a2d75e",
|
||||
"payload_sha256": "8013e45a109fad3362133132b460a2d5bce235fe71c8b8f4014793fb52a49844"
|
||||
},
|
||||
{
|
||||
"conversation_key": "7fc540779979e472bb8d12480b443d1e5eb1098eae546ef2390bee499bbf46be",
|
||||
"nonce": "34905e82105c20de9a2f6cd385a0d541e6bcc10601d12481ff3a7575dc622033",
|
||||
"pattern": "🦄",
|
||||
"repeat": 16383,
|
||||
"plaintext_sha256": "a249558d161b77297bc0cb311dde7d77190f6571b25c7e4429cd19044634a61f",
|
||||
"payload_sha256": "b3348422471da1f3c59d79acfe2fe103f3cd24488109e5b18734cdb5953afd15"
|
||||
}
|
||||
]
|
||||
},
|
||||
"invalid": {
|
||||
"encrypt_msg_lengths": [0, 65536, 100000, 10000000],
|
||||
"get_conversation_key": [
|
||||
{
|
||||
"sec1": "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
|
||||
"pub2": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
|
||||
"note": "sec1 higher than curve.n"
|
||||
},
|
||||
{
|
||||
"sec1": "0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"pub2": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
|
||||
"note": "sec1 is 0"
|
||||
},
|
||||
{
|
||||
"sec1": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364139",
|
||||
"pub2": "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
|
||||
"note": "pub2 is invalid, no sqrt, all-ff"
|
||||
},
|
||||
{
|
||||
"sec1": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",
|
||||
"pub2": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
|
||||
"note": "sec1 == curve.n"
|
||||
},
|
||||
{
|
||||
"sec1": "0000000000000000000000000000000000000000000000000000000000000002",
|
||||
"pub2": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
|
||||
"note": "pub2 is invalid, no sqrt"
|
||||
},
|
||||
{
|
||||
"sec1": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20",
|
||||
"pub2": "0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"note": "pub2 is point of order 3 on twist"
|
||||
},
|
||||
{
|
||||
"sec1": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20",
|
||||
"pub2": "eb1f7200aecaa86682376fb1c13cd12b732221e774f553b0a0857f88fa20f86d",
|
||||
"note": "pub2 is point of order 13 on twist"
|
||||
},
|
||||
{
|
||||
"sec1": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20",
|
||||
"pub2": "709858a4c121e4a84eb59c0ded0261093c71e8ca29efeef21a6161c447bcaf9f",
|
||||
"note": "pub2 is point of order 3319 on twist"
|
||||
}
|
||||
],
|
||||
"decrypt": [
|
||||
{
|
||||
"conversation_key": "ca2527a037347b91bea0c8a30fc8d9600ffd81ec00038671e3a0f0cb0fc9f642",
|
||||
"nonce": "daaea5ca345b268e5b62060ca72c870c48f713bc1e00ff3fc0ddb78e826f10db",
|
||||
"plaintext": "n o b l e",
|
||||
"payload": "#Atqupco0WyaOW2IGDKcshwxI9xO8HgD/P8Ddt46CbxDbrhdG8VmJdU0MIDf06CUvEvdnr1cp1fiMtlM/GrE92xAc1K5odTpCzUB+mjXgbaqtntBUbTToSUoT0ovrlPwzGjyp",
|
||||
"note": "unknown encryption version"
|
||||
},
|
||||
{
|
||||
"conversation_key": "36f04e558af246352dcf73b692fbd3646a2207bd8abd4b1cd26b234db84d9481",
|
||||
"nonce": "ad408d4be8616dc84bb0bf046454a2a102edac937c35209c43cd7964c5feb781",
|
||||
"plaintext": "⚠️",
|
||||
"payload": "AK1AjUvoYW3IS7C/BGRUoqEC7ayTfDUgnEPNeWTF/reBZFaha6EAIRueE9D1B1RuoiuFScC0Q94yjIuxZD3JStQtE8JMNacWFs9rlYP+ZydtHhRucp+lxfdvFlaGV/sQlqZz",
|
||||
"note": "unknown encryption version 0"
|
||||
},
|
||||
{
|
||||
"conversation_key": "ca2527a037347b91bea0c8a30fc8d9600ffd81ec00038671e3a0f0cb0fc9f642",
|
||||
"nonce": "daaea5ca345b268e5b62060ca72c870c48f713bc1e00ff3fc0ddb78e826f10db",
|
||||
"plaintext": "n o s t r",
|
||||
"payload": "Atфupco0WyaOW2IGDKcshwxI9xO8HgD/P8Ddt46CbxDbrhdG8VmJZE0UICD06CUvEvdnr1cp1fiMtlM/GrE92xAc1EwsVCQEgWEu2gsHUVf4JAa3TpgkmFc3TWsax0v6n/Wq",
|
||||
"note": "invalid base64"
|
||||
},
|
||||
{
|
||||
"conversation_key": "cff7bd6a3e29a450fd27f6c125d5edeb0987c475fd1e8d97591e0d4d8a89763c",
|
||||
"nonce": "09ff97750b084012e15ecb84614ce88180d7b8ec0d468508a86b6d70c0361a25",
|
||||
"plaintext": "¯\\_(ツ)_/¯",
|
||||
"payload": "Agn/l3ULCEAS4V7LhGFM6IGA17jsDUaFCKhrbXDANholyySBfeh+EN8wNB9gaLlg4j6wdBYh+3oK+mnxWu3NKRbSvQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
|
||||
"note": "invalid MAC"
|
||||
},
|
||||
{
|
||||
"conversation_key": "cfcc9cf682dfb00b11357f65bdc45e29156b69db424d20b3596919074f5bf957",
|
||||
"nonce": "65b14b0b949aaa7d52c417eb753b390e8ad6d84b23af4bec6d9bfa3e03a08af4",
|
||||
"plaintext": "🥎",
|
||||
"payload": "AmWxSwuUmqp9UsQX63U7OQ6K1thLI69L7G2b+j4DoIr0oRWQ8avl4OLqWZiTJ10vIgKrNqjoaX+fNhE9RqmR5g0f6BtUg1ijFMz71MO1D4lQLQfW7+UHva8PGYgQ1QpHlKgR",
|
||||
"note": "invalid MAC"
|
||||
},
|
||||
{
|
||||
"conversation_key": "5254827d29177622d40a7b67cad014fe7137700c3c523903ebbe3e1b74d40214",
|
||||
"nonce": "7ab65dbb8bbc2b8e35cafb5745314e1f050325a864d11d0475ef75b3660d91c1",
|
||||
"plaintext": "elliptic-curve cryptography",
|
||||
"payload": "Anq2XbuLvCuONcr7V0UxTh8FAyWoZNEdBHXvdbNmDZHB573MI7R7rrTYftpqmvUpahmBC2sngmI14/L0HjOZ7lWGJlzdh6luiOnGPc46cGxf08MRC4CIuxx3i2Lm0KqgJ7vA",
|
||||
"note": "invalid padding"
|
||||
},
|
||||
{
|
||||
"conversation_key": "fea39aca9aa8340c3a78ae1f0902aa7e726946e4efcd7783379df8096029c496",
|
||||
"nonce": "7d4283e3b54c885d6afee881f48e62f0a3f5d7a9e1cb71ccab594a7882c39330",
|
||||
"plaintext": "noble",
|
||||
"payload": "An1Cg+O1TIhdav7ogfSOYvCj9dep4ctxzKtZSniCw5MwRrrPJFyAQYZh5VpjC2QYzny5LIQ9v9lhqmZR4WBYRNJ0ognHVNMwiFV1SHpvUFT8HHZN/m/QarflbvDHAtO6pY16",
|
||||
"note": "invalid padding"
|
||||
},
|
||||
{
|
||||
"conversation_key": "0c4cffb7a6f7e706ec94b2e879f1fc54ff8de38d8db87e11787694d5392d5b3f",
|
||||
"nonce": "6f9fd72667c273acd23ca6653711a708434474dd9eb15c3edb01ce9a95743e9b",
|
||||
"plaintext": "censorship-resistant and global social network",
|
||||
"payload": "Am+f1yZnwnOs0jymZTcRpwhDRHTdnrFcPtsBzpqVdD6b2NZDaNm/TPkZGr75kbB6tCSoq7YRcbPiNfJXNch3Tf+o9+zZTMxwjgX/nm3yDKR2kHQMBhVleCB9uPuljl40AJ8kXRD0gjw+aYRJFUMK9gCETZAjjmrsCM+nGRZ1FfNsHr6Z",
|
||||
"note": "invalid padding"
|
||||
},
|
||||
{
|
||||
"conversation_key": "5cd2d13b9e355aeb2452afbd3786870dbeecb9d355b12cb0a3b6e9da5744cd35",
|
||||
"nonce": "b60036976a1ada277b948fd4caa065304b96964742b89d26f26a25263a5060bd",
|
||||
"plaintext": "0",
|
||||
"payload": "",
|
||||
"note": "invalid payload length: 0"
|
||||
},
|
||||
{
|
||||
"conversation_key": "d61d3f09c7dfe1c0be91af7109b60a7d9d498920c90cbba1e137320fdd938853",
|
||||
"nonce": "1a29d02c8b4527745a2ccb38bfa45655deb37bc338ab9289d756354cea1fd07c",
|
||||
"plaintext": "1",
|
||||
"payload": "Ag==",
|
||||
"note": "invalid payload length: 4"
|
||||
},
|
||||
{
|
||||
"conversation_key": "873bb0fc665eb950a8e7d5971965539f6ebd645c83c08cd6a85aafbad0f0bc47",
|
||||
"nonce": "c826d3c38e765ab8cc42060116cd1464b2a6ce01d33deba5dedfb48615306d4a",
|
||||
"plaintext": "2",
|
||||
"payload": "AqxgToSh3H7iLYRJjoWAM+vSv/Y1mgNlm6OWWjOYUClrFF8=",
|
||||
"note": "invalid payload length: 48"
|
||||
},
|
||||
{
|
||||
"conversation_key": "9f2fef8f5401ac33f74641b568a7a30bb19409c76ffdc5eae2db6b39d2617fbe",
|
||||
"nonce": "9ff6484642545221624eaac7b9ea27133a4cc2356682a6033aceeef043549861",
|
||||
"plaintext": "3",
|
||||
"payload": "Ap/2SEZCVFIhYk6qx7nqJxM6TMI1ZoKmAzrO7vBDVJhhuZXWiM20i/tIsbjT0KxkJs2MZjh1oXNYMO9ggfk7i47WQA==",
|
||||
"note": "invalid payload length: 92"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
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_nil
|
||||
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 "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)
|
||||
.and_raise(StandardError, "boom")
|
||||
|
||||
described_class.perform_now(session.id)
|
||||
|
||||
expect(session.reload).to be_failed
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,31 @@
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe NostrLogoutJob, type: :job do
|
||||
let(:signer_keypair) { Nostr::Keygen.new.generate_key_pair }
|
||||
let(:session) do
|
||||
NostrManager::RemoteSigner::CreateSession.call(
|
||||
flow: "settings",
|
||||
relays: ["wss://relay.example.com"]
|
||||
).tap do |record|
|
||||
record.complete_connection!(
|
||||
remote_signer_pubkey: signer_keypair.public_key.to_s,
|
||||
user_pubkey: SecureRandom.hex(32)
|
||||
)
|
||||
record.update!(status: "disconnecting")
|
||||
end
|
||||
end
|
||||
|
||||
it "destroys the session after attempting logout" do
|
||||
expect(NostrManager::RemoteSigner::Disconnect).to receive(:call).with(session: session).and_return(false)
|
||||
|
||||
described_class.perform_now(session.id)
|
||||
|
||||
expect(NostrSignerSession.exists?(session.id)).to be(false)
|
||||
end
|
||||
|
||||
it "does nothing for a missing session" do
|
||||
expect(NostrManager::RemoteSigner::Disconnect).not_to receive(:call)
|
||||
|
||||
described_class.perform_now(0)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,66 @@
|
||||
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
|
||||
|
||||
it "expires a request when the signer responds after the TTL" do
|
||||
request = build_request
|
||||
signed = Nostr::User.new.create_event(kind: 0, content: "{}", tags: [])
|
||||
allow(NostrManager::RemoteSigner::SignEvent).to receive(:call) do
|
||||
request.update_columns(expires_at: 1.minute.ago)
|
||||
signed
|
||||
end
|
||||
|
||||
described_class.perform_now(request.id)
|
||||
|
||||
expect(request.reload.status).to eq("expired")
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,44 @@
|
||||
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
|
||||
|
||||
it "removes stuck disconnecting sessions" 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(status: "disconnecting", updated_at: 11.minutes.ago)
|
||||
|
||||
described_class.perform_now
|
||||
|
||||
expect(NostrSignerSession.exists?(session.id)).to be(false)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,65 @@
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe NostrSignRequest, type: :model do
|
||||
let(:user) { create :user }
|
||||
let(:template) { { "kind" => 0, "content" => "{}", "tags" => [], "created_at" => Time.current.to_i } }
|
||||
|
||||
def build_request(**overrides)
|
||||
described_class.new(
|
||||
{
|
||||
user: user,
|
||||
kind: 0,
|
||||
template: template,
|
||||
status: "pending",
|
||||
expires_at: 2.minutes.from_now
|
||||
}.merge(overrides)
|
||||
)
|
||||
end
|
||||
|
||||
it "generates a token" do
|
||||
request = build_request
|
||||
request.save!
|
||||
|
||||
expect(request.token).to be_present
|
||||
end
|
||||
|
||||
it "tracks the signed event" do
|
||||
request = build_request
|
||||
request.save!
|
||||
|
||||
signed = { "id" => "abc", "kind" => 0, "content" => "{}", "tags" => [], "created_at" => Time.current.to_i }
|
||||
request.sign!(double(to_h: signed))
|
||||
|
||||
expect(request.reload).to have_attributes(status: "signed", signed_event: signed)
|
||||
end
|
||||
|
||||
it "expires pending requests" do
|
||||
request = build_request(expires_at: 1.minute.ago)
|
||||
request.status = "pending"
|
||||
|
||||
expect(request).not_to be_pending
|
||||
end
|
||||
|
||||
it "defaults to the sign purpose" do
|
||||
request = build_request
|
||||
request.save!
|
||||
|
||||
expect(request.reload.purpose).to eq("sign")
|
||||
end
|
||||
|
||||
it "validates the purpose" do
|
||||
request = build_request(purpose: "invalid")
|
||||
|
||||
expect(request).not_to be_valid
|
||||
expect(request.errors[:purpose]).to be_present
|
||||
end
|
||||
|
||||
it "marks a request as consumed" do
|
||||
request = build_request
|
||||
request.save!
|
||||
|
||||
request.consume!
|
||||
|
||||
expect(request.reload).to be_consumed
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,138 @@
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe NostrSignerSession, type: :model do
|
||||
let(:keypair) { Nostr::Keygen.new.generate_key_pair }
|
||||
|
||||
def build_session(**overrides)
|
||||
described_class.new(
|
||||
{
|
||||
client_private_key: keypair.private_key.to_s,
|
||||
client_public_key: keypair.public_key.to_s,
|
||||
secret: "connection-secret",
|
||||
challenge: "challenge",
|
||||
relays: ["wss://relay.example.com"],
|
||||
flow: "settings",
|
||||
expires_at: 5.minutes.from_now
|
||||
}.merge(overrides)
|
||||
)
|
||||
end
|
||||
|
||||
it "generates a token and stores only its digest" do
|
||||
session = build_session
|
||||
session.save!
|
||||
|
||||
expect(session.token).to be_present
|
||||
expect(session.token_digest).to eq(Digest::SHA256.hexdigest(session.token))
|
||||
expect(session.token_digest).not_to eq(session.token)
|
||||
end
|
||||
|
||||
it "encrypts the client private key at rest" do
|
||||
session = build_session
|
||||
session.save!
|
||||
|
||||
raw = described_class.connection.select_value(
|
||||
"SELECT client_private_key FROM nostr_signer_sessions WHERE id = #{session.id}"
|
||||
)
|
||||
|
||||
expect(session.reload.client_private_key).to eq(keypair.private_key.to_s)
|
||||
expect(raw).not_to eq(keypair.private_key.to_s)
|
||||
end
|
||||
|
||||
it "finds a session by raw token and exposes the token" do
|
||||
session = build_session
|
||||
session.save!
|
||||
|
||||
found = described_class.find_by_token(session.token)
|
||||
|
||||
expect(found).to eq(session)
|
||||
expect(found.token).to eq(session.token)
|
||||
end
|
||||
|
||||
it "builds a nostrconnect URI with relays, permissions, and client metadata" do
|
||||
allow(Setting).to receive(:accounts_domain).and_return("accounts.example.com")
|
||||
allow(Setting).to receive(:nostr_client_icon_url)
|
||||
.and_return("https://assets.example.com/icon.png")
|
||||
|
||||
session = build_session
|
||||
session.save!
|
||||
|
||||
uri = URI.parse(session.nostrconnect_uri)
|
||||
params = URI.decode_www_form(uri.query).to_h
|
||||
|
||||
expect(uri.scheme).to eq("nostrconnect")
|
||||
expect(uri.host).to eq(keypair.public_key.to_s)
|
||||
expect(params["relay"]).to eq("wss://relay.example.com")
|
||||
expect(params["secret"]).to eq("connection-secret")
|
||||
expect(params["name"]).to eq("Kosmos Accounts")
|
||||
expect(params["url"]).to eq("https://accounts.example.com")
|
||||
expect(params["image"]).to eq("https://assets.example.com/icon.png")
|
||||
expect(params["perms"]).to include("sign_event:0")
|
||||
end
|
||||
|
||||
it "rejects non-websocket relays" do
|
||||
session = build_session(relays: ["https://relay.example.com"])
|
||||
|
||||
expect(session).not_to be_valid
|
||||
expect(session.errors[:relays]).to be_present
|
||||
end
|
||||
|
||||
it "knows when it is no longer usable" do
|
||||
session = build_session(expires_at: 1.minute.ago, status: "pending")
|
||||
|
||||
expect(session).not_to be_pending
|
||||
expect(session).not_to be_usable
|
||||
end
|
||||
|
||||
it "marks a verified connection as long-lived" do
|
||||
session = build_session
|
||||
session.save!
|
||||
|
||||
session.complete_connection!(
|
||||
remote_signer_pubkey: SecureRandom.hex(32),
|
||||
user_pubkey: SecureRandom.hex(32)
|
||||
)
|
||||
|
||||
expect(session.reload).to be_verified
|
||||
expect(session.expires_at).to be > 1.day.from_now
|
||||
end
|
||||
|
||||
describe "remember tokens" do
|
||||
let(:user) { create :user }
|
||||
let(:session) do
|
||||
build_session(user: user, status: "connected", verified_at: Time.current,
|
||||
user_pubkey: SecureRandom.hex(32), remote_signer_pubkey: SecureRandom.hex(32))
|
||||
end
|
||||
|
||||
before { session.save! }
|
||||
|
||||
it "generates a token and finds the session by it" do
|
||||
token = session.remember!
|
||||
|
||||
expect(session.reload.remember_token_digest).to eq(Digest::SHA256.hexdigest(token))
|
||||
expect(described_class.find_by_remember_token(token)).to eq(session)
|
||||
end
|
||||
|
||||
it "clears the token" do
|
||||
session.remember!
|
||||
session.clear_remember_token!
|
||||
|
||||
expect(session.reload.remember_token_digest).to be_nil
|
||||
end
|
||||
|
||||
it "is continuable only while connected and not expired" do
|
||||
expect(session).to be_continuable
|
||||
|
||||
session.update!(status: "disconnecting")
|
||||
expect(session).not_to be_continuable
|
||||
|
||||
session.update!(status: "connected", expires_at: 1.minute.ago)
|
||||
expect(session).not_to be_continuable
|
||||
end
|
||||
|
||||
it "refuses to remember a session that is not connected" do
|
||||
session.update!(status: "verified")
|
||||
|
||||
expect { session.remember! }.to raise_error(RuntimeError)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -22,4 +22,17 @@ RSpec.describe Setting, type: :model do
|
||||
end
|
||||
end
|
||||
|
||||
describe ".nostr_media_servers_enabled?" do
|
||||
it "is enabled when a Blossom server is configured" do
|
||||
Setting.nostr_blossom_server_url = "https://blossom.example.com"
|
||||
|
||||
expect(Setting.nostr_media_servers_enabled?).to be(true)
|
||||
end
|
||||
|
||||
it "is disabled without a Blossom server" do
|
||||
Setting.nostr_blossom_server_url = nil
|
||||
|
||||
expect(Setting.nostr_media_servers_enabled?).to be(false)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,130 @@
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe "Settings::NostrSignatures", type: :request do
|
||||
include ActiveJob::TestHelper
|
||||
|
||||
let(:user) { create :user, cn: "mark", ou: "kosmos.org" }
|
||||
let(:user_pubkey) { SecureRandom.hex(32) }
|
||||
let(:template) do
|
||||
{
|
||||
kind: 0,
|
||||
content: '{"name":"mark"}',
|
||||
tags: [],
|
||||
created_at: Time.current.to_i
|
||||
}
|
||||
end
|
||||
|
||||
before do
|
||||
login_as user, scope: :user
|
||||
Rails.cache.clear
|
||||
allow(Setting).to receive(:nostr_signer_relays).and_return(["wss://relay.example.com"])
|
||||
allow_any_instance_of(User).to receive(:nostr_pubkey).and_return(user_pubkey)
|
||||
end
|
||||
|
||||
def create_verified_session
|
||||
signer_session = NostrManager::RemoteSigner::CreateSession.call(flow: "settings", user: user)
|
||||
signer_session.complete_connection!(
|
||||
remote_signer_pubkey: SecureRandom.hex(32),
|
||||
user_pubkey: user_pubkey
|
||||
)
|
||||
signer_session
|
||||
end
|
||||
|
||||
describe "POST /settings/nostr_sign" do
|
||||
it "creates a signing request and enqueues the job" do
|
||||
create_verified_session
|
||||
|
||||
expect do
|
||||
post nostr_sign_settings_path, params: { event: template }, as: :json
|
||||
end.to change(NostrSignRequest, :count).by(1)
|
||||
.and have_enqueued_job(NostrSignEventJob)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
data = JSON.parse(response.body)
|
||||
expect(data["token"]).to be_present
|
||||
expect(data["status"]).to eq("pending")
|
||||
expect(NostrSignRequest.last.purpose).to eq("sign")
|
||||
end
|
||||
|
||||
it "rejects kinds that are not allowed" do
|
||||
create_verified_session
|
||||
|
||||
expect do
|
||||
post nostr_sign_settings_path, params: { event: template.merge(kind: 1) }, as: :json
|
||||
end.not_to change(NostrSignRequest, :count)
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(JSON.parse(response.body)["error"]).to include("not allowed")
|
||||
end
|
||||
|
||||
it "requires an active remote signer" do
|
||||
post nostr_sign_settings_path, params: { event: template }, as: :json
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
end
|
||||
|
||||
it "rejects stale events" do
|
||||
create_verified_session
|
||||
|
||||
post nostr_sign_settings_path,
|
||||
params: { event: template.merge(created_at: 1.hour.ago.to_i) },
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(JSON.parse(response.body)["error"]).to include("stale")
|
||||
end
|
||||
end
|
||||
|
||||
describe "GET /settings/nostr_sign/:token" do
|
||||
it "returns a signed event" do
|
||||
create_verified_session
|
||||
sign_request = NostrSignRequest.create!(
|
||||
user: user,
|
||||
kind: 0,
|
||||
template: template.stringify_keys,
|
||||
status: "signed",
|
||||
signed_event: { id: "abc", kind: 0 },
|
||||
expires_at: 1.minute.from_now
|
||||
)
|
||||
|
||||
get nostr_sign_status_settings_path(token: sign_request.token), as: :json
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(JSON.parse(response.body)["signed_event"]).to eq("id" => "abc", "kind" => 0)
|
||||
end
|
||||
|
||||
it "does not expose reauth requests" do
|
||||
create_verified_session
|
||||
sign_request = NostrSignRequest.create!(
|
||||
user: user,
|
||||
kind: 22242,
|
||||
template: template.stringify_keys,
|
||||
purpose: "reauth",
|
||||
status: "signed",
|
||||
signed_event: { id: "abc", kind: 22242 },
|
||||
expires_at: 1.minute.from_now
|
||||
)
|
||||
|
||||
get nostr_sign_status_settings_path(token: sign_request.token), as: :json
|
||||
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
|
||||
it "returns a failure" do
|
||||
create_verified_session
|
||||
sign_request = NostrSignRequest.create!(
|
||||
user: user,
|
||||
kind: 0,
|
||||
template: template.stringify_keys,
|
||||
status: "failed",
|
||||
error: "No response",
|
||||
expires_at: 1.minute.from_now
|
||||
)
|
||||
|
||||
get nostr_sign_status_settings_path(token: sign_request.token), as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(JSON.parse(response.body)["error"]).to eq("No response")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,286 @@
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe "Settings::NostrSigners", type: :request do
|
||||
let(:user) { create :user, cn: "mark", ou: "kosmos.org" }
|
||||
let(:other_user) { create :user, id: 2, cn: "markymark", ou: "kosmos.org", email: "markymark@example.com" }
|
||||
let(:user_pubkey) { SecureRandom.hex(32) }
|
||||
|
||||
before do
|
||||
login_as user, scope: :user
|
||||
Rails.cache.clear
|
||||
allow(Setting).to receive(:nostr_signer_relays).and_return(["wss://relay.example.com"])
|
||||
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(nil)
|
||||
end
|
||||
|
||||
def create_verified_session
|
||||
session = NostrManager::RemoteSigner::CreateSession.call(flow: "settings", user: user)
|
||||
session.update!(
|
||||
status: "verified",
|
||||
user_pubkey: user_pubkey,
|
||||
remote_signer_pubkey: SecureRandom.hex(32),
|
||||
verified_at: Time.current
|
||||
)
|
||||
session
|
||||
end
|
||||
|
||||
def create_connected_session
|
||||
create_verified_session.tap do |session|
|
||||
session.update!(status: "connected", consumed_at: Time.current)
|
||||
end
|
||||
end
|
||||
|
||||
describe "POST /settings/nostr_signer" do
|
||||
it "creates a pending nostrconnect session" do
|
||||
expect do
|
||||
post nostr_signer_settings_path, as: :json
|
||||
end.to change(NostrSignerSession, :count).by(1)
|
||||
.and have_enqueued_job(NostrConnectListenerJob)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
data = JSON.parse(response.body)
|
||||
expect(data["token"]).to be_present
|
||||
expect(data["uri"]).to start_with("nostrconnect://")
|
||||
end
|
||||
|
||||
it "replaces the signer section with the pending modal for turbo streams" do
|
||||
post nostr_signer_settings_path, headers: { "Accept" => "text/vnd.turbo-stream.html" }
|
||||
|
||||
expect(response.media_type).to eq("text/vnd.turbo-stream.html")
|
||||
expect(response.body).to include('target="nostr-signer-section"')
|
||||
expect(response.body).to include("nostrconnect://")
|
||||
expect(response.body).to include('data-modal-open-value="true"')
|
||||
end
|
||||
|
||||
it "renders the QR code and status poll inside an open modal" do
|
||||
post nostr_signer_settings_path, as: :json
|
||||
|
||||
get setting_path(:nostr)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(response.body).to include("nostrconnect://")
|
||||
expect(response.body).to include('data-nostr-signer-connect-target="status"')
|
||||
expect(response.body).to include("Prefer a bunker:// URI?")
|
||||
expect(response.body).to include('data-modal-open-value="true"')
|
||||
expect(response.body).to include('data-modal-target="background"')
|
||||
expect(response.body).to include("Nostr Connect")
|
||||
expect(response.body).not_to include("Already have a bunker:// URI?")
|
||||
end
|
||||
|
||||
it "keeps the inline connect button when no session is pending" do
|
||||
get setting_path(:nostr)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(response.body).to include("Connect a signer app")
|
||||
expect(response.body).not_to include("bunker:// URI?")
|
||||
expect(response.body).not_to include('data-modal-open-value="true"')
|
||||
end
|
||||
|
||||
it "creates a bunker session" do
|
||||
remote = SecureRandom.hex(32)
|
||||
allow(NostrManager::RelayUrlValidator).to receive(:strict_valid?).and_return(true)
|
||||
|
||||
post nostr_signer_settings_path,
|
||||
params: { bunker_uri: "bunker://#{remote}?relay=wss%3A%2F%2Frelay.example.com&secret=abc" },
|
||||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
session = NostrSignerSession.last
|
||||
expect(session).to be_bunker
|
||||
expect(session.remote_signer_pubkey).to eq(remote)
|
||||
end
|
||||
end
|
||||
|
||||
describe "GET /settings/nostr_signer/section" do
|
||||
it "replaces the signer section for turbo streams" do
|
||||
get nostr_signer_section_settings_path, headers: { "Accept" => "text/vnd.turbo-stream.html" }
|
||||
|
||||
expect(response.media_type).to eq("text/vnd.turbo-stream.html")
|
||||
expect(response.body).to include('target="nostr-signer-section"')
|
||||
end
|
||||
end
|
||||
|
||||
describe "GET /settings/nostr_signer/status" do
|
||||
it "stores the verified pubkey in LDAP once" do
|
||||
session = create_verified_session
|
||||
allow(LdapManager::FetchUserByNostrKey).to receive(:call).with(pubkey: user_pubkey).and_return(nil)
|
||||
expect(LdapManager::UpdateNostrKey).to receive(:call).with(
|
||||
dn: "cn=mark,ou=kosmos.org,cn=users,dc=kosmos,dc=org",
|
||||
pubkey: user_pubkey
|
||||
).once
|
||||
|
||||
2.times do |index|
|
||||
get nostr_signer_status_settings_path(token: session.token), as: :json
|
||||
expect(response.headers["Set-Cookie"]).to include("nostr_remember") if index.zero?
|
||||
end
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(JSON.parse(response.body)["status"]).to eq("connected")
|
||||
expect(session.reload).to be_connected
|
||||
end
|
||||
|
||||
it "rejects a public key already linked to another account" do
|
||||
session = create_verified_session
|
||||
allow(LdapManager::FetchUserByNostrKey).to receive(:call).with(pubkey: user_pubkey).and_return(other_user)
|
||||
expect(LdapManager::UpdateNostrKey).not_to receive(:call)
|
||||
|
||||
get nostr_signer_status_settings_path(token: session.token), as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(JSON.parse(response.body)["error"]).to eq("Public key already in use for a different account")
|
||||
end
|
||||
|
||||
it "returns pending while waiting for the signer" do
|
||||
session = NostrManager::RemoteSigner::CreateSession.call(flow: "settings", user: user)
|
||||
|
||||
get nostr_signer_status_settings_path(token: session.token), as: :json
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(JSON.parse(response.body)["status"]).to eq("pending")
|
||||
end
|
||||
|
||||
it "returns a failure message" do
|
||||
session = NostrManager::RemoteSigner::CreateSession.call(flow: "settings", user: user)
|
||||
session.fail!("Your signer did not respond.")
|
||||
|
||||
get nostr_signer_status_settings_path(token: session.token), as: :json
|
||||
|
||||
expect(JSON.parse(response.body)["status"]).to eq("failed")
|
||||
expect(JSON.parse(response.body)["error"]).to eq("Your signer did not respond.")
|
||||
end
|
||||
|
||||
it "expires a pending session whose TTL has passed" do
|
||||
session = NostrManager::RemoteSigner::CreateSession.call(flow: "settings", user: user)
|
||||
session.update_columns(expires_at: 1.minute.ago)
|
||||
|
||||
get nostr_signer_status_settings_path(token: session.token), as: :json
|
||||
|
||||
expect(JSON.parse(response.body)["status"]).to eq("expired")
|
||||
expect(session.reload).to be_expired
|
||||
end
|
||||
|
||||
it "connects without rewriting LDAP when the signer key already matches" do
|
||||
session = create_verified_session
|
||||
allow_any_instance_of(User).to receive(:nostr_pubkey).and_return(user_pubkey)
|
||||
allow(LdapManager::FetchUserByNostrKey).to receive(:call).with(pubkey: user_pubkey).and_return(nil)
|
||||
expect(LdapManager::SetNostrKey).not_to receive(:call)
|
||||
|
||||
get nostr_signer_status_settings_path(token: session.token), as: :json
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(JSON.parse(response.body)["status"]).to eq("connected")
|
||||
expect(session.reload).to be_connected
|
||||
end
|
||||
|
||||
it "asks to replace instead of overwriting a different existing key" do
|
||||
session = create_verified_session
|
||||
existing = SecureRandom.hex(32)
|
||||
allow_any_instance_of(User).to receive(:nostr_pubkey).and_return(existing)
|
||||
allow(LdapManager::FetchUserByNostrKey).to receive(:call).with(pubkey: user_pubkey).and_return(nil)
|
||||
expect(LdapManager::SetNostrKey).not_to receive(:call)
|
||||
|
||||
get nostr_signer_status_settings_path(token: session.token), as: :json
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
data = JSON.parse(response.body)
|
||||
expect(data["status"]).to eq("replace_required")
|
||||
expect(data["existing_npub"]).to eq(Nostr::PublicKey.new(existing).to_bech32)
|
||||
expect(data["signer_npub"]).to eq(session.user_pubkey_bech32)
|
||||
expect(session.reload).to be_verified
|
||||
expect(response.headers["Set-Cookie"]).not_to include("nostr_remember")
|
||||
end
|
||||
|
||||
it "keeps returning replace_required while the conflict is unresolved" do
|
||||
session = create_verified_session
|
||||
allow_any_instance_of(User).to receive(:nostr_pubkey).and_return(SecureRandom.hex(32))
|
||||
allow(LdapManager::FetchUserByNostrKey).to receive(:call).and_return(nil)
|
||||
|
||||
2.times do
|
||||
get nostr_signer_status_settings_path(token: session.token), as: :json
|
||||
expect(JSON.parse(response.body)["status"]).to eq("replace_required")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe "POST /settings/nostr_signer/replace" do
|
||||
it "overwrites the existing key when replacement is confirmed" do
|
||||
session = create_verified_session
|
||||
allow_any_instance_of(User).to receive(:nostr_pubkey).and_return(SecureRandom.hex(32))
|
||||
allow(LdapManager::FetchUserByNostrKey).to receive(:call).with(pubkey: user_pubkey).and_return(nil)
|
||||
expect(LdapManager::SetNostrKey).to receive(:call)
|
||||
.with(hash_including(pubkey: user_pubkey)).and_return(0)
|
||||
|
||||
post nostr_signer_replace_settings_path(token: session.token), as: :json
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(JSON.parse(response.body)["status"]).to eq("connected")
|
||||
expect(session.reload).to be_connected
|
||||
end
|
||||
|
||||
it "still rejects a key owned by another account" do
|
||||
session = create_verified_session
|
||||
allow_any_instance_of(User).to receive(:nostr_pubkey).and_return(SecureRandom.hex(32))
|
||||
allow(LdapManager::FetchUserByNostrKey).to receive(:call).with(pubkey: user_pubkey).and_return(other_user)
|
||||
expect(LdapManager::SetNostrKey).not_to receive(:call)
|
||||
|
||||
post nostr_signer_replace_settings_path(token: session.token), as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
|
||||
it "rejects a session that is not verified" do
|
||||
session = NostrManager::RemoteSigner::CreateSession.call(flow: "settings", user: user)
|
||||
expect(LdapManager::SetNostrKey).not_to receive(:call)
|
||||
|
||||
post nostr_signer_replace_settings_path(token: session.token), as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
|
||||
it "rejects an unknown token" do
|
||||
post nostr_signer_replace_settings_path(token: "unknown"), as: :json
|
||||
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
end
|
||||
|
||||
describe "DELETE /settings/nostr_signer" do
|
||||
it "removes all active sessions" do
|
||||
NostrManager::RemoteSigner::CreateSession.call(flow: "settings", user: user)
|
||||
|
||||
expect do
|
||||
delete nostr_signer_settings_path, as: :json
|
||||
end.to change(NostrSignerSession, :count).by(-1)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
end
|
||||
|
||||
it "enqueues logout and starts disconnecting a connected session" do
|
||||
signer_session = create_connected_session
|
||||
|
||||
expect do
|
||||
delete nostr_signer_settings_path, as: :json
|
||||
end.to have_enqueued_job(NostrLogoutJob)
|
||||
|
||||
expect(signer_session.reload.status).to eq("disconnecting")
|
||||
end
|
||||
|
||||
it "replaces the signer section for turbo streams when a key is linked" do
|
||||
allow_any_instance_of(User).to receive(:nostr_pubkey).and_return(user_pubkey)
|
||||
create_connected_session
|
||||
|
||||
delete nostr_signer_settings_path, headers: { "Accept" => "text/vnd.turbo-stream.html" }
|
||||
|
||||
expect(response.media_type).to eq("text/vnd.turbo-stream.html")
|
||||
expect(response.body).to include('target="nostr-signer-section"')
|
||||
expect(response.body).to include("Connect a signer app")
|
||||
end
|
||||
|
||||
it "redirects for turbo streams when no key is linked" do
|
||||
delete nostr_signer_settings_path, headers: { "Accept" => "text/vnd.turbo-stream.html" }
|
||||
|
||||
expect(response).to redirect_to(setting_path(:nostr))
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -78,6 +78,47 @@ RSpec.describe "Settings", type: :request do
|
||||
end
|
||||
end
|
||||
|
||||
context "With a different key already on the account" do
|
||||
before do
|
||||
allow_any_instance_of(User).to receive(:nostr_pubkey).and_return("deadbeef" * 8)
|
||||
expect(LdapManager::SetNostrKey).not_to receive(:call)
|
||||
|
||||
post set_nostr_pubkey_settings_path,
|
||||
params: { signed_event: auth_event }.to_json,
|
||||
headers: {
|
||||
"CONTENT_TYPE" => "application/json",
|
||||
"HTTP_ACCEPT" => "application/json"
|
||||
}
|
||||
end
|
||||
|
||||
it "returns a 422 status" do
|
||||
expect(response).to have_http_status(422)
|
||||
end
|
||||
|
||||
it "asks the user to remove or confirm the replacement" do
|
||||
expect(flash[:alert]).to include("already has a different Nostr public key")
|
||||
end
|
||||
end
|
||||
|
||||
context "With a different key and replacement confirmed" do
|
||||
before do
|
||||
allow_any_instance_of(User).to receive(:nostr_pubkey).and_return("deadbeef" * 8)
|
||||
expect(LdapManager::SetNostrKey).to receive(:call)
|
||||
.with(hash_including(pubkey: auth_event["pubkey"])).and_return(0)
|
||||
|
||||
post set_nostr_pubkey_settings_path,
|
||||
params: { signed_event: auth_event, replace: "true" }.to_json,
|
||||
headers: {
|
||||
"CONTENT_TYPE" => "application/json",
|
||||
"HTTP_ACCEPT" => "application/json"
|
||||
}
|
||||
end
|
||||
|
||||
it "returns a success status" do
|
||||
expect(response).to have_http_status(200)
|
||||
end
|
||||
end
|
||||
|
||||
context "With wrong site tag" do
|
||||
before do
|
||||
Setting.accounts_domain = "accounts.wikipedia.org"
|
||||
@@ -152,6 +193,44 @@ RSpec.describe "Settings", type: :request do
|
||||
end
|
||||
end
|
||||
|
||||
describe "DELETE /settings/nostr_pubkey" do
|
||||
let(:user_pubkey) { SecureRandom.hex(32) }
|
||||
|
||||
before do
|
||||
allow(LdapManager::SetNostrKey).to receive(:call).and_return(0)
|
||||
end
|
||||
|
||||
it "removes the key and disconnects an active remote signer" do
|
||||
session = NostrManager::RemoteSigner::CreateSession.call(flow: "settings", user: user)
|
||||
session.update!(
|
||||
status: "connected",
|
||||
user_pubkey: user_pubkey,
|
||||
remote_signer_pubkey: SecureRandom.hex(32),
|
||||
verified_at: Time.current,
|
||||
consumed_at: Time.current
|
||||
)
|
||||
session.remember!
|
||||
|
||||
expect do
|
||||
delete nostr_pubkey_settings_path
|
||||
end.to have_enqueued_job(NostrLogoutJob).with(session.id)
|
||||
|
||||
expect(LdapManager::SetNostrKey).to have_received(:call)
|
||||
.with(hash_including(pubkey: nil))
|
||||
expect(session.reload.status).to eq("disconnecting")
|
||||
expect(session.remember_token_digest).to be_nil
|
||||
expect(response).to redirect_to(setting_path(:nostr))
|
||||
end
|
||||
|
||||
it "destroys a pending signer session" do
|
||||
NostrManager::RemoteSigner::CreateSession.call(flow: "settings", user: user)
|
||||
|
||||
expect do
|
||||
delete nostr_pubkey_settings_path
|
||||
end.to change(NostrSignerSession, :count).by(-1)
|
||||
end
|
||||
end
|
||||
|
||||
describe "GET /settings/fetch_nostr_metadata" do
|
||||
before do
|
||||
allow_any_instance_of(User).to receive(:nostr_pubkey).and_return("abc123")
|
||||
@@ -159,6 +238,8 @@ RSpec.describe "Settings", type: :request do
|
||||
allow(Setting).to receive(:nostr_relay_url).and_return("wss://site.example.com")
|
||||
allow(Setting).to receive(:nostr_discovery_relays)
|
||||
.and_return(["wss://discovery.example.com"])
|
||||
allow(Setting).to receive(:nostr_blossom_server_url)
|
||||
.and_return("https://blossom.example.com")
|
||||
end
|
||||
|
||||
let(:discovery_relays) do
|
||||
@@ -274,6 +355,50 @@ RSpec.describe "Settings", type: :request do
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
end
|
||||
|
||||
it "includes the media servers section when configured" do
|
||||
get nostr_metadata_settings_path(step: "render"),
|
||||
headers: { "HTTP_ACCEPT" => "text/html" }
|
||||
|
||||
expect(response.body).to include("Media servers")
|
||||
end
|
||||
end
|
||||
|
||||
context "without a configured media server" do
|
||||
before do
|
||||
allow(Setting).to receive(:nostr_blossom_server_url).and_return(nil)
|
||||
end
|
||||
|
||||
it "skips the media server list and asks to render next" do
|
||||
expect(NostrManager::DiscoverUserEvent).to receive(:call)
|
||||
.with(pubkey: "abc123", kind: NostrManagerService::PROFILE_KIND,
|
||||
relays: discovery_relays)
|
||||
.and_return(nil)
|
||||
|
||||
get nostr_metadata_settings_path(step: "profile"),
|
||||
headers: { "HTTP_ACCEPT" => "application/json" }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(JSON.parse(response.body)).to eq("next" => "render", "event_id" => nil)
|
||||
end
|
||||
|
||||
it "does not fetch the media server list" do
|
||||
expect(NostrManager::DiscoverUserEvent).not_to receive(:call)
|
||||
|
||||
get nostr_metadata_settings_path(step: "blossom"),
|
||||
headers: { "HTTP_ACCEPT" => "application/json" }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(JSON.parse(response.body)).to eq("next" => "render")
|
||||
end
|
||||
|
||||
it "does not render the media servers section" do
|
||||
get nostr_metadata_settings_path(step: "render"),
|
||||
headers: { "HTTP_ACCEPT" => "text/html" }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(response.body).not_to include("Media servers")
|
||||
end
|
||||
end
|
||||
|
||||
context "with an unknown step" do
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe "Users::NostrConnects", type: :request do
|
||||
include ActiveJob::TestHelper
|
||||
|
||||
let(:user) { create :user, cn: "mark", ou: "kosmos.org" }
|
||||
|
||||
before do
|
||||
Rails.cache.clear
|
||||
allow(Setting).to receive(:nostr_signer_relays).and_return(["wss://relay.example.com"])
|
||||
allow(Setting).to receive(:accounts_domain).and_return("accounts.example.com")
|
||||
end
|
||||
|
||||
describe "GET /users/nostr_connect" do
|
||||
it "creates a pending login session and renders the QR page" do
|
||||
expect do
|
||||
get nostr_connect_path
|
||||
end.to change(NostrSignerSession, :count).by(1)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(response.body).to include("nostrconnect://")
|
||||
expect(NostrSignerSession.last.flow).to eq("login")
|
||||
end
|
||||
|
||||
it "does not enqueue another listener when the page is reloaded" do
|
||||
get nostr_connect_path
|
||||
clear_enqueued_jobs
|
||||
|
||||
expect do
|
||||
get nostr_connect_path
|
||||
end.not_to have_enqueued_job(NostrConnectListenerJob)
|
||||
end
|
||||
|
||||
it "uses the standard login layout" do
|
||||
get nostr_connect_path
|
||||
|
||||
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("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://")
|
||||
expect(html.css("a[data-action='nostr-signer-connect#openSigner']").size).to eq(2)
|
||||
expect(html.css("[data-controller='clipboard']").any?).to be(true)
|
||||
end
|
||||
end
|
||||
|
||||
describe "GET /users/nostr_connect/status" do
|
||||
it "signs in the user linked to the verified pubkey" do
|
||||
get nostr_connect_path
|
||||
signer_session = NostrSignerSession.last
|
||||
signer_session.update!(
|
||||
status: "verified",
|
||||
user_pubkey: SecureRandom.hex(32),
|
||||
remote_signer_pubkey: SecureRandom.hex(32)
|
||||
)
|
||||
allow(LdapManager::FetchUserByNostrKey).to receive(:call)
|
||||
.with(pubkey: signer_session.user_pubkey)
|
||||
.and_return(user)
|
||||
|
||||
get nostr_connect_status_path, as: :json
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
data = JSON.parse(response.body)
|
||||
expect(data["status"]).to eq("connected")
|
||||
expect(data["redirect_url"]).to be_present
|
||||
expect(request.env["warden"].user).to eq(user)
|
||||
expect(signer_session.reload).to be_connected
|
||||
expect(response.headers["Set-Cookie"]).to include("nostr_remember")
|
||||
end
|
||||
|
||||
it "fails when the pubkey is not linked to an account" do
|
||||
get nostr_connect_path
|
||||
signer_session = NostrSignerSession.last
|
||||
signer_session.update!(status: "verified", user_pubkey: SecureRandom.hex(32))
|
||||
allow(LdapManager::FetchUserByNostrKey).to receive(:call).and_return(nil)
|
||||
|
||||
get nostr_connect_status_path, as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(JSON.parse(response.body)["status"]).to eq("failed")
|
||||
expect(signer_session.reload).to be_failed
|
||||
end
|
||||
|
||||
it "expires a pending login session whose TTL has passed" do
|
||||
get nostr_connect_path
|
||||
signer_session = NostrSignerSession.last
|
||||
signer_session.update_columns(expires_at: 1.minute.ago)
|
||||
|
||||
get nostr_connect_status_path, as: :json
|
||||
|
||||
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
|
||||
it "creates a bunker login session and redirects" do
|
||||
remote = SecureRandom.hex(32)
|
||||
allow(NostrManager::RelayUrlValidator).to receive(:strict_valid?).and_return(true)
|
||||
|
||||
post nostr_connect_path,
|
||||
params: { bunker_uri: "bunker://#{remote}?relay=wss%3A%2F%2Frelay.example.com" }
|
||||
|
||||
expect(response).to have_http_status(:redirect)
|
||||
signer_session = NostrSignerSession.last
|
||||
expect(signer_session).to be_bunker
|
||||
expect(signer_session.remote_signer_pubkey).to eq(remote)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,294 @@
|
||||
require "rails_helper"
|
||||
require "support/nostr_remember_cookie"
|
||||
|
||||
RSpec.describe "Users::NostrContinues", type: :request do
|
||||
include ActiveJob::TestHelper
|
||||
include NostrRememberCookieHelper
|
||||
|
||||
let(:user) { create :user, cn: "mark", ou: "kosmos.org" }
|
||||
let(:user_keypair) { Nostr::Keygen.new.generate_key_pair }
|
||||
let(:signer_keypair) { Nostr::Keygen.new.generate_key_pair }
|
||||
let(:user_pubkey) { user_keypair.public_key.to_s }
|
||||
|
||||
before do
|
||||
Rails.cache.clear
|
||||
allow(Setting).to receive(:nostr_signer_relays).and_return(["wss://relay.example.com"])
|
||||
allow(Setting).to receive(:accounts_domain).and_return("accounts.example.com")
|
||||
allow_any_instance_of(User).to receive(:nostr_pubkey).and_return(user_pubkey)
|
||||
end
|
||||
|
||||
def signed_auth_event(template)
|
||||
values = template.symbolize_keys
|
||||
Nostr::User.new(keypair: user_keypair).create_event(
|
||||
kind: values[:kind],
|
||||
content: values[:content],
|
||||
created_at: values[:created_at],
|
||||
tags: values[:tags]
|
||||
)
|
||||
end
|
||||
|
||||
def remember_session
|
||||
set_remembered_nostr_session(
|
||||
user: user,
|
||||
user_pubkey: user_pubkey,
|
||||
remote_signer_pubkey: signer_keypair.public_key.to_s
|
||||
)
|
||||
end
|
||||
|
||||
describe "the login page" do
|
||||
it "offers to continue as the remembered account" do
|
||||
remember_session
|
||||
|
||||
get new_user_session_path
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(response.body).to include("Continue as #{user.address}")
|
||||
expect(response.body).to include("Log in as a different account")
|
||||
expect(response.body).to include("Use username and password")
|
||||
expect(response.body).not_to include("user[password]")
|
||||
expect(response.body).not_to include("bg-emerald-50")
|
||||
expect(response.body).not_to include("Log in with Nostr")
|
||||
end
|
||||
|
||||
it "does not start a sign request just by showing the page" do
|
||||
remember_session
|
||||
|
||||
expect do
|
||||
get new_user_session_path
|
||||
end.not_to change(NostrSignRequest, :count)
|
||||
end
|
||||
|
||||
it "shows the normal login page when password login is requested" do
|
||||
remember_session
|
||||
|
||||
get new_user_session_path(password: 1)
|
||||
|
||||
expect(response.body).to include("user[password]")
|
||||
expect(response.body).to include("Back to continue as #{user.address}")
|
||||
expect(response.body).not_to include("Continue as #{user.address}")
|
||||
end
|
||||
|
||||
it "shows the normal login page without a remembered account" do
|
||||
get new_user_session_path
|
||||
|
||||
expect(response.body).to include("user[password]")
|
||||
expect(response.body).not_to include("Continue as #{user.address}")
|
||||
expect(response.body).to include("Log in with Nostr")
|
||||
expect(response.body).to include("Nostr Connect")
|
||||
expect(response.body).to include("Browser extension")
|
||||
end
|
||||
|
||||
it "forgets a remembered account whose public key no longer matches" do
|
||||
remember_session
|
||||
allow_any_instance_of(User).to receive(:nostr_pubkey).and_return("different-pubkey")
|
||||
|
||||
get new_user_session_path
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(response.body).to include("user[password]")
|
||||
expect(response.body).not_to include("Continue as #{user.address}")
|
||||
expect(cookies[:nostr_remember]).to be_blank
|
||||
end
|
||||
end
|
||||
|
||||
describe "POST /users/nostr_continue" do
|
||||
it "does nothing without a remembered account" do
|
||||
expect do
|
||||
post nostr_continue_path, as: :json
|
||||
end.not_to change(NostrSignRequest, :count)
|
||||
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
end
|
||||
|
||||
it "creates a reauth request for the remembered account" do
|
||||
remember_session
|
||||
|
||||
expect do
|
||||
post nostr_continue_path
|
||||
end.to change(NostrSignRequest, :count).by(1)
|
||||
.and have_enqueued_job(NostrSignEventJob)
|
||||
|
||||
sign_request = NostrSignRequest.reauth.last
|
||||
expect(response).to have_http_status(:redirect)
|
||||
expect(sign_request.kind).to eq(22242)
|
||||
expect(sign_request).to be_pending
|
||||
expect(sign_request.template["tags"]).to include(["site", "accounts.example.com"])
|
||||
|
||||
get nostr_continue_page_path
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(response.body).to include("Continue as #{user.address}")
|
||||
expect(response.body).to include("Check your signer app")
|
||||
end
|
||||
|
||||
it "invalidates an earlier pending request" do
|
||||
remember_session
|
||||
post nostr_continue_path
|
||||
first = NostrSignRequest.reauth.last
|
||||
|
||||
post nostr_continue_path
|
||||
second = NostrSignRequest.reauth.last
|
||||
|
||||
expect(first.reload).to be_expired
|
||||
expect(second).to be_pending
|
||||
end
|
||||
|
||||
it "is unavailable when Nostr is disabled" do
|
||||
allow(Setting).to receive(:nostr_enabled?).and_return(false)
|
||||
|
||||
post nostr_continue_path, as: :json
|
||||
|
||||
expect(response).to have_http_status(:service_unavailable)
|
||||
end
|
||||
end
|
||||
|
||||
describe "GET /users/nostr_continue/status" do
|
||||
def create_signed_request
|
||||
post nostr_continue_path
|
||||
sign_request = NostrSignRequest.reauth.last
|
||||
event = signed_auth_event(sign_request.template)
|
||||
sign_request.update!(status: "signed", signed_event: event.to_h.stringify_keys)
|
||||
sign_request
|
||||
end
|
||||
|
||||
it "signs in the remembered user" do
|
||||
remember_session
|
||||
old_cookie = cookies[:nostr_remember]
|
||||
sign_request = create_signed_request
|
||||
|
||||
get nostr_continue_status_path, as: :json
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(JSON.parse(response.body)["status"]).to eq("connected")
|
||||
expect(request.env["warden"].user).to eq(user)
|
||||
expect(sign_request.reload).to be_consumed
|
||||
expect(cookies[:nostr_remember]).to be_present
|
||||
expect(cookies[:nostr_remember]).not_to eq(old_cookie)
|
||||
end
|
||||
|
||||
it "rejects an event with a different challenge" do
|
||||
remember_session
|
||||
post nostr_continue_path
|
||||
sign_request = NostrSignRequest.reauth.last
|
||||
template = sign_request.template.deep_dup
|
||||
template["tags"].find { |tag| tag[0] == "challenge" }[1] = "wrong"
|
||||
event = signed_auth_event(template)
|
||||
sign_request.update!(status: "signed", signed_event: event.to_h.stringify_keys)
|
||||
|
||||
get nostr_continue_status_path, as: :json
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(sign_request.reload).to be_failed
|
||||
expect(request.env["warden"].user).not_to eq(user)
|
||||
end
|
||||
|
||||
it "returns gone without a remembered request" do
|
||||
get nostr_continue_status_path, as: :json
|
||||
|
||||
expect(response).to have_http_status(:gone)
|
||||
end
|
||||
|
||||
it "does not sign in a consumed request twice" do
|
||||
remember_session
|
||||
sign_request = create_signed_request
|
||||
|
||||
get nostr_continue_status_path, as: :json
|
||||
get nostr_continue_status_path, as: :json
|
||||
|
||||
expect(response).to have_http_status(:gone)
|
||||
expect(sign_request.reload).to be_consumed
|
||||
end
|
||||
end
|
||||
|
||||
describe "POST /users/nostr_continue/different_account" do
|
||||
it "disconnects and forgets the remembered remote signer" do
|
||||
signer_session = remember_session
|
||||
|
||||
expect do
|
||||
post different_account_nostr_continue_path
|
||||
end.to have_enqueued_job(NostrLogoutJob)
|
||||
|
||||
expect(response).to have_http_status(:redirect)
|
||||
expect(signer_session.reload.status).to eq("disconnecting")
|
||||
expect(cookies[:nostr_remember]).to be_blank
|
||||
end
|
||||
end
|
||||
|
||||
describe "when already signed in" do
|
||||
it "redirects instead of starting a sign request" do
|
||||
remember_session
|
||||
login_as user, scope: :user
|
||||
|
||||
expect do
|
||||
post nostr_continue_path
|
||||
end.not_to change(NostrSignRequest, :count)
|
||||
|
||||
expect(response).to redirect_to(root_path)
|
||||
expect(flash[:notice]).to eq("You are already logged in.")
|
||||
end
|
||||
|
||||
it "redirects the waiting page" do
|
||||
login_as user, scope: :user
|
||||
|
||||
get nostr_continue_page_path
|
||||
|
||||
expect(response).to redirect_to(root_path)
|
||||
end
|
||||
end
|
||||
|
||||
describe "a consumed request" do
|
||||
def consume_pending_request
|
||||
post nostr_continue_path
|
||||
request = NostrSignRequest.reauth.last
|
||||
request.update!(status: "signed", consumed_at: Time.current)
|
||||
request
|
||||
end
|
||||
|
||||
it "does not report connected when signed out" do
|
||||
remember_session
|
||||
request = consume_pending_request
|
||||
|
||||
get nostr_continue_status_path, as: :json
|
||||
|
||||
expect(response).to have_http_status(:gone)
|
||||
expect(JSON.parse(response.body)["status"]).to eq("expired")
|
||||
expect(session[:nostr_reauth_token]).to be_nil
|
||||
expect(request.reload).to be_consumed
|
||||
end
|
||||
|
||||
it "reports connected when signed in as the remembered user" do
|
||||
remember_session
|
||||
consume_pending_request
|
||||
login_as user, scope: :user
|
||||
|
||||
get nostr_continue_status_path, as: :json
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(JSON.parse(response.body)["status"]).to eq("connected")
|
||||
end
|
||||
end
|
||||
|
||||
describe "an expired request" do
|
||||
it "clears the reauth token" do
|
||||
remember_session
|
||||
post nostr_continue_path
|
||||
NostrSignRequest.reauth.last.update!(expires_at: 1.minute.ago)
|
||||
|
||||
get nostr_continue_status_path, as: :json
|
||||
|
||||
expect(response).to have_http_status(:gone)
|
||||
expect(session[:nostr_reauth_token]).to be_nil
|
||||
end
|
||||
end
|
||||
|
||||
describe "signing out" do
|
||||
it "clears the reauth token" do
|
||||
remember_session
|
||||
post nostr_continue_path
|
||||
login_as user, scope: :user
|
||||
|
||||
get destroy_user_session_path
|
||||
|
||||
expect(session[:nostr_reauth_token]).to be_nil
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,24 @@
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe LdapManager::SetNostrKey, type: :model do
|
||||
let(:user) { create :user, cn: "mark", ou: "kosmos.org" }
|
||||
let(:dn) { "cn=mark,ou=kosmos.org,cn=users,dc=kosmos,dc=org" }
|
||||
|
||||
before do
|
||||
allow(user).to receive(:dn).and_return(dn)
|
||||
end
|
||||
|
||||
it "writes the key through the low-level LDAP writer" do
|
||||
expect(LdapManager::UpdateNostrKey).to receive(:call)
|
||||
.with(dn: dn, pubkey: "abc").and_return(0)
|
||||
|
||||
described_class.call(user: user, pubkey: "abc")
|
||||
end
|
||||
|
||||
it "removes the key when the pubkey is blank" do
|
||||
expect(LdapManager::UpdateNostrKey).to receive(:call)
|
||||
.with(dn: dn, pubkey: nil).and_return(0)
|
||||
|
||||
described_class.call(user: user, pubkey: nil)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,136 @@
|
||||
require "rails_helper"
|
||||
require "digest"
|
||||
|
||||
RSpec.describe NostrManager::Nip44, type: :model do
|
||||
let(:vectors) { JSON.parse(File.read(Rails.root.join("spec/fixtures/nostr/nip44_vectors.json")))["v2"] }
|
||||
|
||||
describe ".available?" do
|
||||
it "supports secp256k1 ECDH and ChaCha20" do
|
||||
expect(described_class.available?).to be(true)
|
||||
end
|
||||
end
|
||||
|
||||
describe ".conversation_key" do
|
||||
it "matches the official valid vectors" do
|
||||
vectors["valid"]["get_conversation_key"].each do |vector|
|
||||
key = described_class.conversation_key(vector["sec1"], vector["pub2"])
|
||||
|
||||
expect(key).to eq([vector["conversation_key"]].pack("H*")), vector.inspect
|
||||
end
|
||||
end
|
||||
|
||||
it "rejects the official invalid vectors" do
|
||||
vectors["invalid"]["get_conversation_key"].each do |vector|
|
||||
expect do
|
||||
described_class.conversation_key(vector["sec1"], vector["pub2"])
|
||||
end.to raise_error(NostrManager::Nip44::Error), vector.inspect
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe "#derive_message_keys" do
|
||||
it "matches the official message-key vectors" do
|
||||
vector = vectors["valid"]["get_message_keys"]
|
||||
cipher = described_class.new("0" * 64, "0" * 64)
|
||||
allow(cipher).to receive(:conversation_key).and_return([vector["conversation_key"]].pack("H*"))
|
||||
|
||||
vector["keys"].each do |entry|
|
||||
chacha_key, chacha_nonce, hmac_key = cipher.derive_message_keys([entry["nonce"]].pack("H*"))
|
||||
|
||||
expect(chacha_key.unpack1("H*")).to eq(entry["chacha_key"])
|
||||
expect(chacha_nonce.unpack1("H*")).to eq(entry["chacha_nonce"])
|
||||
expect(hmac_key.unpack1("H*")).to eq(entry["hmac_key"])
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe "#calc_padded_len" do
|
||||
it "matches the official padding ladder" do
|
||||
cipher = described_class.new("0" * 64, "0" * 64)
|
||||
|
||||
vectors["valid"]["calc_padded_len"].each do |unpadded, padded|
|
||||
expect(cipher.calc_padded_len(unpadded)).to eq(padded), "unpadded=#{unpadded}"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe "encrypt/decrypt" do
|
||||
it "matches the official vectors in both directions" do
|
||||
vectors["valid"]["encrypt_decrypt"].each do |vector|
|
||||
nonce = [vector["nonce"]].pack("H*")
|
||||
alice, bob = ciphers_for(vector["sec1"], vector["sec2"])
|
||||
|
||||
payload = alice.encrypt(vector["plaintext"], nonce: nonce)
|
||||
expect(payload).to eq(vector["payload"]), vector["plaintext"].inspect
|
||||
expect(bob.decrypt(payload)).to eq(vector["plaintext"])
|
||||
expect(alice.decrypt(payload)).to eq(vector["plaintext"])
|
||||
end
|
||||
end
|
||||
|
||||
it "matches the official long-message vectors" do
|
||||
vectors["valid"]["encrypt_decrypt_long_msg"].each do |vector|
|
||||
plaintext = vector["pattern"] * vector["repeat"]
|
||||
nonce = [vector["nonce"]].pack("H*")
|
||||
|
||||
expect(Digest::SHA256.hexdigest(plaintext)).to eq(vector["plaintext_sha256"])
|
||||
|
||||
cipher = described_class.new("0" * 64, "0" * 64)
|
||||
allow(cipher).to receive(:conversation_key).and_return([vector["conversation_key"]].pack("H*"))
|
||||
|
||||
payload = cipher.encrypt(plaintext, nonce: nonce)
|
||||
expect(Digest::SHA256.hexdigest(payload)).to eq(vector["payload_sha256"])
|
||||
expect(cipher.decrypt(payload)).to eq(plaintext)
|
||||
end
|
||||
end
|
||||
|
||||
it "round-trips plaintexts that use the extended padding prefix" do
|
||||
alice, bob = key_pair
|
||||
|
||||
[65_536, 100_000].each do |length|
|
||||
payload = alice.encrypt("a" * length)
|
||||
|
||||
expect(bob.decrypt(payload)).to eq("a" * length)
|
||||
end
|
||||
end
|
||||
|
||||
it "rejects invalid plaintext lengths" do
|
||||
alice, = key_pair
|
||||
|
||||
expect { alice.encrypt("") }.to raise_error(NostrManager::Nip44::Error)
|
||||
expect { alice.encrypt("a" * (described_class::MAX_PLAINTEXT_BYTES + 1)) }
|
||||
.to raise_error(NostrManager::Nip44::Error)
|
||||
end
|
||||
|
||||
it "rejects the official invalid ciphertexts" do
|
||||
vectors["invalid"]["decrypt"].each do |vector|
|
||||
cipher = described_class.new("0" * 64, "0" * 64)
|
||||
allow(cipher).to receive(:conversation_key).and_return([vector["conversation_key"]].pack("H*"))
|
||||
|
||||
expect { cipher.decrypt(vector["payload"]) }
|
||||
.to raise_error(NostrManager::Nip44::Error), vector["note"]
|
||||
end
|
||||
end
|
||||
|
||||
it "raises a specific error for NIP-04 payloads" do
|
||||
alice, = key_pair
|
||||
|
||||
expect { alice.decrypt("abc?iv=def") }
|
||||
.to raise_error(NostrManager::Nip44::UnsupportedTransportError)
|
||||
end
|
||||
end
|
||||
|
||||
def key_pair
|
||||
ciphers_for(SecureRandom.hex(32), SecureRandom.hex(32))
|
||||
end
|
||||
|
||||
def ciphers_for(alice_private_key, bob_private_key)
|
||||
keygen = Nostr::Keygen.new
|
||||
alice_public_key = keygen.extract_public_key(Nostr::PrivateKey.new(alice_private_key))
|
||||
bob_public_key = keygen.extract_public_key(Nostr::PrivateKey.new(bob_private_key))
|
||||
|
||||
[
|
||||
described_class.new(alice_private_key, bob_public_key.to_s),
|
||||
described_class.new(bob_private_key, alice_public_key.to_s)
|
||||
]
|
||||
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,51 @@
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe NostrManager::RemoteSigner::DisconnectSessions, type: :model do
|
||||
let(:user) { create :user, cn: "mark", ou: "kosmos.org" }
|
||||
let(:user_pubkey) { SecureRandom.hex(32) }
|
||||
|
||||
def connected_session
|
||||
NostrManager::RemoteSigner::CreateSession.call(flow: "settings", user: user).tap do |session|
|
||||
session.update!(
|
||||
status: "connected",
|
||||
remote_signer_pubkey: SecureRandom.hex(32),
|
||||
user_pubkey: user_pubkey,
|
||||
verified_at: Time.current,
|
||||
consumed_at: Time.current
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
it "starts a NIP-46 logout and clears the remember token for a connected session" do
|
||||
session = connected_session
|
||||
session.remember!
|
||||
|
||||
expect do
|
||||
described_class.call(sessions: NostrSignerSession.where(id: session.id))
|
||||
end.to have_enqueued_job(NostrLogoutJob).with(session.id)
|
||||
|
||||
expect(session.reload.status).to eq("disconnecting")
|
||||
expect(session.remember_token_digest).to be_nil
|
||||
end
|
||||
|
||||
it "destroys a pending session without logging out" do
|
||||
session = NostrManager::RemoteSigner::CreateSession.call(flow: "settings", user: user)
|
||||
|
||||
expect do
|
||||
described_class.call(sessions: NostrSignerSession.where(id: session.id))
|
||||
end.not_to have_enqueued_job(NostrLogoutJob)
|
||||
|
||||
expect(NostrSignerSession.find_by(id: session.id)).to be_nil
|
||||
end
|
||||
|
||||
it "ignores already disconnecting and nil sessions" do
|
||||
session = connected_session
|
||||
session.update!(status: "disconnecting")
|
||||
|
||||
expect do
|
||||
described_class.call(sessions: [session, nil])
|
||||
end.not_to have_enqueued_job(NostrLogoutJob)
|
||||
|
||||
expect(session.reload.status).to eq("disconnecting")
|
||||
end
|
||||
end
|
||||
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user