Process and relay Nostr profile images server-side
Add a server-side API for avatar and header images: uploads are cropped with Vips (400x400 and 1500x500, GIFs passed through, EXIF stripped, transparency flattened to white) and stored as one pending attachment per field. Saving the profile flushes them to the configured Blossom server, authorized by a user-signed kind-24242 token whose x tags cover the stored hashes.
This commit is contained in:
11 files changed
+755
No files matched your search
@@ -0,0 +1,109 @@
|
||||
module Settings
|
||||
class NostrMediaController < ApplicationController
|
||||
before_action :authenticate_user!
|
||||
|
||||
AUTH_KIND = 24242
|
||||
CLOCK_SKEW = 5.minutes
|
||||
EXPIRATION_WINDOW = 24.hours
|
||||
MAX_TAGS = 20
|
||||
MAX_TAG_BYTES = 512
|
||||
RATE_LIMIT = 6
|
||||
RATE_WINDOW = 5.minutes
|
||||
|
||||
def create
|
||||
return render_error("This account has no Nostr public key", :forbidden) if current_user.nostr_pubkey.blank?
|
||||
return render_error("Media server is not configured", :unprocessable_entity) if BlossomManagerService.server_url.blank?
|
||||
return render_error("Too many upload attempts. Please try again later.", :too_many_requests) if rate_limited?
|
||||
|
||||
auth_event = verified_auth_event(params[:signed_event])
|
||||
return render_error("Invalid authorization", :unprocessable_entity) if auth_event.nil?
|
||||
|
||||
hashes = authorized_hashes(auth_event)
|
||||
uploads = []
|
||||
|
||||
pending_images.each do |field, attachment|
|
||||
bytes = attachment.blob.download
|
||||
sha256 = Digest::SHA256.hexdigest(bytes)
|
||||
next unless hashes.include?(sha256)
|
||||
|
||||
descriptor = BlossomManager::UploadBlob.call(
|
||||
bytes: bytes, content_type: attachment.blob.content_type, sha256: sha256, auth_event: auth_event
|
||||
)
|
||||
return render_error("Upload failed", :bad_gateway) if descriptor.nil?
|
||||
|
||||
uploads << { field: field, url: descriptor["url"] }
|
||||
end
|
||||
|
||||
render json: { uploads: uploads }
|
||||
rescue ActionController::ParameterMissing, ArgumentError, TypeError, JSON::ParserError
|
||||
render_error("Invalid upload", :unprocessable_entity)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def pending_images
|
||||
{
|
||||
"picture" => current_user.nostr_picture,
|
||||
"banner" => current_user.nostr_banner
|
||||
}.select { |_field, attachment| attachment.attached? }
|
||||
end
|
||||
|
||||
def verified_auth_event(raw)
|
||||
return nil if raw.blank?
|
||||
|
||||
data = (raw.respond_to?(:to_unsafe_h) ? raw.to_unsafe_h : raw.to_h).symbolize_keys
|
||||
event = Nostr::Event.new(**data.slice(:id, :pubkey, :created_at, :kind, :tags, :content, :sig))
|
||||
return nil unless event.kind == AUTH_KIND && event.pubkey == current_user.nostr_pubkey
|
||||
return nil unless created_at_valid?(event.created_at)
|
||||
return nil unless NostrManager::VerifySignedEvent.call(event: event, allowed_kinds: [AUTH_KIND])
|
||||
return nil unless within_tag_limits?(event.tags)
|
||||
return nil unless auth_tags_valid?(event.tags)
|
||||
|
||||
event
|
||||
rescue JSON::ParserError, ArgumentError, TypeError, NoMethodError
|
||||
nil
|
||||
end
|
||||
|
||||
def created_at_valid?(created_at)
|
||||
created_at.is_a?(Integer) && created_at <= (Time.current.to_i + CLOCK_SKEW.to_i)
|
||||
end
|
||||
|
||||
def within_tag_limits?(tags)
|
||||
tags = Array(tags)
|
||||
return false if tags.size > MAX_TAGS
|
||||
|
||||
tags.all? do |tag|
|
||||
tag.is_a?(Array) &&
|
||||
tag.all? { |value| value.is_a?(String) } &&
|
||||
tag.sum(&:bytesize) <= MAX_TAG_BYTES
|
||||
end
|
||||
end
|
||||
|
||||
def auth_tags_valid?(tags)
|
||||
verbs = tags.select { |tag| tag[0] == "t" }.map { |tag| tag[1] }
|
||||
return false unless verbs.include?("upload")
|
||||
|
||||
expiration = tags.find { |tag| tag[0] == "expiration" }&.[](1)
|
||||
return false unless expiration.to_s.match?(/\A\d+\z/)
|
||||
|
||||
expiration.to_i.between?(Time.current.to_i, (Time.current.to_i + EXPIRATION_WINDOW.to_i))
|
||||
end
|
||||
|
||||
def authorized_hashes(event)
|
||||
Array(event.tags).select { |tag| tag[0] == "x" }.map { |tag| tag[1] }
|
||||
end
|
||||
|
||||
def rate_limited?
|
||||
key = "nostr_media:#{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,93 @@
|
||||
require "marcel"
|
||||
|
||||
module Settings
|
||||
class NostrProfileImagesController < ApplicationController
|
||||
before_action :authenticate_user!
|
||||
|
||||
FIELDS = BlossomManagerService::MAX_UPLOAD_BYTES.keys.freeze
|
||||
ALLOWED_CONTENT_TYPES = %w[image/jpeg image/png image/webp image/gif].freeze
|
||||
EXTENSIONS = {
|
||||
"image/jpeg" => "jpg", "image/png" => "png", "image/webp" => "webp", "image/gif" => "gif"
|
||||
}.freeze
|
||||
REQUEST_SLACK = 64.kilobytes
|
||||
MAX_CAP = BlossomManagerService::MAX_UPLOAD_BYTES.values.max
|
||||
RATE_LIMIT = 10
|
||||
RATE_WINDOW = 5.minutes
|
||||
|
||||
def create
|
||||
return render_error("Media server is not configured", :unprocessable_entity) if BlossomManagerService.server_url.blank?
|
||||
return render_error("Too many upload attempts. Please try again later.", :too_many_requests) if rate_limited?
|
||||
return render_error("File is too large", :payload_too_large) if request.content_length.to_i > MAX_CAP + REQUEST_SLACK
|
||||
|
||||
field = upload_field
|
||||
return render_error("Invalid upload", :unprocessable_entity) if field.nil?
|
||||
|
||||
file = params.require(:file)
|
||||
return render_error("Invalid upload", :unprocessable_entity) unless file.is_a?(ActionDispatch::Http::UploadedFile)
|
||||
return render_error("File is too large", :payload_too_large) if file.size > BlossomManagerService.max_upload_bytes(field)
|
||||
|
||||
content_type = detect_content_type(file)
|
||||
return render_error("Unsupported file type", :unprocessable_entity) unless ALLOWED_CONTENT_TYPES.include?(content_type)
|
||||
|
||||
bytes = NostrManager::ProcessProfileImage.call(field: field, io: file, content_type: content_type)
|
||||
return render_error("Could not process image", :unprocessable_entity) if bytes.blank?
|
||||
|
||||
store(field, bytes)
|
||||
|
||||
sha256 = Digest::SHA256.hexdigest(bytes)
|
||||
render json: { sha256: sha256, previewUrl: nostr_profile_image_settings_path(field, v: sha256) }
|
||||
rescue ActionController::ParameterMissing, ArgumentError, TypeError => e
|
||||
Rails.logger.warn("[nostr] Malformed profile image upload: #{e.class}: #{e.message}")
|
||||
render_error("Invalid upload", :unprocessable_entity)
|
||||
end
|
||||
|
||||
def show
|
||||
field = upload_field
|
||||
attachment = field && current_user.public_send(attachment_name(field))
|
||||
http_status :not_found and return unless attachment&.attached?
|
||||
|
||||
send_data attachment.blob.download, type: attachment.blob.content_type, disposition: "inline"
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def upload_field
|
||||
field = params[:field].to_s
|
||||
FIELDS.include?(field) ? field : nil
|
||||
end
|
||||
|
||||
def attachment_name(field)
|
||||
field == "banner" ? :nostr_banner : :nostr_picture
|
||||
end
|
||||
|
||||
def detect_content_type(file)
|
||||
file.rewind
|
||||
Marcel::MimeType.for(file.tempfile, name: file.original_filename.to_s, declared_type: file.content_type)
|
||||
ensure
|
||||
file.rewind
|
||||
end
|
||||
|
||||
def store(field, bytes)
|
||||
content_type = Marcel::MimeType.for(StringIO.new(bytes))
|
||||
current_user.public_send(attachment_name(field)).attach(
|
||||
io: StringIO.new(bytes),
|
||||
filename: "#{field}.#{EXTENSIONS.fetch(content_type, "jpg")}",
|
||||
content_type: content_type
|
||||
)
|
||||
current_user.save
|
||||
end
|
||||
|
||||
def rate_limited?
|
||||
key = "nostr_profile_image:#{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
|
||||
@@ -32,6 +32,8 @@ class User < ApplicationRecord
|
||||
#
|
||||
|
||||
has_one_attached :avatar
|
||||
has_one_attached :nostr_picture
|
||||
has_one_attached :nostr_banner
|
||||
|
||||
#
|
||||
# Validations
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
module BlossomManager
|
||||
class UploadBlob < BlossomManagerService
|
||||
def initialize(bytes:, content_type:, sha256:, auth_event:, server_url: self.class.server_url)
|
||||
@bytes = bytes
|
||||
@content_type = content_type
|
||||
@sha256 = sha256
|
||||
@auth_event = auth_event
|
||||
@server_url = server_url
|
||||
end
|
||||
|
||||
def call
|
||||
return nil if @server_url.blank?
|
||||
|
||||
response = connection.put("#{@server_url}/upload") do |req|
|
||||
req.headers["Content-Type"] = @content_type
|
||||
req.headers["X-SHA-256"] = @sha256
|
||||
req.headers["Authorization"] = "Nostr #{encoded_auth}"
|
||||
req.body = @bytes
|
||||
end
|
||||
return nil unless [200, 201, 409].include?(response.status)
|
||||
|
||||
descriptor = JSON.parse(response.body)
|
||||
return nil unless descriptor["sha256"] == @sha256
|
||||
return nil if descriptor["url"].blank?
|
||||
|
||||
descriptor
|
||||
rescue Faraday::Error, JSON::ParserError, TypeError
|
||||
nil
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def encoded_auth
|
||||
Base64.urlsafe_encode64(@auth_event.to_h.to_json, padding: false)
|
||||
end
|
||||
|
||||
def connection
|
||||
Faraday.new do |conn|
|
||||
conn.options.open_timeout = SERVER_TIMEOUT
|
||||
conn.options.timeout = SERVER_TIMEOUT
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,19 @@
|
||||
class BlossomManagerService < ApplicationService
|
||||
SERVER_TIMEOUT = 15
|
||||
|
||||
# Per-field upload caps: the header image is allowed to be larger than the avatar.
|
||||
MAX_UPLOAD_BYTES = {
|
||||
"picture" => 1.megabyte,
|
||||
"banner" => 2.megabytes
|
||||
}.freeze
|
||||
|
||||
DEFAULT_FIELD = "picture"
|
||||
|
||||
def self.server_url
|
||||
Setting.nostr_blossom_server_url.to_s.strip.chomp("/")
|
||||
end
|
||||
|
||||
def self.max_upload_bytes(field)
|
||||
MAX_UPLOAD_BYTES.fetch(field.to_s, MAX_UPLOAD_BYTES.fetch(DEFAULT_FIELD))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,56 @@
|
||||
module NostrManager
|
||||
class ProcessProfileImage < NostrManagerService
|
||||
DIMENSIONS = { "picture" => [400, 400], "banner" => [1500, 500] }.freeze
|
||||
PASSTHROUGH_TYPES = %w[image/gif].freeze
|
||||
OUTPUT_EXTENSIONS = { "image/png" => "png" }.freeze
|
||||
DEFAULT_EXTENSION = "jpg"
|
||||
MAX_PIXELS = 50_000_000
|
||||
MAX_SIDE = 20_000
|
||||
|
||||
def initialize(field:, io:, content_type:)
|
||||
@field = field.to_s
|
||||
@io = io
|
||||
@content_type = content_type
|
||||
end
|
||||
|
||||
def call
|
||||
dimensions = DIMENSIONS[@field]
|
||||
return nil if dimensions.nil? || @io.nil?
|
||||
|
||||
Tempfile.create(["nostr-profile-image", ".#{output_extension}"]) do |source|
|
||||
source.binmode
|
||||
source.write(@io.read)
|
||||
source.rewind
|
||||
|
||||
image = Vips::Image.new_from_file(source.path)
|
||||
return nil unless within_bounds?(image)
|
||||
return File.binread(source.path) if PASSTHROUGH_TYPES.include?(@content_type)
|
||||
|
||||
width, height = dimensions
|
||||
pipeline = ImageProcessing::Vips.source(source.path).resize_to_fill(width, height)
|
||||
pipeline = pipeline.flatten(background: [255]) if jpeg_output? && image.has_alpha?
|
||||
pipeline.saver(strip: true).call.read
|
||||
end
|
||||
rescue Vips::Error => e
|
||||
Rails.logger.warn { "Nostr profile image processing failed: #{e.message}" }
|
||||
nil
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def output_extension
|
||||
OUTPUT_EXTENSIONS.fetch(@content_type, DEFAULT_EXTENSION)
|
||||
end
|
||||
|
||||
def jpeg_output?
|
||||
output_extension == DEFAULT_EXTENSION
|
||||
end
|
||||
|
||||
def within_bounds?(image)
|
||||
return false unless image.width.between?(1, MAX_SIDE)
|
||||
return false unless image.height.between?(1, MAX_SIDE)
|
||||
|
||||
image.width * image.height <= MAX_PIXELS
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -67,6 +67,9 @@ 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_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
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
require "rails_helper"
|
||||
require "webmock/rspec"
|
||||
|
||||
RSpec.describe "Settings::NostrMedia", type: :request do
|
||||
let(:user) { create :user, cn: "mike", ou: "kosmos.org" }
|
||||
let(:pubkey) { Setting.nostr_public_key }
|
||||
let(:keypair) do
|
||||
Nostr::KeyPair.new(
|
||||
private_key: Nostr::PrivateKey.new(Setting.nostr_private_key),
|
||||
public_key: Nostr::PublicKey.new(Setting.nostr_public_key)
|
||||
)
|
||||
end
|
||||
let(:nostr_user) { Nostr::User.new(keypair: keypair) }
|
||||
let(:fixture_path) { Rails.root.join("spec/fixtures/files/taipei.jpg") }
|
||||
let(:pending_bytes) { File.binread(fixture_path) }
|
||||
let(:sha256) { Digest::SHA256.hexdigest(pending_bytes) }
|
||||
let(:blossom_server) { "https://blossom.example.com" }
|
||||
let(:descriptor) do
|
||||
{
|
||||
"url" => "#{blossom_server}/#{sha256}.jpg",
|
||||
"sha256" => sha256,
|
||||
"size" => pending_bytes.bytesize,
|
||||
"type" => "image/jpeg",
|
||||
"uploaded" => Time.current.to_i
|
||||
}
|
||||
end
|
||||
|
||||
before do
|
||||
login_as user, :scope => :user
|
||||
allow_any_instance_of(User).to receive(:nostr_pubkey).and_return(pubkey)
|
||||
allow(Setting).to receive(:nostr_blossom_server_url).and_return(blossom_server)
|
||||
|
||||
stub_request(:put, "#{blossom_server}/upload").to_return(
|
||||
status: 201, body: descriptor.to_json, headers: { "Content-Type" => "application/json" }
|
||||
)
|
||||
end
|
||||
|
||||
def attach_pending(field: :nostr_picture, data: pending_bytes)
|
||||
user.public_send(field).attach(
|
||||
io: StringIO.new(data), filename: "#{field}.jpg", content_type: "image/jpeg"
|
||||
)
|
||||
end
|
||||
|
||||
def auth_event(x: [sha256], verb: "upload", expiration: 5.minutes.from_now.to_i)
|
||||
tags = [["t", verb]] + x.map { |hash| ["x", hash] }
|
||||
tags << ["expiration", expiration.to_s] if expiration
|
||||
nostr_user.create_event(
|
||||
kind: 24242, created_at: Time.current.to_i, tags: tags, content: "Upload profile images"
|
||||
)
|
||||
end
|
||||
|
||||
def flush(event)
|
||||
post nostr_media_settings_path, params: { signed_event: event.to_h }, as: :json
|
||||
end
|
||||
|
||||
describe "POST /settings/nostr_media" do
|
||||
it "uploads the pending image to the blossom server" do
|
||||
attach_pending
|
||||
|
||||
flush(auth_event)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(JSON.parse(response.body)).to eq(
|
||||
"uploads" => [{ "field" => "picture", "url" => descriptor["url"] }]
|
||||
)
|
||||
expect(WebMock).to have_requested(:put, "#{blossom_server}/upload").with(body: pending_bytes)
|
||||
end
|
||||
|
||||
it "uploads every pending field covered by the token" do
|
||||
attach_pending
|
||||
attach_pending(field: :nostr_banner)
|
||||
|
||||
flush(auth_event)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(JSON.parse(response.body)["uploads"].map { |u| u["field"] }).to eq(%w[picture banner])
|
||||
expect(WebMock).to have_requested(:put, "#{blossom_server}/upload").twice
|
||||
end
|
||||
|
||||
it "returns no uploads when nothing is pending" do
|
||||
flush(auth_event(x: []))
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(JSON.parse(response.body)).to eq("uploads" => [])
|
||||
expect(WebMock).not_to have_requested(:put, "#{blossom_server}/upload")
|
||||
end
|
||||
|
||||
it "skips a pending image the token does not authorize" do
|
||||
attach_pending
|
||||
|
||||
flush(auth_event(x: ["0" * 64]))
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(JSON.parse(response.body)).to eq("uploads" => [])
|
||||
expect(WebMock).not_to have_requested(:put, "#{blossom_server}/upload")
|
||||
end
|
||||
|
||||
it "rejects a token signed by another key" do
|
||||
attach_pending
|
||||
|
||||
flush(Nostr::Event.new(**auth_event.to_h.merge(pubkey: "0" * 64)))
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
|
||||
context "when the account has no public key" do
|
||||
before { allow_any_instance_of(User).to receive(:nostr_pubkey).and_return(nil) }
|
||||
|
||||
it "is forbidden" do
|
||||
flush(auth_event)
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
end
|
||||
end
|
||||
|
||||
context "when no blossom server is configured" do
|
||||
before { allow(Setting).to receive(:nostr_blossom_server_url).and_return(nil) }
|
||||
|
||||
it "is rejected" do
|
||||
flush(auth_event)
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
end
|
||||
|
||||
context "when the blossom upload fails" do
|
||||
it "returns a bad gateway" do
|
||||
attach_pending
|
||||
stub_request(:put, "#{blossom_server}/upload").to_return(status: 500, body: "boom")
|
||||
|
||||
flush(auth_event)
|
||||
|
||||
expect(response).to have_http_status(:bad_gateway)
|
||||
end
|
||||
end
|
||||
|
||||
context "when blossom returns 409 with a matching descriptor" do
|
||||
it "is treated as success" do
|
||||
attach_pending
|
||||
stub_request(:put, "#{blossom_server}/upload").to_return(status: 409, body: descriptor.to_json)
|
||||
|
||||
flush(auth_event)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(JSON.parse(response.body)["uploads"].first["url"]).to eq(descriptor["url"])
|
||||
end
|
||||
end
|
||||
|
||||
context "when rate limited" do
|
||||
before { allow(Rails).to receive(:cache).and_return(ActiveSupport::Cache::MemoryStore.new) }
|
||||
|
||||
it "rejects after too many attempts" do
|
||||
Settings::NostrMediaController::RATE_LIMIT.times { flush(auth_event(x: [])) }
|
||||
|
||||
flush(auth_event(x: []))
|
||||
|
||||
expect(response).to have_http_status(:too_many_requests)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,105 @@
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe "Settings::NostrProfileImages", type: :request do
|
||||
let(:user) { create :user, cn: "mike", ou: "kosmos.org" }
|
||||
let(:fixture_path) { Rails.root.join("spec/fixtures/files/taipei.jpg") }
|
||||
|
||||
before do
|
||||
login_as user, :scope => :user
|
||||
allow(Setting).to receive(:nostr_blossom_server_url).and_return("https://blossom.example.com")
|
||||
end
|
||||
|
||||
def upload(field:, file: Rack::Test::UploadedFile.new(fixture_path.to_s, "image/jpeg"))
|
||||
post nostr_profile_images_settings_path, params: { field: field, file: file }
|
||||
end
|
||||
|
||||
def dimensions(bytes)
|
||||
image = Vips::Image.new_from_buffer(bytes, "")
|
||||
[image.width, image.height]
|
||||
end
|
||||
|
||||
describe "POST /settings/nostr_profile_images" do
|
||||
it "stores a cropped avatar and returns the hash and preview url" do
|
||||
upload(field: "picture")
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
body = JSON.parse(response.body)
|
||||
expect(body["previewUrl"]).to eq("/settings/nostr_profile_images/picture?v=#{body["sha256"]}")
|
||||
|
||||
user.reload
|
||||
expect(user.nostr_picture).to be_attached
|
||||
stored = user.nostr_picture.blob.download
|
||||
expect(body["sha256"]).to eq(Digest::SHA256.hexdigest(stored))
|
||||
expect(dimensions(stored)).to eq([400, 400])
|
||||
end
|
||||
|
||||
it "stores a cropped header image" do
|
||||
upload(field: "banner")
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
stored = user.reload.nostr_banner.blob.download
|
||||
expect(dimensions(stored)).to eq([1500, 500])
|
||||
end
|
||||
|
||||
it "rejects an unknown field" do
|
||||
upload(field: "avatar")
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
|
||||
it "rejects an oversized avatar" do
|
||||
big = Tempfile.create(["big", ".jpg"])
|
||||
big.truncate(BlossomManagerService.max_upload_bytes("picture") + 1)
|
||||
|
||||
upload(field: "picture", file: Rack::Test::UploadedFile.new(big.path, "image/jpeg"))
|
||||
|
||||
expect(response).to have_http_status(:payload_too_large)
|
||||
ensure
|
||||
big.close
|
||||
File.delete(big.path) if File.exist?(big.path)
|
||||
end
|
||||
|
||||
it "rejects a non-image" do
|
||||
pdf = Rack::Test::UploadedFile.new(Rails.root.join("spec/fixtures/files/bitcoin.pdf").to_s, "application/pdf")
|
||||
upload(field: "picture", file: pdf)
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
|
||||
context "when no blossom server is configured" do
|
||||
before { allow(Setting).to receive(:nostr_blossom_server_url).and_return(nil) }
|
||||
|
||||
it "is rejected" do
|
||||
upload(field: "picture")
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
end
|
||||
|
||||
context "when rate limited" do
|
||||
before { allow(Rails).to receive(:cache).and_return(ActiveSupport::Cache::MemoryStore.new) }
|
||||
|
||||
it "rejects after too many attempts" do
|
||||
Settings::NostrProfileImagesController::RATE_LIMIT.times { upload(field: "picture") }
|
||||
|
||||
upload(field: "picture")
|
||||
|
||||
expect(response).to have_http_status(:too_many_requests)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe "GET /settings/nostr_profile_images/:field" do
|
||||
it "serves the stored preview" do
|
||||
upload(field: "picture")
|
||||
|
||||
get nostr_profile_image_settings_path("picture")
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(response.media_type).to eq("image/jpeg")
|
||||
expect(response.body.bytesize).to be > 0
|
||||
end
|
||||
|
||||
it "is not found when nothing is stored" do
|
||||
get nostr_profile_image_settings_path("picture")
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,104 @@
|
||||
require "rails_helper"
|
||||
require "webmock/rspec"
|
||||
|
||||
RSpec.describe BlossomManager::UploadBlob, type: :model do
|
||||
let(:bytes) { File.binread(Rails.root.join("spec/fixtures/files/taipei.jpg")) }
|
||||
let(:sha256) { Digest::SHA256.hexdigest(bytes) }
|
||||
let(:server_url) { "https://blossom.example.com" }
|
||||
let(:auth_event) do
|
||||
Nostr::Event.new(
|
||||
id: "a" * 64, pubkey: "b" * 64, created_at: Time.current.to_i, kind: 24242,
|
||||
tags: [["t", "upload"], ["x", sha256]], content: "Upload profile picture", sig: "c" * 128
|
||||
)
|
||||
end
|
||||
let(:descriptor) do
|
||||
{
|
||||
"url" => "https://blossom.example.com/#{sha256}.jpg",
|
||||
"sha256" => sha256,
|
||||
"size" => bytes.bytesize,
|
||||
"type" => "image/jpeg",
|
||||
"uploaded" => Time.current.to_i
|
||||
}
|
||||
end
|
||||
|
||||
before do
|
||||
stub_request(:put, "#{server_url}/upload").to_return(
|
||||
status: 201, body: descriptor.to_json, headers: { "Content-Type" => "application/json" }
|
||||
)
|
||||
end
|
||||
|
||||
it "PUTs the bytes with a Nostr authorization header and returns the descriptor" do
|
||||
result = described_class.call(
|
||||
bytes: bytes, content_type: "image/jpeg", sha256: sha256,
|
||||
auth_event: auth_event, server_url: server_url
|
||||
)
|
||||
|
||||
expect(result).to eq(descriptor)
|
||||
expect(WebMock).to have_requested(:put, "#{server_url}/upload").with(
|
||||
body: bytes,
|
||||
headers: {
|
||||
"Authorization" => "Nostr #{Base64.urlsafe_encode64(auth_event.to_h.to_json, padding: false)}",
|
||||
"Content-Type" => "image/jpeg",
|
||||
"X-SHA-256" => sha256
|
||||
}
|
||||
)
|
||||
end
|
||||
|
||||
it "returns nil when the descriptor hash does not match the upload" do
|
||||
stub_request(:put, "#{server_url}/upload").to_return(
|
||||
status: 201, body: { "url" => "https://x/y.jpg", "sha256" => "0" * 64 }.to_json
|
||||
)
|
||||
|
||||
result = described_class.call(
|
||||
bytes: bytes, content_type: "image/jpeg", sha256: sha256,
|
||||
auth_event: auth_event, server_url: server_url
|
||||
)
|
||||
|
||||
expect(result).to be_nil
|
||||
end
|
||||
|
||||
it "returns nil on a non-success response" do
|
||||
stub_request(:put, "#{server_url}/upload").to_return(status: 500, body: "boom")
|
||||
|
||||
result = described_class.call(
|
||||
bytes: bytes, content_type: "image/jpeg", sha256: sha256,
|
||||
auth_event: auth_event, server_url: server_url
|
||||
)
|
||||
|
||||
expect(result).to be_nil
|
||||
end
|
||||
|
||||
it "returns nil when the descriptor has no url" do
|
||||
stub_request(:put, "#{server_url}/upload").to_return(
|
||||
status: 201, body: { "sha256" => sha256 }.to_json
|
||||
)
|
||||
|
||||
result = described_class.call(
|
||||
bytes: bytes, content_type: "image/jpeg", sha256: sha256,
|
||||
auth_event: auth_event, server_url: server_url
|
||||
)
|
||||
|
||||
expect(result).to be_nil
|
||||
end
|
||||
|
||||
it "accepts a 409 conflict when the descriptor matches" do
|
||||
stub_request(:put, "#{server_url}/upload").to_return(status: 409, body: descriptor.to_json)
|
||||
|
||||
result = described_class.call(
|
||||
bytes: bytes, content_type: "image/jpeg", sha256: sha256,
|
||||
auth_event: auth_event, server_url: server_url
|
||||
)
|
||||
|
||||
expect(result).to eq(descriptor)
|
||||
end
|
||||
|
||||
it "returns nil when no server is configured" do
|
||||
result = described_class.call(
|
||||
bytes: bytes, content_type: "image/jpeg", sha256: sha256,
|
||||
auth_event: auth_event, server_url: ""
|
||||
)
|
||||
|
||||
expect(result).to be_nil
|
||||
expect(WebMock).not_to have_requested(:put, "#{server_url}/upload")
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,61 @@
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe NostrManager::ProcessProfileImage, type: :model do
|
||||
let(:fixture_path) { Rails.root.join("spec/fixtures/files/taipei.jpg") }
|
||||
let(:bytes) { File.binread(fixture_path) }
|
||||
let(:gif_bytes) { Base64.decode64("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7") }
|
||||
|
||||
def process(field:, content_type: "image/jpeg", data: bytes)
|
||||
described_class.call(field: field, io: StringIO.new(data), content_type: content_type)
|
||||
end
|
||||
|
||||
def dimensions(image_bytes)
|
||||
image = Vips::Image.new_from_buffer(image_bytes, "")
|
||||
[image.width, image.height]
|
||||
end
|
||||
|
||||
it "cover-crops the avatar to 400x400 without flattening a non-alpha image" do
|
||||
result = process(field: "picture")
|
||||
expect(dimensions(result)).to eq([400, 400])
|
||||
expect(Vips::Image.new_from_buffer(result, "").bands).to eq(3)
|
||||
end
|
||||
|
||||
it "cover-crops the header image to 1500x500" do
|
||||
result = process(field: "banner")
|
||||
expect(dimensions(result)).to eq([1500, 500])
|
||||
end
|
||||
|
||||
it "passes GIFs through unchanged" do
|
||||
expect(process(field: "picture", content_type: "image/gif", data: gif_bytes)).to eq(gif_bytes)
|
||||
end
|
||||
|
||||
it "flattens transparency to white for JPEG output" do
|
||||
transparent = Vips::Image.black(50, 50, bands: 4).write_to_buffer(".webp")
|
||||
result = process(field: "picture", content_type: "image/webp", data: transparent)
|
||||
|
||||
image = Vips::Image.new_from_buffer(result, "")
|
||||
expect(image.bands).to eq(3)
|
||||
expect(image.getpoint(20, 20)).to eq([255.0, 255.0, 255.0])
|
||||
end
|
||||
|
||||
it "preserves alpha for PNG output" do
|
||||
transparent = Vips::Image.black(50, 50, bands: 4).write_to_buffer(".png")
|
||||
result = process(field: "picture", content_type: "image/png", data: transparent)
|
||||
|
||||
image = Vips::Image.new_from_buffer(result, "")
|
||||
expect(image.bands).to eq(4)
|
||||
end
|
||||
|
||||
it "rejects unknown fields" do
|
||||
expect(process(field: "something")).to be_nil
|
||||
end
|
||||
|
||||
it "rejects data that is not an image" do
|
||||
expect(process(field: "picture", data: "not an image")).to be_nil
|
||||
end
|
||||
|
||||
it "rejects images over the pixel/size guard" do
|
||||
stub_const("NostrManager::ProcessProfileImage::MAX_SIDE", 10)
|
||||
expect(process(field: "picture")).to be_nil
|
||||
end
|
||||
end
|
||||
Reference in new issue
Block a user