mirror of
https://github.com/nbd-wtf/nostr-tools.git
synced 2025-12-08 16:28:49 +00:00
Compare commits
16 Commits
v2.13.2
...
node-webso
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
719462f041 | ||
|
|
de1cf0ed60 | ||
|
|
d706ef961f | ||
|
|
2f529b3f8a | ||
|
|
f0357805c3 | ||
|
|
ffa7fb926e | ||
|
|
12acb900ab | ||
|
|
d773012658 | ||
|
|
b8f91c37fa | ||
|
|
2da3528362 | ||
|
|
315e9a472c | ||
|
|
a2b1bf0338 | ||
|
|
861a77e2b3 | ||
|
|
9132b722f3 | ||
|
|
ae2f97655b | ||
|
|
5b78a829c7 |
@@ -4,7 +4,7 @@ Tools for developing [Nostr](https://github.com/fiatjaf/nostr) clients.
|
||||
|
||||
Only depends on _@scure_ and _@noble_ packages.
|
||||
|
||||
This package is only providing lower-level functionality. If you want more higher-level features, take a look at [Nostrify](https://nostrify.dev), or if you want an easy-to-use fully-fledged solution that abstracts the hard parts of Nostr and makes decisions on your behalf, take a look at [NDK](https://github.com/nostr-dev-kit/ndk) and [@snort/system](https://www.npmjs.com/package/@snort/system).
|
||||
This package is only providing lower-level functionality. If you want higher-level features, take a look at [@nostr/gadgets](https://jsr.io/@nostr/gadgets) which is based on this library and expands upon it and has other goodies (it's only available on jsr).
|
||||
|
||||
## Installation
|
||||
|
||||
|
||||
@@ -12,13 +12,15 @@ import type { Event, EventTemplate, Nostr, VerifiedEvent } from './core.ts'
|
||||
import { type Filter } from './filter.ts'
|
||||
import { alwaysTrue } from './helpers.ts'
|
||||
|
||||
export type SubCloser = { close: () => void }
|
||||
export type SubCloser = { close: (reason?: string) => void }
|
||||
|
||||
export type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {}
|
||||
|
||||
export type SubscribeManyParams = Omit<SubscriptionParams, 'onclose'> & {
|
||||
maxWait?: number
|
||||
onclose?: (reasons: string[]) => void
|
||||
onauth?: (event: EventTemplate) => Promise<VerifiedEvent>
|
||||
// Deprecated: use onauth instead
|
||||
doauth?: (event: EventTemplate) => Promise<VerifiedEvent>
|
||||
id?: string
|
||||
label?: string
|
||||
@@ -48,6 +50,9 @@ export class AbstractSimplePool {
|
||||
verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent,
|
||||
websocketImplementation: this._WebSocket,
|
||||
})
|
||||
relay.onclose = () => {
|
||||
this.relays.delete(url)
|
||||
}
|
||||
if (params?.connectionTimeout) relay.connectionTimeout = params.connectionTimeout
|
||||
this.relays.set(url, relay)
|
||||
}
|
||||
@@ -59,10 +64,13 @@ export class AbstractSimplePool {
|
||||
close(relays: string[]) {
|
||||
relays.map(normalizeURL).forEach(url => {
|
||||
this.relays.get(url)?.close()
|
||||
this.relays.delete(url)
|
||||
})
|
||||
}
|
||||
|
||||
subscribe(relays: string[], filter: Filter, params: SubscribeManyParams): SubCloser {
|
||||
params.onauth = params.onauth || params.doauth
|
||||
|
||||
return this.subscribeMap(
|
||||
relays.map(url => ({ url, filter })),
|
||||
params,
|
||||
@@ -70,6 +78,8 @@ export class AbstractSimplePool {
|
||||
}
|
||||
|
||||
subscribeMany(relays: string[], filters: Filter[], params: SubscribeManyParams): SubCloser {
|
||||
params.onauth = params.onauth || params.doauth
|
||||
|
||||
return this.subscribeMap(
|
||||
relays.flatMap(url => filters.map(filter => ({ url, filter }))),
|
||||
params,
|
||||
@@ -77,6 +87,8 @@ export class AbstractSimplePool {
|
||||
}
|
||||
|
||||
subscribeMap(requests: { url: string; filter: Filter }[], params: SubscribeManyParams): SubCloser {
|
||||
params.onauth = params.onauth || params.doauth
|
||||
|
||||
if (this.trackRelays) {
|
||||
params.receivedEvent = (relay: AbstractRelay, id: string) => {
|
||||
let set = this.seenOn.get(id)
|
||||
@@ -141,9 +153,9 @@ export class AbstractSimplePool {
|
||||
...params,
|
||||
oneose: () => handleEose(i),
|
||||
onclose: reason => {
|
||||
if (reason.startsWith('auth-required:') && params.doauth) {
|
||||
if (reason.startsWith('auth-required: ') && params.onauth) {
|
||||
relay
|
||||
.auth(params.doauth)
|
||||
.auth(params.onauth)
|
||||
.then(() => {
|
||||
relay.subscribe([filter], {
|
||||
...params,
|
||||
@@ -171,10 +183,10 @@ export class AbstractSimplePool {
|
||||
)
|
||||
|
||||
return {
|
||||
async close() {
|
||||
async close(reason?: string) {
|
||||
await allOpened
|
||||
subs.forEach(sub => {
|
||||
sub.close()
|
||||
sub.close(reason)
|
||||
})
|
||||
},
|
||||
}
|
||||
@@ -183,12 +195,14 @@ export class AbstractSimplePool {
|
||||
subscribeEose(
|
||||
relays: string[],
|
||||
filter: Filter,
|
||||
params: Pick<SubscribeManyParams, 'label' | 'id' | 'onevent' | 'onclose' | 'maxWait' | 'doauth'>,
|
||||
params: Pick<SubscribeManyParams, 'label' | 'id' | 'onevent' | 'onclose' | 'maxWait' | 'onauth' | 'doauth'>,
|
||||
): SubCloser {
|
||||
params.onauth = params.onauth || params.doauth
|
||||
|
||||
const subcloser = this.subscribe(relays, filter, {
|
||||
...params,
|
||||
oneose() {
|
||||
subcloser.close()
|
||||
subcloser.close('closed automatically on eose')
|
||||
},
|
||||
})
|
||||
return subcloser
|
||||
@@ -197,12 +211,14 @@ export class AbstractSimplePool {
|
||||
subscribeManyEose(
|
||||
relays: string[],
|
||||
filters: Filter[],
|
||||
params: Pick<SubscribeManyParams, 'label' | 'id' | 'onevent' | 'onclose' | 'maxWait' | 'doauth'>,
|
||||
params: Pick<SubscribeManyParams, 'label' | 'id' | 'onevent' | 'onclose' | 'maxWait' | 'onauth' | 'doauth'>,
|
||||
): SubCloser {
|
||||
params.onauth = params.onauth || params.doauth
|
||||
|
||||
const subcloser = this.subscribeMany(relays, filters, {
|
||||
...params,
|
||||
oneose() {
|
||||
subcloser.close()
|
||||
subcloser.close('closed automatically on eose')
|
||||
},
|
||||
})
|
||||
return subcloser
|
||||
@@ -238,7 +254,11 @@ export class AbstractSimplePool {
|
||||
return events[0] || null
|
||||
}
|
||||
|
||||
publish(relays: string[], event: Event): Promise<string>[] {
|
||||
publish(
|
||||
relays: string[],
|
||||
event: Event,
|
||||
options?: { onauth?: (evt: EventTemplate) => Promise<VerifiedEvent> },
|
||||
): Promise<string>[] {
|
||||
return relays.map(normalizeURL).map(async (url, i, arr) => {
|
||||
if (arr.indexOf(url) !== i) {
|
||||
// duplicate
|
||||
@@ -246,17 +266,26 @@ export class AbstractSimplePool {
|
||||
}
|
||||
|
||||
let r = await this.ensureRelay(url)
|
||||
return r.publish(event).then(reason => {
|
||||
if (this.trackRelays) {
|
||||
let set = this.seenOn.get(event.id)
|
||||
if (!set) {
|
||||
set = new Set()
|
||||
this.seenOn.set(event.id, set)
|
||||
return r
|
||||
.publish(event)
|
||||
.catch(async err => {
|
||||
if (err instanceof Error && err.message.startsWith('auth-required: ') && options?.onauth) {
|
||||
await r.auth(options.onauth)
|
||||
return r.publish(event) // retry
|
||||
}
|
||||
set.add(r)
|
||||
}
|
||||
return reason
|
||||
})
|
||||
throw err
|
||||
})
|
||||
.then(reason => {
|
||||
if (this.trackRelays) {
|
||||
let set = this.seenOn.get(event.id)
|
||||
if (!set) {
|
||||
set = new Set()
|
||||
this.seenOn.set(event.id, set)
|
||||
}
|
||||
set.add(r)
|
||||
}
|
||||
return reason
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,35 @@
|
||||
/* global WebSocket */
|
||||
|
||||
import type { Event, EventTemplate, VerifiedEvent, Nostr } from './core.ts'
|
||||
import type { Event, EventTemplate, VerifiedEvent, Nostr, NostrEvent } from './core.ts'
|
||||
import { matchFilters, type Filter } from './filter.ts'
|
||||
import { getHex64, getSubscriptionId } from './fakejson.ts'
|
||||
import { Queue, normalizeURL } from './utils.ts'
|
||||
import { makeAuthEvent } from './nip42.ts'
|
||||
import { yieldThread } from './helpers.ts'
|
||||
|
||||
export type RelayRecord = Record<string, { read: boolean; write: boolean }>
|
||||
|
||||
export interface WebSocketBase {
|
||||
new (url: string | URL, protocols?: string | string[] | undefined): WebSocketBaseConn
|
||||
}
|
||||
|
||||
export interface WebSocketBaseConn {
|
||||
onopen: ((this: WebSocketBaseConn, ev: Event) => any) | null
|
||||
onclose: ((this: WebSocketBaseConn) => void) | null
|
||||
onerror: ((this: WebSocketBaseConn, _: MessageEvent<any>) => void) | null
|
||||
onmessage: ((_: MessageEvent<any>) => void) | null
|
||||
}
|
||||
|
||||
export type AbstractRelayConstructorOptions = {
|
||||
verifyEvent: Nostr['verifyEvent']
|
||||
websocketImplementation?: typeof WebSocket
|
||||
websocketImplementation?: WebSocketBase
|
||||
}
|
||||
|
||||
export class SendingOnClosedConnection extends Error {
|
||||
constructor(message: string, relay: string) {
|
||||
super(`Tried to send message '${message} on a closed connection to ${relay}.`)
|
||||
this.name = 'SendingOnClosedConnection'
|
||||
}
|
||||
}
|
||||
|
||||
export class AbstractRelay {
|
||||
@@ -19,9 +39,6 @@ export class AbstractRelay {
|
||||
public onclose: (() => void) | null = null
|
||||
public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)
|
||||
|
||||
// this is exposed just to help in ndk migration, shouldn't be relied upon
|
||||
public _onauth: ((challenge: string) => void) | null = null
|
||||
|
||||
public baseEoseTimeout: number = 4400
|
||||
public connectionTimeout: number = 4400
|
||||
public publishTimeout: number = 4400
|
||||
@@ -39,7 +56,7 @@ export class AbstractRelay {
|
||||
private serial: number = 0
|
||||
private verifyEvent: Nostr['verifyEvent']
|
||||
|
||||
private _WebSocket: typeof WebSocket
|
||||
private _WebSocket: WebSocketBase
|
||||
|
||||
constructor(url: string, opts: AbstractRelayConstructorOptions) {
|
||||
this.url = normalizeURL(url)
|
||||
@@ -112,7 +129,7 @@ export class AbstractRelay {
|
||||
}
|
||||
}
|
||||
|
||||
this.ws.onclose = (ev) => {
|
||||
this.ws.onclose = ev => {
|
||||
clearTimeout(this.connectionTimeoutHandle)
|
||||
reject((ev as any).message || 'websocket closed')
|
||||
if (this._connected) {
|
||||
@@ -178,7 +195,7 @@ export class AbstractRelay {
|
||||
switch (data[0]) {
|
||||
case 'EVENT': {
|
||||
const so = this.openSubs.get(data[1] as string) as Subscription
|
||||
const event = data[2] as Event
|
||||
const event = data[2] as NostrEvent
|
||||
if (this.verifyEvent(event) && matchFilters(so.filters, event)) {
|
||||
so.onevent(event)
|
||||
}
|
||||
@@ -226,7 +243,6 @@ export class AbstractRelay {
|
||||
return
|
||||
case 'AUTH': {
|
||||
this.challenge = data[1] as string
|
||||
this._onauth?.(data[1] as string)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -236,7 +252,7 @@ export class AbstractRelay {
|
||||
}
|
||||
|
||||
public async send(message: string) {
|
||||
if (!this.connectionPromise) throw new Error('sending on closed connection')
|
||||
if (!this.connectionPromise) throw new SendingOnClosedConnection(message, this.url)
|
||||
|
||||
this.connectionPromise.then(() => {
|
||||
this.ws?.send(message)
|
||||
@@ -249,16 +265,20 @@ export class AbstractRelay {
|
||||
if (this.authPromise) return this.authPromise
|
||||
|
||||
this.authPromise = new Promise<string>(async (resolve, reject) => {
|
||||
const evt = await signAuthEvent(makeAuthEvent(this.url, challenge))
|
||||
const timeout = setTimeout(() => {
|
||||
const ep = this.openEventPublishes.get(evt.id) as EventPublishResolver
|
||||
if (ep) {
|
||||
ep.reject(new Error('auth timed out'))
|
||||
this.openEventPublishes.delete(evt.id)
|
||||
}
|
||||
}, this.publishTimeout)
|
||||
this.openEventPublishes.set(evt.id, { resolve, reject, timeout })
|
||||
this.send('["AUTH",' + JSON.stringify(evt) + ']')
|
||||
try {
|
||||
let evt = await signAuthEvent(makeAuthEvent(this.url, challenge))
|
||||
let timeout = setTimeout(() => {
|
||||
let ep = this.openEventPublishes.get(evt.id) as EventPublishResolver
|
||||
if (ep) {
|
||||
ep.reject(new Error('auth timed out'))
|
||||
this.openEventPublishes.delete(evt.id)
|
||||
}
|
||||
}, this.publishTimeout)
|
||||
this.openEventPublishes.set(evt.id, { resolve, reject, timeout })
|
||||
this.send('["AUTH",' + JSON.stringify(evt) + ']')
|
||||
} catch (err) {
|
||||
console.warn('subscribe auth function failed:', err)
|
||||
}
|
||||
})
|
||||
return this.authPromise
|
||||
}
|
||||
@@ -312,6 +332,7 @@ export class AbstractRelay {
|
||||
this.closeAllSubscriptions('relay connection closed by us')
|
||||
this._connected = false
|
||||
this.ws?.close()
|
||||
this.onclose?.()
|
||||
}
|
||||
|
||||
// this is the function assigned to this.ws.onmessage
|
||||
@@ -379,7 +400,15 @@ export class Subscription {
|
||||
if (!this.closed && this.relay.connected) {
|
||||
// if the connection was closed by the user calling .close() we will send a CLOSE message
|
||||
// otherwise this._open will be already set to false so we will skip this
|
||||
this.relay.send('["CLOSE",' + JSON.stringify(this.id) + ']')
|
||||
try {
|
||||
this.relay.send('["CLOSE",' + JSON.stringify(this.id) + ']')
|
||||
} catch (err) {
|
||||
if (err instanceof SendingOnClosedConnection) {
|
||||
/* doesn't matter, it's ok */
|
||||
} else {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
this.closed = true
|
||||
}
|
||||
this.relay.openSubs.delete(this.id)
|
||||
|
||||
6
jsr.json
6
jsr.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@nostr/tools",
|
||||
"version": "2.13.2",
|
||||
"version": "2.15.1",
|
||||
"exports": {
|
||||
".": "./index.ts",
|
||||
"./core": "./core.ts",
|
||||
@@ -42,7 +42,9 @@
|
||||
"./nip94": "./nip94.ts",
|
||||
"./nip98": "./nip98.ts",
|
||||
"./nip99": "./nip99.ts",
|
||||
"./nipb7": "./nipb7.ts",
|
||||
"./fakejson": "./fakejson.ts",
|
||||
"./utils": "./utils.ts"
|
||||
"./utils": "./utils.ts",
|
||||
"./signer": "./signer.ts"
|
||||
}
|
||||
}
|
||||
|
||||
2
justfile
2
justfile
@@ -13,7 +13,7 @@ test-only file:
|
||||
|
||||
publish: build
|
||||
# publish to jsr first because it is more strict and will catch some errors
|
||||
perl -i -0pe "s/},\n \"optionalDependencies\": {\n/,/" package.json
|
||||
jq 'delete(.optionalDependencies)' package.json | sponge package.json
|
||||
jsr publish --allow-dirty
|
||||
git checkout -- package.json
|
||||
|
||||
|
||||
3
kinds.ts
3
kinds.ts
@@ -20,9 +20,6 @@ export function isAddressableKind(kind: number): boolean {
|
||||
return 30000 <= kind && kind < 40000
|
||||
}
|
||||
|
||||
/** @deprecated use isAddressableKind instead */
|
||||
export const isParameterizedReplaceableKind = isAddressableKind
|
||||
|
||||
/** Classification of the event kind. */
|
||||
export type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import { decode } from './nip19.ts'
|
||||
import { wrapEvent, wrapManyEvents, unwrapEvent } from './nip17.ts'
|
||||
import { hexToBytes } from '@noble/hashes/utils'
|
||||
|
||||
const senderPrivateKey = decode(`nsec1p0ht6p3wepe47sjrgesyn4m50m6avk2waqudu9rl324cg2c4ufesyp6rdg`).data as Uint8Array
|
||||
const senderPrivateKey = decode(`nsec1p0ht6p3wepe47sjrgesyn4m50m6avk2waqudu9rl324cg2c4ufesyp6rdg`).data
|
||||
|
||||
const sk1 = hexToBytes('f09ac9b695d0a4c6daa418fe95b977eea20f54d9545592bc36a4f9e14f3eb840')
|
||||
const sk2 = hexToBytes('5393a825e5892d8e18d4a5ea61ced105e8bb2a106f42876be3a40522e0b13747')
|
||||
|
||||
@@ -1,17 +1,14 @@
|
||||
import { test, expect, describe } from 'bun:test'
|
||||
import { generateSecretKey, getPublicKey } from './pure.ts'
|
||||
import { describe, expect, test } from 'bun:test'
|
||||
import {
|
||||
decode,
|
||||
naddrEncode,
|
||||
neventEncode,
|
||||
NostrTypeGuard,
|
||||
nprofileEncode,
|
||||
npubEncode,
|
||||
nsecEncode,
|
||||
neventEncode,
|
||||
type AddressPointer,
|
||||
type ProfilePointer,
|
||||
EventPointer,
|
||||
NostrTypeGuard,
|
||||
nsecEncode
|
||||
} from './nip19.ts'
|
||||
import { generateSecretKey, getPublicKey } from './pure.ts'
|
||||
|
||||
test('encode and decode nsec', () => {
|
||||
let sk = generateSecretKey()
|
||||
@@ -38,7 +35,7 @@ test('encode and decode nprofile', () => {
|
||||
expect(nprofile).toMatch(/nprofile1\w+/)
|
||||
let { type, data } = decode(nprofile)
|
||||
expect(type).toEqual('nprofile')
|
||||
const pointer = data as ProfilePointer
|
||||
const pointer = data
|
||||
expect(pointer.pubkey).toEqual(pk)
|
||||
expect(pointer.relays).toContain(relays[0])
|
||||
expect(pointer.relays).toContain(relays[1])
|
||||
@@ -67,7 +64,7 @@ test('encode and decode naddr', () => {
|
||||
expect(naddr).toMatch(/naddr1\w+/)
|
||||
let { type, data } = decode(naddr)
|
||||
expect(type).toEqual('naddr')
|
||||
const pointer = data as AddressPointer
|
||||
const pointer = data
|
||||
expect(pointer.pubkey).toEqual(pk)
|
||||
expect(pointer.relays).toContain(relays[0])
|
||||
expect(pointer.relays).toContain(relays[1])
|
||||
@@ -86,7 +83,7 @@ test('encode and decode nevent', () => {
|
||||
expect(nevent).toMatch(/nevent1\w+/)
|
||||
let { type, data } = decode(nevent)
|
||||
expect(type).toEqual('nevent')
|
||||
const pointer = data as EventPointer
|
||||
const pointer = data
|
||||
expect(pointer.id).toEqual(pk)
|
||||
expect(pointer.relays).toContain(relays[0])
|
||||
expect(pointer.kind).toEqual(30023)
|
||||
@@ -103,7 +100,7 @@ test('encode and decode nevent with kind 0', () => {
|
||||
expect(nevent).toMatch(/nevent1\w+/)
|
||||
let { type, data } = decode(nevent)
|
||||
expect(type).toEqual('nevent')
|
||||
const pointer = data as EventPointer
|
||||
const pointer = data
|
||||
expect(pointer.id).toEqual(pk)
|
||||
expect(pointer.relays).toContain(relays[0])
|
||||
expect(pointer.kind).toEqual(0)
|
||||
@@ -121,7 +118,7 @@ test('encode and decode naddr with empty "d"', () => {
|
||||
expect(naddr).toMatch(/naddr\w+/)
|
||||
let { type, data } = decode(naddr)
|
||||
expect(type).toEqual('naddr')
|
||||
const pointer = data as AddressPointer
|
||||
const pointer = data
|
||||
expect(pointer.identifier).toEqual('')
|
||||
expect(pointer.relays).toContain(relays[0])
|
||||
expect(pointer.kind).toEqual(3)
|
||||
@@ -133,7 +130,7 @@ test('decode naddr from habla.news', () => {
|
||||
'naddr1qq98yetxv4ex2mnrv4esygrl54h466tz4v0re4pyuavvxqptsejl0vxcmnhfl60z3rth2xkpjspsgqqqw4rsf34vl5',
|
||||
)
|
||||
expect(type).toEqual('naddr')
|
||||
const pointer = data as AddressPointer
|
||||
const pointer = data
|
||||
expect(pointer.pubkey).toEqual('7fa56f5d6962ab1e3cd424e758c3002b8665f7b0d8dcee9fe9e288d7751ac194')
|
||||
expect(pointer.kind).toEqual(30023)
|
||||
expect(pointer.identifier).toEqual('references')
|
||||
@@ -145,7 +142,7 @@ test('decode naddr from go-nostr with different TLV ordering', () => {
|
||||
)
|
||||
|
||||
expect(type).toEqual('naddr')
|
||||
const pointer = data as AddressPointer
|
||||
const pointer = data
|
||||
expect(pointer.pubkey).toEqual('3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d')
|
||||
expect(pointer.relays).toContain('wss://relay.nostr.example.mydomain.example.com')
|
||||
expect(pointer.relays).toContain('wss://nostr.banana.com')
|
||||
|
||||
65
nip19.ts
65
nip19.ts
@@ -70,31 +70,46 @@ export function decodeNostrURI(nip19code: string): ReturnType<typeof decode> | {
|
||||
}
|
||||
}
|
||||
|
||||
export function decode(code: string):
|
||||
| {
|
||||
type: 'nevent'
|
||||
data: EventPointer
|
||||
}
|
||||
| {
|
||||
type: 'nprofile'
|
||||
data: ProfilePointer
|
||||
}
|
||||
| {
|
||||
type: 'naddr'
|
||||
data: AddressPointer
|
||||
}
|
||||
| {
|
||||
type: 'npub'
|
||||
data: string
|
||||
}
|
||||
| {
|
||||
type: 'nsec'
|
||||
data: Uint8Array
|
||||
}
|
||||
| {
|
||||
type: 'note'
|
||||
data: string
|
||||
} {
|
||||
export type DecodedNevent = {
|
||||
type: 'nevent'
|
||||
data: EventPointer
|
||||
}
|
||||
|
||||
export type DecodedNprofile = {
|
||||
type: 'nprofile'
|
||||
data: ProfilePointer
|
||||
}
|
||||
|
||||
export type DecodedNaddr = {
|
||||
type: 'naddr'
|
||||
data: AddressPointer
|
||||
}
|
||||
|
||||
export type DecodedNsec = {
|
||||
type: 'nsec'
|
||||
data: Uint8Array
|
||||
}
|
||||
|
||||
export type DecodedNpub = {
|
||||
type: 'npub'
|
||||
data: string
|
||||
}
|
||||
|
||||
export type DecodedNote = {
|
||||
type: 'note'
|
||||
data: string
|
||||
}
|
||||
|
||||
export type DecodedResult = DecodedNevent | DecodedNprofile | DecodedNaddr | DecodedNpub | DecodedNsec | DecodedNote
|
||||
|
||||
export function decode(nip19: NEvent): DecodedNevent
|
||||
export function decode(nip19: NProfile): DecodedNprofile
|
||||
export function decode(nip19: NAddr): DecodedNaddr
|
||||
export function decode(nip19: NSec): DecodedNsec
|
||||
export function decode(nip19: NPub): DecodedNpub
|
||||
export function decode(nip19: Note): DecodedNote
|
||||
export function decode(code: string): DecodedResult
|
||||
export function decode(code: string): DecodedResult {
|
||||
let { prefix, words } = bech32.decode(code, Bech32MaxSize)
|
||||
let data = new Uint8Array(bech32.fromWords(words))
|
||||
|
||||
|
||||
6
nip29.ts
6
nip29.ts
@@ -2,7 +2,7 @@ import { AbstractSimplePool } from './abstract-pool.ts'
|
||||
import { Subscription } from './abstract-relay.ts'
|
||||
import type { Event, EventTemplate } from './core.ts'
|
||||
import { fetchRelayInformation, RelayInformation } from './nip11.ts'
|
||||
import { AddressPointer, decode } from './nip19.ts'
|
||||
import { AddressPointer, decode, NostrTypeGuard } from './nip19.ts'
|
||||
import { normalizeURL } from './utils.ts'
|
||||
|
||||
/**
|
||||
@@ -518,11 +518,11 @@ export async function loadGroupFromCode(pool: AbstractSimplePool, code: string):
|
||||
* @returns A GroupReference object if the code is valid, otherwise null.
|
||||
*/
|
||||
export function parseGroupCode(code: string): null | GroupReference {
|
||||
if (code.startsWith('naddr1')) {
|
||||
if (NostrTypeGuard.isNAddr(code)) {
|
||||
try {
|
||||
let { data } = decode(code)
|
||||
|
||||
let { relays, identifier } = data as AddressPointer
|
||||
let { relays, identifier } = data
|
||||
if (!relays || relays.length === 0) return null
|
||||
|
||||
let host = relays![0]
|
||||
|
||||
3
nip46.ts
3
nip46.ts
@@ -6,6 +6,7 @@ import { NIP05_REGEX } from './nip05.ts'
|
||||
import { SimplePool } from './pool.ts'
|
||||
import { Handlerinformation, NostrConnect } from './kinds.ts'
|
||||
import type { RelayRecord } from './relay.ts'
|
||||
import { Signer } from './signer.ts'
|
||||
|
||||
var _fetch: any
|
||||
|
||||
@@ -82,7 +83,7 @@ export type BunkerSignerParams = {
|
||||
onauth?: (url: string) => void
|
||||
}
|
||||
|
||||
export class BunkerSigner {
|
||||
export class BunkerSigner implements Signer {
|
||||
private params: BunkerSignerParams
|
||||
private pool: AbstractSimplePool
|
||||
private subCloser: SubCloser | undefined
|
||||
|
||||
@@ -5,6 +5,16 @@ import { decrypt } from './nip04.ts'
|
||||
import { NWCWalletRequest } from './kinds.ts'
|
||||
|
||||
describe('parseConnectionString', () => {
|
||||
test('returns pubkey, relay, and secret if connection string has double slash', () => {
|
||||
const connectionString =
|
||||
'nostr+walletconnect://b889ff5b1513b641e2a139f661a661364979c5beee91842f8f0ef42ab558e9d4?relay=wss%3A%2F%2Frelay.damus.io&secret=71a8c14c1407c113601079c4302dab36460f0ccd0ad506f1f2dc73b5100e4f3c'
|
||||
const { pubkey, relay, secret } = parseConnectionString(connectionString)
|
||||
|
||||
expect(pubkey).toBe('b889ff5b1513b641e2a139f661a661364979c5beee91842f8f0ef42ab558e9d4')
|
||||
expect(relay).toBe('wss://relay.damus.io')
|
||||
expect(secret).toBe('71a8c14c1407c113601079c4302dab36460f0ccd0ad506f1f2dc73b5100e4f3c')
|
||||
})
|
||||
|
||||
test('returns pubkey, relay, and secret if connection string is valid', () => {
|
||||
const connectionString =
|
||||
'nostr+walletconnect:b889ff5b1513b641e2a139f661a661364979c5beee91842f8f0ef42ab558e9d4?relay=wss%3A%2F%2Frelay.damus.io&secret=71a8c14c1407c113601079c4302dab36460f0ccd0ad506f1f2dc73b5100e4f3c'
|
||||
|
||||
4
nip47.ts
4
nip47.ts
@@ -9,8 +9,8 @@ interface NWCConnection {
|
||||
}
|
||||
|
||||
export function parseConnectionString(connectionString: string): NWCConnection {
|
||||
const { pathname, searchParams } = new URL(connectionString)
|
||||
const pubkey = pathname
|
||||
const { host, pathname, searchParams } = new URL(connectionString)
|
||||
const pubkey = pathname || host
|
||||
const relay = searchParams.get('relay')
|
||||
const secret = searchParams.get('secret')
|
||||
|
||||
|
||||
55
nipb7.test.ts
Normal file
55
nipb7.test.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { test, expect } from 'bun:test'
|
||||
import { BlossomClient } from './nipb7.ts'
|
||||
import { sha256 } from '@noble/hashes/sha256'
|
||||
import { bytesToHex } from './utils.ts'
|
||||
import { PlainKeySigner } from './signer.ts'
|
||||
import { generateSecretKey } from './pure.ts'
|
||||
|
||||
test('blossom', async () => {
|
||||
const BLOSSOM_SERVER = 'blossom.primal.net'
|
||||
const TEST_CONTENT = 'hello world'
|
||||
const TEST_BLOB = new Blob([TEST_CONTENT], { type: 'text/plain' })
|
||||
|
||||
const expectedHash = bytesToHex(sha256(new TextEncoder().encode(TEST_CONTENT)))
|
||||
|
||||
const signer = new PlainKeySigner(generateSecretKey())
|
||||
const client = new BlossomClient(BLOSSOM_SERVER, signer)
|
||||
expect(client).toBeDefined()
|
||||
|
||||
// check for non-existent file should throw
|
||||
const invalidHash = expectedHash.slice(0, 62) + 'ba'
|
||||
let hasThrown = false
|
||||
try {
|
||||
await client.check(invalidHash)
|
||||
} catch (err) {
|
||||
hasThrown = true
|
||||
}
|
||||
expect(hasThrown).toBeTrue()
|
||||
|
||||
// upload hello world blob
|
||||
const descriptor = await client.uploadBlob(TEST_BLOB, 'text/plain')
|
||||
expect(descriptor).toBeDefined()
|
||||
expect(descriptor.sha256).toBe(expectedHash)
|
||||
expect(descriptor.size).toBe(TEST_CONTENT.length)
|
||||
expect(descriptor.type).toBe('text/plain')
|
||||
expect(descriptor.url).toContain(expectedHash)
|
||||
expect(descriptor.uploaded).toBeGreaterThan(0)
|
||||
await client.check(expectedHash)
|
||||
|
||||
// download and verify
|
||||
const downloadedBuffer = await client.download(expectedHash)
|
||||
const downloadedContent = new TextDecoder().decode(downloadedBuffer)
|
||||
expect(downloadedContent).toBe(TEST_CONTENT)
|
||||
|
||||
// list blobs should include our uploaded file
|
||||
const blobs = await client.list()
|
||||
|
||||
expect(Array.isArray(blobs)).toBe(true)
|
||||
const ourBlob = blobs.find(blob => blob.sha256 === expectedHash)
|
||||
expect(ourBlob).toBeDefined()
|
||||
expect(ourBlob?.type).toBe('text/plain')
|
||||
expect(ourBlob?.size).toBe(TEST_CONTENT.length)
|
||||
|
||||
// delete
|
||||
await client.delete(expectedHash)
|
||||
})
|
||||
203
nipb7.ts
Normal file
203
nipb7.ts
Normal file
@@ -0,0 +1,203 @@
|
||||
import { sha256 } from '@noble/hashes/sha256'
|
||||
import { EventTemplate } from './core.ts'
|
||||
import { Signer } from './signer.ts'
|
||||
import { bytesToHex } from './utils.ts'
|
||||
|
||||
export type BlobDescriptor = {
|
||||
url: string
|
||||
sha256: string
|
||||
size: number
|
||||
type: string
|
||||
uploaded: number
|
||||
}
|
||||
|
||||
export class BlossomClient {
|
||||
private mediaserver: string
|
||||
private signer: Signer
|
||||
|
||||
constructor(mediaserver: string, signer: Signer) {
|
||||
if (!mediaserver.startsWith('http')) {
|
||||
mediaserver = 'https://' + mediaserver
|
||||
}
|
||||
this.mediaserver = mediaserver.replace(/\/$/, '') + '/'
|
||||
this.signer = signer
|
||||
}
|
||||
|
||||
private async httpCall(
|
||||
method: string,
|
||||
url: string,
|
||||
contentType?: string,
|
||||
addAuthorization?: () => Promise<string>,
|
||||
body?: File | Blob,
|
||||
result?: any,
|
||||
): Promise<any> {
|
||||
const headers: { [_: string]: string } = {}
|
||||
|
||||
if (contentType) {
|
||||
headers['Content-Type'] = contentType
|
||||
}
|
||||
|
||||
if (addAuthorization) {
|
||||
const auth = await addAuthorization()
|
||||
if (auth) {
|
||||
headers['Authorization'] = auth
|
||||
}
|
||||
}
|
||||
|
||||
const response = await fetch(this.mediaserver + url, {
|
||||
method,
|
||||
headers,
|
||||
body,
|
||||
})
|
||||
|
||||
if (response.status >= 300) {
|
||||
const reason = response.headers.get('X-Reason') || response.statusText
|
||||
throw new Error(`${url} returned an error (${response.status}): ${reason}`)
|
||||
}
|
||||
|
||||
if (result !== null && response.headers.get('content-type')?.includes('application/json')) {
|
||||
return await response.json()
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
private async authorizationHeader(modify?: (event: EventTemplate) => void): Promise<string> {
|
||||
const now = Math.floor(Date.now() / 1000)
|
||||
const event: EventTemplate = {
|
||||
created_at: now,
|
||||
kind: 24242,
|
||||
content: 'blossom stuff',
|
||||
tags: [['expiration', String(now + 60)]],
|
||||
}
|
||||
|
||||
if (modify) {
|
||||
modify(event)
|
||||
}
|
||||
|
||||
try {
|
||||
const signedEvent = await this.signer.signEvent(event)
|
||||
const eventJson = JSON.stringify(signedEvent)
|
||||
return 'Nostr ' + btoa(eventJson)
|
||||
} catch (error) {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
private isValid32ByteHex(hash: string): boolean {
|
||||
return /^[a-f0-9]{64}$/i.test(hash)
|
||||
}
|
||||
|
||||
async check(hash: string): Promise<void> {
|
||||
if (!this.isValid32ByteHex(hash)) {
|
||||
throw new Error(`${hash} is not a valid 32-byte hex string`)
|
||||
}
|
||||
|
||||
try {
|
||||
await this.httpCall('HEAD', hash)
|
||||
} catch (error) {
|
||||
throw new Error(`failed to check for ${hash}: ${error}`)
|
||||
}
|
||||
}
|
||||
|
||||
async uploadBlob(file: File | Blob, contentType?: string): Promise<BlobDescriptor> {
|
||||
const hash = bytesToHex(sha256(new Uint8Array(await file.arrayBuffer())))
|
||||
const actualContentType = contentType || file.type || 'application/octet-stream'
|
||||
|
||||
const bd = await this.httpCall(
|
||||
'PUT',
|
||||
'upload',
|
||||
actualContentType,
|
||||
() =>
|
||||
this.authorizationHeader(evt => {
|
||||
evt.tags.push(['t', 'upload'])
|
||||
evt.tags.push(['x', hash])
|
||||
}),
|
||||
file,
|
||||
{},
|
||||
)
|
||||
|
||||
return bd
|
||||
}
|
||||
|
||||
async uploadFile(file: File): Promise<BlobDescriptor> {
|
||||
return this.uploadBlob(file, file.type)
|
||||
}
|
||||
|
||||
async download(hash: string): Promise<ArrayBuffer> {
|
||||
if (!this.isValid32ByteHex(hash)) {
|
||||
throw new Error(`${hash} is not a valid 32-byte hex string`)
|
||||
}
|
||||
|
||||
const authHeader = await this.authorizationHeader(evt => {
|
||||
evt.tags.push(['t', 'get'])
|
||||
evt.tags.push(['x', hash])
|
||||
})
|
||||
|
||||
const response = await fetch(this.mediaserver + hash, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: authHeader,
|
||||
},
|
||||
})
|
||||
|
||||
if (response.status >= 300) {
|
||||
throw new Error(`${hash} is not present in ${this.mediaserver}: ${response.status}`)
|
||||
}
|
||||
|
||||
return await response.arrayBuffer()
|
||||
}
|
||||
|
||||
async downloadAsBlob(hash: string): Promise<Blob> {
|
||||
const arrayBuffer = await this.download(hash)
|
||||
return new Blob([arrayBuffer])
|
||||
}
|
||||
|
||||
async list(): Promise<BlobDescriptor[]> {
|
||||
const pubkey = await this.signer.getPublicKey()
|
||||
|
||||
if (!this.isValid32ByteHex(pubkey)) {
|
||||
throw new Error(`pubkey ${pubkey} is not valid`)
|
||||
}
|
||||
|
||||
try {
|
||||
const bds = await this.httpCall(
|
||||
'GET',
|
||||
`list/${pubkey}`,
|
||||
undefined,
|
||||
() =>
|
||||
this.authorizationHeader(evt => {
|
||||
evt.tags.push(['t', 'list'])
|
||||
}),
|
||||
undefined,
|
||||
[],
|
||||
)
|
||||
return bds
|
||||
} catch (error) {
|
||||
throw new Error(`failed to list blobs: ${error}`)
|
||||
}
|
||||
}
|
||||
|
||||
async delete(hash: string): Promise<void> {
|
||||
if (!this.isValid32ByteHex(hash)) {
|
||||
throw new Error(`${hash} is not a valid 32-byte hex string`)
|
||||
}
|
||||
|
||||
try {
|
||||
await this.httpCall(
|
||||
'DELETE',
|
||||
hash,
|
||||
undefined,
|
||||
() =>
|
||||
this.authorizationHeader(evt => {
|
||||
evt.tags.push(['t', 'delete'])
|
||||
evt.tags.push(['x', hash])
|
||||
}),
|
||||
undefined,
|
||||
null,
|
||||
)
|
||||
} catch (error) {
|
||||
throw new Error(`failed to delete ${hash}: ${error}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
29
node-ws-relay.ts
Normal file
29
node-ws-relay.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import WebSocket from 'ws'
|
||||
import { verifyEvent } from './pure.ts'
|
||||
import { AbstractRelay, WebSocketBase } from './abstract-relay.ts'
|
||||
|
||||
class NodeWs extends WebSocket implements WebSocketBase {
|
||||
constructor(url: string | URL, protocols?: string | string[] | undefined) {
|
||||
super(url, {
|
||||
protocol: Array.isArray(protocols) ? protocols[0] : protocols,
|
||||
})
|
||||
|
||||
setInterval(() => {
|
||||
this.ping()
|
||||
}, 29000)
|
||||
}
|
||||
}
|
||||
|
||||
export class NodeWsRelay extends AbstractRelay {
|
||||
constructor(url: string) {
|
||||
super(url, { verifyEvent, websocketImplementation: NodeWs })
|
||||
}
|
||||
|
||||
static async connect(url: string): Promise<NodeWsRelay> {
|
||||
const relay = new NodeWsRelay(url)
|
||||
await relay.connect()
|
||||
return relay
|
||||
}
|
||||
}
|
||||
|
||||
export * from './abstract-relay.ts'
|
||||
19
package.json
19
package.json
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"type": "module",
|
||||
"name": "nostr-tools",
|
||||
"version": "2.13.2",
|
||||
"version": "2.15.0",
|
||||
"description": "Tools for making a Nostr client.",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -213,11 +213,21 @@
|
||||
"require": "./lib/cjs/nip99.js",
|
||||
"types": "./lib/types/nip99.d.ts"
|
||||
},
|
||||
"./nipb7": {
|
||||
"import": "./lib/esm/nipb7.js",
|
||||
"require": "./lib/cjs/nipb7.js",
|
||||
"types": "./lib/types/nipb7.d.ts"
|
||||
},
|
||||
"./fakejson": {
|
||||
"import": "./lib/esm/fakejson.js",
|
||||
"require": "./lib/cjs/fakejson.js",
|
||||
"types": "./lib/types/fakejson.d.ts"
|
||||
},
|
||||
"./signer": {
|
||||
"import": "./lib/esm/signer.js",
|
||||
"require": "./lib/cjs/signer.js",
|
||||
"types": "./lib/types/signer.d.ts"
|
||||
},
|
||||
"./utils": {
|
||||
"import": "./lib/esm/utils.js",
|
||||
"require": "./lib/cjs/utils.js",
|
||||
@@ -231,12 +241,15 @@
|
||||
"@noble/hashes": "1.3.1",
|
||||
"@scure/base": "1.1.1",
|
||||
"@scure/bip32": "1.3.1",
|
||||
"@scure/bip39": "1.2.1",
|
||||
"nostr-wasm": "0.1.0"
|
||||
"@scure/bip39": "1.2.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": ">=5.0.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"nostr-wasm": "0.1.0",
|
||||
"ws": "^8.18.3"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"typescript": {
|
||||
"optional": true
|
||||
|
||||
23
relay.ts
23
relay.ts
@@ -1,28 +1,13 @@
|
||||
/* global WebSocket */
|
||||
|
||||
import { verifyEvent } from './pure.ts'
|
||||
import { AbstractRelay } from './abstract-relay.ts'
|
||||
import { AbstractRelay, WebSocketBaseConn } from './abstract-relay.ts'
|
||||
|
||||
/**
|
||||
* @deprecated use Relay.connect() instead.
|
||||
*/
|
||||
export function relayConnect(url: string): Promise<Relay> {
|
||||
return Relay.connect(url)
|
||||
}
|
||||
|
||||
var _WebSocket: typeof WebSocket
|
||||
|
||||
try {
|
||||
_WebSocket = WebSocket
|
||||
} catch {}
|
||||
|
||||
export function useWebSocketImplementation(websocketImplementation: any) {
|
||||
_WebSocket = websocketImplementation
|
||||
}
|
||||
class BrowserWs extends WebSocket implements WebSocketBase, WebSocketBaseConn {}
|
||||
|
||||
export class Relay extends AbstractRelay {
|
||||
constructor(url: string) {
|
||||
super(url, { verifyEvent, websocketImplementation: _WebSocket })
|
||||
super(url, { verifyEvent, websocketImplementation: BrowserWs })
|
||||
}
|
||||
|
||||
static async connect(url: string): Promise<Relay> {
|
||||
@@ -32,6 +17,4 @@ export class Relay extends AbstractRelay {
|
||||
}
|
||||
}
|
||||
|
||||
export type RelayRecord = Record<string, { read: boolean; write: boolean }>
|
||||
|
||||
export * from './abstract-relay.ts'
|
||||
|
||||
23
signer.ts
Normal file
23
signer.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { EventTemplate, VerifiedEvent } from './core.ts'
|
||||
import { finalizeEvent, getPublicKey } from './pure.ts'
|
||||
|
||||
export interface Signer {
|
||||
getPublicKey(): Promise<string>
|
||||
signEvent(event: EventTemplate): Promise<VerifiedEvent>
|
||||
}
|
||||
|
||||
export class PlainKeySigner implements Signer {
|
||||
private secretKey: Uint8Array
|
||||
|
||||
constructor(secretKey: Uint8Array) {
|
||||
this.secretKey = secretKey
|
||||
}
|
||||
|
||||
async getPublicKey(): Promise<string> {
|
||||
return getPublicKey(this.secretKey)
|
||||
}
|
||||
|
||||
async signEvent(event: EventTemplate): Promise<VerifiedEvent> {
|
||||
return finalizeEvent(event, this.secretKey)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user