Compare commits

..

12 Commits

Author SHA1 Message Date
lemonknowsall
b40f59af74 Upgrade to @noble/curves ^2.0.1 and @noble/hashes ^2.0.1
This commit upgrades the noble cryptography dependencies to v2.0.1, which includes:

Breaking changes addressed:
- Updated all @noble imports to include .js extensions (required by v2 ESM-only API)
- Changed @noble/hashes/sha256 to @noble/hashes/sha2.js across 8 files
- Fixed secp256k1 API changes: methods now require Uint8Array instead of hex strings
- Updated schnorr.utils.randomPrivateKey() to schnorr.utils.randomSecretKey()

Files modified (27 total):
- package.json: Bump dependency versions
- Source files (12): pure.ts, nip04.ts, nip06.ts, nip13.ts, nip19.ts, nip44.ts,
  nip49.ts, nip77.ts, nip98.ts, nipb7.ts, utils.ts, wasm.ts
- Test files (14): All corresponding test files updated

Benefits:
- Latest security updates from audited noble libraries
- Smaller bundle sizes from v2 optimizations
- Future-proof ESM-only compatibility
- All tests passing

Co-authored-by: OpenCode <opencode@anomalyco.com>
2026-01-24 09:41:15 -03:00
fiatjaf
bfa40da316 nip46: improve fromURI() and implement "switch_relays". 2026-01-22 21:50:30 -03:00
fiatjaf
9078f45a64 optionally take an AbortSignal on subscriptions. 2026-01-22 21:49:39 -03:00
fiatjaf
6ebe59f123 nip27: support note1 entities for now, but treat them like nevent. 2025-12-17 17:48:35 -03:00
fiatjaf
0235b490fa nip27: fix trailing / in urls. 2025-12-11 21:23:32 -03:00
fiatjaf
e290f98a86 label forced ping subscription. 2025-12-10 21:06:31 -03:00
fiatjaf
7a50d9328d add some more kinds. 2025-12-09 10:56:43 -03:00
fiatjaf
65412e5b85 NostrEvent > Event. 2025-12-06 12:21:56 -03:00
fiatjaf
ca36ae9530 update README with new enableReconnect() behavior. 2025-12-05 21:59:52 -03:00
fiatjaf
0b6543e1a8 use setInterval() instead of nested setTimeout()s for pingpong.
prevent call stacks from building up
2025-12-05 21:46:16 -03:00
fiatjaf
693b262b7c CLOSED answers to dummyReq are also ok. 2025-12-05 21:03:34 -03:00
fiatjaf
85c964be3d enableReconnect() always update the filters to the time of the last received event on each subscription. 2025-12-05 13:24:49 -03:00
37 changed files with 257 additions and 288 deletions

View File

@@ -160,16 +160,7 @@ Using both `enablePing: true` and `enableReconnect: true` is recommended as it w
const pool = new SimplePool({ enablePing: true, enableReconnect: true }) 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. 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.
```js
const pool = new SimplePool({
enableReconnect: (filters) => {
const newSince = Math.floor(Date.now() / 1000)
return filters.map(filter => ({ ...filter, since: newSince }))
}
})
```
### Parsing references (mentions) from a content based on NIP-27 ### Parsing references (mentions) from a content based on NIP-27

View File

@@ -23,6 +23,7 @@ export type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {
export type SubscribeManyParams = Omit<SubscriptionParams, 'onclose'> & { export type SubscribeManyParams = Omit<SubscriptionParams, 'onclose'> & {
maxWait?: number maxWait?: number
abort?: AbortSignal
onclose?: (reasons: string[]) => void onclose?: (reasons: string[]) => void
onauth?: (event: EventTemplate) => Promise<VerifiedEvent> onauth?: (event: EventTemplate) => Promise<VerifiedEvent>
id?: string id?: string
@@ -36,7 +37,7 @@ export class AbstractSimplePool {
public verifyEvent: Nostr['verifyEvent'] public verifyEvent: Nostr['verifyEvent']
public enablePing: boolean | undefined public enablePing: boolean | undefined
public enableReconnect: boolean | ((filters: Filter[]) => Filter[]) | undefined 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()
@@ -46,11 +47,17 @@ export class AbstractSimplePool {
this.verifyEvent = opts.verifyEvent this.verifyEvent = opts.verifyEvent
this._WebSocket = opts.websocketImplementation this._WebSocket = opts.websocketImplementation
this.enablePing = opts.enablePing this.enablePing = opts.enablePing
this.enableReconnect = opts.enableReconnect this.enableReconnect = opts.enableReconnect || false
this.automaticallyAuth = opts.automaticallyAuth 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) url = normalizeURL(url)
let relay = this.relays.get(url) let relay = this.relays.get(url)
@@ -66,7 +73,6 @@ export class AbstractSimplePool {
this.relays.delete(url) this.relays.delete(url)
} }
} }
if (params?.connectionTimeout) relay.connectionTimeout = params.connectionTimeout
this.relays.set(url, relay) 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 return relay
} }
@@ -176,6 +185,7 @@ export class AbstractSimplePool {
try { try {
relay = await this.ensureRelay(url, { relay = await this.ensureRelay(url, {
connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1000) : undefined, connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1000) : undefined,
abort: params.abort,
}) })
} catch (err) { } catch (err) {
handleClose(i, (err as any)?.message || String(err)) handleClose(i, (err as any)?.message || String(err))
@@ -198,6 +208,7 @@ export class AbstractSimplePool {
}, },
alreadyHaveEvent: localAlreadyHaveEventHandler, alreadyHaveEvent: localAlreadyHaveEventHandler,
eoseTimeout: params.maxWait, eoseTimeout: params.maxWait,
abort: params.abort,
}) })
}) })
.catch(err => { .catch(err => {
@@ -209,6 +220,7 @@ export class AbstractSimplePool {
}, },
alreadyHaveEvent: localAlreadyHaveEventHandler, alreadyHaveEvent: localAlreadyHaveEventHandler,
eoseTimeout: params.maxWait, eoseTimeout: params.maxWait,
abort: params.abort,
}) })
subs.push(subscription) subs.push(subscription)

View File

@@ -16,7 +16,7 @@ export type AbstractRelayConstructorOptions = {
verifyEvent: Nostr['verifyEvent'] verifyEvent: Nostr['verifyEvent']
websocketImplementation?: typeof WebSocket websocketImplementation?: typeof WebSocket
enablePing?: boolean enablePing?: boolean
enableReconnect?: boolean | ((filters: Filter[]) => Filter[]) enableReconnect?: boolean
} }
export class SendingOnClosedConnection extends Error { export class SendingOnClosedConnection extends Error {
@@ -35,17 +35,15 @@ export class AbstractRelay {
public onauth: undefined | ((evt: EventTemplate) => Promise<VerifiedEvent>) public onauth: undefined | ((evt: EventTemplate) => Promise<VerifiedEvent>)
public baseEoseTimeout: number = 4400 public baseEoseTimeout: number = 4400
public connectionTimeout: number = 4400
public publishTimeout: number = 4400 public publishTimeout: number = 4400
public pingFrequency: number = 20000 public pingFrequency: number = 29000
public pingTimeout: number = 20000 public pingTimeout: number = 20000
public resubscribeBackoff: number[] = [10000, 10000, 10000, 20000, 20000, 30000, 60000] public resubscribeBackoff: number[] = [10000, 10000, 10000, 20000, 20000, 30000, 60000]
public openSubs: Map<string, Subscription> = new Map() public openSubs: Map<string, Subscription> = new Map()
public enablePing: boolean | undefined public enablePing: boolean | undefined
public enableReconnect: boolean | ((filters: Filter[]) => Filter[]) public enableReconnect: boolean
private connectionTimeoutHandle: ReturnType<typeof setTimeout> | undefined
private reconnectTimeoutHandle: 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 reconnectAttempts: number = 0
private closedIntentionally: boolean = false private closedIntentionally: boolean = false
@@ -70,9 +68,12 @@ export class AbstractRelay {
this.enableReconnect = opts.enableReconnect || false 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) const relay = new AbstractRelay(url, opts)
await relay.connect() await relay.connect(opts)
return relay return relay
} }
@@ -111,9 +112,9 @@ export class AbstractRelay {
} }
private handleHardClose(reason: string) { private handleHardClose(reason: string) {
if (this.pingTimeoutHandle) { if (this.pingIntervalHandle) {
clearTimeout(this.pingTimeoutHandle) clearInterval(this.pingIntervalHandle)
this.pingTimeoutHandle = undefined this.pingIntervalHandle = undefined
} }
this._connected = false 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 if (this.connectionPromise) return this.connectionPromise
this.challenge = undefined this.challenge = undefined
this.authPromise = undefined this.authPromise = undefined
this.connectionPromise = new Promise((resolve, reject) => { this.connectionPromise = new Promise((resolve, reject) => {
this.connectionTimeoutHandle = setTimeout(() => { if (opts?.timeout) {
reject('connection timed out') connectionTimeoutHandle = setTimeout(() => {
this.connectionPromise = undefined reject('connection timed out')
this.onclose?.() this.connectionPromise = undefined
this.closeAllSubscriptions('relay connection timed out') this.onclose?.()
}, this.connectionTimeout) this.closeAllSubscriptions('relay connection timed out')
}, opts.timeout)
}
if (opts?.abort) {
opts.abort.onabort = reject
}
try { try {
this.ws = new this._WebSocket(this.url) this.ws = new this._WebSocket(this.url)
} catch (err) { } catch (err) {
clearTimeout(this.connectionTimeoutHandle) clearTimeout(connectionTimeoutHandle)
reject(err) reject(err)
return return
} }
@@ -157,7 +166,7 @@ export class AbstractRelay {
clearTimeout(this.reconnectTimeoutHandle) clearTimeout(this.reconnectTimeoutHandle)
this.reconnectTimeoutHandle = undefined this.reconnectTimeoutHandle = undefined
} }
clearTimeout(this.connectionTimeoutHandle) clearTimeout(connectionTimeoutHandle)
this._connected = true this._connected = true
const isReconnection = this.reconnectAttempts > 0 const isReconnection = this.reconnectAttempts > 0
@@ -166,26 +175,30 @@ export class AbstractRelay {
// resubscribe to all open subscriptions // resubscribe to all open subscriptions
for (const sub of this.openSubs.values()) { for (const sub of this.openSubs.values()) {
sub.eosed = false sub.eosed = false
if (isReconnection && typeof this.enableReconnect === 'function') { if (isReconnection) {
sub.filters = this.enableReconnect(sub.filters) for (let f = 0; f < sub.filters.length; f++) {
if (sub.lastEmitted) {
sub.filters[f].since = sub.lastEmitted + 1
}
}
} }
sub.fire() sub.fire()
} }
if (this.enablePing) { if (this.enablePing) {
this.pingpong() this.pingIntervalHandle = setInterval(() => this.pingpong(), this.pingFrequency)
} }
resolve() resolve()
} }
this.ws.onerror = ev => { this.ws.onerror = ev => {
clearTimeout(this.connectionTimeoutHandle) clearTimeout(connectionTimeoutHandle)
reject((ev as any).message || 'websocket error') reject((ev as any).message || 'websocket error')
this.handleHardClose('relay connection errored') this.handleHardClose('relay connection errored')
} }
this.ws.onclose = ev => { this.ws.onclose = ev => {
clearTimeout(this.connectionTimeoutHandle) clearTimeout(connectionTimeoutHandle)
reject((ev as any).message || 'websocket closed') reject((ev as any).message || 'websocket closed')
this.handleHardClose('relay connection closed') this.handleHardClose('relay connection closed')
} }
@@ -205,20 +218,31 @@ export class AbstractRelay {
}) })
} }
private async waitForDummyReq() { private waitForDummyReq() {
return new Promise((resolve, _) => { 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 // make a dummy request with expected empty eose reply
// ["REQ", "_", {"ids":["aaaa...aaaa"], "limit": 0}] // ["REQ", "_", {"ids":["aaaa...aaaa"], "limit": 0}]
const sub = this.subscribe( try {
[{ ids: ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'], limit: 0 }], const sub = this.subscribe(
{ [{ ids: ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'], limit: 0 }],
oneose: () => { {
sub.close() label: 'forced-ping',
resolve(true) 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)
}
}) })
} }
@@ -233,10 +257,8 @@ export class AbstractRelay {
this.ws && this.ws.ping && (this.ws as any).once ? this.waitForPingPong() : this.waitForDummyReq(), this.ws && this.ws.ping && (this.ws as any).once ? this.waitForPingPong() : this.waitForDummyReq(),
new Promise(res => setTimeout(() => res(false), this.pingTimeout)), new Promise(res => setTimeout(() => res(false), this.pingTimeout)),
]) ])
if (result) {
// schedule another pingpong if (!result) {
this.pingTimeoutHandle = setTimeout(() => this.pingpong(), this.pingFrequency)
} else {
// pingpong closing socket // pingpong closing socket
if (this.ws?.readyState === this._WebSocket.OPEN) { if (this.ws?.readyState === this._WebSocket.OPEN) {
this.ws?.close() this.ws?.close()
@@ -299,6 +321,7 @@ export class AbstractRelay {
if (this.verifyEvent(event) && matchFilters(so.filters, event)) { if (this.verifyEvent(event) && matchFilters(so.filters, event)) {
so.onevent(event) so.onevent(event)
} }
if (!so.lastEmitted || so.lastEmitted < event.created_at) so.lastEmitted = event.created_at
return return
} }
case 'COUNT': { case 'COUNT': {
@@ -423,6 +446,11 @@ export class AbstractRelay {
): Subscription { ): Subscription {
const sub = this.prepareSubscription(filters, params) const sub = this.prepareSubscription(filters, params)
sub.fire() sub.fire()
if (params.abort) {
params.abort.onabort = () => sub.close(String(params.abort!.reason || '<aborted>'))
}
return sub return sub
} }
@@ -443,9 +471,9 @@ export class AbstractRelay {
clearTimeout(this.reconnectTimeoutHandle) clearTimeout(this.reconnectTimeoutHandle)
this.reconnectTimeoutHandle = undefined this.reconnectTimeoutHandle = undefined
} }
if (this.pingTimeoutHandle) { if (this.pingIntervalHandle) {
clearTimeout(this.pingTimeoutHandle) clearInterval(this.pingIntervalHandle)
this.pingTimeoutHandle = undefined this.pingIntervalHandle = undefined
} }
this.closeAllSubscriptions('relay connection closed by us') this.closeAllSubscriptions('relay connection closed by us')
this._connected = false this._connected = false
@@ -469,6 +497,7 @@ export class Subscription {
public readonly relay: AbstractRelay public readonly relay: AbstractRelay
public readonly id: string public readonly id: string
public lastEmitted: number | undefined
public closed: boolean = false public closed: boolean = false
public eosed: boolean = false public eosed: boolean = false
public filters: Filter[] public filters: Filter[]
@@ -548,6 +577,7 @@ export type SubscriptionParams = {
alreadyHaveEvent?: (id: string) => boolean alreadyHaveEvent?: (id: string) => boolean
receivedEvent?: (relay: AbstractRelay, id: string) => void receivedEvent?: (relay: AbstractRelay, id: string) => void
eoseTimeout?: number eoseTimeout?: number
abort?: AbortSignal
} }
export type CountResolver = { export type CountResolver = {

View File

@@ -8,7 +8,7 @@ export interface Nostr {
/** Designates a verified event signature. */ /** Designates a verified event signature. */
export const verifiedSymbol = Symbol('verified') export const verifiedSymbol = Symbol('verified')
export interface Event { export type NostrEvent = {
kind: number kind: number
tags: string[][] tags: string[][]
content: string content: string
@@ -19,7 +19,7 @@ export interface Event {
[verifiedSymbol]?: boolean [verifiedSymbol]?: boolean
} }
export type NostrEvent = Event export type Event = NostrEvent
export type EventTemplate = Pick<Event, 'kind' | 'tags' | 'content' | 'created_at'> export type EventTemplate = Pick<Event, 'kind' | 'tags' | 'content' | 'created_at'>
export type UnsignedEvent = Pick<Event, 'kind' | 'tags' | 'content' | 'created_at' | 'pubkey'> export type UnsignedEvent = Pick<Event, 'kind' | 'tags' | 'content' | 'created_at' | 'pubkey'>

View File

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

View File

@@ -55,12 +55,24 @@ export const Reaction = 7
export type Reaction = typeof Reaction export type Reaction = typeof Reaction
export const BadgeAward = 8 export const BadgeAward = 8
export type BadgeAward = typeof BadgeAward 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 const Seal = 13
export type Seal = typeof Seal export type Seal = typeof Seal
export const PrivateDirectMessage = 14 export const PrivateDirectMessage = 14
export type PrivateDirectMessage = typeof PrivateDirectMessage export type PrivateDirectMessage = typeof PrivateDirectMessage
export const FileMessage = 15
export type FileMessage = typeof FileMessage
export const GenericRepost = 16 export const GenericRepost = 16
export type GenericRepost = typeof GenericRepost 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 const ChannelCreation = 40
export type ChannelCreation = typeof ChannelCreation export type ChannelCreation = typeof ChannelCreation
export const ChannelMetadata = 41 export const ChannelMetadata = 41
@@ -75,10 +87,18 @@ export const OpenTimestamps = 1040
export type OpenTimestamps = typeof OpenTimestamps export type OpenTimestamps = typeof OpenTimestamps
export const GiftWrap = 1059 export const GiftWrap = 1059
export type GiftWrap = typeof GiftWrap export type GiftWrap = typeof GiftWrap
export const Poll = 1068
export type Poll = typeof Poll
export const FileMetadata = 1063 export const FileMetadata = 1063
export type FileMetadata = typeof FileMetadata export type FileMetadata = typeof FileMetadata
export const Comment = 1111
export type Comment = typeof Comment
export const LiveChatMessage = 1311 export const LiveChatMessage = 1311
export type LiveChatMessage = typeof LiveChatMessage 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 const ProblemTracker = 1971
export type ProblemTracker = typeof ProblemTracker export type ProblemTracker = typeof ProblemTracker
export const Report = 1984 export const Report = 1984
@@ -103,6 +123,8 @@ export const Zap = 9735
export type Zap = typeof Zap export type Zap = typeof Zap
export const Highlights = 9802 export const Highlights = 9802
export type Highlights = typeof Highlights export type Highlights = typeof Highlights
export const PollResponse = 1018
export type PollResponse = typeof PollResponse
export const Mutelist = 10000 export const Mutelist = 10000
export type Mutelist = typeof Mutelist export type Mutelist = typeof Mutelist
export const Pinlist = 10001 export const Pinlist = 10001
@@ -119,6 +141,8 @@ export const BlockedRelaysList = 10006
export type BlockedRelaysList = typeof BlockedRelaysList export type BlockedRelaysList = typeof BlockedRelaysList
export const SearchRelaysList = 10007 export const SearchRelaysList = 10007
export type SearchRelaysList = typeof SearchRelaysList export type SearchRelaysList = typeof SearchRelaysList
export const FavoriteRelays = 10012
export type FavoriteRelays = typeof FavoriteRelays
export const InterestsList = 10015 export const InterestsList = 10015
export type InterestsList = typeof InterestsList export type InterestsList = typeof InterestsList
export const UserEmojiList = 10030 export const UserEmojiList = 10030
@@ -127,6 +151,8 @@ export const DirectMessageRelaysList = 10050
export type DirectMessageRelaysList = typeof DirectMessageRelaysList export type DirectMessageRelaysList = typeof DirectMessageRelaysList
export const FileServerPreference = 10096 export const FileServerPreference = 10096
export type FileServerPreference = typeof FileServerPreference export type FileServerPreference = typeof FileServerPreference
export const BlossomServerList = 10063
export type BlossomServerList = typeof BlossomServerList
export const NWCWalletInfo = 13194 export const NWCWalletInfo = 13194
export type NWCWalletInfo = typeof NWCWalletInfo export type NWCWalletInfo = typeof NWCWalletInfo
export const LightningPubRPC = 21000 export const LightningPubRPC = 21000
@@ -185,9 +211,13 @@ export const Calendar = 31924
export type Calendar = typeof Calendar export type Calendar = typeof Calendar
export const CalendarEventRSVP = 31925 export const CalendarEventRSVP = 31925
export type CalendarEventRSVP = typeof CalendarEventRSVP export type CalendarEventRSVP = typeof CalendarEventRSVP
export const RelayReview = 31987
export type RelayReview = typeof RelayReview
export const Handlerrecommendation = 31989 export const Handlerrecommendation = 31989
export type Handlerrecommendation = typeof Handlerrecommendation export type Handlerrecommendation = typeof Handlerrecommendation
export const Handlerinformation = 31990 export const Handlerinformation = 31990
export type Handlerinformation = typeof Handlerinformation export type Handlerinformation = typeof Handlerinformation
export const CommunityDefinition = 34550 export const CommunityDefinition = 34550
export type CommunityDefinition = typeof CommunityDefinition export type CommunityDefinition = typeof CommunityDefinition
export const GroupMetadata = 39000
export type GroupMetadata = typeof GroupMetadata

View File

@@ -2,7 +2,7 @@ import { test, expect } from 'bun:test'
import { encrypt, decrypt } from './nip04.ts' import { encrypt, decrypt } from './nip04.ts'
import { getPublicKey, generateSecretKey } from './pure.ts' import { getPublicKey, generateSecretKey } from './pure.ts'
import { bytesToHex, hexToBytes } from '@noble/hashes/utils' import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'
test('encrypt and decrypt message', async () => { test('encrypt and decrypt message', async () => {
let sk1 = generateSecretKey() let sk1 = generateSecretKey()

View File

@@ -1,13 +1,13 @@
import { bytesToHex, randomBytes } from '@noble/hashes/utils' import { bytesToHex, hexToBytes, randomBytes } from '@noble/hashes/utils.js'
import { secp256k1 } from '@noble/curves/secp256k1' import { secp256k1 } from '@noble/curves/secp256k1.js'
import { cbc } from '@noble/ciphers/aes' import { cbc } from '@noble/ciphers/aes'
import { base64 } from '@scure/base' import { base64 } from '@scure/base'
import { utf8Decoder, utf8Encoder } from './utils.ts' import { utf8Decoder, utf8Encoder } from './utils.ts'
export function encrypt(secretKey: string | Uint8Array, pubkey: string, text: string): string { export function encrypt(secretKey: string | Uint8Array, pubkey: string, text: string): string {
const privkey: string = secretKey instanceof Uint8Array ? bytesToHex(secretKey) : secretKey const privkey: Uint8Array = secretKey instanceof Uint8Array ? secretKey : hexToBytes(secretKey)
const key = secp256k1.getSharedSecret(privkey, '02' + pubkey) const key = secp256k1.getSharedSecret(privkey, hexToBytes('02' + pubkey))
const normalizedKey = getNormalizedX(key) const normalizedKey = getNormalizedX(key)
let iv = Uint8Array.from(randomBytes(16)) let iv = Uint8Array.from(randomBytes(16))
@@ -22,9 +22,9 @@ export function encrypt(secretKey: string | Uint8Array, pubkey: string, text: st
} }
export function decrypt(secretKey: string | Uint8Array, pubkey: string, data: string): string { export function decrypt(secretKey: string | Uint8Array, pubkey: string, data: string): string {
const privkey: string = secretKey instanceof Uint8Array ? bytesToHex(secretKey) : secretKey const privkey: Uint8Array = secretKey instanceof Uint8Array ? secretKey : hexToBytes(secretKey)
let [ctb64, ivb64] = data.split('?iv=') let [ctb64, ivb64] = data.split('?iv=')
let key = secp256k1.getSharedSecret(privkey, '02' + pubkey) let key = secp256k1.getSharedSecret(privkey, hexToBytes('02' + pubkey))
let normalizedKey = getNormalizedX(key) let normalizedKey = getNormalizedX(key)
let iv = base64.decode(ivb64) let iv = base64.decode(ivb64)

View File

@@ -5,7 +5,7 @@ import {
extendedKeysFromSeedWords, extendedKeysFromSeedWords,
accountFromExtendedKey, accountFromExtendedKey,
} from './nip06.ts' } from './nip06.ts'
import { hexToBytes } from '@noble/hashes/utils' import { hexToBytes } from '@noble/hashes/utils.js'
test('generate private key from a mnemonic', async () => { test('generate private key from a mnemonic', async () => {
const mnemonic = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong' const mnemonic = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong'

View File

@@ -1,4 +1,4 @@
import { bytesToHex } from '@noble/hashes/utils' import { bytesToHex } from '@noble/hashes/utils.js'
import { wordlist } from '@scure/bip39/wordlists/english' import { wordlist } from '@scure/bip39/wordlists/english'
import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39' import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39'
import { HDKey } from '@scure/bip32' import { HDKey } from '@scure/bip32'

View File

@@ -1,6 +1,6 @@
import { bytesToHex } from '@noble/hashes/utils' import { bytesToHex } from '@noble/hashes/utils.js'
import { type UnsignedEvent, type Event } from './pure.ts' import { type UnsignedEvent, type Event } from './pure.ts'
import { sha256 } from '@noble/hashes/sha256' import { sha256 } from '@noble/hashes/sha2.js'
import { utf8Encoder } from './utils.ts' import { utf8Encoder } from './utils.ts'

View File

@@ -2,7 +2,7 @@ import { test, expect } from 'bun:test'
import { getPublicKey } from './pure.ts' import { getPublicKey } from './pure.ts'
import { decode } from './nip19.ts' import { decode } from './nip19.ts'
import { wrapEvent, wrapManyEvents, unwrapEvent } from './nip17.ts' import { wrapEvent, wrapManyEvents, unwrapEvent } from './nip17.ts'
import { hexToBytes } from '@noble/hashes/utils' import { hexToBytes } from '@noble/hashes/utils.js'
const senderPrivateKey = decode(`nsec1p0ht6p3wepe47sjrgesyn4m50m6avk2waqudu9rl324cg2c4ufesyp6rdg`).data const senderPrivateKey = decode(`nsec1p0ht6p3wepe47sjrgesyn4m50m6avk2waqudu9rl324cg2c4ufesyp6rdg`).data

View File

@@ -1,5 +1,5 @@
import { describe, test, expect } from 'bun:test' import { describe, test, expect } from 'bun:test'
import { hexToBytes } from '@noble/hashes/utils' import { hexToBytes } from '@noble/hashes/utils.js'
import { EventTemplate, finalizeEvent, getPublicKey } from './pure.ts' import { EventTemplate, finalizeEvent, getPublicKey } from './pure.ts'
import { GenericRepost, Repost, ShortTextNote, BadgeDefinition as BadgeDefinitionKind } from './kinds.ts' import { GenericRepost, Repost, ShortTextNote, BadgeDefinition as BadgeDefinitionKind } from './kinds.ts'
import { finishRepostEvent, getRepostedEventPointer, getRepostedEvent } from './nip18.ts' import { finishRepostEvent, getRepostedEventPointer, getRepostedEvent } from './nip18.ts'

View File

@@ -1,4 +1,4 @@
import { bytesToHex, concatBytes, hexToBytes } from '@noble/hashes/utils' import { bytesToHex, concatBytes, hexToBytes } from '@noble/hashes/utils.js'
import { bech32 } from '@scure/base' import { bech32 } from '@scure/base'
import { utf8Decoder, utf8Encoder } from './utils.ts' import { utf8Decoder, utf8Encoder } from './utils.ts'

View File

@@ -1,5 +1,5 @@
import { describe, test, expect } from 'bun:test' import { describe, test, expect } from 'bun:test'
import { hexToBytes } from '@noble/hashes/utils' import { hexToBytes } from '@noble/hashes/utils.js'
import { finalizeEvent, getPublicKey } from './pure.ts' import { finalizeEvent, getPublicKey } from './pure.ts'
import { Reaction, ShortTextNote } from './kinds.ts' import { Reaction, ShortTextNote } from './kinds.ts'
import { finishReactionEvent, getReactedEventPointer } from './nip25.ts' import { finishReactionEvent, getReactedEventPointer } from './nip25.ts'

View File

@@ -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', () => { 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 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!` 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)) const blocks = Array.from(parse(content))
expect(blocks).toEqual([ expect(blocks).toEqual([
{ type: 'text', text: ':' }, { 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: 'text', text: "; this was a relay and now here's a video -> " },
{ type: 'video', url: 'https://videos.com/video.mp4' }, { type: 'video', url: 'https://videos.com/video.mp4' },
{ type: 'text', text: '! and some music:\n' }, { 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:' }]) 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/' },
])
})

View File

@@ -41,7 +41,7 @@ export type Block =
} }
const noCharacter = /\W/m const noCharacter = /\W/m
const noURLCharacter = /\W |\W$|$|,| /m const noURLCharacter = /[^\w\/] |[^\w\/]$|$|,| /m
const MAX_HASHTAG_LENGTH = 42 const MAX_HASHTAG_LENGTH = 42
export function* parse(content: string | NostrEvent): Iterable<Block> { export function* parse(content: string | NostrEvent): Iterable<Block> {
@@ -96,8 +96,10 @@ export function* parse(content: string | NostrEvent): Iterable<Block> {
case 'npub': case 'npub':
pointer = { pubkey: data } as ProfilePointer pointer = { pubkey: data } as ProfilePointer
break break
case 'nsec':
case 'note': case 'note':
pointer = { id: data } as EventPointer
break
case 'nsec':
// ignore this, treat it as not a valid uri // ignore this, treat it as not a valid uri
index = end + 1 index = end + 1
continue continue

View File

@@ -1,5 +1,5 @@
import { describe, test, expect } from 'bun:test' import { describe, test, expect } from 'bun:test'
import { hexToBytes } from '@noble/hashes/utils' import { hexToBytes } from '@noble/hashes/utils.js'
import { getPublicKey } from './pure.ts' import { getPublicKey } from './pure.ts'
import * as Kind from './kinds.ts' import * as Kind from './kinds.ts'
import { import {

View File

@@ -1,8 +1,8 @@
import { test, expect } from 'bun:test' import { test, expect } from 'bun:test'
import { v2 } from './nip44.js' import { v2 } from './nip44.js'
import { bytesToHex, hexToBytes } from '@noble/hashes/utils' import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'
import { default as vec } from './nip44.vectors.json' with { type: 'json' } import { default as vec } from './nip44.vectors.json' with { type: 'json' }
import { schnorr } from '@noble/curves/secp256k1' import { schnorr } from '@noble/curves/secp256k1.js'
const v2vec = vec.v2 const v2vec = vec.v2
test('get_conversation_key', () => { test('get_conversation_key', () => {
@@ -14,7 +14,7 @@ test('get_conversation_key', () => {
test('encrypt_decrypt', () => { test('encrypt_decrypt', () => {
for (const v of v2vec.valid.encrypt_decrypt) { for (const v of v2vec.valid.encrypt_decrypt) {
const pub2 = bytesToHex(schnorr.getPublicKey(v.sec2)) const pub2 = bytesToHex(schnorr.getPublicKey(hexToBytes(v.sec2)))
const key = v2.utils.getConversationKey(hexToBytes(v.sec1), pub2) const key = v2.utils.getConversationKey(hexToBytes(v.sec1), pub2)
expect(bytesToHex(key)).toEqual(v.conversation_key) expect(bytesToHex(key)).toEqual(v.conversation_key)
const ciphertext = v2.encrypt(v.plaintext, key, hexToBytes(v.nonce)) const ciphertext = v2.encrypt(v.plaintext, key, hexToBytes(v.nonce))
@@ -40,7 +40,7 @@ test('decrypt', async () => {
test('get_conversation_key', async () => { test('get_conversation_key', async () => {
for (const v of v2vec.invalid.get_conversation_key) { for (const v of v2vec.invalid.get_conversation_key) {
expect(() => v2.utils.getConversationKey(hexToBytes(v.sec1), v.pub2)).toThrow( expect(() => v2.utils.getConversationKey(hexToBytes(v.sec1), v.pub2)).toThrow(
/(Point is not on curve|Cannot find square root)/, /(Point is not on curve|Cannot find square root|invalid field element)/,
) )
} }
}) })

View File

@@ -1,10 +1,10 @@
import { chacha20 } from '@noble/ciphers/chacha' import { chacha20 } from '@noble/ciphers/chacha'
import { equalBytes } from '@noble/ciphers/utils' import { equalBytes } from '@noble/ciphers/utils'
import { secp256k1 } from '@noble/curves/secp256k1' import { secp256k1 } from '@noble/curves/secp256k1.js'
import { extract as hkdf_extract, expand as hkdf_expand } from '@noble/hashes/hkdf' import { extract as hkdf_extract, expand as hkdf_expand } from '@noble/hashes/hkdf.js'
import { hmac } from '@noble/hashes/hmac' import { hmac } from '@noble/hashes/hmac.js'
import { sha256 } from '@noble/hashes/sha256' import { sha256 } from '@noble/hashes/sha2.js'
import { concatBytes, randomBytes } from '@noble/hashes/utils' import { concatBytes, hexToBytes, randomBytes } from '@noble/hashes/utils.js'
import { base64 } from '@scure/base' import { base64 } from '@scure/base'
import { utf8Decoder, utf8Encoder } from './utils.ts' import { utf8Decoder, utf8Encoder } from './utils.ts'
@@ -13,8 +13,8 @@ const minPlaintextSize = 0x0001 // 1b msg => padded to 32b
const maxPlaintextSize = 0xffff // 65535 (64kb-1) => padded to 64kb const maxPlaintextSize = 0xffff // 65535 (64kb-1) => padded to 64kb
export function getConversationKey(privkeyA: Uint8Array, pubkeyB: string): Uint8Array { export function getConversationKey(privkeyA: Uint8Array, pubkeyB: string): Uint8Array {
const sharedX = secp256k1.getSharedSecret(privkeyA, '02' + pubkeyB).subarray(1, 33) const sharedX = secp256k1.getSharedSecret(privkeyA, hexToBytes('02' + pubkeyB)).subarray(1, 33)
return hkdf_extract(sha256, sharedX, 'nip44-v2') return hkdf_extract(sha256, sharedX, utf8Encoder.encode('nip44-v2'))
} }
function getMessageKeys( function getMessageKeys(

157
nip46.ts
View File

@@ -87,31 +87,7 @@ export type NostrConnectParams = {
image?: string 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 { 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() const queryParams = new URLSearchParams()
params.relays.forEach(relay => { params.relays.forEach(relay => {
@@ -136,55 +112,6 @@ export function createNostrConnectURI(params: NostrConnectParams): string {
return `nostrconnect://${params.clientPubkey}?${queryParams.toString()}` 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 = { export type BunkerSignerParams = {
pool?: AbstractSimplePool pool?: AbstractSimplePool
onauth?: (url: string) => void onauth?: (url: string) => void
@@ -238,7 +165,7 @@ export class BunkerSigner implements Signer {
params: BunkerSignerParams = {}, params: BunkerSignerParams = {},
): BunkerSigner { ): BunkerSigner {
if (bp.relays.length === 0) { 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) const signer = new BunkerSigner(clientSecretKey, params)
@@ -246,7 +173,7 @@ export class BunkerSigner implements Signer {
signer.conversationKey = getConversationKey(clientSecretKey, bp.pubkey) signer.conversationKey = getConversationKey(clientSecretKey, bp.pubkey)
signer.bp = bp signer.bp = bp
signer.setupSubscription(params) signer.setupSubscription()
return signer return signer
} }
@@ -257,22 +184,22 @@ export class BunkerSigner implements Signer {
public static async fromURI( public static async fromURI(
clientSecretKey: Uint8Array, clientSecretKey: Uint8Array,
connectionURI: string, connectionURI: string,
params: BunkerSignerParams = {}, bunkerParams: BunkerSignerParams = {},
maxWait: number = 300_000, maxWaitOrAbort: number | AbortSignal = 300_000,
): Promise<BunkerSigner> { ): Promise<BunkerSigner> {
const signer = new BunkerSigner(clientSecretKey, params) const signer = new BunkerSigner(clientSecretKey, bunkerParams)
const parsedURI = parseNostrConnectURI(connectionURI) const uri = new URL(connectionURI)
const clientPubkey = getPublicKey(clientSecretKey) const clientPubkey = getPublicKey(clientSecretKey)
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const timer = setTimeout(() => { let success = false
sub.close()
reject(new Error(`Connection timed out after ${maxWait / 1000} seconds`))
}, maxWait)
const sub = signer.pool.subscribe( const sub = signer.pool.subscribe(
parsedURI.params.relays, uri.searchParams.getAll('relay'),
{ kinds: [NostrConnect], '#p': [clientPubkey] }, {
kinds: [NostrConnect],
'#p': [clientPubkey],
limit: 0,
},
{ {
onevent: async (event: NostrEvent) => { onevent: async (event: NostrEvent) => {
try { try {
@@ -281,41 +208,48 @@ export class BunkerSigner implements Signer {
const response = JSON.parse(decryptedContent) const response = JSON.parse(decryptedContent)
if (response.result === parsedURI.params.secret) { if (response.result === uri.searchParams.get('secret')) {
clearTimeout(timer)
sub.close() sub.close()
signer.bp = { signer.bp = {
pubkey: event.pubkey, pubkey: event.pubkey,
relays: parsedURI.params.relays, relays: uri.searchParams.getAll('relay'),
secret: parsedURI.params.secret, secret: uri.searchParams.get('secret'),
} }
signer.conversationKey = getConversationKey(clientSecretKey, event.pubkey) 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) resolve(signer)
} }
} catch (e) { } catch (e) {
console.warn('Failed to process potential connection event', e) console.warn('failed to process potential connection event', e)
} }
}, },
onclose: () => { onclose: () => {
clearTimeout(timer) if (!success) reject(new Error('subscription closed before connection was established.'))
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 listeners = this.listeners
const waitingForAuth = this.waitingForAuth const waitingForAuth = this.waitingForAuth
const convKey = this.conversationKey const convKey = this.conversationKey
this.subCloser = this.pool.subscribe( this.subCloser = this.pool.subscribe(
this.bp.relays, 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) => { onevent: async (event: NostrEvent) => {
const o = JSON.parse(decrypt(event.content, convKey)) const o = JSON.parse(decrypt(event.content, convKey))
@@ -324,8 +258,8 @@ export class BunkerSigner implements Signer {
if (result === 'auth_url' && waitingForAuth[id]) { if (result === 'auth_url' && waitingForAuth[id]) {
delete waitingForAuth[id] delete waitingForAuth[id]
if (params.onauth) { if (this.params.onauth) {
params.onauth(error) this.params.onauth(error)
} else { } else {
console.warn( console.warn(
`nostr-tools/nip46: remote signer ${this.bp.pubkey} tried to send an "auth_url"='${error}' but there was no onauth() callback configured.`, `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 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 // closes the subscription -- this object can't be used anymore after this
async close() { async close() {
this.isOpen = false this.isOpen = false
@@ -359,7 +314,7 @@ export class BunkerSigner implements Signer {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
try { try {
if (!this.isOpen) throw new Error('this signer is not open anymore, create a new one') 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++ this.serial++
const id = `${this.idPrefix}-${this.serial}` const id = `${this.idPrefix}-${this.serial}`
@@ -469,7 +424,7 @@ export async function createAccount(
email?: string, email?: string,
localSecretKey: Uint8Array = generateSecretKey(), localSecretKey: Uint8Array = generateSecretKey(),
): Promise<BunkerSigner> { ): 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) let rpc = BunkerSigner.fromBunker(localSecretKey, bunker.bunkerPointer, params)

View File

@@ -1,5 +1,5 @@
import { describe, test, expect } from 'bun:test' import { describe, test, expect } from 'bun:test'
import { hexToBytes } from '@noble/hashes/utils' import { hexToBytes } from '@noble/hashes/utils.js'
import { makeNwcRequestEvent, parseConnectionString } from './nip47.ts' import { makeNwcRequestEvent, parseConnectionString } from './nip47.ts'
import { decrypt } from './nip04.ts' import { decrypt } from './nip04.ts'
import { NWCWalletRequest } from './kinds.ts' import { NWCWalletRequest } from './kinds.ts'

View File

@@ -1,6 +1,6 @@
import { test, expect } from 'bun:test' import { test, expect } from 'bun:test'
import { decrypt, encrypt } from './nip49.ts' import { decrypt, encrypt } from './nip49.ts'
import { hexToBytes } from '@noble/hashes/utils' import { hexToBytes } from '@noble/hashes/utils.js'
test('encrypt and decrypt', () => { test('encrypt and decrypt', () => {
for (let i = 0; i < vectors.length; i++) { for (let i = 0; i < vectors.length; i++) {

View File

@@ -1,6 +1,6 @@
import { scrypt } from '@noble/hashes/scrypt' import { scrypt } from '@noble/hashes/scrypt.js'
import { xchacha20poly1305 } from '@noble/ciphers/chacha' import { xchacha20poly1305 } from '@noble/ciphers/chacha'
import { concatBytes, randomBytes } from '@noble/hashes/utils' import { concatBytes, randomBytes } from '@noble/hashes/utils.js'
import { Bech32MaxSize, Ncryptsec, encodeBytes } from './nip19.ts' import { Bech32MaxSize, Ncryptsec, encodeBytes } from './nip19.ts'
import { bech32 } from '@scure/base' import { bech32 } from '@scure/base'

View File

@@ -4,7 +4,7 @@ import { decode } from './nip19.ts'
import { NostrEvent, getPublicKey } from './pure.ts' import { NostrEvent, getPublicKey } from './pure.ts'
import { SimplePool } from './pool.ts' import { SimplePool } from './pool.ts'
import { GiftWrap } from './kinds.ts' import { GiftWrap } from './kinds.ts'
import { hexToBytes } from '@noble/hashes/utils' import { hexToBytes } from '@noble/hashes/utils.js'
const senderPrivateKey = decode(`nsec1p0ht6p3wepe47sjrgesyn4m50m6avk2waqudu9rl324cg2c4ufesyp6rdg`).data as Uint8Array const senderPrivateKey = decode(`nsec1p0ht6p3wepe47sjrgesyn4m50m6avk2waqudu9rl324cg2c4ufesyp6rdg`).data as Uint8Array
const recipientPrivateKey = decode(`nsec1uyyrnx7cgfp40fcskcr2urqnzekc20fj0er6de0q8qvhx34ahazsvs9p36`).data as Uint8Array const recipientPrivateKey = decode(`nsec1uyyrnx7cgfp40fcskcr2urqnzekc20fj0er6de0q8qvhx34ahazsvs9p36`).data as Uint8Array

View File

@@ -1,7 +1,7 @@
import { bytesToHex, hexToBytes } from '@noble/ciphers/utils' import { bytesToHex, hexToBytes } from '@noble/ciphers/utils'
import { Filter } from './filter.ts' import { Filter } from './filter.ts'
import { AbstractRelay, Subscription } from './relay.ts' import { AbstractRelay, Subscription } from './relay.ts'
import { sha256 } from '@noble/hashes/sha256' import { sha256 } from '@noble/hashes/sha2.js'
// Negentropy implementation by Doug Hoyte // Negentropy implementation by Doug Hoyte
const PROTOCOL_VERSION = 0x61 // Version 1 const PROTOCOL_VERSION = 0x61 // Version 1

View File

@@ -1,5 +1,5 @@
import { sha256 } from '@noble/hashes/sha256' import { sha256 } from '@noble/hashes/sha2.js'
import { bytesToHex } from '@noble/hashes/utils' import { bytesToHex } from '@noble/hashes/utils.js'
import { describe, expect, test } from 'bun:test' import { describe, expect, test } from 'bun:test'
import { HTTPAuth } from './kinds.ts' import { HTTPAuth } from './kinds.ts'

View File

@@ -1,5 +1,5 @@
import { sha256 } from '@noble/hashes/sha256' import { sha256 } from '@noble/hashes/sha2.js'
import { bytesToHex } from '@noble/hashes/utils' import { bytesToHex } from '@noble/hashes/utils.js'
import { base64 } from '@scure/base' import { base64 } from '@scure/base'
import { HTTPAuth } from './kinds.ts' import { HTTPAuth } from './kinds.ts'

View File

@@ -1,6 +1,6 @@
import { test, expect } from 'bun:test' import { test, expect } from 'bun:test'
import { BlossomClient } from './nipb7.ts' import { BlossomClient } from './nipb7.ts'
import { sha256 } from '@noble/hashes/sha256' import { sha256 } from '@noble/hashes/sha2.js'
import { bytesToHex } from './utils.ts' import { bytesToHex } from './utils.ts'
import { PlainKeySigner } from './signer.ts' import { PlainKeySigner } from './signer.ts'
import { generateSecretKey } from './pure.ts' import { generateSecretKey } from './pure.ts'

View File

@@ -1,4 +1,4 @@
import { sha256 } from '@noble/hashes/sha256' import { sha256 } from '@noble/hashes/sha2.js'
import { EventTemplate } from './core.ts' import { EventTemplate } from './core.ts'
import { Signer } from './signer.ts' import { Signer } from './signer.ts'
import { bytesToHex } from './utils.ts' import { bytesToHex } from './utils.ts'

View File

@@ -1,7 +1,7 @@
{ {
"type": "module", "type": "module",
"name": "nostr-tools", "name": "nostr-tools",
"version": "2.19.0", "version": "2.20.0",
"description": "Tools for making a Nostr client.", "description": "Tools for making a Nostr client.",
"repository": { "repository": {
"type": "git", "type": "git",
@@ -237,8 +237,8 @@
"license": "Unlicense", "license": "Unlicense",
"dependencies": { "dependencies": {
"@noble/ciphers": "^0.5.1", "@noble/ciphers": "^0.5.1",
"@noble/curves": "1.2.0", "@noble/curves": "^2.0.1",
"@noble/hashes": "1.3.1", "@noble/hashes": "^2.0.1",
"@scure/base": "1.1.1", "@scure/base": "1.1.1",
"@scure/bip32": "1.3.1", "@scure/bip32": "1.3.1",
"@scure/bip39": "1.2.1", "@scure/bip39": "1.2.1",

View File

@@ -3,7 +3,7 @@ import { afterEach, beforeEach, expect, test } from 'bun:test'
import { SimplePool, useWebSocketImplementation } from './pool.ts' import { SimplePool, useWebSocketImplementation } from './pool.ts'
import { finalizeEvent, generateSecretKey, getPublicKey, type Event } from './pure.ts' import { finalizeEvent, generateSecretKey, getPublicKey, type Event } from './pure.ts'
import { MockRelay, MockWebSocketClient } from './test-helpers.ts' import { MockRelay, MockWebSocketClient } from './test-helpers.ts'
import { hexToBytes } from '@noble/hashes/utils' import { hexToBytes } from '@noble/hashes/utils.js'
useWebSocketImplementation(MockWebSocketClient) useWebSocketImplementation(MockWebSocketClient)
@@ -306,12 +306,9 @@ test('reconnect on disconnect in pool', async () => {
test('reconnect with filter update in pool', async () => { test('reconnect with filter update in pool', async () => {
const mockRelay = mockRelays[0] const mockRelay = mockRelays[0]
const newSince = Math.floor(Date.now() / 1000)
pool = new SimplePool({ pool = new SimplePool({
enablePing: true, enablePing: true,
enableReconnect: filters => { enableReconnect: true,
return filters.map(f => ({ ...f, since: newSince }))
},
}) })
const relay = await pool.ensureRelay(mockRelay.url) const relay = await pool.ensureRelay(mockRelay.url)
relay.pingTimeout = 50 relay.pingTimeout = 50
@@ -364,7 +361,7 @@ test('reconnect with filter update in pool', async () => {
expect(closes).toBe(1) expect(closes).toBe(1)
// check if filter was updated // check if filter was updated
expect(sub.filters[0].since).toBe(newSince) expect(sub.filters[0].since).toBeGreaterThan(1)
}) })
test('track relays when publishing', async () => { test('track relays when publishing', async () => {

View File

@@ -11,7 +11,7 @@ import {
generateSecretKey, generateSecretKey,
} from './pure.ts' } from './pure.ts'
import { ShortTextNote } from './kinds.ts' import { ShortTextNote } from './kinds.ts'
import { bytesToHex, hexToBytes } from '@noble/hashes/utils' import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'
test('private key generation', () => { test('private key generation', () => {
expect(bytesToHex(generateSecretKey())).toMatch(/[a-f0-9]{64}/) expect(bytesToHex(generateSecretKey())).toMatch(/[a-f0-9]{64}/)

12
pure.ts
View File

@@ -1,13 +1,13 @@
import { schnorr } from '@noble/curves/secp256k1' import { schnorr } from '@noble/curves/secp256k1.js'
import { bytesToHex } from '@noble/hashes/utils' import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'
import { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts' import { Nostr, Event, EventTemplate, UnsignedEvent, VerifiedEvent, verifiedSymbol, validateEvent } from './core.ts'
import { sha256 } from '@noble/hashes/sha256' import { sha256 } from '@noble/hashes/sha2.js'
import { utf8Encoder } from './utils.ts' import { utf8Encoder } from './utils.ts'
class JS implements Nostr { class JS implements Nostr {
generateSecretKey(): Uint8Array { generateSecretKey(): Uint8Array {
return schnorr.utils.randomPrivateKey() return schnorr.utils.randomSecretKey()
} }
getPublicKey(secretKey: Uint8Array): string { getPublicKey(secretKey: Uint8Array): string {
return bytesToHex(schnorr.getPublicKey(secretKey)) return bytesToHex(schnorr.getPublicKey(secretKey))
@@ -16,7 +16,7 @@ class JS implements Nostr {
const event = t as VerifiedEvent const event = t as VerifiedEvent
event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey)) event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey))
event.id = getEventHash(event) event.id = getEventHash(event)
event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey)) event.sig = bytesToHex(schnorr.sign(hexToBytes(getEventHash(event)), secretKey))
event[verifiedSymbol] = true event[verifiedSymbol] = true
return event return event
} }
@@ -30,7 +30,7 @@ class JS implements Nostr {
} }
try { try {
const valid = schnorr.verify(event.sig, hash, event.pubkey) const valid = schnorr.verify(hexToBytes(event.sig), hexToBytes(hash), hexToBytes(event.pubkey))
event[verifiedSymbol] = valid event[verifiedSymbol] = valid
return valid return valid
} catch (err) { } catch (err) {

View File

@@ -336,66 +336,3 @@ test('reconnect on disconnect', async () => {
expect(relay.connected).toBeTrue() expect(relay.connected).toBeTrue()
expect(closes).toBe(1) // should not have closed again expect(closes).toBe(1) // should not have closed again
}) })
test('reconnect with filter update', async () => {
const mockRelay = new MockRelay()
const newSince = Math.floor(Date.now() / 1000)
const relay = new Relay(mockRelay.url, {
enablePing: true,
enableReconnect: filters => {
return filters.map(f => ({ ...f, since: newSince }))
},
})
relay.pingTimeout = 50
relay.pingFrequency = 50
relay.resubscribeBackoff = [50, 100]
let closes = 0
relay.onclose = () => {
closes++
}
await relay.connect()
expect(relay.connected).toBeTrue()
const sub = relay.subscribe([{ kinds: [1], since: 0 }], { onevent: () => {} })
expect(sub.filters[0].since).toBe(0)
// wait for the first ping to succeed
await new Promise(resolve => setTimeout(resolve, 75))
expect(closes).toBe(0)
// now make it unresponsive
mockRelay.unresponsive = true
// wait for the second ping to fail, which will trigger a close
await new Promise(resolve => {
const interval = setInterval(() => {
if (closes > 0) {
clearInterval(interval)
resolve(null)
}
}, 10)
})
expect(closes).toBe(1)
expect(relay.connected).toBeFalse()
// now make it responsive again
mockRelay.unresponsive = false
// wait for reconnect
await new Promise(resolve => {
const interval = setInterval(() => {
if (relay.connected) {
clearInterval(interval)
resolve(null)
}
}, 10)
})
expect(relay.connected).toBeTrue()
expect(closes).toBe(1)
// check if filter was updated
expect(sub.filters[0].since).toBe(newSince)
})

View File

@@ -3,7 +3,7 @@ import type { Event } from './core.ts'
export const utf8Decoder: TextDecoder = new TextDecoder('utf-8') export const utf8Decoder: TextDecoder = new TextDecoder('utf-8')
export const utf8Encoder: TextEncoder = new TextEncoder() export const utf8Encoder: TextEncoder = new TextEncoder()
export { bytesToHex, hexToBytes } from '@noble/hashes/utils' export { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'
export function normalizeURL(url: string): string { export function normalizeURL(url: string): string {
try { try {

View File

@@ -1,4 +1,4 @@
import { bytesToHex } from '@noble/hashes/utils' import { bytesToHex } from '@noble/hashes/utils.js'
import { Nostr as NostrWasm } from 'nostr-wasm' import { Nostr as NostrWasm } from 'nostr-wasm'
import { EventTemplate, Event, Nostr, VerifiedEvent, verifiedSymbol } from './core.ts' import { EventTemplate, Event, Nostr, VerifiedEvent, verifiedSymbol } from './core.ts'