Compare commits

...

2 Commits

Author SHA1 Message Date
Jon Staab 925f540640 Clean up domain a bit
tests / tests (push) Failing after 5m5s
2026-06-18 12:49:13 -07:00
Jon Staab 0a08057786 Remove serialization from domain 2026-06-18 12:33:15 -07:00
6 changed files with 198 additions and 281 deletions
+6 -15
View File
@@ -12,7 +12,7 @@ const c = "cc".repeat(32)
describe("MuteList", () => {
it("round-trips public and private mutes through encryption", async () => {
const list = MuteList.make().addPublicly(a).addPrivately(b)
const list = MuteList.init().addPublicly(a).addPrivately(b)
expect(list.pubkeys.sort()).toEqual([a, b].sort())
expect(list.includes(a)).toBe(true)
@@ -41,7 +41,7 @@ describe("MuteList", () => {
})
it("removes from both public and private entries", async () => {
const list = MuteList.make().addPublicly(a).addPrivately(b)
const list = MuteList.init().addPublicly(a).addPrivately(b)
list.remove(a)
list.remove(b)
@@ -50,39 +50,30 @@ describe("MuteList", () => {
})
it("preserves undecrypted ciphertext on pass-through serialization", async () => {
const event = await MuteList.make().addPrivately(b).toEvent(signer)
const event = await MuteList.init().addPrivately(b).toEvent(signer)
const undecrypted = await MuteList.parse(event)
// We never decrypted, so the original ciphertext must survive untouched.
const template = await undecrypted.getTemplate(signer)
const template = await undecrypted.toTemplate(signer)
expect(template.content).toBe(event.content)
})
it("refuses private mutation when undecrypted", async () => {
const event = await MuteList.make().addPrivately(b).toEvent(signer)
const event = await MuteList.init().addPrivately(b).toEvent(signer)
const undecrypted = await MuteList.parse(event)
expect(() => undecrypted.addPrivately(c)).toThrow()
})
it("toRumor encrypts but does not sign", async () => {
const rumor = await MuteList.make().addPrivately(b).toRumor(signer)
const rumor = await MuteList.init().addPrivately(b).toRumor(signer)
expect(rumor.id).toBeTruthy()
expect((rumor as TrustedEvent).sig).toBeUndefined()
expect(rumor.content).not.toBe("")
})
it("serializes to JSON", async () => {
const list = MuteList.make().addPublicly(a).addPrivately(b)
const json = JSON.parse(JSON.stringify(list))
expect(json.kind).toBe(MUTES)
expect(json.publicTags).toEqual([["p", a]])
expect(json.privateTags).toEqual([["p", b]])
})
it("throws on the wrong kind", async () => {
const event = {kind: FOLLOWS, tags: [], content: "", pubkey: a} as TrustedEvent
+11 -17
View File
@@ -26,7 +26,7 @@ describe("Profile", () => {
tags: [["alt", "profile"]],
})
const profile = Profile.parse(event)
const profile = await Profile.parse(event)
expect(profile.values.name).toBe("alice")
expect(profile.hasName()).toBe(true)
@@ -41,33 +41,27 @@ describe("Profile", () => {
})
it("derives lnurl from a lud16 address", () => {
const profile = Profile.make({lud16: "alice@example.com"})
const profile = Profile.init({lud16: "alice@example.com"})
expect(profile.values.lnurl).toBeTruthy()
})
it("set merges and re-derives values", () => {
const profile = Profile.make({name: "alice"})
it("gets and sets values by key", () => {
const profile = Profile.init({name: "alice"})
profile.set({about: "hello"})
profile.set("about", "hello")
expect(profile.values.name).toBe("alice")
expect(profile.values.about).toBe("hello")
expect(profile.get("name")).toBe("alice")
expect(profile.get("about")).toBe("hello")
})
it("display falls back to a shortened npub", () => {
const profile = Profile.parse(makeEvent({content: "{}"}))
it("display falls back to a shortened npub", async () => {
const profile = await Profile.parse(makeEvent({content: "{}"}))
expect(profile.display()).toBe(displayPubkey(pubkey))
})
it("serializes to JSON", () => {
const profile = Profile.make({name: "alice"})
expect(JSON.parse(JSON.stringify(profile))).toEqual({name: "alice"})
})
it("throws on the wrong kind", () => {
expect(() => Profile.parse(makeEvent({kind: NOTE}))).toThrow()
it("throws on the wrong kind", async () => {
await expect(Profile.parse(makeEvent({kind: NOTE}))).rejects.toThrow()
})
})
+74 -114
View File
@@ -8,27 +8,29 @@ import {DomainObject} from "./base.js"
const isValidTag = (tag: unknown): tag is string[] =>
Array.isArray(tag) && tag.length > 0 && tag.every(v => typeof v === "string")
export type DecryptedTags = {
export type ListValues = {
publicTags: string[][]
privateTags: string[][]
// True when the private content was read (or there was none), false when we
// hold ciphertext we couldn't decrypt. See `EncryptableList.isDecrypted`.
// True when `privateTags` reflects decrypted content; false when we hold
// ciphertext we couldn't read (so private entries are unknown).
decrypted: boolean
}
/**
* Read and decrypt the private tags stored in an event's content. Returns
* `decrypted: false` (and leaves `privateTags` empty) when there is encrypted
* content but no signer, or when decryption fails — in that case the original
* ciphertext is preserved verbatim on serialization.
*/
export const makeListValues = (values: Partial<ListValues> = {}): ListValues => ({
publicTags: [],
privateTags: [],
decrypted: true,
...values,
})
// Decrypt the private tags in an event's content. Returns decrypted: false when
// there's content but no signer, or decryption fails.
export const decryptListContent = async (
event: TrustedEvent,
signer?: ISigner,
): Promise<DecryptedTags> => {
// No private content to read.
): Promise<Pick<ListValues, "privateTags" | "decrypted">> => {
if (!event.content) return {privateTags: [], decrypted: true}
// No signer to read it with — keep the ciphertext, mark it undecrypted.
if (!signer) return {privateTags: [], decrypted: false}
try {
@@ -41,117 +43,85 @@ export const decryptListContent = async (
}
}
export type EncryptableListParams = {
publicTags?: string[][]
privateTags?: string[][]
decrypted?: boolean
event?: TrustedEvent
}
// Base for NIP-51 lists: public entries in tags, private entries as an encrypted
// JSON array in content. Subclasses fix the kind and add domain accessors.
export abstract class EncryptableList extends DomainObject<ListValues> {
values = makeListValues()
/**
* Base class for replaceable lists that carry public entries in tags and
* private entries as an encrypted JSON array in content (NIP-51 style). The
* private entries are decrypted to plaintext on `parse` and re-encrypted on
* `getTemplate`, so all in-between reads and writes are synchronous.
*
* Subclasses fix the `kind` and add domain-specific accessors (see
* `MuteList`). The generic tag mechanics live here.
*/
export abstract class EncryptableList extends DomainObject {
abstract readonly kind: number
publicTags: string[][]
privateTags: string[][]
readonly event?: TrustedEvent
// Whether `privateTags` reflects the real (decrypted) private content. False
// means we're holding ciphertext we couldn't read, so private entries are
// unknown and must not be mutated.
protected decrypted: boolean
constructor({
publicTags = [],
privateTags = [],
decrypted = true,
event,
}: EncryptableListParams = {}) {
super()
this.publicTags = publicTags
this.privateTags = privateTags
this.decrypted = decrypted
this.event = event
protected normalizeValues(values: Partial<ListValues> = {}) {
return makeListValues(values)
}
/**
* Whether the private entries were successfully decrypted (or there were
* none). When false, only public entries are available and private mutations
* throw.
*/
get isDecrypted() {
return this.decrypted
protected async parseEvent(event: TrustedEvent, signer?: ISigner): Promise<Partial<ListValues>> {
const {privateTags, decrypted} = await decryptListContent(event, signer)
return {publicTags: event.tags, privateTags, decrypted}
}
/** All entries, merging public and (when decrypted) private tags. */
getTags() {
return [...this.publicTags, ...this.privateTags]
tags() {
return [...this.values.publicTags, ...this.values.privateTags]
}
getPublicTags() {
return this.publicTags
}
getPrivateTags() {
return this.privateTags
}
/** Add one or more tags to the public (cleartext) entries. */
addPublicTags(...tags: string[][]) {
this.publicTags = uniqTags([...this.publicTags, ...tags])
this.values.publicTags = uniqTags([...this.values.publicTags, ...tags])
return this
}
/** Add one or more tags to the private (encrypted) entries. */
addPrivateTags(...tags: string[][]) {
this.assertDecrypted()
this.privateTags = uniqTags([...this.privateTags, ...tags])
return this
}
/** Remove every tag matching `pred` from both public and private entries. */
removeTagsBy(pred: (tag: string[]) => boolean) {
this.publicTags = this.publicTags.filter(t => !pred(t))
if (this.decrypted) {
this.privateTags = this.privateTags.filter(t => !pred(t))
}
return this
}
/** Remove every tag whose value (index 1) equals `value`, public or private. */
removeTagsByValue(value: string) {
return this.removeTagsBy(nthEq(1, value))
}
protected assertDecrypted() {
if (!this.decrypted) {
if (!this.values.decrypted) {
throw new Error("Cannot modify the private entries of a list that has not been decrypted")
}
this.values.privateTags = uniqTags([...this.values.privateTags, ...tags])
return this
}
async getTemplate(signer?: ISigner): Promise<EventTemplate> {
const tags = this.publicTags
keepTags(pred: (tag: string[]) => boolean) {
this.values.publicTags = this.values.publicTags.filter(t => !pred(t))
// Preserve the original ciphertext when we never decrypted it, so a
// pass-through round trip doesn't destroy private entries we can't read.
if (this.values.decrypted) {
this.values.privateTags = this.values.privateTags.filter(t => !pred(t))
}
return this
}
keepTagsWithKey(key: string) {
return this.keepTags(nthEq(0, key))
}
keepTagsWithValue(value: string) {
return this.keepTags(nthEq(1, value))
}
removeTags(pred: (tag: string[]) => boolean) {
this.values.publicTags = this.values.publicTags.filter(t => !pred(t))
if (this.values.decrypted) {
this.values.privateTags = this.values.privateTags.filter(t => !pred(t))
}
return this
}
removeTagsWithKey(key: string) {
return this.removeTags(nthEq(0, key))
}
removeTagsWithValue(value: string) {
return this.removeTags(nthEq(1, value))
}
async toTemplate(signer?: ISigner): Promise<EventTemplate> {
const tags = this.values.publicTags
// Preserve the original ciphertext when we never decrypted it.
let content = this.event?.content || ""
if (this.decrypted) {
if (this.privateTags.length === 0) {
if (this.values.decrypted) {
if (this.values.privateTags.length === 0) {
content = ""
} else {
if (!signer) {
@@ -160,20 +130,10 @@ export abstract class EncryptableList extends DomainObject {
const pubkey = await signer.getPubkey()
content = await signer.nip44.encrypt(pubkey, JSON.stringify(this.privateTags))
content = await signer.nip44.encrypt(pubkey, JSON.stringify(this.values.privateTags))
}
}
return {kind: this.kind, tags, content}
}
toJSON() {
return {
kind: this.kind,
publicTags: this.publicTags,
privateTags: this.privateTags,
decrypted: this.decrypted,
event: this.event,
}
}
}
+8 -45
View File
@@ -1,66 +1,29 @@
import {uniq} from "@welshman/lib"
import {MUTES, getPubkeyTagValues} from "@welshman/util"
import type {TrustedEvent} from "@welshman/util"
import type {ISigner} from "@welshman/signer"
import {EncryptableList, decryptListContent} from "./List.js"
import {EncryptableList} from "./List.js"
/**
* A NIP-51 kind-10000 mute list. Pubkeys can be muted publicly (in tags) or
* privately (in encrypted content); the convenience accessors here treat both
* as one merged set.
*
* @example
* const mutes = await MuteList.parse(event, signer) // decrypts if able
* mutes.addPrivately(pubkey1)
* mutes.remove(pubkey2) // public and private
* mutes.pubkeys // merged
* mutes.includes(pubkey)
* const signed = await mutes.toEvent(signer) // encrypts + signs
*/
// NIP-51 kind-10000 mute list. Pubkeys can be muted publicly (tags) or privately
// (encrypted content); the accessors treat both as one merged set.
export class MuteList extends EncryptableList {
readonly kind = MUTES
/** Create an empty, decrypted mute list (e.g. for a user with none yet). */
static make() {
return new MuteList()
pubkeys() {
return uniq(getPubkeyTagValues(this.tags))
}
/**
* Parse a kind-10000 event into a `MuteList`, decrypting its private entries
* when a capable signer is supplied. Throws on the wrong kind.
*/
static async parse(event: TrustedEvent, signer?: ISigner) {
if (event.kind !== MUTES) {
throw new Error(`Expected a kind ${MUTES} event, got kind ${event.kind}`)
}
const {privateTags, decrypted} = await decryptListContent(event, signer)
return new MuteList({event, publicTags: event.tags, privateTags, decrypted})
}
/** The muted pubkeys, merging public and (when decrypted) private entries. */
get pubkeys() {
return uniq(getPubkeyTagValues(this.getTags()))
}
/** Whether `pubkey` is muted, publicly or privately. */
includes(pubkey: string) {
return this.pubkeys.includes(pubkey)
}
/** Mute a pubkey publicly (visible to anyone who reads the event). */
addPublicly(pubkey: string) {
mutePublicly(pubkey: string) {
return this.addPublicTags(["p", pubkey])
}
/** Mute a pubkey privately (stored in encrypted content). */
addPrivately(pubkey: string) {
mutePrivately(pubkey: string) {
return this.addPrivateTags(["p", pubkey])
}
/** Unmute a pubkey, removing it from both public and private entries. */
remove(pubkey: string) {
unmute(pubkey: string) {
return this.removeTagsByValue(pubkey)
}
}
+32 -50
View File
@@ -17,10 +17,7 @@ export type ProfileValues = {
display_name?: string
}
/**
* Normalize raw profile values, deriving `lnurl` from a `lud06` or `lud16`
* address when present.
*/
// Apply defaults, deriving `lnurl` from a `lud06` or `lud16` address.
export const makeProfileValues = (values: Partial<ProfileValues> = {}): ProfileValues => {
const result: ProfileValues = {...values}
@@ -43,75 +40,60 @@ export const displayPubkey = (pubkey: string) => {
return d.slice(0, 8) + "…" + d.slice(-5)
}
/**
* A kind-0 profile. Profile data lives unencrypted in the event content as
* JSON, so this is the simplest kind of domain object — `getTemplate` ignores
* the signer and only `toEvent`/`toRumor` need one (to sign).
*
* @example
* const profile = Profile.parse(event)
* profile.set({about: "hello"})
* const signed = await profile.toEvent(signer)
*/
export class Profile extends DomainObject {
export class Profile extends DomainObject<ProfileValues> {
readonly kind = PROFILE
readonly event?: TrustedEvent
values = makeProfileValues()
values: ProfileValues
constructor(values: Partial<ProfileValues> = {}, event?: TrustedEvent) {
super()
this.values = makeProfileValues(values)
this.event = event
protected normalizeValues(values: Partial<ProfileValues> = {}) {
return makeProfileValues(values)
}
static make(values: Partial<ProfileValues> = {}) {
return new Profile(values)
protected parseEvent(event: TrustedEvent): Partial<ProfileValues> {
return parseJson(event.content) || {}
}
/** Parse a kind-0 event into a `Profile`. Throws on the wrong kind. */
static parse(event: TrustedEvent) {
if (event.kind !== PROFILE) {
throw new Error(`Expected a kind ${PROFILE} event, got kind ${event.kind}`)
}
return new Profile(parseJson(event.content) || {}, event)
name() {
return this.values.name || this.values.display_name
}
/** Merge `updates` into the profile values, re-deriving `lnurl` as needed. */
set(updates: Partial<ProfileValues>) {
this.values = makeProfileValues({...this.values, ...updates})
return this
nip05() {
return this.values.
}
/** Whether the profile has a display-worthy name. */
hasName() {
return Boolean(this.values.name || this.values.display_name)
lnurl() {
return this.values.
}
about() {
return this.values.
}
banner() {
return this.values.
}
picture() {
return this.values.
}
website() {
return this.values.
}
/** A human-readable label, falling back to a shortened npub, then `fallback`. */
display(fallback = "") {
const {name, display_name} = this.values
const name = this.name()
if (name) return ellipsize(name, 60).trim()
if (display_name) return ellipsize(display_name, 60).trim()
if (this.event) return displayPubkey(this.event.pubkey).trim()
return fallback.trim()
}
async getTemplate(): Promise<EventTemplate> {
async toTemplate(): Promise<EventTemplate> {
return {
kind: PROFILE,
kind: this.kind,
content: JSON.stringify(this.values),
// Preserve any tags from the source event (e.g. nip05/relay hints).
tags: this.event?.tags || [],
}
}
toJSON() {
return {...this.values}
}
}
+67 -40
View File
@@ -5,60 +5,87 @@ import type {ISigner} from "@welshman/signer"
/**
* The base class for domain objects.
*
* A domain object is an in-memory, mutable, JSON-serializable view of a single
* nostr event. The pattern is "decrypt on parse, mutate in memory, encrypt on
* serialize": concrete subclasses decrypt private content up front (in their
* static `parse`), expose synchronous accessors and mutators over the
* plaintext, and only touch the signer again when building an event.
* A domain object is an in-memory, mutable view of a single nostr event whose
* state lives in a plain `values` property. The pattern is "decrypt on parse,
* mutate in memory, encrypt on serialize": concrete subclasses decrypt private
* content up front (in `parse`), expose synchronous accessors and mutators over
* `values`, and only touch the signer again when building an event.
*
* Subclasses provide:
* There are two construction entry points, both of which populate `values` and
* return `this`:
*
* - a static `parse(event, signer?)` that reads (and, when possible, decrypts)
* an event into a domain object
* - `getTemplate(signer?)` that builds (and, when needed, encrypts) the event
* template — the signer is optional for objects with no private content
* - `toJSON()` for plain-object serialization
* - `init(values?)` builds a fresh object from raw input
* - `parse(event, signer?)` reads (and, when possible, decrypts) an event
*
* The base provides the shared signing/wrapping orchestration on top of
* `getTemplate`.
* Subclasses also implement `toTemplate(signer?)` to build (and, when needed,
* encrypt) the event template; the base provides the signing/wrapping
* orchestration on top of it.
*/
export abstract class DomainObject {
/**
* The source event, present when this object was parsed from one and absent
* when it was freshly constructed.
*/
abstract readonly event?: TrustedEvent
export abstract class DomainObject<V extends Record<string, unknown>> {
abstract readonly kind: number
abstract values: V
event?: TrustedEvent
/**
* Build the event template for this object, encrypting any private content
* with the signer. Subclasses that hold no private data may ignore the
* signer (which is why it is optional).
*/
abstract getTemplate(signer?: ISigner): Promise<EventTemplate>
static init<T extends DomainObject<Record<string, unknown>>>(
this: new () => T,
values?: Partial<T["values"]>,
): T {
return new this().init(values)
}
/**
* A plain-JSON snapshot of this object — safe for storage, `structuredClone`,
* or `postMessage`. Also lets `JSON.stringify` work transparently.
*/
abstract toJSON(): object
static parse<T extends DomainObject<Record<string, unknown>>>(
this: new () => T,
event: TrustedEvent,
signer?: ISigner,
): Promise<T> {
return new this().parse(event, signer)
}
init(values: Partial<V> = {}) {
this.values = this.normalizeValues(values)
return this
}
async parse(event: TrustedEvent, signer?: ISigner) {
if (event.kind !== this.kind) {
throw new Error(`Expected a kind ${this.kind} event, got kind ${event.kind}`)
}
this.event = event
this.values = this.normalizeValues(await this.parseEvent(event, signer))
return this
}
protected abstract normalizeValues(values?: Partial<V>): V
protected abstract parseEvent(
event: TrustedEvent,
signer?: ISigner,
): Partial<V> | Promise<Partial<V>>
abstract toTemplate(signer?: ISigner): Promise<EventTemplate>
/**
* Build a hashed-but-unsigned rumor (the inner event of a NIP-59 gift wrap),
* encrypting private content as needed. A fresh `created_at` is stamped.
*/
async toRumor(signer: ISigner): Promise<HashedEvent> {
const [template, pubkey] = await Promise.all([this.getTemplate(signer), signer.getPubkey()])
const [template, pubkey] = await Promise.all([this.toTemplate(signer), signer.getPubkey()])
return prep(template, pubkey)
}
/**
* Build and sign a full event, encrypting private content as needed. A fresh
* `created_at` is stamped so the result supersedes any prior version.
*/
async toEvent(signer: ISigner): Promise<SignedEvent> {
const template = await this.getTemplate(signer)
const template = await this.toTemplate(signer)
return signer.sign(stamp(template))
}
get<K extends keyof V>(key: K): V[K] {
return this.values[key]
}
set<K extends keyof V>(key: K, value: V[K]) {
this.values[key] = value
return this
}
}