Compare commits

...

1 Commits

4 changed files with 42 additions and 4 deletions

View File

@@ -11,6 +11,7 @@ import { normalizeURL } from './utils.ts'
import type { Event, EventTemplate, Nostr, VerifiedEvent } from './core.ts' import type { Event, EventTemplate, Nostr, VerifiedEvent } from './core.ts'
import { type Filter } from './filter.ts' import { type Filter } from './filter.ts'
import { alwaysTrue } from './helpers.ts' import { alwaysTrue } from './helpers.ts'
import { Relay } from './relay.ts'
export type SubCloser = { close: (reason?: string) => void } export type SubCloser = { close: (reason?: string) => void }
@@ -19,6 +20,11 @@ export type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {
// in case that relay shouldn't be authenticated against // in case that relay shouldn't be authenticated against
// or a function to sign the AUTH event template otherwise (that function may still throw in case of failure) // or a function to sign the AUTH event template otherwise (that function may still throw in case of failure)
automaticallyAuth?: (relayURL: string) => null | ((event: EventTemplate) => Promise<VerifiedEvent>) automaticallyAuth?: (relayURL: string) => null | ((event: EventTemplate) => Promise<VerifiedEvent>)
// onRelayConnectionFailure is called with the URL of a relay that failed the initial connection
onRelayConnectionFailure?: (url: string) => void
// allowConnectingToRelay takes a relay URL and the operation being performed
// return false to skip connecting to that relay
allowConnectingToRelay?: (url: string, operation: ['read', Filter[]] | ['write', Event]) => boolean
} }
export type SubscribeManyParams = Omit<SubscriptionParams, 'onclose'> & { export type SubscribeManyParams = Omit<SubscriptionParams, 'onclose'> & {
@@ -40,6 +46,8 @@ export class AbstractSimplePool {
public enableReconnect: boolean public enableReconnect: boolean
public automaticallyAuth?: (relayURL: string) => null | ((event: EventTemplate) => Promise<VerifiedEvent>) public automaticallyAuth?: (relayURL: string) => null | ((event: EventTemplate) => Promise<VerifiedEvent>)
public trustedRelayURLs: Set<string> = new Set() public trustedRelayURLs: Set<string> = new Set()
public onRelayConnectionFailure?: (url: string) => void
public allowConnectingToRelay?: (url: string, operation: ['read', Filter[]] | ['write', Event]) => boolean
private _WebSocket?: typeof WebSocket private _WebSocket?: typeof WebSocket
@@ -49,6 +57,8 @@ export class AbstractSimplePool {
this.enablePing = opts.enablePing this.enablePing = opts.enablePing
this.enableReconnect = opts.enableReconnect || false this.enableReconnect = opts.enableReconnect || false
this.automaticallyAuth = opts.automaticallyAuth this.automaticallyAuth = opts.automaticallyAuth
this.onRelayConnectionFailure = opts.onRelayConnectionFailure
this.allowConnectingToRelay = opts.allowConnectingToRelay
} }
async ensureRelay( async ensureRelay(
@@ -181,6 +191,11 @@ export class AbstractSimplePool {
// open a subscription in all given relays // open a subscription in all given relays
const allOpened = Promise.all( const allOpened = Promise.all(
groupedRequests.map(async ({ url, filters }, i) => { groupedRequests.map(async ({ url, filters }, i) => {
if (this.allowConnectingToRelay?.(url, ['read', filters]) === false) {
handleClose(i, 'connection skipped by allowConnectingToRelay')
return
}
let relay: AbstractRelay let relay: AbstractRelay
try { try {
relay = await this.ensureRelay(url, { relay = await this.ensureRelay(url, {
@@ -188,6 +203,7 @@ export class AbstractSimplePool {
abort: params.abort, abort: params.abort,
}) })
} catch (err) { } catch (err) {
this.onRelayConnectionFailure?.(url)
handleClose(i, (err as any)?.message || String(err)) handleClose(i, (err as any)?.message || String(err))
return return
} }
@@ -306,7 +322,18 @@ export class AbstractSimplePool {
return Promise.reject('duplicate url') return Promise.reject('duplicate url')
} }
let r = await this.ensureRelay(url) if (this.allowConnectingToRelay?.(url, ['write', event]) === false) {
return Promise.reject('connection skipped by allowConnectingToRelay')
}
let r: Relay
try {
r = await this.ensureRelay(url)
} catch (err) {
this.onRelayConnectionFailure?.(url)
return String('connection failure: ' + String(err))
}
return r return r
.publish(event) .publish(event)
.catch(async err => { .catch(async err => {

View File

@@ -145,7 +145,7 @@ export class AbstractRelay {
reject('connection timed out') reject('connection timed out')
this.connectionPromise = undefined this.connectionPromise = undefined
this.onclose?.() this.onclose?.()
this.closeAllSubscriptions('relay connection timed out') this.handleHardClose('relay connection timed out')
}, opts.timeout) }, opts.timeout)
} }
@@ -153,8 +153,17 @@ export class AbstractRelay {
opts.abort.onabort = reject opts.abort.onabort = reject
} }
const connectionFailed = () => {
clearTimeout(connectionTimeoutHandle)
reject('connection failed')
this.connectionPromise = undefined
this.onclose?.()
this.handleHardClose('relay connection failed')
}
try { try {
this.ws = new this._WebSocket(this.url) this.ws = new this._WebSocket(this.url)
this.ws.addEventListener('error', connectionFailed)
} catch (err) { } catch (err) {
clearTimeout(connectionTimeoutHandle) clearTimeout(connectionTimeoutHandle)
reject(err) reject(err)
@@ -162,6 +171,8 @@ export class AbstractRelay {
} }
this.ws.onopen = () => { this.ws.onopen = () => {
this.ws?.removeEventListener('error', connectionFailed)
if (this.reconnectTimeoutHandle) { if (this.reconnectTimeoutHandle) {
clearTimeout(this.reconnectTimeoutHandle) clearTimeout(this.reconnectTimeoutHandle)
this.reconnectTimeoutHandle = undefined this.reconnectTimeoutHandle = undefined

View File

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

View File

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