Add models for NIP-46 signer sessions and signing requests

This commit is contained in:
raucao committed 2026-11-27 15:43:00 +04:00
1 parent dc3a022dca
commit d3801050f6
8 files changed
+432 -1

No files matched your search

+48
View File
@@ -0,0 +1,48 @@
require "securerandom"
class NostrSignRequest < ApplicationRecord
TTL = 2.minutes
STATUSES = %w[pending signed failed expired].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 :expires_at, presence: true
scope :pending, -> { where(status: "pending") }
scope :stale, -> { where("expires_at < ?", Time.current).where(status: "pending") }
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 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
+141
View File
@@ -0,0 +1,141 @@
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].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
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 :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.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 usable?
verified? || connected? || pending?
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
domain = Setting.accounts_domain.to_s
params = relays.map { |relay| ["relay", relay] }
params << ["secret", secret] if secret.present?
params << ["name", domain] if domain.present?
params << ["url", "https://#{domain}"] if domain.present?
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
+3
View File
@@ -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,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
+51 -1
View File
@@ -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_24_121000) 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,54 @@ 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 "created_at", null: false
t.string "error"
t.datetime "expires_at", null: false
t.integer "kind", 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", "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 "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 ["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 +230,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"
+42
View File
@@ -0,0 +1,42 @@
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
end
+91
View File
@@ -0,0 +1,91 @@
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 and permissions" do
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["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
end