Compare commits

...

4 Commits

Author SHA1 Message Date
António Conselheiro
9132b722f3 improve signature for decode function (#489) 2025-06-01 11:08:57 -03:00
fiatjaf
ae2f97655b remove two deprecated things. 2025-05-31 20:04:46 -03:00
fiatjaf
5b78a829c7 ignore error when sending on a CLOSE to a closed connection. 2025-05-31 12:29:24 -03:00
fiatjaf
de26ee98c5 failed to connect to a websocket should reject the promise. 2025-05-31 11:16:22 -03:00
9 changed files with 80 additions and 61 deletions

View File

@@ -1,6 +1,6 @@
/* global WebSocket */
import type { Event, EventTemplate, VerifiedEvent, Nostr } from './core.ts'
import type { Event, EventTemplate, VerifiedEvent, Nostr, NostrEvent } from './core.ts'
import { matchFilters, type Filter } from './filter.ts'
import { getHex64, getSubscriptionId } from './fakejson.ts'
import { Queue, normalizeURL } from './utils.ts'
@@ -12,6 +12,13 @@ export type AbstractRelayConstructorOptions = {
websocketImplementation?: typeof WebSocket
}
export class SendingOnClosedConnection extends Error {
constructor(message: string, relay: string) {
super(`Tried to send message '${message} on a closed connection to ${relay}.`)
this.name = 'SendingOnClosedConnection'
}
}
export class AbstractRelay {
public readonly url: string
private _connected: boolean = false
@@ -112,7 +119,9 @@ export class AbstractRelay {
}
}
this.ws.onclose = async () => {
this.ws.onclose = ev => {
clearTimeout(this.connectionTimeoutHandle)
reject((ev as any).message || 'websocket closed')
if (this._connected) {
this._connected = false
this.connectionPromise = undefined
@@ -176,7 +185,7 @@ export class AbstractRelay {
switch (data[0]) {
case 'EVENT': {
const so = this.openSubs.get(data[1] as string) as Subscription
const event = data[2] as Event
const event = data[2] as NostrEvent
if (this.verifyEvent(event) && matchFilters(so.filters, event)) {
so.onevent(event)
}
@@ -234,7 +243,7 @@ export class AbstractRelay {
}
public async send(message: string) {
if (!this.connectionPromise) throw new Error('sending on closed connection')
if (!this.connectionPromise) throw new SendingOnClosedConnection(message, this.url)
this.connectionPromise.then(() => {
this.ws?.send(message)
@@ -377,7 +386,15 @@ export class Subscription {
if (!this.closed && this.relay.connected) {
// if the connection was closed by the user calling .close() we will send a CLOSE message
// otherwise this._open will be already set to false so we will skip this
this.relay.send('["CLOSE",' + JSON.stringify(this.id) + ']')
try {
this.relay.send('["CLOSE",' + JSON.stringify(this.id) + ']')
} catch (err) {
if (err instanceof SendingOnClosedConnection) {
/* doesn't matter, it's ok */
} else {
throw err
}
}
this.closed = true
}
this.relay.openSubs.delete(this.id)

View File

@@ -1,6 +1,6 @@
{
"name": "@nostr/tools",
"version": "2.13.1",
"version": "2.13.3",
"exports": {
".": "./index.ts",
"./core": "./core.ts",

View File

@@ -20,9 +20,6 @@ export function isAddressableKind(kind: number): boolean {
return 30000 <= kind && kind < 40000
}
/** @deprecated use isAddressableKind instead */
export const isParameterizedReplaceableKind = isAddressableKind
/** Classification of the event kind. */
export type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'

View File

@@ -4,7 +4,7 @@ import { decode } from './nip19.ts'
import { wrapEvent, wrapManyEvents, unwrapEvent } from './nip17.ts'
import { hexToBytes } from '@noble/hashes/utils'
const senderPrivateKey = decode(`nsec1p0ht6p3wepe47sjrgesyn4m50m6avk2waqudu9rl324cg2c4ufesyp6rdg`).data as Uint8Array
const senderPrivateKey = decode(`nsec1p0ht6p3wepe47sjrgesyn4m50m6avk2waqudu9rl324cg2c4ufesyp6rdg`).data
const sk1 = hexToBytes('f09ac9b695d0a4c6daa418fe95b977eea20f54d9545592bc36a4f9e14f3eb840')
const sk2 = hexToBytes('5393a825e5892d8e18d4a5ea61ced105e8bb2a106f42876be3a40522e0b13747')

View File

@@ -1,17 +1,14 @@
import { test, expect, describe } from 'bun:test'
import { generateSecretKey, getPublicKey } from './pure.ts'
import { describe, expect, test } from 'bun:test'
import {
decode,
naddrEncode,
neventEncode,
NostrTypeGuard,
nprofileEncode,
npubEncode,
nsecEncode,
neventEncode,
type AddressPointer,
type ProfilePointer,
EventPointer,
NostrTypeGuard,
nsecEncode
} from './nip19.ts'
import { generateSecretKey, getPublicKey } from './pure.ts'
test('encode and decode nsec', () => {
let sk = generateSecretKey()
@@ -38,7 +35,7 @@ test('encode and decode nprofile', () => {
expect(nprofile).toMatch(/nprofile1\w+/)
let { type, data } = decode(nprofile)
expect(type).toEqual('nprofile')
const pointer = data as ProfilePointer
const pointer = data
expect(pointer.pubkey).toEqual(pk)
expect(pointer.relays).toContain(relays[0])
expect(pointer.relays).toContain(relays[1])
@@ -67,7 +64,7 @@ test('encode and decode naddr', () => {
expect(naddr).toMatch(/naddr1\w+/)
let { type, data } = decode(naddr)
expect(type).toEqual('naddr')
const pointer = data as AddressPointer
const pointer = data
expect(pointer.pubkey).toEqual(pk)
expect(pointer.relays).toContain(relays[0])
expect(pointer.relays).toContain(relays[1])
@@ -86,7 +83,7 @@ test('encode and decode nevent', () => {
expect(nevent).toMatch(/nevent1\w+/)
let { type, data } = decode(nevent)
expect(type).toEqual('nevent')
const pointer = data as EventPointer
const pointer = data
expect(pointer.id).toEqual(pk)
expect(pointer.relays).toContain(relays[0])
expect(pointer.kind).toEqual(30023)
@@ -103,7 +100,7 @@ test('encode and decode nevent with kind 0', () => {
expect(nevent).toMatch(/nevent1\w+/)
let { type, data } = decode(nevent)
expect(type).toEqual('nevent')
const pointer = data as EventPointer
const pointer = data
expect(pointer.id).toEqual(pk)
expect(pointer.relays).toContain(relays[0])
expect(pointer.kind).toEqual(0)
@@ -121,7 +118,7 @@ test('encode and decode naddr with empty "d"', () => {
expect(naddr).toMatch(/naddr\w+/)
let { type, data } = decode(naddr)
expect(type).toEqual('naddr')
const pointer = data as AddressPointer
const pointer = data
expect(pointer.identifier).toEqual('')
expect(pointer.relays).toContain(relays[0])
expect(pointer.kind).toEqual(3)
@@ -133,7 +130,7 @@ test('decode naddr from habla.news', () => {
'naddr1qq98yetxv4ex2mnrv4esygrl54h466tz4v0re4pyuavvxqptsejl0vxcmnhfl60z3rth2xkpjspsgqqqw4rsf34vl5',
)
expect(type).toEqual('naddr')
const pointer = data as AddressPointer
const pointer = data
expect(pointer.pubkey).toEqual('7fa56f5d6962ab1e3cd424e758c3002b8665f7b0d8dcee9fe9e288d7751ac194')
expect(pointer.kind).toEqual(30023)
expect(pointer.identifier).toEqual('references')
@@ -145,7 +142,7 @@ test('decode naddr from go-nostr with different TLV ordering', () => {
)
expect(type).toEqual('naddr')
const pointer = data as AddressPointer
const pointer = data
expect(pointer.pubkey).toEqual('3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d')
expect(pointer.relays).toContain('wss://relay.nostr.example.mydomain.example.com')
expect(pointer.relays).toContain('wss://nostr.banana.com')

View File

@@ -70,31 +70,46 @@ export function decodeNostrURI(nip19code: string): ReturnType<typeof decode> | {
}
}
export function decode(code: string):
| {
type: 'nevent'
data: EventPointer
}
| {
type: 'nprofile'
data: ProfilePointer
}
| {
type: 'naddr'
data: AddressPointer
}
| {
type: 'npub'
data: string
}
| {
type: 'nsec'
data: Uint8Array
}
| {
type: 'note'
data: string
} {
export type DecodedNevent = {
type: 'nevent'
data: EventPointer
}
export type DecodedNprofile = {
type: 'nprofile'
data: ProfilePointer
}
export type DecodedNaddr = {
type: 'naddr'
data: AddressPointer
}
export type DecodedNsec = {
type: 'nsec'
data: Uint8Array
}
export type DecodedNpub = {
type: 'npub'
data: string
}
export type DecodedNote = {
type: 'note'
data: string
}
export type DecodedResult = DecodedNevent | DecodedNprofile | DecodedNaddr | DecodedNpub | DecodedNsec | DecodedNote
export function decode(nip19: NEvent): DecodedNevent
export function decode(nip19: NProfile): DecodedNprofile
export function decode(nip19: NAddr): DecodedNaddr
export function decode(nip19: NSec): DecodedNsec
export function decode(nip19: NPub): DecodedNpub
export function decode(nip19: Note): DecodedNote
export function decode(code: string): DecodedResult
export function decode(code: string): DecodedResult {
let { prefix, words } = bech32.decode(code, Bech32MaxSize)
let data = new Uint8Array(bech32.fromWords(words))

View File

@@ -2,7 +2,7 @@ import { AbstractSimplePool } from './abstract-pool.ts'
import { Subscription } from './abstract-relay.ts'
import type { Event, EventTemplate } from './core.ts'
import { fetchRelayInformation, RelayInformation } from './nip11.ts'
import { AddressPointer, decode } from './nip19.ts'
import { AddressPointer, decode, NostrTypeGuard } from './nip19.ts'
import { normalizeURL } from './utils.ts'
/**
@@ -518,11 +518,11 @@ export async function loadGroupFromCode(pool: AbstractSimplePool, code: string):
* @returns A GroupReference object if the code is valid, otherwise null.
*/
export function parseGroupCode(code: string): null | GroupReference {
if (code.startsWith('naddr1')) {
if (NostrTypeGuard.isNAddr(code)) {
try {
let { data } = decode(code)
let { relays, identifier } = data as AddressPointer
let { relays, identifier } = data
if (!relays || relays.length === 0) return null
let host = relays![0]

View File

@@ -1,7 +1,7 @@
{
"type": "module",
"name": "nostr-tools",
"version": "2.13.1",
"version": "2.13.3",
"description": "Tools for making a Nostr client.",
"repository": {
"type": "git",

View File

@@ -3,13 +3,6 @@
import { verifyEvent } from './pure.ts'
import { AbstractRelay } from './abstract-relay.ts'
/**
* @deprecated use Relay.connect() instead.
*/
export function relayConnect(url: string): Promise<Relay> {
return Relay.connect(url)
}
var _WebSocket: typeof WebSocket
try {