Compare commits

..

10 Commits

Author SHA1 Message Date
fiatjaf
929d62bbbb nip57: cleanup useless tests. 2025-08-01 20:28:49 -03:00
fiatjaf
b575e47844 nip57: include "k" tag. 2025-08-01 19:38:03 -03:00
fiatjaf
b076c34a2f tag new minor because of the pingpong stuff. 2025-08-01 14:12:53 -03:00
fiatjaf
4bb3eb2d40 remove unnecessary normalizeURL() call that can throw sometimes. 2025-08-01 14:11:44 -03:00
Chris McCormick
87f2c74bb3 Get pingpong working in the browser with dummy REQ (#499) 2025-07-24 11:22:15 -03:00
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
11 changed files with 105 additions and 153 deletions

View File

@@ -133,6 +133,14 @@ import WebSocket from 'ws'
useWebSocketImplementation(WebSocket) useWebSocketImplementation(WebSocket)
``` ```
You can enable regular pings of connected relays with the `enablePing` option. This will set up a heartbeat that closes the websocket if it doesn't receive a response in time. Some platforms don't report websocket disconnections due to network issues, and enabling this can increase reliability.
```js
import { SimplePool } from 'nostr-tools/pool'
const pool = new SimplePool({ enablePing: true })
```
### Parsing references (mentions) from a content based on NIP-27 ### Parsing references (mentions) from a content based on NIP-27
```js ```js

View File

@@ -32,6 +32,7 @@ export class AbstractSimplePool {
public trackRelays: boolean = false public trackRelays: boolean = false
public verifyEvent: Nostr['verifyEvent'] public verifyEvent: Nostr['verifyEvent']
public enablePing: boolean | undefined
public trustedRelayURLs: Set<string> = new Set() public trustedRelayURLs: Set<string> = new Set()
private _WebSocket?: typeof WebSocket private _WebSocket?: typeof WebSocket
@@ -39,6 +40,7 @@ export class AbstractSimplePool {
constructor(opts: AbstractPoolConstructorOptions) { constructor(opts: AbstractPoolConstructorOptions) {
this.verifyEvent = opts.verifyEvent this.verifyEvent = opts.verifyEvent
this._WebSocket = opts.websocketImplementation this._WebSocket = opts.websocketImplementation
this.enablePing = opts.enablePing
} }
async ensureRelay(url: string, params?: { connectionTimeout?: number }): Promise<AbstractRelay> { async ensureRelay(url: string, params?: { connectionTimeout?: number }): Promise<AbstractRelay> {
@@ -49,6 +51,7 @@ export class AbstractSimplePool {
relay = new AbstractRelay(url, { relay = new AbstractRelay(url, {
verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent, verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent,
websocketImplementation: this._WebSocket, websocketImplementation: this._WebSocket,
enablePing: this.enablePing,
}) })
relay.onclose = () => { relay.onclose = () => {
this.relays.delete(url) this.relays.delete(url)
@@ -137,8 +140,6 @@ 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(
requests.map(async ({ url, filter }, i) => { requests.map(async ({ url, filter }, i) => {
url = normalizeURL(url)
let relay: AbstractRelay let relay: AbstractRelay
try { try {
relay = await this.ensureRelay(url, { relay = await this.ensureRelay(url, {

View File

@@ -7,9 +7,15 @@ 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
enablePing?: boolean
} }
export class SendingOnClosedConnection extends Error { export class SendingOnClosedConnection extends Error {
@@ -29,13 +35,16 @@ export class AbstractRelay {
public baseEoseTimeout: number = 4400 public baseEoseTimeout: number = 4400
public connectionTimeout: number = 4400 public connectionTimeout: number = 4400
public publishTimeout: number = 4400 public publishTimeout: number = 4400
public pingFrequency: number = 20000
public pingTimeout: number = 20000
public openSubs: Map<string, Subscription> = new Map() public openSubs: Map<string, Subscription> = new Map()
public enablePing: boolean | undefined
private connectionTimeoutHandle: ReturnType<typeof setTimeout> | undefined private connectionTimeoutHandle: ReturnType<typeof setTimeout> | undefined
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 +58,7 @@ 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.enablePing = opts.enablePing
} }
static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise<AbstractRelay> { static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise<AbstractRelay> {
@@ -102,6 +112,9 @@ export class AbstractRelay {
this.ws.onopen = () => { this.ws.onopen = () => {
clearTimeout(this.connectionTimeoutHandle) clearTimeout(this.connectionTimeoutHandle)
this._connected = true this._connected = true
if (this.enablePing) {
this.pingpong()
}
resolve() resolve()
} }
@@ -133,6 +146,53 @@ export class AbstractRelay {
return this.connectionPromise return this.connectionPromise
} }
private async waitForPingPong() {
return new Promise((res, err) => {
// listen for pong
;(this.ws && this.ws.on && this.ws.on('pong', () => res(true))) || err("ws can't listen for pong")
// send a ping
this.ws && this.ws.ping && this.ws.ping()
})
}
private async waitForDummyReq() {
return new Promise((res, err) => {
// make a dummy request with expected empty eose reply
// ["REQ", "_", {"ids":["aaaa...aaaa"]}]
const sub = this.subscribe([{ ids: ['a'.repeat(64)] }], {
oneose: () => {
sub.close()
res(true)
},
eoseTimeout: this.pingTimeout + 1000,
})
})
}
// 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) {
// wait for either a ping-pong reply or a timeout
const result = await Promise.any([
// browsers don't have ping so use a dummy req
this.ws && this.ws.ping && this.ws.on ? this.waitForPingPong() : this.waitForDummyReq(),
new Promise(res => setTimeout(() => res(false), this.pingTimeout)),
])
if (result) {
// schedule another pingpong
setTimeout(() => this.pingpong(), this.pingFrequency)
} else {
// pingpong closing socket
this.closeAllSubscriptions('pingpong timed out')
this._connected = false
this.ws?.close()
this.onclose?.()
}
}
}
private async runQueue() { private async runQueue() {
this.queueRunning = true this.queueRunning = true
while (true) { while (true) {

View File

@@ -1,6 +1,6 @@
{ {
"name": "@nostr/tools", "name": "@nostr/tools",
"version": "2.15.1", "version": "2.16.1",
"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

@@ -1,4 +1,5 @@
import { describe, expect, test } from 'bun:test' import { describe, expect, test } from 'bun:test'
// prettier-ignore
import { import {
decode, decode,
naddrEncode, naddrEncode,

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

@@ -1,112 +1,7 @@
import { describe, test, expect, mock } from 'bun:test' import { describe, test, expect } from 'bun:test'
import { finalizeEvent } from './pure.ts' import { finalizeEvent } from './pure.ts'
import { getPublicKey, generateSecretKey } from './pure.ts' import { getPublicKey, generateSecretKey } from './pure.ts'
import { import { getSatoshisAmountFromBolt11, makeZapReceipt, validateZapRequest } from './nip57.ts'
getSatoshisAmountFromBolt11,
getZapEndpoint,
makeZapReceipt,
makeZapRequest,
useFetchImplementation,
validateZapRequest,
} from './nip57.ts'
import { buildEvent } from './test-helpers.ts'
describe('getZapEndpoint', () => {
test('returns null if neither lud06 nor lud16 is present', async () => {
const metadata = buildEvent({ kind: 0, content: '{}' })
const result = await getZapEndpoint(metadata)
expect(result).toBeNull()
})
test('returns null if fetch fails', async () => {
const fetchImplementation = mock(() => Promise.reject(new Error()))
useFetchImplementation(fetchImplementation)
const metadata = buildEvent({ kind: 0, content: '{"lud16": "name@domain"}' })
const result = await getZapEndpoint(metadata)
expect(result).toBeNull()
expect(fetchImplementation).toHaveBeenCalledWith('https://domain/.well-known/lnurlp/name')
})
test('returns null if the response does not allow Nostr payments', async () => {
const fetchImplementation = mock(() => Promise.resolve({ json: () => ({ allowsNostr: false }) }))
useFetchImplementation(fetchImplementation)
const metadata = buildEvent({ kind: 0, content: '{"lud16": "name@domain"}' })
const result = await getZapEndpoint(metadata)
expect(result).toBeNull()
expect(fetchImplementation).toHaveBeenCalledWith('https://domain/.well-known/lnurlp/name')
})
test('returns the callback URL if the response allows Nostr payments', async () => {
const fetchImplementation = mock(() =>
Promise.resolve({
json: () => ({
allowsNostr: true,
nostrPubkey: 'pubkey',
callback: 'callback',
}),
}),
)
useFetchImplementation(fetchImplementation)
const metadata = buildEvent({ kind: 0, content: '{"lud16": "name@domain"}' })
const result = await getZapEndpoint(metadata)
expect(result).toBe('callback')
expect(fetchImplementation).toHaveBeenCalledWith('https://domain/.well-known/lnurlp/name')
})
})
describe('makeZapRequest', () => {
test('throws an error if amount is not given', () => {
expect(() =>
// @ts-expect-error
makeZapRequest({
profile: 'profile',
event: null,
relays: [],
comment: '',
}),
).toThrow()
})
test('throws an error if profile is not given', () => {
expect(() =>
// @ts-expect-error
makeZapRequest({
event: null,
amount: 100,
relays: [],
comment: '',
}),
).toThrow()
})
test('returns a valid Zap request', () => {
const result = makeZapRequest({
profile: 'profile',
event: 'event',
amount: 100,
relays: ['relay1', 'relay2'],
comment: 'comment',
})
expect(result.kind).toBe(9734)
expect(result.created_at).toBeCloseTo(Date.now() / 1000, 0)
expect(result.content).toBe('comment')
expect(result.tags).toEqual(
expect.arrayContaining([
['p', 'profile'],
['amount', '100'],
['relays', 'relay1', 'relay2'],
['e', 'event'],
]),
)
})
})
describe('validateZapRequest', () => { describe('validateZapRequest', () => {
test('returns an error message for invalid JSON', () => { test('returns an error message for invalid JSON', () => {

View File

@@ -1,6 +1,6 @@
import { bech32 } from '@scure/base' import { bech32 } from '@scure/base'
import { validateEvent, verifyEvent, type Event, type EventTemplate } from './pure.ts' import { NostrEvent, validateEvent, verifyEvent, type Event, type EventTemplate } from './pure.ts'
import { utf8Decoder } from './utils.ts' import { utf8Decoder } from './utils.ts'
import { isReplaceableKind, isAddressableKind } from './kinds.ts' import { isReplaceableKind, isAddressableKind } from './kinds.ts'
@@ -42,48 +42,43 @@ export async function getZapEndpoint(metadata: Event): Promise<null | string> {
return null return null
} }
export function makeZapRequest({ type ProfileZap = {
profile, pubkey: string
event,
amount,
relays,
comment = '',
}: {
profile: string
event: string | Event | null
amount: number amount: number
comment: string comment?: string
relays: string[] relays: string[]
}): EventTemplate { }
if (!amount) throw new Error('amount not given')
if (!profile) throw new Error('profile not given')
type EventZap = {
event: NostrEvent
amount: number
comment?: string
relays: string[]
}
export function makeZapRequest(params: ProfileZap | EventZap): EventTemplate {
let zr: EventTemplate = { let zr: EventTemplate = {
kind: 9734, kind: 9734,
created_at: Math.round(Date.now() / 1000), created_at: Math.round(Date.now() / 1000),
content: comment, content: params.comment || '',
tags: [ tags: [
['p', profile], ['p', 'pubkey' in params ? params.pubkey : params.event.pubkey],
['amount', amount.toString()], ['amount', params.amount.toString()],
['relays', ...relays], ['relays', ...params.relays],
], ],
} }
if (event && typeof event === 'string') { if ('event' in params) {
zr.tags.push(['e', event]) if (isReplaceableKind(params.event.kind)) {
} const a = ['a', `${params.event.kind}:${params.event.pubkey}:`]
if (event && typeof event === 'object') {
// replacable event
if (isReplaceableKind(event.kind)) {
const a = ['a', `${event.kind}:${event.pubkey}:`]
zr.tags.push(a) zr.tags.push(a)
// addressable event } else if (isAddressableKind(params.event.kind)) {
} else if (isAddressableKind(event.kind)) { let d = params.event.tags.find(([t, v]) => t === 'd' && v)
let d = event.tags.find(([t, v]) => t === 'd' && v)
if (!d) throw new Error('d tag not found or is empty') if (!d) throw new Error('d tag not found or is empty')
const a = ['a', `${event.kind}:${event.pubkey}:${d[1]}`] const a = ['a', `${params.event.kind}:${params.event.pubkey}:${d[1]}`]
zr.tags.push(a) zr.tags.push(a)
} }
zr.tags.push(['k', params.event.kind.toString()])
} }
return zr return zr

View File

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

View File

@@ -14,8 +14,8 @@ export function useWebSocketImplementation(websocketImplementation: any) {
} }
export class SimplePool extends AbstractSimplePool { export class SimplePool extends AbstractSimplePool {
constructor() { constructor(options?: { enablePing?: boolean }) {
super({ verifyEvent, websocketImplementation: _WebSocket }) super({ verifyEvent, websocketImplementation: _WebSocket, ...options })
} }
} }