Merge branch 'feature/nostr-profile-fields' into live

This commit is contained in:
raucao committed 2026-11-19 22:00:26 +04:00
commit 8a3847ce31
22 files changed
+1154 -70

No files matched your search

@@ -1,32 +1,54 @@
<div class="w-[72vw] md:w-[640px] lg:w-[760px]">
<header class="absolute z-10 h-36 sm:h-44 inset-x-1 top-1 rounded-t
bg-cover bg-center bg-gray-50"
style="<%= "background-image: url('#{banner_url}');" if banner_url %>">
<div class="inline-block z-20 size-28 sm:size-32 ml-4 mt-16 sm:mt-20">
<% if picture_url.present? %>
<img src="<%= picture_url %>"
class="inline-block size-28 sm:size-32 rounded-full border-2 border-white" />
<% else %>
<span class="inline-block size-28 sm:size-32 overflow-hidden rounded-full border-2 border-white bg-gray-100">
<svg class="size-full text-gray-300" fill="currentColor" viewBox="0 0 24 24">
<path d="M24 20.993V24H0v-2.996A14.977 14.977 0 0112.004 15c4.904 0 9.26 2.354 11.996 5.993zM16.002 8.999a4 4 0 11-8 0 4 4 0 018 0z" />
</svg>
</span>
<% end %>
</div>
</header>
<main class="mt-44 sm:mt-52">
<%= form_for(@user, url: "#", html: {
:method => :put,
data: {
controller: "nostr-profile-editor",
action: "submit->nostr-profile-editor#save",
:'nostr-profile-editor-profile-value' => @profile.to_json,
:'nostr-profile-editor-handle-value' => @user.cn,
:'nostr-profile-editor-display-name-keys-value' => NostrManagerService::DISPLAY_NAME_KEYS.to_json,
:'nostr-profile-editor-account-avatar-url-value' => account_avatar_url.to_s
}
}) do |f| %>
<div class="w-[72vw] md:w-[640px] lg:w-[760px]"
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") %>"
data-nostr-image-upload-banner-max-bytes-value="<%= BlossomManagerService.max_upload_bytes("banner") %>"
data-nostr-image-upload-descriptions-value="<%= asset_descriptions.to_json %>"
data-nostr-image-upload-nostr-profile-editor-outlet="[data-controller~='nostr-profile-editor']">
<%= form_for(@user, url: "#", html: {
:method => :put,
data: {
controller: "nostr-profile-editor",
action: "submit->nostr-profile-editor#save",
:'nostr-profile-editor-profile-value' => @profile.to_json,
:'nostr-profile-editor-handle-value' => @user.cn,
:'nostr-profile-editor-display-name-keys-value' => NostrManagerService::DISPLAY_NAME_KEYS.to_json,
:'nostr-profile-editor-picture-value' => picture_value,
:'nostr-profile-editor-banner-value' => banner_value,
:'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
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">
<%= 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" } %>
<span class="inline-block size-28 sm:size-32 overflow-hidden rounded-full border-2 border-white bg-gray-100 <%= "hidden" if picture_url %>"
data-nostr-profile-editor-target="picturePlaceholder">
<svg class="size-full text-gray-300" fill="currentColor" viewBox="0 0 24 24">
<path d="M24 20.993V24H0v-2.996A14.977 14.977 0 0112.004 15c4.904 0 9.26 2.354 11.996 5.993zM16.002 8.999a4 4 0 11-8 0 4 4 0 018 0z" />
</svg>
</span>
</div>
<% if blossom_enabled? %>
<div class="absolute z-20 right-3 top-3 flex gap-2">
<button type="button" class="btn-sm btn-gray"
data-action="click->nostr-image-upload#open"
data-nostr-image-upload-field-param="picture">
Edit avatar
</button>
<button type="button" class="btn-sm btn-gray"
data-action="click->nostr-image-upload#open"
data-nostr-image-upload-field-param="banner">
Edit header
</button>
</div>
<% end %>
</header>
<main class="mt-44 sm:mt-52">
<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 %>
@@ -168,8 +190,31 @@
<%= f.submit "Save profile", class: "btn-md btn-blue w-full md:w-auto md:ml-auto",
data: { :'nostr-profile-editor-target' => "submit" } %>
</div>
<% end %>
</main>
</main>
<% end %>
<div class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"
data-nostr-image-upload-target="panel"
data-action="click->nostr-image-upload#closeBackground">
<div class="w-full max-w-md rounded bg-white p-6 shadow">
<h3 class="mb-1" data-nostr-image-upload-target="title">Upload image</h3>
<p class="mb-4 text-sm text-gray-500" data-nostr-image-upload-target="description"></p>
<input type="file" accept="image/jpeg,image/png,image/webp,image/gif" class="w-full"
data-nostr-image-upload-target="file"
data-action="change->nostr-image-upload#preview" />
<img class="mt-4 hidden max-h-48 rounded border border-gray-200" alt=""
data-nostr-image-upload-target="preview" />
<p class="error-msg mt-2 hidden" data-nostr-image-upload-target="error"></p>
<div class="mt-6 flex justify-end gap-3">
<button type="button" class="btn-md btn-gray"
data-action="click->nostr-image-upload#close">Cancel</button>
<button type="button" class="btn-md btn-blue"
data-nostr-image-upload-target="submit"
data-action="click->nostr-image-upload#save">Save</button>
</div>
</div>
</div>
<footer>
<%# <%= @profile.inspect %>
<%# <%= @profile_event.inspect %>
@@ -42,6 +42,29 @@ module Settings
safe_image_url(image_url_for(@user.avatar))
end
def picture_value
picture_url.to_s
end
def banner_value
banner_url.to_s
end
def blossom_enabled?
BlossomManagerService.server_url.present?
end
def asset_descriptions
{
"picture" => "Square image, cropped to 400×400. JPEG, PNG, WebP or GIF up to " \
"#{helpers.number_to_human_size(BlossomManagerService.max_upload_bytes("picture"))}. " \
"Location data is stripped; animated GIFs keep their animation.",
"banner" => "Wide image, cropped to 1500×500. JPEG, PNG, WebP or GIF up to " \
"#{helpers.number_to_human_size(BlossomManagerService.max_upload_bytes("banner"))}. " \
"Location data is stripped; animated GIFs keep their animation."
}
end
private
def safe_image_url(value)
@@ -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
@@ -0,0 +1,130 @@
import { Controller } from "@hotwired/stimulus"
import { csrfToken } from "lib/csrf"
const ALLOWED_TYPES = [ "image/jpeg", "image/png", "image/webp", "image/gif" ]
const TITLES = { picture: "Avatar", banner: "Header image" }
export default class extends Controller {
static targets = [ "panel", "title", "description", "file", "preview", "error", "submit" ]
static values = {
field: String,
storeUrl: String,
maxBytes: { type: Number, default: 0 },
pictureMaxBytes: Number,
bannerMaxBytes: Number,
descriptions: { type: Object, default: {} }
}
static outlets = [ "nostr-profile-editor" ]
open (event) {
this.fieldValue = event.params.field
this.opener = event.currentTarget
this.maxBytesValue = this.fieldValue === "banner" ? this.bannerMaxBytesValue : this.pictureMaxBytesValue
if (this.hasTitleTarget) this.titleTarget.textContent = TITLES[this.fieldValue] || "Image"
if (this.hasDescriptionTarget) this.descriptionTarget.textContent = this.descriptionsValue[this.fieldValue] || ""
this.clearError()
this.resetFile()
this.panelTarget.classList.remove("hidden")
}
close () {
this.panelTarget.classList.add("hidden")
this.clearError()
this.resetFile()
this.setBusy(false)
if (this.opener && typeof this.opener.focus === "function") this.opener.focus()
this.opener = null
}
closeBackground (event) {
if (event.target === this.panelTarget) this.close()
}
preview () {
const file = this.selectedFile()
if (!file || !this.hasPreviewTarget) return
if (this.objectUrl) URL.revokeObjectURL(this.objectUrl)
this.objectUrl = URL.createObjectURL(file)
this.previewTarget.src = this.objectUrl
this.previewTarget.classList.remove("hidden")
}
async save (event) {
event.preventDefault()
this.clearError()
const file = this.selectedFile()
if (!file) { this.showError("Please choose an image."); return }
if (!ALLOWED_TYPES.includes(file.type)) { this.showError("Unsupported image type."); return }
if (this.maxBytesValue && file.size > this.maxBytesValue) { this.showError("This image is too large."); return }
this.setBusy(true)
try {
const response = await fetch(this.storeUrlValue, {
method: "POST",
credentials: "include",
headers: { "Accept": "application/json", "X-CSRF-Token": csrfToken() },
body: this.formData(file)
})
const data = await response.json().catch(() => ({}))
if (!response.ok) throw new Error(data.error || `Upload failed (HTTP ${response.status})`)
if (this.hasNostrProfileEditorOutlet) {
this.nostrProfileEditorOutlet.setPending(this.fieldValue, data.sha256, data.previewUrl)
}
this.close()
} catch (error) {
this.showError(error.message)
} finally {
this.setBusy(false)
}
}
resetFile () {
if (this.hasFileTarget) this.fileTarget.value = ""
if (this.objectUrl) {
URL.revokeObjectURL(this.objectUrl)
this.objectUrl = null
}
if (this.hasPreviewTarget) {
this.previewTarget.removeAttribute("src")
this.previewTarget.classList.add("hidden")
}
}
selectedFile () {
return this.hasFileTarget ? this.fileTarget.files[0] : null
}
formData (file) {
const form = new FormData()
form.append("field", this.fieldValue)
form.append("file", file)
return form
}
setBusy (busy) {
if (!this.hasSubmitTarget) return
this.submitTarget.disabled = busy
}
showError (message) {
if (!this.hasErrorTarget) return
this.errorTarget.textContent = message
this.errorTarget.classList.remove("hidden")
}
clearError () {
if (!this.hasErrorTarget) return
this.errorTarget.textContent = ""
this.errorTarget.classList.add("hidden")
}
}
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus"
import { csrfToken } from "lib/csrf"
// Connects to data-controller="nostr-login"
export default class extends Controller {
@@ -30,7 +31,7 @@ export default class extends Controller {
const res = await fetch("/users/nostr_login", {
method: "POST", credentials: "include", headers: {
"Accept": "application/json", 'Content-Type': 'application/json',
"X-CSRF-Token": this.csrfToken
"X-CSRF-Token": csrfToken()
}, body: JSON.stringify({ signed_event: signedEvent })
})
@@ -45,9 +46,4 @@ export default class extends Controller {
this.loginButtonTarget.disabled = false
}
}
get csrfToken () {
const element = document.head.querySelector('meta[name="csrf-token"]')
return element.getAttribute("content")
}
}
@@ -1,17 +1,26 @@
import { Controller } from "@hotwired/stimulus"
import { signAndPublish, hasNostrExtension } from "lib/nostr_publish"
import { csrfToken } from "lib/csrf"
const PROFILE_KIND = 0
const AUTH_KIND = 24242
const TOKEN_TTL = 5 * 60
const ADDRESS_PATTERN = /^[^@\s]+@[^@\s]+\.[^@\s]+$/
const URL_PATTERN = /^https?:\/\/\S+$/i
export default class extends Controller {
static targets = [ "error", "submit" ]
static targets = [ "error", "submit", "picturePreview", "picturePlaceholder", "bannerPreview" ]
static values = {
profile: { type: Object, default: {} },
handle: String,
displayNameKeys: { type: Array, default: [ "display_name" ] },
accountAvatarUrl: { type: String, default: "" }
pictureValue: { type: String, default: "" },
bannerValue: { type: String, default: "" },
flushUrl: String
}
connect () {
this.pending = {}
}
async save (event) {
@@ -42,12 +51,16 @@ export default class extends Controller {
this.setBusy(true)
try {
const content = this.content()
await this.uploadPendingImages(content)
const signedEvent = await signAndPublish({
kind: PROFILE_KIND,
created_at: Math.floor(Date.now() / 1000),
tags: [],
content: JSON.stringify(this.content())
content: JSON.stringify(content)
})
this.pending = {}
this.element.dispatchEvent(new CustomEvent("nostr:publish", {
bubbles: true,
detail: { kind: PROFILE_KIND, eventId: signedEvent.id }
@@ -59,6 +72,64 @@ export default class extends Controller {
}
}
setPending (field, sha256, previewUrl) {
this.pending[field] = { sha256, previewUrl }
this.showPreview(field, previewUrl)
}
showPreview (field, url) {
if (!url) return
if (field === "picture") {
if (this.hasPicturePreviewTarget) {
this.picturePreviewTarget.src = url
this.picturePreviewTarget.classList.remove("hidden")
}
if (this.hasPicturePlaceholderTarget) this.picturePlaceholderTarget.classList.add("hidden")
} else if (field === "banner") {
if (this.hasBannerPreviewTarget) {
this.bannerPreviewTarget.style.backgroundImage = `url('${url}')`
}
}
}
async uploadPendingImages (content) {
const fields = Object.keys(this.pending)
if (fields.length === 0) return
const now = Math.floor(Date.now() / 1000)
const signedEvent = await window.nostr.signEvent({
kind: AUTH_KIND,
created_at: now,
tags: [
[ "t", "upload" ],
...fields.map((field) => [ "x", this.pending[field].sha256 ]),
[ "expiration", String(now + TOKEN_TTL) ]
],
content: "Upload profile images"
})
const response = await fetch(this.flushUrlValue, {
method: "POST",
credentials: "include",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"X-CSRF-Token": csrfToken()
},
body: JSON.stringify({ signed_event: signedEvent })
})
const data = await response.json().catch(() => ({}))
if (!response.ok) throw new Error(data.error || `Upload failed (HTTP ${response.status})`)
const uploads = data.uploads || []
const uploaded = new Set(uploads.map((upload) => upload.field))
uploads.forEach(({ field, url }) => { content[field] = url })
fields.forEach((field) => {
if (!uploaded.has(field)) throw new Error("Could not upload the image. Please try again.")
})
}
content () {
const content = { ...(this.profileValue || {}) }
@@ -69,9 +140,8 @@ export default class extends Controller {
this.assign(content, "about", this.field("about"))
this.assign(content, "website", this.field("website"))
if ((!content.picture || !URL_PATTERN.test(content.picture)) && this.accountAvatarUrlValue) {
content.picture = this.accountAvatarUrlValue
}
this.assignIfPresent(content, "picture", this.pictureValue)
this.assignIfPresent(content, "banner", this.bannerValue)
if (!content.name && this.handleValue) {
content.name = this.handleValue
@@ -88,6 +158,10 @@ export default class extends Controller {
}
}
assignIfPresent (content, key, value) {
if (value) content[key] = value
}
field (name) {
const input = this.element.querySelector(`[name='user[${name}]']`)
return input ? input.value.trim() : ""
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus"
import { csrfToken } from "lib/csrf"
export default class extends Controller {
static targets = ["buttons", "countdown"]
@@ -42,7 +43,7 @@ export default class extends Controller {
dataType: 'script',
credentials: "include",
headers: {
"X-CSRF-Token": this.csrfToken
"X-CSRF-Token": csrfToken()
},
})
.then(response => {
@@ -106,9 +107,4 @@ export default class extends Controller {
this.element.remove();
}, 300);
}
get csrfToken() {
const element = document.head.querySelector('meta[name="csrf-token"]')
return element.getAttribute("content")
}
}
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus"
import { csrfToken } from "lib/csrf"
// Connects to data-controller="settings--nostr-pubkey"
export default class extends Controller {
@@ -38,7 +39,7 @@ export default class extends Controller {
const res = await fetch("/settings/set_nostr_pubkey", {
method: "POST", credentials: "include", headers: {
"Accept": "application/json", 'Content-Type': 'application/json',
"X-CSRF-Token": this.csrfToken
"X-CSRF-Token": csrfToken()
}, body: JSON.stringify({ signed_event: signedEvent })
});
@@ -48,9 +49,4 @@ export default class extends Controller {
this.setPubkeyTarget.disabled = false
}
}
get csrfToken () {
const element = document.head.querySelector('meta[name="csrf-token"]')
return element.getAttribute("content")
}
}
+3
View File
@@ -0,0 +1,3 @@
export function csrfToken () {
return document.head.querySelector('meta[name="csrf-token"]')?.getAttribute("content")
}
+2 -4
View File
@@ -1,3 +1,5 @@
import { csrfToken } from "lib/csrf"
const DEFAULT_URL = "/settings/nostr_publish"
export function hasNostrExtension () {
@@ -34,7 +36,3 @@ export async function publish (signedEvent, { url = DEFAULT_URL } = {}) {
return data
}
function csrfToken () {
return document.head.querySelector('meta[name="csrf-token"]')?.getAttribute("content")
}
+2
View File
@@ -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
+19
View File
@@ -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
+3
View File
@@ -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
+17 -1
View File
@@ -69,7 +69,13 @@ The account settings page lets users publish their own Nostr data:
preserved. The display name is read from the first present of `display_name`, `displayName`,
`name` or `username`, and written to all of them for maximum client compatibility. When the
published profile has no usable `picture` (missing, blank, or not an http(s) URL), the account
avatar's public URL is used instead and written to the profile on save.
avatar's public URL is used instead and written to the profile on save. The avatar and header
image can be replaced from an upload panel: the browser uploads the image to akkounts, which
crops it server-side (avatar 400×400, header 1500×500; animated GIFs pass through) and stores it
as a pending attachment that is shown as the preview. When the profile is saved, the browser
signs a NIP-07 Blossom upload authorization (kind `24242`, `t=upload`, `x` = the pending images'
hashes, `expiration`) and the app uploads the stored bytes to the configured Blossom server; the
returned URLs are written into the profile.
* **Relay list** (NIP-65, kind `10002`) — the site relay is pre-included; entries can be marked
read-only or write-only.
* **Media server list** (Blossom, kind `10063`) — the configured Blossom server is pre-included.
@@ -104,5 +110,15 @@ Relevant settings (admin → Services → Nostr):
then no longer blank — the fallback does not re-trigger.
* The fallback URL's host is taken from the request at save time, so saving from an alternate
hostname publishes that hostname.
* Avatar and header uploads are processed server-side (cover-cropped, EXIF/GPS stripped; animated
GIFs passed through unchanged) and stored as one pending attachment per field. The avatar is
limited to 1 MB and the header image to 2 MB; both accept JPEG/PNG/WebP/GIF, MIME-sniffed from
the bytes.
* akkounts now temporarily stores the processed images in ActiveStorage until the profile is saved
or the image is replaced, so at most one small processed image per field is retained.
* An image that is flushed to Blossom but whose profile is never published is left orphaned on the
Blossom server (uploads are not rolled back); Blossom dedupes by hash, so re-saving is free.
* While the image upload panel is open, Esc closes the whole profile editor (the panel does not
handle Esc), discarding the pending upload.
[1]: https://github.com/hoytech/strfry
@@ -121,6 +121,10 @@ RSpec.describe Settings::NostrEditProfileComponent, type: :component do
end
describe "image URL sanitization" do
def preview_img(rendered)
rendered.css("img[data-nostr-profile-editor-target='picturePreview']").first
end
it "ignores non-http(s) banner and picture URLs" do
profile_event = {
"content" => {
@@ -130,7 +134,7 @@ RSpec.describe Settings::NostrEditProfileComponent, type: :component do
}
rendered = render_inline(described_class.new(user: user, profile_event: profile_event))
expect(rendered.css("img")).to be_empty
expect(preview_img(rendered)["class"]).to include("hidden")
expect(rendered.css("header").first["style"]).to be_blank
end
@@ -143,11 +147,52 @@ RSpec.describe Settings::NostrEditProfileComponent, type: :component do
}
rendered = render_inline(described_class.new(user: user, profile_event: profile_event))
expect(rendered.css("img").first["src"]).to eq("https://example.com/p.png")
expect(preview_img(rendered)["src"]).to eq("https://example.com/p.png")
expect(preview_img(rendered)["class"]).not_to include("hidden")
expect(rendered.css("header").first["style"]).to include("https://example.com/b.png")
end
end
it "seeds the banner value from the profile" do
profile_event = { "content" => { "banner" => "https://example.com/b.png" }.to_json }
rendered = render_inline(described_class.new(user: user, profile_event: profile_event))
form = rendered.css("form").first
expect(form["data-nostr-profile-editor-banner-value"]).to eq("https://example.com/b.png")
end
describe "image upload affordances" do
it "shows the edit buttons and panel when a Blossom server is configured" do
allow(Setting).to receive(:nostr_blossom_server_url).and_return("https://blossom.example.com")
rendered = render_inline(described_class.new(user: user, profile_event: nil))
expect(rendered.css("button[data-nostr-image-upload-field-param='picture']")).to be_present
expect(rendered.css("button[data-nostr-image-upload-field-param='banner']")).to be_present
expect(rendered.css("[data-nostr-image-upload-target='panel']")).to be_present
root = rendered.css("[data-controller='nostr-image-upload']").first
expect(root["data-nostr-image-upload-store-url-value"]).to eq("/settings/nostr_profile_images")
expect(root["data-nostr-image-upload-nostr-profile-editor-outlet"]).to eq("[data-controller~='nostr-profile-editor']")
expect(root["data-nostr-image-upload-picture-max-bytes-value"]).to eq("1048576")
expect(root["data-nostr-image-upload-banner-max-bytes-value"]).to eq("2097152")
descriptions = JSON.parse(root["data-nostr-image-upload-descriptions-value"])
expect(descriptions["picture"]).to include("400×400", "1 MB")
expect(descriptions["banner"]).to include("1500×500", "2 MB")
form = rendered.css("form").first
expect(form["data-nostr-profile-editor-flush-url-value"]).to eq("/settings/nostr_media")
end
it "hides the edit buttons when no Blossom server is configured" do
allow(Setting).to receive(:nostr_blossom_server_url).and_return(nil)
rendered = render_inline(described_class.new(user: user, profile_event: nil))
expect(rendered.css("button[data-nostr-image-upload-field-param='picture']")).to be_empty
expect(rendered.css("button[data-nostr-image-upload-field-param='banner']")).to be_empty
end
end
describe "account avatar fallback" do
context "with an account avatar" do
let(:user) { create(:user, cn: "alice") }
@@ -163,38 +208,45 @@ RSpec.describe Settings::NostrEditProfileComponent, type: :component do
).tap { |blob| user.avatar.attach(blob) }
end
it "previews the account avatar and passes it to the editor when the profile has no picture" do
it "seeds the picture with the account avatar when the profile has none" do
rendered = render_inline(described_class.new(user: user, profile_event: nil))
expect(rendered.css("img").first["src"]).to match(avatar_src)
img = rendered.css("img[data-nostr-profile-editor-target='picturePreview']").first
expect(img["src"]).to match(avatar_src)
form = rendered.css("form").first
expect(form["data-nostr-profile-editor-account-avatar-url-value"]).to match(avatar_src)
expect(form["data-nostr-profile-editor-picture-value"]).to match(avatar_src)
end
it "prefers the profile's picture over the account avatar" do
profile_event = { "content" => { "picture" => "https://example.com/p.png" }.to_json }
rendered = render_inline(described_class.new(user: user, profile_event: profile_event))
expect(rendered.css("img").first["src"]).to eq("https://example.com/p.png")
form = rendered.css("form").first
expect(form["data-nostr-profile-editor-picture-value"]).to eq("https://example.com/p.png")
end
it "treats a non-URL picture as absent" do
profile_event = { "content" => { "picture" => "ftp://example.com/x.png" }.to_json }
rendered = render_inline(described_class.new(user: user, profile_event: profile_event))
expect(rendered.css("img").first["src"]).to match(avatar_src)
form = rendered.css("form").first
expect(form["data-nostr-profile-editor-picture-value"]).to match(avatar_src)
end
end
context "without an account avatar" do
it "renders the placeholder and passes no avatar URL" do
it "renders the placeholder and seeds an empty picture value" do
rendered = render_inline(described_class.new(user: user, profile_event: nil))
expect(rendered.css("img")).to be_empty
img = rendered.css("img[data-nostr-profile-editor-target='picturePreview']").first
expect(img["class"]).to include("hidden")
placeholder = rendered.css("[data-nostr-profile-editor-target='picturePlaceholder']").first
expect(placeholder["class"].split).not_to include("hidden")
form = rendered.css("form").first
expect(form["data-nostr-profile-editor-account-avatar-url-value"]).to eq("")
expect(form["data-nostr-profile-editor-picture-value"]).to eq("")
end
end
end
+159
View File
@@ -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