Merge pull request 'Nostr profile editor improvements' (#272) from feature/nostr-profile-fields into master
CI / Test (push) Successful in 1m6s
CI / Test (push) Successful in 1m6s
Reviewed-on: #272
This commit was merged in pull request #272.
This commit is contained in:
24 files changed
+1461
-204
No files matched your search
@@ -1,161 +1,220 @@
|
||||
<div class="w-[72vw] md:w-[500px]">
|
||||
<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
|
||||
}
|
||||
}) do |f| %>
|
||||
<%= render FormElements::FieldsetComponent.new(tag: "div", title: "Display name") do %>
|
||||
<%= f.text_field :display_name, value: @display_name, class: "w-full sm:w-3/5" %>
|
||||
<% end %>
|
||||
<%= render FormElements::FieldsetComponent.new(tag: "div", title: "Nostr address (NIP-05)") do %>
|
||||
<% if @nip05_state[:status] == :added %>
|
||||
<div class="w-full sm:w-3/5 flex flex-col" data-controller="field-suggestion"
|
||||
data-field-suggestion-added-value-value="<%= @user.address %>">
|
||||
<div class="relative">
|
||||
<%= f.text_field :nip05_address, value: @nip05_state[:value],
|
||||
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 class="mt-1.5 flex items-center justify-between text-xs text-amber-800 bg-amber-50 rounded px-2.5 py-1.5 border border-amber-200 hidden"
|
||||
data-field-suggestion-target="suggestion">
|
||||
<span>Account address: <strong><%= @user.address %></strong></span>
|
||||
<button type="button" class="font-semibold text-blue-600 hover:text-blue-800 underline ml-2"
|
||||
data-action="click->field-suggestion#apply"
|
||||
data-field-suggestion-value-param="<%= @user.address %>">
|
||||
Use this
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<% elsif @nip05_state[:status] == :different %>
|
||||
<div class="w-full sm:w-3/5 flex flex-col" data-controller="field-suggestion"
|
||||
data-field-suggestion-added-value-value="<%= @nip05_state[:suggested] %>">
|
||||
<div class="relative">
|
||||
<%= f.text_field :nip05_address, value: @nip05_state[:value],
|
||||
data: {
|
||||
:'field-suggestion-target' => "input",
|
||||
action: "input->field-suggestion#checkAdded"
|
||||
},
|
||||
class: "w-full pr-20 border-amber-400 ring-1 ring-amber-400 focus:border-amber-400 focus:ring-amber-400" %>
|
||||
<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-amber-100 px-2 py-0.5 text-xs font-semibold text-amber-800">
|
||||
different
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-1.5 flex items-center justify-between text-xs text-amber-800 bg-amber-50 rounded px-2.5 py-1.5 border border-amber-200"
|
||||
data-field-suggestion-target="suggestion">
|
||||
<span>Account address: <strong><%= @nip05_state[:suggested] %></strong></span>
|
||||
<button type="button" class="font-semibold text-blue-600 hover:text-blue-800 underline ml-2"
|
||||
data-action="click->field-suggestion#apply"
|
||||
data-field-suggestion-value-param="<%= @nip05_state[:suggested] %>">
|
||||
Use this
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<% else %>
|
||||
<%= f.text_field :nip05_address, value: @nip05_state[:value], class: "w-full sm:w-3/5" %>
|
||||
<% end %>
|
||||
<% end %>
|
||||
<%= render FormElements::FieldsetComponent.new(tag: "div", title: "Lightning address for Zaps") do %>
|
||||
<% if @lud16_state[:status] == :added %>
|
||||
<div class="w-full sm:w-3/5 flex flex-col" data-controller="field-suggestion"
|
||||
data-field-suggestion-added-value-value="<%= @user.address %>">
|
||||
<div class="relative">
|
||||
<%= f.text_field :lud16_address, value: @lud16_state[:value],
|
||||
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 class="mt-1.5 flex items-center justify-between text-xs text-amber-800 bg-amber-50 rounded px-2.5 py-1.5 border border-amber-200 hidden"
|
||||
data-field-suggestion-target="suggestion">
|
||||
<span>Account address: <strong><%= @user.address %></strong></span>
|
||||
<button type="button" class="font-semibold text-blue-600 hover:text-blue-800 underline ml-2"
|
||||
data-action="click->field-suggestion#apply"
|
||||
data-field-suggestion-value-param="<%= @user.address %>">
|
||||
Use this
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<% elsif @lud16_state[:status] == :different %>
|
||||
<div class="w-full sm:w-3/5 flex flex-col" data-controller="field-suggestion"
|
||||
data-field-suggestion-added-value-value="<%= @lud16_state[:suggested] %>">
|
||||
<div class="relative">
|
||||
<%= f.text_field :lud16_address, value: @lud16_state[:value],
|
||||
data: {
|
||||
:'field-suggestion-target' => "input",
|
||||
action: "input->field-suggestion#checkAdded"
|
||||
},
|
||||
class: "w-full pr-20 border-amber-400 ring-1 ring-amber-400 focus:border-amber-400 focus:ring-amber-400" %>
|
||||
<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-amber-100 px-2 py-0.5 text-xs font-semibold text-amber-800">
|
||||
different
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-1.5 flex items-center justify-between text-xs text-amber-800 bg-amber-50 rounded px-2.5 py-1.5 border border-amber-200"
|
||||
data-field-suggestion-target="suggestion">
|
||||
<span>Account address: <strong><%= @lud16_state[:suggested] %></strong></span>
|
||||
<button type="button" class="font-semibold text-blue-600 hover:text-blue-800 underline ml-2"
|
||||
data-action="click->field-suggestion#apply"
|
||||
data-field-suggestion-value-param="<%= @lud16_state[:suggested] %>">
|
||||
Use this
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<% else %>
|
||||
<%= f.text_field :lud16_address, value: @lud16_state[:value], class: "w-full sm:w-3/5" %>
|
||||
<% end %>
|
||||
<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 %>
|
||||
<%= f.text_field :display_name, value: @display_name, class: "w-full" %>
|
||||
<% end %>
|
||||
<%= render FormElements::FieldsetComponent.new(tag: "div", title: "About") do %>
|
||||
<%= f.text_area :about, value: @about, rows: 3, class: "w-full" %>
|
||||
<% end %>
|
||||
<%= render FormElements::FieldsetComponent.new(tag: "div", title: "Website") do %>
|
||||
<%= f.text_field :website, value: @website, class: "w-full",
|
||||
placeholder: "https://example.com" %>
|
||||
<% end %>
|
||||
</div>
|
||||
|
||||
<p class="error-msg mt-2 hidden" data-nostr-profile-editor-target="error"></p>
|
||||
<div>
|
||||
<%= render FormElements::FieldsetComponent.new(tag: "div", title: "Nostr address (NIP-05)") do %>
|
||||
<% if @nip05_state[:status] == :added %>
|
||||
<div class="w-full flex flex-col" data-controller="field-suggestion"
|
||||
data-field-suggestion-added-value-value="<%= @user.address %>">
|
||||
<div class="relative">
|
||||
<%= f.text_field :nip05_address, value: @nip05_state[:value],
|
||||
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 class="mt-1.5 flex items-center justify-between text-xs text-amber-800 bg-amber-50 rounded px-2.5 py-1.5 border border-amber-200 hidden"
|
||||
data-field-suggestion-target="suggestion">
|
||||
<span>Account address: <strong><%= @user.address %></strong></span>
|
||||
<button type="button" class="font-semibold text-blue-600 hover:text-blue-800 underline ml-2"
|
||||
data-action="click->field-suggestion#apply"
|
||||
data-field-suggestion-value-param="<%= @user.address %>">
|
||||
Use this
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<% elsif @nip05_state[:status] == :different %>
|
||||
<div class="w-full flex flex-col" data-controller="field-suggestion"
|
||||
data-field-suggestion-added-value-value="<%= @nip05_state[:suggested] %>">
|
||||
<div class="relative">
|
||||
<%= f.text_field :nip05_address, value: @nip05_state[:value],
|
||||
data: {
|
||||
:'field-suggestion-target' => "input",
|
||||
action: "input->field-suggestion#checkAdded"
|
||||
},
|
||||
class: "w-full pr-20 border-amber-400 ring-1 ring-amber-400 focus:border-amber-400 focus:ring-amber-400" %>
|
||||
<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-amber-100 px-2 py-0.5 text-xs font-semibold text-amber-800">
|
||||
different
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-1.5 flex items-center justify-between text-xs text-amber-800 bg-amber-50 rounded px-2.5 py-1.5 border border-amber-200"
|
||||
data-field-suggestion-target="suggestion">
|
||||
<span>Account address: <strong><%= @nip05_state[:suggested] %></strong></span>
|
||||
<button type="button" class="font-semibold text-blue-600 hover:text-blue-800 underline ml-2"
|
||||
data-action="click->field-suggestion#apply"
|
||||
data-field-suggestion-value-param="<%= @nip05_state[:suggested] %>">
|
||||
Use this
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<% else %>
|
||||
<%= f.text_field :nip05_address, value: @nip05_state[:value], class: "w-full" %>
|
||||
<% end %>
|
||||
<% end %>
|
||||
<%= render FormElements::FieldsetComponent.new(tag: "div", title: "Lightning address for Zaps") do %>
|
||||
<% if @lud16_state[:status] == :added %>
|
||||
<div class="w-full flex flex-col" data-controller="field-suggestion"
|
||||
data-field-suggestion-added-value-value="<%= @user.address %>">
|
||||
<div class="relative">
|
||||
<%= f.text_field :lud16_address, value: @lud16_state[:value],
|
||||
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 class="mt-1.5 flex items-center justify-between text-xs text-amber-800 bg-amber-50 rounded px-2.5 py-1.5 border border-amber-200 hidden"
|
||||
data-field-suggestion-target="suggestion">
|
||||
<span>Account address: <strong><%= @user.address %></strong></span>
|
||||
<button type="button" class="font-semibold text-blue-600 hover:text-blue-800 underline ml-2"
|
||||
data-action="click->field-suggestion#apply"
|
||||
data-field-suggestion-value-param="<%= @user.address %>">
|
||||
Use this
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<% elsif @lud16_state[:status] == :different %>
|
||||
<div class="w-full flex flex-col" data-controller="field-suggestion"
|
||||
data-field-suggestion-added-value-value="<%= @lud16_state[:suggested] %>">
|
||||
<div class="relative">
|
||||
<%= f.text_field :lud16_address, value: @lud16_state[:value],
|
||||
data: {
|
||||
:'field-suggestion-target' => "input",
|
||||
action: "input->field-suggestion#checkAdded"
|
||||
},
|
||||
class: "w-full pr-20 border-amber-400 ring-1 ring-amber-400 focus:border-amber-400 focus:ring-amber-400" %>
|
||||
<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-amber-100 px-2 py-0.5 text-xs font-semibold text-amber-800">
|
||||
different
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-1.5 flex items-center justify-between text-xs text-amber-800 bg-amber-50 rounded px-2.5 py-1.5 border border-amber-200"
|
||||
data-field-suggestion-target="suggestion">
|
||||
<span>Account address: <strong><%= @lud16_state[:suggested] %></strong></span>
|
||||
<button type="button" class="font-semibold text-blue-600 hover:text-blue-800 underline ml-2"
|
||||
data-action="click->field-suggestion#apply"
|
||||
data-field-suggestion-value-param="<%= @lud16_state[:suggested] %>">
|
||||
Use this
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<% else %>
|
||||
<%= f.text_field :lud16_address, value: @lud16_state[:value], class: "w-full" %>
|
||||
<% end %>
|
||||
<% end %>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="mt-8">
|
||||
<%= f.submit "Save profile", class: "btn-md btn-blue w-full",
|
||||
<div class="mt-8 pt-6 border-t border-gray-200 flex flex-col gap-2 md:flex-row md:items-center md:gap-4">
|
||||
<p class="error-msg hidden" data-nostr-profile-editor-target="error"></p>
|
||||
<%= f.submit "Save profile", class: "btn-md btn-blue w-full md:w-auto md:ml-auto",
|
||||
data: { :'nostr-profile-editor-target' => "submit" } %>
|
||||
</p>
|
||||
<% end %>
|
||||
</main>
|
||||
</div>
|
||||
</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 %>
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
|
||||
module Settings
|
||||
class NostrEditProfileComponent < ViewComponent::Base
|
||||
attr_reader :user, :profile, :profile_event, :display_name, :nip05_state, :lud16_state
|
||||
include ApplicationHelper
|
||||
|
||||
attr_reader :user, :profile, :profile_event, :display_name, :nip05_state, :lud16_state,
|
||||
:about, :website
|
||||
|
||||
def initialize(user:, profile_event: nil)
|
||||
@user = user
|
||||
@@ -18,6 +21,9 @@ module Settings
|
||||
.map { |key| @profile[key] }
|
||||
.find(&:present?) || @user.display_name
|
||||
|
||||
@about = @profile["about"] if @profile["about"].is_a?(String)
|
||||
@website = @profile["website"] if @profile["website"].is_a?(String)
|
||||
|
||||
@nip05_state = compute_field_state(@profile["nip05"])
|
||||
@lud16_state = compute_field_state(@profile["lud16"])
|
||||
end
|
||||
@@ -27,7 +33,36 @@ module Settings
|
||||
end
|
||||
|
||||
def picture_url
|
||||
safe_image_url(@profile["picture"])
|
||||
safe_image_url(@profile["picture"]) || account_avatar_url
|
||||
end
|
||||
|
||||
def account_avatar_url
|
||||
return nil unless @user.avatar.attached?
|
||||
|
||||
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
|
||||
|
||||
@@ -20,14 +20,16 @@ module Settings
|
||||
return render_error("Too many publish attempts. Please try again later.", :too_many_requests) if rate_limited?
|
||||
|
||||
event = Nostr::Event.new(**event_params)
|
||||
return render_error("Invalid event", :unprocessable_entity) unless valid_event?(event)
|
||||
reason = invalid_event_reason(event)
|
||||
return render_error("Invalid event: #{reason}", :unprocessable_entity) if reason
|
||||
|
||||
NostrPublishUserEventJob.perform_later(event: event.to_h.transform_keys(&:to_s))
|
||||
clear_metadata_cache
|
||||
|
||||
render json: { ok: true }
|
||||
rescue ActionController::ParameterMissing, ArgumentError, TypeError
|
||||
render_error("Invalid event", :unprocessable_entity)
|
||||
rescue ActionController::ParameterMissing, ArgumentError, TypeError => e
|
||||
Rails.logger.warn("[nostr] Malformed publish request from user #{current_user&.id}: #{e.class}: #{e.message}")
|
||||
render_error("Invalid event: malformed request", :unprocessable_entity)
|
||||
end
|
||||
|
||||
private
|
||||
@@ -45,15 +47,30 @@ module Settings
|
||||
}
|
||||
end
|
||||
|
||||
def valid_event?(event)
|
||||
return false unless event.pubkey == current_user.nostr_pubkey
|
||||
return false unless event.created_at.is_a?(Integer) && event.kind.is_a?(Integer)
|
||||
return false unless NostrManager::VerifySignedEvent.call(
|
||||
event: event, allowed_kinds: ALLOWED_KINDS
|
||||
)
|
||||
return false unless fresh?(event)
|
||||
def invalid_event_reason(event)
|
||||
reason =
|
||||
if event.pubkey != current_user.nostr_pubkey
|
||||
"public key mismatch"
|
||||
elsif !event.created_at.is_a?(Integer) || !event.kind.is_a?(Integer)
|
||||
"created_at/kind are not integers"
|
||||
elsif !ALLOWED_KINDS.include?(event.kind)
|
||||
"kind #{event.kind} not allowed"
|
||||
elsif !NostrManager::VerifySignedEvent.call(event: event)
|
||||
"invalid id or signature"
|
||||
elsif !fresh?(event)
|
||||
"stale created_at"
|
||||
elsif !within_size_limits?(event)
|
||||
"content or tags too large"
|
||||
end
|
||||
|
||||
within_size_limits?(event)
|
||||
return nil if reason.nil?
|
||||
|
||||
Rails.logger.warn(
|
||||
"[nostr] Rejected kind #{event.kind} event from #{event.pubkey} for user #{current_user.id}: " \
|
||||
"#{reason} (created_at=#{event.created_at.inspect}, tags=#{Array(event.tags).size}, " \
|
||||
"content_bytes=#{event.content.to_s.bytesize})"
|
||||
)
|
||||
reason
|
||||
end
|
||||
|
||||
def fresh?(event)
|
||||
|
||||
@@ -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,24 +1,35 @@
|
||||
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" ] }
|
||||
displayNameKeys: { type: Array, default: [ "display_name" ] },
|
||||
pictureValue: { type: String, default: "" },
|
||||
bannerValue: { type: String, default: "" },
|
||||
flushUrl: String
|
||||
}
|
||||
|
||||
connect () {
|
||||
this.pending = {}
|
||||
}
|
||||
|
||||
async save (event) {
|
||||
event.preventDefault()
|
||||
this.clearError()
|
||||
|
||||
const displayName = this.field("display_name")
|
||||
const nip05 = this.field("nip05_address")
|
||||
const lud16 = this.field("lud16_address")
|
||||
const website = this.field("website")
|
||||
|
||||
if (nip05 && !ADDRESS_PATTERN.test(nip05)) {
|
||||
this.showError("Please enter a valid NIP-05 address, e.g. name@example.com.")
|
||||
@@ -28,6 +39,10 @@ export default class extends Controller {
|
||||
this.showError("Please enter a valid Lightning address, e.g. name@example.com.")
|
||||
return
|
||||
}
|
||||
if (website && !URL_PATTERN.test(website)) {
|
||||
this.showError("Please enter a valid website URL, e.g. https://example.com.")
|
||||
return
|
||||
}
|
||||
if (!hasNostrExtension()) {
|
||||
this.showError("No Nostr extension (NIP-07) found.")
|
||||
return
|
||||
@@ -36,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(displayName, nip05, lud16))
|
||||
content: JSON.stringify(content)
|
||||
})
|
||||
this.pending = {}
|
||||
this.element.dispatchEvent(new CustomEvent("nostr:publish", {
|
||||
bubbles: true,
|
||||
detail: { kind: PROFILE_KIND, eventId: signedEvent.id }
|
||||
@@ -53,12 +72,76 @@ export default class extends Controller {
|
||||
}
|
||||
}
|
||||
|
||||
content (displayName, nip05, lud16) {
|
||||
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 || {}) }
|
||||
|
||||
const displayName = this.field("display_name")
|
||||
this.displayNameKeysValue.forEach((key) => this.assign(content, key, displayName))
|
||||
this.assign(content, "nip05", nip05)
|
||||
this.assign(content, "lud16", lud16)
|
||||
this.assign(content, "nip05", this.field("nip05_address"))
|
||||
this.assign(content, "lud16", this.field("lud16_address"))
|
||||
this.assign(content, "about", this.field("about"))
|
||||
this.assign(content, "website", this.field("website"))
|
||||
|
||||
this.assignIfPresent(content, "picture", this.pictureValue)
|
||||
this.assignIfPresent(content, "banner", this.bannerValue)
|
||||
|
||||
if (!content.name && this.handleValue) {
|
||||
content.name = this.handleValue
|
||||
@@ -75,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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export function csrfToken () {
|
||||
return document.head.querySelector('meta[name="csrf-token"]')?.getAttribute("content")
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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
|
||||
|
||||
|
||||
+29
-4
@@ -64,10 +64,18 @@ it to your local strfry for example:
|
||||
|
||||
The account settings page lets users publish their own Nostr data:
|
||||
|
||||
* **Profile** (kind `0`) — display name, NIP-05 address and Lightning address. Edited fields are
|
||||
merged into the existing profile JSON, so unknown keys (`about`, `picture`, …) are 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.
|
||||
* **Profile** (kind `0`) — display name, about, website, NIP-05 address and Lightning address.
|
||||
Edited fields are merged into the existing profile JSON, so other keys (`banner`, …) are
|
||||
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. 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.
|
||||
@@ -95,5 +103,22 @@ Relevant settings (admin → Services → Nostr):
|
||||
entries cannot be saved unchanged.
|
||||
* Metadata discovery is sequential (relays → profile → media server list) and can take a while on
|
||||
slow relays.
|
||||
* The account-avatar fallback for `picture` carves out an exception to preserving existing values:
|
||||
a `picture` that is missing, blank, or not an http(s) URL is replaced by the account avatar URL.
|
||||
* That fallback is one-shot and can go stale: the published URL embeds the avatar's content hash, so
|
||||
it starts 404ing once the account avatar is replaced, and — because the published `picture` is
|
||||
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
|
||||
@@ -78,16 +78,53 @@ RSpec.describe Settings::NostrEditProfileComponent, type: :component do
|
||||
|
||||
it "passes the existing profile to the editor so unknown keys survive" do
|
||||
profile_event = {
|
||||
"content" => { "about" => "hi", "nip05" => "alice@kosmos.org" }.to_json
|
||||
"content" => { "picture" => "https://example.com/p.png", "nip05" => "alice@kosmos.org" }.to_json
|
||||
}
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: profile_event))
|
||||
|
||||
form = rendered.css("form").first
|
||||
profile = JSON.parse(form["data-nostr-profile-editor-profile-value"])
|
||||
expect(profile).to eq("about" => "hi", "nip05" => "alice@kosmos.org")
|
||||
expect(profile).to eq("picture" => "https://example.com/p.png", "nip05" => "alice@kosmos.org")
|
||||
end
|
||||
|
||||
describe "about and website fields" do
|
||||
it "prefills them from the profile" do
|
||||
profile_event = {
|
||||
"content" => {
|
||||
"about" => "Hello there",
|
||||
"website" => "https://alice.example.com"
|
||||
}.to_json
|
||||
}
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: profile_event))
|
||||
|
||||
expect(rendered.css("textarea[name='user[about]']").first.text).to eq("Hello there")
|
||||
expect(rendered.css("input[name='user[website]']").first["value"])
|
||||
.to eq("https://alice.example.com")
|
||||
end
|
||||
|
||||
it "renders them blank when absent" do
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: nil))
|
||||
|
||||
expect(rendered.css("textarea[name='user[about]']").first.text).to be_blank
|
||||
expect(rendered.css("input[name='user[website]']").first["value"]).to be_blank
|
||||
end
|
||||
|
||||
it "ignores non-string values" do
|
||||
profile_event = {
|
||||
"content" => { "about" => 42, "website" => ["https://x.example.com"] }.to_json
|
||||
}
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: profile_event))
|
||||
|
||||
expect(rendered.css("textarea[name='user[about]']").first.text).to be_blank
|
||||
expect(rendered.css("input[name='user[website]']").first["value"]).to be_blank
|
||||
end
|
||||
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" => {
|
||||
@@ -97,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
|
||||
|
||||
@@ -110,11 +147,110 @@ 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") }
|
||||
let(:fixture_path) { Rails.root.join("spec/fixtures/files/taipei.jpg") }
|
||||
let(:img_hash) { Digest::SHA256.hexdigest(File.read(fixture_path)) }
|
||||
let(:avatar_src) { %r{users/alice/avatars/#{img_hash}\.jpg} }
|
||||
|
||||
before do
|
||||
ActiveStorage::Blob.create_and_upload!(
|
||||
io: File.open(fixture_path),
|
||||
filename: "#{img_hash}.jpg",
|
||||
content_type: "image/jpeg"
|
||||
).tap { |blob| user.avatar.attach(blob) }
|
||||
end
|
||||
|
||||
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))
|
||||
|
||||
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-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))
|
||||
|
||||
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))
|
||||
|
||||
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 seeds an empty picture value" do
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: nil))
|
||||
|
||||
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-picture-value"]).to eq("")
|
||||
end
|
||||
end
|
||||
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
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: nil))
|
||||
|
||||
@@ -34,6 +34,10 @@ RSpec.describe "Settings::NostrEvents", type: :request do
|
||||
}
|
||||
end
|
||||
|
||||
def error_message
|
||||
JSON.parse(response.body)["error"]
|
||||
end
|
||||
|
||||
describe "POST /settings/nostr_publish" do
|
||||
it "enqueues a publish job and reports success" do
|
||||
expect(NostrPublishUserEventJob).to receive(:perform_later)
|
||||
@@ -117,6 +121,7 @@ RSpec.describe "Settings::NostrEvents", type: :request do
|
||||
post_signed_event(forged)
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(error_message).to eq("Invalid event: public key mismatch")
|
||||
end
|
||||
end
|
||||
|
||||
@@ -129,6 +134,7 @@ RSpec.describe "Settings::NostrEvents", type: :request do
|
||||
post_signed_event(forged)
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(error_message).to eq("Invalid event: invalid id or signature")
|
||||
end
|
||||
end
|
||||
|
||||
@@ -139,6 +145,7 @@ RSpec.describe "Settings::NostrEvents", type: :request do
|
||||
post_signed_event(signed_event(kind: 1))
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(error_message).to eq("Invalid event: kind 1 not allowed")
|
||||
end
|
||||
end
|
||||
|
||||
@@ -149,6 +156,7 @@ RSpec.describe "Settings::NostrEvents", type: :request do
|
||||
post_signed_event(signed_event(created_at: 1.hour.ago.to_i))
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(error_message).to eq("Invalid event: stale created_at")
|
||||
end
|
||||
end
|
||||
|
||||
@@ -159,6 +167,7 @@ RSpec.describe "Settings::NostrEvents", type: :request do
|
||||
post_signed_event(signed_event(created_at: 1.hour.from_now.to_i))
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(error_message).to eq("Invalid event: stale created_at")
|
||||
end
|
||||
end
|
||||
|
||||
@@ -169,6 +178,7 @@ RSpec.describe "Settings::NostrEvents", type: :request do
|
||||
post_signed_event(signed_event(content: "x" * 10_001))
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(error_message).to eq("Invalid event: content or tags too large")
|
||||
end
|
||||
end
|
||||
|
||||
@@ -182,6 +192,7 @@ RSpec.describe "Settings::NostrEvents", type: :request do
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(error_message).to eq("Invalid event: malformed request")
|
||||
end
|
||||
|
||||
it "returns 422 when signed_event is not an object" do
|
||||
@@ -193,6 +204,7 @@ RSpec.describe "Settings::NostrEvents", type: :request do
|
||||
}
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(error_message).to eq("Invalid event: malformed request")
|
||||
end
|
||||
end
|
||||
|
||||
@@ -203,6 +215,18 @@ RSpec.describe "Settings::NostrEvents", type: :request do
|
||||
post_signed_event(signed_event(tags: ["not-an-array"]))
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(error_message).to eq("Invalid event: content or tags too large")
|
||||
end
|
||||
end
|
||||
|
||||
context "when an event is rejected" do
|
||||
it "logs the specific reason" do
|
||||
allow(Rails.logger).to receive(:warn)
|
||||
|
||||
post_signed_event(Nostr::Event.new(**signed_event.to_h.merge(pubkey: "0" * 64)))
|
||||
|
||||
expect(Rails.logger).to have_received(:warn).with(a_string_including("public key mismatch"))
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
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