Upload avatar and header images from the Nostr profile editor
CI / Test (pull_request) Successful in 49s
Release Drafter / Update release notes draft (pull_request) Successful in 37s

The editor gains edit affordances over the avatar and header image and an upload panel that stores the image (previewing the server-cropped result) and records it as pending. Saving the profile signs a Blossom upload token, flushes the pending images, merges the returned URLs into the kind-0 content, and keeps pending state until the publish succeeds so a retry re-flushes.
This commit is contained in:
raucao committed 2026-11-19 21:58:12 +04:00
1 parent ab3c2bffd6
commit be133af6fa
6 files changed
+388 -48

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,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,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() : ""
+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