Compare commits

..

7 Commits

Author SHA1 Message Date
fiatjaf
4b6cc19b9c cleanup. 2025-07-23 16:22:25 -03:00
fiatjaf
b2f3a01439 nip46: remove deprecated getRelays() 2025-07-23 16:22:16 -03:00
Chris McCormick
6ec19b618c WIP: pingpong with logging. 2025-07-23 16:16:12 -03:00
Chris McCormick
b3cc9f50e5 WIP: hack in pingpong #495
TypeScript does not like the duck typing of .on and .ping (only valid on Node ws).
2025-07-23 16:16:12 -03:00
vornis101
de1cf0ed60 Fix JSON syntax of jsr.json 2025-07-19 08:58:05 -03:00
fiatjaf
d706ef961f pool: closed relays must be eliminated. 2025-07-17 23:39:16 -03:00
SondreB
2f529b3f8a enhance parseConnectionString to support double slash URL format 2025-07-13 11:59:04 -03:00
8 changed files with 63 additions and 15 deletions

View File

@@ -50,6 +50,9 @@ export class AbstractSimplePool {
verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent, verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent,
websocketImplementation: this._WebSocket, websocketImplementation: this._WebSocket,
}) })
relay.onclose = () => {
this.relays.delete(url)
}
if (params?.connectionTimeout) relay.connectionTimeout = params.connectionTimeout if (params?.connectionTimeout) relay.connectionTimeout = params.connectionTimeout
this.relays.set(url, relay) this.relays.set(url, relay)
} }
@@ -61,6 +64,7 @@ export class AbstractSimplePool {
close(relays: string[]) { close(relays: string[]) {
relays.map(normalizeURL).forEach(url => { relays.map(normalizeURL).forEach(url => {
this.relays.get(url)?.close() this.relays.get(url)?.close()
this.relays.delete(url)
}) })
} }

View File

@@ -7,6 +7,11 @@ import { Queue, normalizeURL } from './utils.ts'
import { makeAuthEvent } from './nip42.ts' import { makeAuthEvent } from './nip42.ts'
import { yieldThread } from './helpers.ts' import { yieldThread } from './helpers.ts'
type RelayWebSocket = WebSocket & {
ping?(): void
on?(event: 'pong', listener: () => void): any
}
export type AbstractRelayConstructorOptions = { export type AbstractRelayConstructorOptions = {
verifyEvent: Nostr['verifyEvent'] verifyEvent: Nostr['verifyEvent']
websocketImplementation?: typeof WebSocket websocketImplementation?: typeof WebSocket
@@ -35,7 +40,7 @@ export class AbstractRelay {
private connectionPromise: Promise<void> | undefined private connectionPromise: Promise<void> | undefined
private openCountRequests = new Map<string, CountResolver>() private openCountRequests = new Map<string, CountResolver>()
private openEventPublishes = new Map<string, EventPublishResolver>() private openEventPublishes = new Map<string, EventPublishResolver>()
private ws: WebSocket | undefined private ws: RelayWebSocket | undefined
private incomingMessageQueue = new Queue<string>() private incomingMessageQueue = new Queue<string>()
private queueRunning = false private queueRunning = false
private challenge: string | undefined private challenge: string | undefined
@@ -49,6 +54,9 @@ export class AbstractRelay {
this.url = normalizeURL(url) this.url = normalizeURL(url)
this.verifyEvent = opts.verifyEvent this.verifyEvent = opts.verifyEvent
this._WebSocket = opts.websocketImplementation || WebSocket this._WebSocket = opts.websocketImplementation || WebSocket
// this.pingHeartBeat = opts.pingHeartBeat
// this.pingFrequency = opts.pingFrequency
// this.pingTimeout = opts.pingTimeout
} }
static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise<AbstractRelay> { static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise<AbstractRelay> {
@@ -102,6 +110,10 @@ export class AbstractRelay {
this.ws.onopen = () => { this.ws.onopen = () => {
clearTimeout(this.connectionTimeoutHandle) clearTimeout(this.connectionTimeoutHandle)
this._connected = true this._connected = true
if (this.ws && this.ws.ping) {
// && this.pingHeartBeat
this.pingpong()
}
resolve() resolve()
} }
@@ -133,6 +145,35 @@ export class AbstractRelay {
return this.connectionPromise return this.connectionPromise
} }
private async receivePong() {
return new Promise((res, err) => {
;(this.ws && this.ws.on && this.ws.on('pong', () => res(true))) || err("ws can't listen for pong")
})
}
// nodejs requires this magic here to ensure connections are closed when internet goes off and stuff
// in browsers it's done automatically. see https://github.com/nbd-wtf/nostr-tools/issues/491
private async pingpong() {
// if the websocket is connected
if (this.ws?.readyState == 1) {
// send a ping
this.ws && this.ws.ping && this.ws.ping()
// wait for either a pong or a timeout
const result = await Promise.any([
this.receivePong(),
new Promise(res => setTimeout(() => res(false), 10000)), // TODO: opts.pingTimeout
])
console.error('pingpong result', result)
if (result) {
// schedule another pingpong
setTimeout(() => this.pingpong(), 10000) // TODO: opts.pingFrequency
} else {
// pingpong closing socket
this.ws && this.ws.close()
}
}
}
private async runQueue() { private async runQueue() {
this.queueRunning = true this.queueRunning = true
while (true) { while (true) {
@@ -319,6 +360,7 @@ export class AbstractRelay {
this.closeAllSubscriptions('relay connection closed by us') this.closeAllSubscriptions('relay connection closed by us')
this._connected = false this._connected = false
this.ws?.close() this.ws?.close()
this.onclose?.()
} }
// this is the function assigned to this.ws.onmessage // this is the function assigned to this.ws.onmessage

View File

@@ -1,6 +1,6 @@
{ {
"name": "@nostr/tools", "name": "@nostr/tools",
"version": "2.15.0", "version": "2.15.2",
"exports": { "exports": {
".": "./index.ts", ".": "./index.ts",
"./core": "./core.ts", "./core": "./core.ts",
@@ -44,7 +44,7 @@
"./nip99": "./nip99.ts", "./nip99": "./nip99.ts",
"./nipb7": "./nipb7.ts", "./nipb7": "./nipb7.ts",
"./fakejson": "./fakejson.ts", "./fakejson": "./fakejson.ts",
"./utils": "./utils.ts" "./utils": "./utils.ts",
"./signer": "./signer.ts" "./signer": "./signer.ts"
} }
} }

View File

@@ -2,7 +2,7 @@ import { AbstractSimplePool } from './abstract-pool.ts'
import { Subscription } from './abstract-relay.ts' import { Subscription } from './abstract-relay.ts'
import type { Event, EventTemplate } from './core.ts' import type { Event, EventTemplate } from './core.ts'
import { fetchRelayInformation, RelayInformation } from './nip11.ts' import { fetchRelayInformation, RelayInformation } from './nip11.ts'
import { AddressPointer, decode, NostrTypeGuard } from './nip19.ts' import { decode, NostrTypeGuard } from './nip19.ts'
import { normalizeURL } from './utils.ts' import { normalizeURL } from './utils.ts'
/** /**

View File

@@ -5,7 +5,6 @@ import { getConversationKey, decrypt, encrypt } from './nip44.ts'
import { NIP05_REGEX } from './nip05.ts' import { NIP05_REGEX } from './nip05.ts'
import { SimplePool } from './pool.ts' import { SimplePool } from './pool.ts'
import { Handlerinformation, NostrConnect } from './kinds.ts' import { Handlerinformation, NostrConnect } from './kinds.ts'
import type { RelayRecord } from './relay.ts'
import { Signer } from './signer.ts' import { Signer } from './signer.ts'
var _fetch: any var _fetch: any
@@ -238,13 +237,6 @@ export class BunkerSigner implements Signer {
return this.cachedPubKey return this.cachedPubKey
} }
/**
* @deprecated removed from NIP
*/
async getRelays(): Promise<RelayRecord> {
return JSON.parse(await this.sendRequest('get_relays', []))
}
/** /**
* Signs an event using the remote private key. * Signs an event using the remote private key.
* @param event - The event to sign. * @param event - The event to sign.

View File

@@ -5,6 +5,16 @@ import { decrypt } from './nip04.ts'
import { NWCWalletRequest } from './kinds.ts' import { NWCWalletRequest } from './kinds.ts'
describe('parseConnectionString', () => { describe('parseConnectionString', () => {
test('returns pubkey, relay, and secret if connection string has double slash', () => {
const connectionString =
'nostr+walletconnect://b889ff5b1513b641e2a139f661a661364979c5beee91842f8f0ef42ab558e9d4?relay=wss%3A%2F%2Frelay.damus.io&secret=71a8c14c1407c113601079c4302dab36460f0ccd0ad506f1f2dc73b5100e4f3c'
const { pubkey, relay, secret } = parseConnectionString(connectionString)
expect(pubkey).toBe('b889ff5b1513b641e2a139f661a661364979c5beee91842f8f0ef42ab558e9d4')
expect(relay).toBe('wss://relay.damus.io')
expect(secret).toBe('71a8c14c1407c113601079c4302dab36460f0ccd0ad506f1f2dc73b5100e4f3c')
})
test('returns pubkey, relay, and secret if connection string is valid', () => { test('returns pubkey, relay, and secret if connection string is valid', () => {
const connectionString = const connectionString =
'nostr+walletconnect:b889ff5b1513b641e2a139f661a661364979c5beee91842f8f0ef42ab558e9d4?relay=wss%3A%2F%2Frelay.damus.io&secret=71a8c14c1407c113601079c4302dab36460f0ccd0ad506f1f2dc73b5100e4f3c' 'nostr+walletconnect:b889ff5b1513b641e2a139f661a661364979c5beee91842f8f0ef42ab558e9d4?relay=wss%3A%2F%2Frelay.damus.io&secret=71a8c14c1407c113601079c4302dab36460f0ccd0ad506f1f2dc73b5100e4f3c'

View File

@@ -9,8 +9,8 @@ interface NWCConnection {
} }
export function parseConnectionString(connectionString: string): NWCConnection { export function parseConnectionString(connectionString: string): NWCConnection {
const { pathname, searchParams } = new URL(connectionString) const { host, pathname, searchParams } = new URL(connectionString)
const pubkey = pathname const pubkey = pathname || host
const relay = searchParams.get('relay') const relay = searchParams.get('relay')
const secret = searchParams.get('secret') const secret = searchParams.get('secret')

View File

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