Files
dashtab/app/utils/nostr-events.js
raucao 6750c61d87 Add Nostr photo feeds and wallpaper selection
Read the curated photo feeds from wss://nostr.kosmos.org, verify events, cache originals and thumbnails, and let users pick a wallpaper from the Photos section. Nature is the default feed; City Nights is opt-in. Adds the manual publishing scripts, real event fixtures, protocol documentation, and tests with stubbed network connections.
2026-11-08 21:51:23 +04:00

73 lines
1.6 KiB
JavaScript

import { schnorr } from '@noble/curves/secp256k1.js';
import { sha256 } from '@noble/hashes/sha2.js';
import { bytesToHex, hexToBytes, utf8ToBytes } from '@noble/hashes/utils.js';
// NIP-01 canonical serialization. The event id is the SHA-256 of this JSON
// array, not of the full event object (which contains the id and signature).
export function canonicalEvent(event) {
return JSON.stringify([
0,
event.pubkey,
event.created_at,
event.kind,
event.tags,
event.content,
]);
}
export function eventId(event) {
return bytesToHex(sha256(utf8ToBytes(canonicalEvent(event))));
}
export function isHex(value, length) {
if (typeof value !== 'string' || value.length !== length) {
return false;
}
return /^[0-9a-f]+$/.test(value);
}
export function hasValidEventId(event) {
try {
return isHex(event?.id, 64) && eventId(event) === event.id;
} catch {
return false;
}
}
export function hasValidSignature(event) {
try {
if (
!isHex(event?.id, 64) ||
!isHex(event?.pubkey, 64) ||
!isHex(event?.sig, 128)
) {
return false;
}
return schnorr.verify(
hexToBytes(event.sig),
hexToBytes(event.id),
hexToBytes(event.pubkey)
);
} catch {
return false;
}
}
export function verifyEvent(event) {
if (!event || typeof event !== 'object') {
return false;
}
return hasValidEventId(event) && hasValidSignature(event);
}
export function tagValues(event, name) {
return (event?.tags ?? []).filter((tag) => tag?.[0] === name);
}
export function tagValue(event, name) {
return tagValues(event, name)[0]?.[1] ?? null;
}