Files
raucao 4c8525b45f Extract the CSRF token helper for the JS controllers
Four controllers each read the csrf-token meta tag themselves. Move the lookup into lib/csrf.js and import it, ahead of the profile image upload controller that also needs it.
2026-11-19 21:58:03 +04:00

39 lines
1023 B
JavaScript

import { csrfToken } from "lib/csrf"
const DEFAULT_URL = "/settings/nostr_publish"
export function hasNostrExtension () {
return Boolean(window.nostr && window.nostr.signEvent)
}
export async function signAndPublish (eventTemplate, { url = DEFAULT_URL } = {}) {
if (!hasNostrExtension()) {
throw new Error("No Nostr extension (NIP-07) found")
}
const signedEvent = await window.nostr.signEvent(eventTemplate)
await publish(signedEvent, { url })
return signedEvent
}
export async function publish (signedEvent, { url = DEFAULT_URL } = {}) {
const response = await fetch(url, {
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 || `Publishing failed (HTTP ${response.status})`)
}
return data
}