mirror of
https://github.com/nbd-wtf/nostr-tools.git
synced 2026-01-31 14:38:51 +00:00
Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bfa40da316 | ||
|
|
9078f45a64 | ||
|
|
6ebe59f123 | ||
|
|
0235b490fa | ||
|
|
e290f98a86 | ||
|
|
7a50d9328d | ||
|
|
65412e5b85 | ||
|
|
ca36ae9530 | ||
|
|
0b6543e1a8 | ||
|
|
693b262b7c |
15
README.md
15
README.md
@@ -160,16 +160,7 @@ Using both `enablePing: true` and `enableReconnect: true` is recommended as it w
|
||||
const pool = new SimplePool({ enablePing: true, enableReconnect: true })
|
||||
```
|
||||
|
||||
The `enableReconnect` option can also be a callback function which will receive the current subscription filters and should return a new set of filters. This is useful if you want to modify the subscription on reconnect, for example, to update the `since` parameter to fetch only new events.
|
||||
|
||||
```js
|
||||
const pool = new SimplePool({
|
||||
enableReconnect: (filters) => {
|
||||
const newSince = Math.floor(Date.now() / 1000)
|
||||
return filters.map(filter => ({ ...filter, since: newSince }))
|
||||
}
|
||||
})
|
||||
```
|
||||
When reconnecting, all existing subscriptions will have their filters automatically updated with `since:` set to the timestamp of the last event received on them `+1`, then restarted.
|
||||
|
||||
### Parsing references (mentions) from a content based on NIP-27
|
||||
|
||||
@@ -253,7 +244,7 @@ const event = await bunker.signEvent({
|
||||
await signer.close()
|
||||
pool.close([])
|
||||
```
|
||||
> **Note on Reconnecting:** Once a connection has been successfully established and the `BunkerPointer` is stored, you do **not** need to call `await bunker.connect()` on subsequent sessions.
|
||||
> **Note on Reconnecting:** Once a connection has been successfully established and the `BunkerPointer` is stored, you do **not** need to call `await bunker.connect()` on subsequent sessions.
|
||||
|
||||
### Method 2: Using a Client-generated URI (`nostrconnect://`)
|
||||
|
||||
@@ -293,7 +284,7 @@ const event = await signer.signEvent({
|
||||
await signer.close()
|
||||
pool.close([])
|
||||
```
|
||||
> **Note on Persistence:** This method is ideal for the initial sign-in. To allow users to stay logged in across sessions, you should store the connection details and use `Method 1` for subsequent reconnections.
|
||||
> **Note on Persistence:** This method is ideal for the initial sign-in. To allow users to stay logged in across sessions, you should store the connection details and use `Method 1` for subsequent reconnections.
|
||||
|
||||
### Parsing thread from any note based on NIP-10
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ export type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {
|
||||
|
||||
export type SubscribeManyParams = Omit<SubscriptionParams, 'onclose'> & {
|
||||
maxWait?: number
|
||||
abort?: AbortSignal
|
||||
onclose?: (reasons: string[]) => void
|
||||
onauth?: (event: EventTemplate) => Promise<VerifiedEvent>
|
||||
id?: string
|
||||
@@ -50,7 +51,13 @@ export class AbstractSimplePool {
|
||||
this.automaticallyAuth = opts.automaticallyAuth
|
||||
}
|
||||
|
||||
async ensureRelay(url: string, params?: { connectionTimeout?: number }): Promise<AbstractRelay> {
|
||||
async ensureRelay(
|
||||
url: string,
|
||||
params?: {
|
||||
connectionTimeout?: number
|
||||
abort?: AbortSignal
|
||||
},
|
||||
): Promise<AbstractRelay> {
|
||||
url = normalizeURL(url)
|
||||
|
||||
let relay = this.relays.get(url)
|
||||
@@ -66,7 +73,6 @@ export class AbstractSimplePool {
|
||||
this.relays.delete(url)
|
||||
}
|
||||
}
|
||||
if (params?.connectionTimeout) relay.connectionTimeout = params.connectionTimeout
|
||||
this.relays.set(url, relay)
|
||||
}
|
||||
|
||||
@@ -77,7 +83,10 @@ export class AbstractSimplePool {
|
||||
}
|
||||
}
|
||||
|
||||
await relay.connect()
|
||||
await relay.connect({
|
||||
timeout: params?.connectionTimeout,
|
||||
abort: params?.abort,
|
||||
})
|
||||
|
||||
return relay
|
||||
}
|
||||
@@ -176,6 +185,7 @@ export class AbstractSimplePool {
|
||||
try {
|
||||
relay = await this.ensureRelay(url, {
|
||||
connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1000) : undefined,
|
||||
abort: params.abort,
|
||||
})
|
||||
} catch (err) {
|
||||
handleClose(i, (err as any)?.message || String(err))
|
||||
@@ -198,6 +208,7 @@ export class AbstractSimplePool {
|
||||
},
|
||||
alreadyHaveEvent: localAlreadyHaveEventHandler,
|
||||
eoseTimeout: params.maxWait,
|
||||
abort: params.abort,
|
||||
})
|
||||
})
|
||||
.catch(err => {
|
||||
@@ -209,6 +220,7 @@ export class AbstractSimplePool {
|
||||
},
|
||||
alreadyHaveEvent: localAlreadyHaveEventHandler,
|
||||
eoseTimeout: params.maxWait,
|
||||
abort: params.abort,
|
||||
})
|
||||
|
||||
subs.push(subscription)
|
||||
|
||||
@@ -35,17 +35,15 @@ export class AbstractRelay {
|
||||
public onauth: undefined | ((evt: EventTemplate) => Promise<VerifiedEvent>)
|
||||
|
||||
public baseEoseTimeout: number = 4400
|
||||
public connectionTimeout: number = 4400
|
||||
public publishTimeout: number = 4400
|
||||
public pingFrequency: number = 20000
|
||||
public pingFrequency: number = 29000
|
||||
public pingTimeout: number = 20000
|
||||
public resubscribeBackoff: number[] = [10000, 10000, 10000, 20000, 20000, 30000, 60000]
|
||||
public openSubs: Map<string, Subscription> = new Map()
|
||||
public enablePing: boolean | undefined
|
||||
public enableReconnect: boolean
|
||||
private connectionTimeoutHandle: ReturnType<typeof setTimeout> | undefined
|
||||
private reconnectTimeoutHandle: ReturnType<typeof setTimeout> | undefined
|
||||
private pingTimeoutHandle: ReturnType<typeof setTimeout> | undefined
|
||||
private pingIntervalHandle: ReturnType<typeof setInterval> | undefined
|
||||
private reconnectAttempts: number = 0
|
||||
private closedIntentionally: boolean = false
|
||||
|
||||
@@ -70,9 +68,12 @@ export class AbstractRelay {
|
||||
this.enableReconnect = opts.enableReconnect || false
|
||||
}
|
||||
|
||||
static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise<AbstractRelay> {
|
||||
static async connect(
|
||||
url: string,
|
||||
opts: AbstractRelayConstructorOptions & Parameters<AbstractRelay['connect']>[0],
|
||||
): Promise<AbstractRelay> {
|
||||
const relay = new AbstractRelay(url, opts)
|
||||
await relay.connect()
|
||||
await relay.connect(opts)
|
||||
return relay
|
||||
}
|
||||
|
||||
@@ -111,9 +112,9 @@ export class AbstractRelay {
|
||||
}
|
||||
|
||||
private handleHardClose(reason: string) {
|
||||
if (this.pingTimeoutHandle) {
|
||||
clearTimeout(this.pingTimeoutHandle)
|
||||
this.pingTimeoutHandle = undefined
|
||||
if (this.pingIntervalHandle) {
|
||||
clearInterval(this.pingIntervalHandle)
|
||||
this.pingIntervalHandle = undefined
|
||||
}
|
||||
|
||||
this._connected = false
|
||||
@@ -131,23 +132,31 @@ export class AbstractRelay {
|
||||
}
|
||||
}
|
||||
|
||||
public async connect(): Promise<void> {
|
||||
public async connect(opts?: { timeout?: number; abort?: AbortSignal }): Promise<void> {
|
||||
let connectionTimeoutHandle: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
if (this.connectionPromise) return this.connectionPromise
|
||||
|
||||
this.challenge = undefined
|
||||
this.authPromise = undefined
|
||||
this.connectionPromise = new Promise((resolve, reject) => {
|
||||
this.connectionTimeoutHandle = setTimeout(() => {
|
||||
reject('connection timed out')
|
||||
this.connectionPromise = undefined
|
||||
this.onclose?.()
|
||||
this.closeAllSubscriptions('relay connection timed out')
|
||||
}, this.connectionTimeout)
|
||||
if (opts?.timeout) {
|
||||
connectionTimeoutHandle = setTimeout(() => {
|
||||
reject('connection timed out')
|
||||
this.connectionPromise = undefined
|
||||
this.onclose?.()
|
||||
this.closeAllSubscriptions('relay connection timed out')
|
||||
}, opts.timeout)
|
||||
}
|
||||
|
||||
if (opts?.abort) {
|
||||
opts.abort.onabort = reject
|
||||
}
|
||||
|
||||
try {
|
||||
this.ws = new this._WebSocket(this.url)
|
||||
} catch (err) {
|
||||
clearTimeout(this.connectionTimeoutHandle)
|
||||
clearTimeout(connectionTimeoutHandle)
|
||||
reject(err)
|
||||
return
|
||||
}
|
||||
@@ -157,7 +166,7 @@ export class AbstractRelay {
|
||||
clearTimeout(this.reconnectTimeoutHandle)
|
||||
this.reconnectTimeoutHandle = undefined
|
||||
}
|
||||
clearTimeout(this.connectionTimeoutHandle)
|
||||
clearTimeout(connectionTimeoutHandle)
|
||||
this._connected = true
|
||||
|
||||
const isReconnection = this.reconnectAttempts > 0
|
||||
@@ -177,19 +186,19 @@ export class AbstractRelay {
|
||||
}
|
||||
|
||||
if (this.enablePing) {
|
||||
this.pingpong()
|
||||
this.pingIntervalHandle = setInterval(() => this.pingpong(), this.pingFrequency)
|
||||
}
|
||||
resolve()
|
||||
}
|
||||
|
||||
this.ws.onerror = ev => {
|
||||
clearTimeout(this.connectionTimeoutHandle)
|
||||
clearTimeout(connectionTimeoutHandle)
|
||||
reject((ev as any).message || 'websocket error')
|
||||
this.handleHardClose('relay connection errored')
|
||||
}
|
||||
|
||||
this.ws.onclose = ev => {
|
||||
clearTimeout(this.connectionTimeoutHandle)
|
||||
clearTimeout(connectionTimeoutHandle)
|
||||
reject((ev as any).message || 'websocket closed')
|
||||
this.handleHardClose('relay connection closed')
|
||||
}
|
||||
@@ -209,20 +218,31 @@ export class AbstractRelay {
|
||||
})
|
||||
}
|
||||
|
||||
private async waitForDummyReq() {
|
||||
return new Promise((resolve, _) => {
|
||||
private waitForDummyReq() {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!this.connectionPromise) return reject(new Error(`no connection to ${this.url}, can't ping`))
|
||||
|
||||
// make a dummy request with expected empty eose reply
|
||||
// ["REQ", "_", {"ids":["aaaa...aaaa"], "limit": 0}]
|
||||
const sub = this.subscribe(
|
||||
[{ ids: ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'], limit: 0 }],
|
||||
{
|
||||
oneose: () => {
|
||||
sub.close()
|
||||
resolve(true)
|
||||
try {
|
||||
const sub = this.subscribe(
|
||||
[{ ids: ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'], limit: 0 }],
|
||||
{
|
||||
label: 'forced-ping',
|
||||
oneose: () => {
|
||||
resolve(true)
|
||||
sub.close()
|
||||
},
|
||||
onclose() {
|
||||
// if we get a CLOSED it's because the relay is alive
|
||||
resolve(true)
|
||||
},
|
||||
eoseTimeout: this.pingTimeout + 1000,
|
||||
},
|
||||
eoseTimeout: this.pingTimeout + 1000,
|
||||
},
|
||||
)
|
||||
)
|
||||
} catch (err) {
|
||||
reject(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -237,10 +257,8 @@ export class AbstractRelay {
|
||||
this.ws && this.ws.ping && (this.ws as any).once ? this.waitForPingPong() : this.waitForDummyReq(),
|
||||
new Promise(res => setTimeout(() => res(false), this.pingTimeout)),
|
||||
])
|
||||
if (result) {
|
||||
// schedule another pingpong
|
||||
this.pingTimeoutHandle = setTimeout(() => this.pingpong(), this.pingFrequency)
|
||||
} else {
|
||||
|
||||
if (!result) {
|
||||
// pingpong closing socket
|
||||
if (this.ws?.readyState === this._WebSocket.OPEN) {
|
||||
this.ws?.close()
|
||||
@@ -428,6 +446,11 @@ export class AbstractRelay {
|
||||
): Subscription {
|
||||
const sub = this.prepareSubscription(filters, params)
|
||||
sub.fire()
|
||||
|
||||
if (params.abort) {
|
||||
params.abort.onabort = () => sub.close(String(params.abort!.reason || '<aborted>'))
|
||||
}
|
||||
|
||||
return sub
|
||||
}
|
||||
|
||||
@@ -448,9 +471,9 @@ export class AbstractRelay {
|
||||
clearTimeout(this.reconnectTimeoutHandle)
|
||||
this.reconnectTimeoutHandle = undefined
|
||||
}
|
||||
if (this.pingTimeoutHandle) {
|
||||
clearTimeout(this.pingTimeoutHandle)
|
||||
this.pingTimeoutHandle = undefined
|
||||
if (this.pingIntervalHandle) {
|
||||
clearInterval(this.pingIntervalHandle)
|
||||
this.pingIntervalHandle = undefined
|
||||
}
|
||||
this.closeAllSubscriptions('relay connection closed by us')
|
||||
this._connected = false
|
||||
@@ -554,6 +577,7 @@ export type SubscriptionParams = {
|
||||
alreadyHaveEvent?: (id: string) => boolean
|
||||
receivedEvent?: (relay: AbstractRelay, id: string) => void
|
||||
eoseTimeout?: number
|
||||
abort?: AbortSignal
|
||||
}
|
||||
|
||||
export type CountResolver = {
|
||||
|
||||
4
core.ts
4
core.ts
@@ -8,7 +8,7 @@ export interface Nostr {
|
||||
/** Designates a verified event signature. */
|
||||
export const verifiedSymbol = Symbol('verified')
|
||||
|
||||
export interface Event {
|
||||
export type NostrEvent = {
|
||||
kind: number
|
||||
tags: string[][]
|
||||
content: string
|
||||
@@ -19,7 +19,7 @@ export interface Event {
|
||||
[verifiedSymbol]?: boolean
|
||||
}
|
||||
|
||||
export type NostrEvent = Event
|
||||
export type Event = NostrEvent
|
||||
export type EventTemplate = Pick<Event, 'kind' | 'tags' | 'content' | 'created_at'>
|
||||
export type UnsignedEvent = Pick<Event, 'kind' | 'tags' | 'content' | 'created_at' | 'pubkey'>
|
||||
|
||||
|
||||
2
jsr.json
2
jsr.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@nostr/tools",
|
||||
"version": "2.19.1",
|
||||
"version": "2.20.0",
|
||||
"exports": {
|
||||
".": "./index.ts",
|
||||
"./core": "./core.ts",
|
||||
|
||||
30
kinds.ts
30
kinds.ts
@@ -55,12 +55,24 @@ export const Reaction = 7
|
||||
export type Reaction = typeof Reaction
|
||||
export const BadgeAward = 8
|
||||
export type BadgeAward = typeof BadgeAward
|
||||
export const ChatMessage = 9
|
||||
export type ChatMessage = typeof ChatMessage
|
||||
export const ForumThread = 11
|
||||
export type ForumThread = typeof ForumThread
|
||||
export const Seal = 13
|
||||
export type Seal = typeof Seal
|
||||
export const PrivateDirectMessage = 14
|
||||
export type PrivateDirectMessage = typeof PrivateDirectMessage
|
||||
export const FileMessage = 15
|
||||
export type FileMessage = typeof FileMessage
|
||||
export const GenericRepost = 16
|
||||
export type GenericRepost = typeof GenericRepost
|
||||
export const Photo = 20
|
||||
export type Photo = typeof Photo
|
||||
export const NormalVideo = 21
|
||||
export type NormalVideo = typeof NormalVideo
|
||||
export const ShortVideo = 22
|
||||
export type ShortVideo = typeof ShortVideo
|
||||
export const ChannelCreation = 40
|
||||
export type ChannelCreation = typeof ChannelCreation
|
||||
export const ChannelMetadata = 41
|
||||
@@ -75,10 +87,18 @@ export const OpenTimestamps = 1040
|
||||
export type OpenTimestamps = typeof OpenTimestamps
|
||||
export const GiftWrap = 1059
|
||||
export type GiftWrap = typeof GiftWrap
|
||||
export const Poll = 1068
|
||||
export type Poll = typeof Poll
|
||||
export const FileMetadata = 1063
|
||||
export type FileMetadata = typeof FileMetadata
|
||||
export const Comment = 1111
|
||||
export type Comment = typeof Comment
|
||||
export const LiveChatMessage = 1311
|
||||
export type LiveChatMessage = typeof LiveChatMessage
|
||||
export const Voice = 1222
|
||||
export type Voice = typeof Voice
|
||||
export const VoiceComment = 1244
|
||||
export type VoiceComment = typeof VoiceComment
|
||||
export const ProblemTracker = 1971
|
||||
export type ProblemTracker = typeof ProblemTracker
|
||||
export const Report = 1984
|
||||
@@ -103,6 +123,8 @@ export const Zap = 9735
|
||||
export type Zap = typeof Zap
|
||||
export const Highlights = 9802
|
||||
export type Highlights = typeof Highlights
|
||||
export const PollResponse = 1018
|
||||
export type PollResponse = typeof PollResponse
|
||||
export const Mutelist = 10000
|
||||
export type Mutelist = typeof Mutelist
|
||||
export const Pinlist = 10001
|
||||
@@ -119,6 +141,8 @@ export const BlockedRelaysList = 10006
|
||||
export type BlockedRelaysList = typeof BlockedRelaysList
|
||||
export const SearchRelaysList = 10007
|
||||
export type SearchRelaysList = typeof SearchRelaysList
|
||||
export const FavoriteRelays = 10012
|
||||
export type FavoriteRelays = typeof FavoriteRelays
|
||||
export const InterestsList = 10015
|
||||
export type InterestsList = typeof InterestsList
|
||||
export const UserEmojiList = 10030
|
||||
@@ -127,6 +151,8 @@ export const DirectMessageRelaysList = 10050
|
||||
export type DirectMessageRelaysList = typeof DirectMessageRelaysList
|
||||
export const FileServerPreference = 10096
|
||||
export type FileServerPreference = typeof FileServerPreference
|
||||
export const BlossomServerList = 10063
|
||||
export type BlossomServerList = typeof BlossomServerList
|
||||
export const NWCWalletInfo = 13194
|
||||
export type NWCWalletInfo = typeof NWCWalletInfo
|
||||
export const LightningPubRPC = 21000
|
||||
@@ -185,9 +211,13 @@ export const Calendar = 31924
|
||||
export type Calendar = typeof Calendar
|
||||
export const CalendarEventRSVP = 31925
|
||||
export type CalendarEventRSVP = typeof CalendarEventRSVP
|
||||
export const RelayReview = 31987
|
||||
export type RelayReview = typeof RelayReview
|
||||
export const Handlerrecommendation = 31989
|
||||
export type Handlerrecommendation = typeof Handlerrecommendation
|
||||
export const Handlerinformation = 31990
|
||||
export type Handlerinformation = typeof Handlerinformation
|
||||
export const CommunityDefinition = 34550
|
||||
export type CommunityDefinition = typeof CommunityDefinition
|
||||
export const GroupMetadata = 39000
|
||||
export type GroupMetadata = typeof GroupMetadata
|
||||
|
||||
@@ -16,14 +16,14 @@ test('first: parse simple content with 1 url and 1 nostr uri', () => {
|
||||
})
|
||||
|
||||
test('second: parse content with 3 urls of different types', () => {
|
||||
const content = `:wss://oa.ao; this was a relay and now here's a video -> https://videos.com/video.mp4! and some music:
|
||||
const content = `:wss://oa.ao/a/; this was a relay and now here's a video -> https://videos.com/video.mp4! and some music:
|
||||
http://music.com/song.mp3
|
||||
and a regular link: https://regular.com/page?ok=true. and now a broken link: https://kjxkxk and a broken nostr ref: nostr:nevent1qqsr0f9w78uyy09qwmjt0kv63j4l7sxahq33725lqyyp79whlfjurwspz4mhxue69uhh56nzv34hxcfwv9ehw6nyddhq0ag9xg and a fake nostr ref: nostr:llll ok but finally https://ok.com!`
|
||||
const blocks = Array.from(parse(content))
|
||||
|
||||
expect(blocks).toEqual([
|
||||
{ type: 'text', text: ':' },
|
||||
{ type: 'relay', url: 'wss://oa.ao/' },
|
||||
{ type: 'relay', url: 'wss://oa.ao/a/' },
|
||||
{ type: 'text', text: "; this was a relay and now here's a video -> " },
|
||||
{ type: 'video', url: 'https://videos.com/video.mp4' },
|
||||
{ type: 'text', text: '! and some music:\n' },
|
||||
@@ -113,3 +113,18 @@ test('emoji shortcodes are treated as text if no event tags', () => {
|
||||
|
||||
expect(blocks).toEqual([{ type: 'text', text: 'hello :alpaca:' }])
|
||||
})
|
||||
|
||||
test("a thing that didn't work well in the wild", () => {
|
||||
const blocks = Array.from(
|
||||
parse(
|
||||
`Crowdsourcing doesn't mean just users clicking, by the way (although that could be possible too), it means a bunch of machines competing: https://leaderboard.sbstats.uk/`,
|
||||
),
|
||||
)
|
||||
expect(blocks).toEqual([
|
||||
{
|
||||
type: 'text',
|
||||
text: `Crowdsourcing doesn't mean just users clicking, by the way (although that could be possible too), it means a bunch of machines competing: `,
|
||||
},
|
||||
{ type: 'url', url: 'https://leaderboard.sbstats.uk/' },
|
||||
])
|
||||
})
|
||||
|
||||
6
nip27.ts
6
nip27.ts
@@ -41,7 +41,7 @@ export type Block =
|
||||
}
|
||||
|
||||
const noCharacter = /\W/m
|
||||
const noURLCharacter = /\W |\W$|$|,| /m
|
||||
const noURLCharacter = /[^\w\/] |[^\w\/]$|$|,| /m
|
||||
const MAX_HASHTAG_LENGTH = 42
|
||||
|
||||
export function* parse(content: string | NostrEvent): Iterable<Block> {
|
||||
@@ -96,8 +96,10 @@ export function* parse(content: string | NostrEvent): Iterable<Block> {
|
||||
case 'npub':
|
||||
pointer = { pubkey: data } as ProfilePointer
|
||||
break
|
||||
case 'nsec':
|
||||
case 'note':
|
||||
pointer = { id: data } as EventPointer
|
||||
break
|
||||
case 'nsec':
|
||||
// ignore this, treat it as not a valid uri
|
||||
index = end + 1
|
||||
continue
|
||||
|
||||
157
nip46.ts
157
nip46.ts
@@ -87,31 +87,7 @@ export type NostrConnectParams = {
|
||||
image?: string
|
||||
}
|
||||
|
||||
export type ParsedNostrConnectURI = {
|
||||
protocol: 'nostrconnect'
|
||||
clientPubkey: string
|
||||
params: {
|
||||
relays: string[]
|
||||
secret: string
|
||||
perms?: string[]
|
||||
name?: string
|
||||
url?: string
|
||||
image?: string
|
||||
}
|
||||
originalString: string
|
||||
}
|
||||
|
||||
export function createNostrConnectURI(params: NostrConnectParams): string {
|
||||
if (!params.clientPubkey) {
|
||||
throw new Error('clientPubkey is required.')
|
||||
}
|
||||
if (!params.relays || params.relays.length === 0) {
|
||||
throw new Error('At least one relay is required.')
|
||||
}
|
||||
if (!params.secret) {
|
||||
throw new Error('secret is required.')
|
||||
}
|
||||
|
||||
const queryParams = new URLSearchParams()
|
||||
|
||||
params.relays.forEach(relay => {
|
||||
@@ -136,55 +112,6 @@ export function createNostrConnectURI(params: NostrConnectParams): string {
|
||||
return `nostrconnect://${params.clientPubkey}?${queryParams.toString()}`
|
||||
}
|
||||
|
||||
export function parseNostrConnectURI(uri: string): ParsedNostrConnectURI {
|
||||
if (!uri.startsWith('nostrconnect://')) {
|
||||
throw new Error('Invalid nostrconnect URI: Must start with "nostrconnect://".')
|
||||
}
|
||||
|
||||
const [protocolAndPubkey, queryString] = uri.split('?')
|
||||
if (!protocolAndPubkey || !queryString) {
|
||||
throw new Error('Invalid nostrconnect URI: Missing query string.')
|
||||
}
|
||||
|
||||
const clientPubkey = protocolAndPubkey.substring('nostrconnect://'.length)
|
||||
if (!clientPubkey) {
|
||||
throw new Error('Invalid nostrconnect URI: Missing client-pubkey.')
|
||||
}
|
||||
|
||||
const queryParams = new URLSearchParams(queryString)
|
||||
|
||||
const relays = queryParams.getAll('relay')
|
||||
if (relays.length === 0) {
|
||||
throw new Error('Invalid nostrconnect URI: Missing "relay" parameter.')
|
||||
}
|
||||
|
||||
const secret = queryParams.get('secret')
|
||||
if (!secret) {
|
||||
throw new Error('Invalid nostrconnect URI: Missing "secret" parameter.')
|
||||
}
|
||||
|
||||
const permsString = queryParams.get('perms')
|
||||
const perms = permsString ? permsString.split(',') : undefined
|
||||
|
||||
const name = queryParams.get('name') || undefined
|
||||
const url = queryParams.get('url') || undefined
|
||||
const image = queryParams.get('image') || undefined
|
||||
|
||||
return {
|
||||
protocol: 'nostrconnect',
|
||||
clientPubkey,
|
||||
params: {
|
||||
relays,
|
||||
secret,
|
||||
perms,
|
||||
name,
|
||||
url,
|
||||
image,
|
||||
},
|
||||
originalString: uri,
|
||||
}
|
||||
}
|
||||
|
||||
export type BunkerSignerParams = {
|
||||
pool?: AbstractSimplePool
|
||||
onauth?: (url: string) => void
|
||||
@@ -238,7 +165,7 @@ export class BunkerSigner implements Signer {
|
||||
params: BunkerSignerParams = {},
|
||||
): BunkerSigner {
|
||||
if (bp.relays.length === 0) {
|
||||
throw new Error('No relays specified for this bunker')
|
||||
throw new Error('no relays specified for this bunker')
|
||||
}
|
||||
|
||||
const signer = new BunkerSigner(clientSecretKey, params)
|
||||
@@ -246,7 +173,7 @@ export class BunkerSigner implements Signer {
|
||||
signer.conversationKey = getConversationKey(clientSecretKey, bp.pubkey)
|
||||
signer.bp = bp
|
||||
|
||||
signer.setupSubscription(params)
|
||||
signer.setupSubscription()
|
||||
return signer
|
||||
}
|
||||
|
||||
@@ -257,22 +184,22 @@ export class BunkerSigner implements Signer {
|
||||
public static async fromURI(
|
||||
clientSecretKey: Uint8Array,
|
||||
connectionURI: string,
|
||||
params: BunkerSignerParams = {},
|
||||
maxWait: number = 300_000,
|
||||
bunkerParams: BunkerSignerParams = {},
|
||||
maxWaitOrAbort: number | AbortSignal = 300_000,
|
||||
): Promise<BunkerSigner> {
|
||||
const signer = new BunkerSigner(clientSecretKey, params)
|
||||
const parsedURI = parseNostrConnectURI(connectionURI)
|
||||
const signer = new BunkerSigner(clientSecretKey, bunkerParams)
|
||||
const uri = new URL(connectionURI)
|
||||
const clientPubkey = getPublicKey(clientSecretKey)
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
sub.close()
|
||||
reject(new Error(`Connection timed out after ${maxWait / 1000} seconds`))
|
||||
}, maxWait)
|
||||
|
||||
let success = false
|
||||
const sub = signer.pool.subscribe(
|
||||
parsedURI.params.relays,
|
||||
{ kinds: [NostrConnect], '#p': [clientPubkey] },
|
||||
uri.searchParams.getAll('relay'),
|
||||
{
|
||||
kinds: [NostrConnect],
|
||||
'#p': [clientPubkey],
|
||||
limit: 0,
|
||||
},
|
||||
{
|
||||
onevent: async (event: NostrEvent) => {
|
||||
try {
|
||||
@@ -281,41 +208,48 @@ export class BunkerSigner implements Signer {
|
||||
|
||||
const response = JSON.parse(decryptedContent)
|
||||
|
||||
if (response.result === parsedURI.params.secret) {
|
||||
clearTimeout(timer)
|
||||
if (response.result === uri.searchParams.get('secret')) {
|
||||
sub.close()
|
||||
|
||||
signer.bp = {
|
||||
pubkey: event.pubkey,
|
||||
relays: parsedURI.params.relays,
|
||||
secret: parsedURI.params.secret,
|
||||
relays: uri.searchParams.getAll('relay'),
|
||||
secret: uri.searchParams.get('secret'),
|
||||
}
|
||||
signer.conversationKey = getConversationKey(clientSecretKey, event.pubkey)
|
||||
signer.setupSubscription(params)
|
||||
signer.setupSubscription()
|
||||
|
||||
success = true
|
||||
await Promise.race([new Promise(resolve => setTimeout(resolve, 1000)), signer.switchRelays()])
|
||||
resolve(signer)
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('Failed to process potential connection event', e)
|
||||
console.warn('failed to process potential connection event', e)
|
||||
}
|
||||
},
|
||||
onclose: () => {
|
||||
clearTimeout(timer)
|
||||
reject(new Error('Subscription closed before connection was established.'))
|
||||
if (!success) reject(new Error('subscription closed before connection was established.'))
|
||||
},
|
||||
maxWait,
|
||||
maxWait: typeof maxWaitOrAbort === 'number' ? maxWaitOrAbort : undefined,
|
||||
abort: typeof maxWaitOrAbort !== 'number' ? maxWaitOrAbort : undefined,
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
private setupSubscription(params: BunkerSignerParams) {
|
||||
private setupSubscription() {
|
||||
const listeners = this.listeners
|
||||
const waitingForAuth = this.waitingForAuth
|
||||
const convKey = this.conversationKey
|
||||
|
||||
this.subCloser = this.pool.subscribe(
|
||||
this.bp.relays,
|
||||
{ kinds: [NostrConnect], authors: [this.bp.pubkey], '#p': [getPublicKey(this.secretKey)] },
|
||||
{
|
||||
kinds: [NostrConnect],
|
||||
authors: [this.bp.pubkey],
|
||||
'#p': [getPublicKey(this.secretKey)],
|
||||
limit: 0,
|
||||
},
|
||||
{
|
||||
onevent: async (event: NostrEvent) => {
|
||||
const o = JSON.parse(decrypt(event.content, convKey))
|
||||
@@ -324,8 +258,8 @@ export class BunkerSigner implements Signer {
|
||||
if (result === 'auth_url' && waitingForAuth[id]) {
|
||||
delete waitingForAuth[id]
|
||||
|
||||
if (params.onauth) {
|
||||
params.onauth(error)
|
||||
if (this.params.onauth) {
|
||||
this.params.onauth(error)
|
||||
} else {
|
||||
console.warn(
|
||||
`nostr-tools/nip46: remote signer ${this.bp.pubkey} tried to send an "auth_url"='${error}' but there was no onauth() callback configured.`,
|
||||
@@ -349,6 +283,27 @@ export class BunkerSigner implements Signer {
|
||||
this.isOpen = true
|
||||
}
|
||||
|
||||
async switchRelays(): Promise<boolean> {
|
||||
try {
|
||||
const switchResp = await this.sendRequest('switch_relays', [])
|
||||
let relays = JSON.parse(switchResp) as string[] | null
|
||||
if (!relays) return false
|
||||
if (JSON.stringify(relays.sort()) === JSON.stringify(this.bp.relays)) return false
|
||||
|
||||
this.bp.relays = relays
|
||||
let previousCloser = this.subCloser!
|
||||
setTimeout(() => {
|
||||
previousCloser.close()
|
||||
}, 5000)
|
||||
|
||||
this.subCloser = undefined
|
||||
this.setupSubscription()
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// closes the subscription -- this object can't be used anymore after this
|
||||
async close() {
|
||||
this.isOpen = false
|
||||
@@ -359,7 +314,7 @@ export class BunkerSigner implements Signer {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
if (!this.isOpen) throw new Error('this signer is not open anymore, create a new one')
|
||||
if (!this.subCloser) this.setupSubscription(this.params)
|
||||
if (!this.subCloser) this.setupSubscription()
|
||||
|
||||
this.serial++
|
||||
const id = `${this.idPrefix}-${this.serial}`
|
||||
@@ -469,7 +424,7 @@ export async function createAccount(
|
||||
email?: string,
|
||||
localSecretKey: Uint8Array = generateSecretKey(),
|
||||
): Promise<BunkerSigner> {
|
||||
if (email && !EMAIL_REGEX.test(email)) throw new Error('Invalid email')
|
||||
if (email && !EMAIL_REGEX.test(email)) throw new Error('invalid email')
|
||||
|
||||
let rpc = BunkerSigner.fromBunker(localSecretKey, bunker.bunkerPointer, params)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"type": "module",
|
||||
"name": "nostr-tools",
|
||||
"version": "2.19.1",
|
||||
"version": "2.20.0",
|
||||
"description": "Tools for making a Nostr client.",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
Reference in New Issue
Block a user