Tools for developing Nostr clients.
Go to file
fiatjaf 967d7fe63a
normalizeURL prepends ws:// when necessary.
2024-01-20 12:48:28 -03:00
.github/workflows remove auto-publishing to npm. 2023-12-19 10:33:06 -03:00
.editorconfig Add .editorconfig 2023-04-01 08:18:57 -03:00
.eslintrc.json suppress eqeqeq eslint rule 2024-01-18 11:50:35 -03:00
.gitignore unsplit, backwards-compatibility, wasm relay and pool must be configured manually from the abstract classes. 2023-12-21 19:57:28 -03:00
.prettierrc.yaml prettier: increase printWidth, enable bracketSpacing, alphabetize 2023-08-31 13:00:50 -05:00
LICENSE Add Unlicense 2023-04-20 12:22:39 -03:00
README.md update readme example. 2023-12-27 11:14:19 -03:00
abstract-pool.ts unsplit, backwards-compatibility, wasm relay and pool must be configured manually from the abstract classes. 2023-12-21 19:57:28 -03:00
abstract-relay.ts auth() returns a promise that resolves on OK. 2023-12-26 07:56:55 -03:00
benchmarks.ts rename benchmark.ts -> benchmarks.ts 2023-12-22 11:48:07 -03:00
build.js fix problem when required from CommonJS 2023-12-23 08:31:39 -03:00
bun.lockb unify mock-socket interface into a single implementation. 2024-01-19 16:01:06 -03:00
core.test.ts change tests and nips to use the new api. 2023-12-19 13:58:37 -03:00
core.ts unsplit, backwards-compatibility, wasm relay and pool must be configured manually from the abstract classes. 2023-12-21 19:57:28 -03:00
fakejson.test.ts move to bun and bun:test and remove jest. 2023-12-16 14:53:32 -03:00
fakejson.ts fakejson match subscription id. 2023-02-08 14:15:54 -03:00
filter.test.ts Add getFilterLimit function 2024-01-04 09:56:02 -03:00
filter.ts format with prettier 2024-01-18 11:51:13 -03:00
helpers.ts fix yieldThread memory leak 2023-12-30 13:50:44 -03:00
index.ts fix relay.ts imports after 7f11c0c618. 2023-12-22 06:58:01 -03:00
justfile rename benchmark.ts -> benchmarks.ts 2023-12-22 11:48:07 -03:00
kinds.test.ts move to bun and bun:test and remove jest. 2023-12-16 14:53:32 -03:00
kinds.ts Sort kinds 2024-01-08 13:50:36 -03:00
nip04.test.ts change tests and nips to use the new api. 2023-12-19 13:58:37 -03:00
nip04.ts change tests and nips to use the new api. 2023-12-19 13:58:37 -03:00
nip05.test.ts move to bun and bun:test and remove jest. 2023-12-16 14:53:32 -03:00
nip05.ts just format 2023-08-31 13:42:15 -05:00
nip06.test.ts move to bun and bun:test and remove jest. 2023-12-16 14:53:32 -03:00
nip06.ts prettify and lint. 2023-12-16 12:39:24 -03:00
nip10.test.ts remove broken useless tests. 2023-12-17 22:41:22 -03:00
nip10.ts import from core.ts instead of pure.ts whenever possible. 2023-12-21 17:27:32 -03:00
nip11.test.ts revert nip11.test.ts with a todo flag 2024-01-20 11:50:05 +03:30
nip11.ts cleanup nip-11. 2023-12-16 11:00:46 -03:00
nip13.test.ts move to bun and bun:test and remove jest. 2023-12-16 14:53:32 -03:00
nip13.ts change tests and nips to use the new api. 2023-12-19 13:58:37 -03:00
nip18.test.ts change tests and nips to use the new api. 2023-12-19 13:58:37 -03:00
nip18.ts change tests and nips to use the new api. 2023-12-19 13:58:37 -03:00
nip19.test.ts nip19: length 0 on TLV is not forbidden. 2023-12-26 07:56:55 -03:00
nip19.ts nip19: length 0 on TLV is not forbidden. 2023-12-26 07:56:55 -03:00
nip21.test.ts move to bun and bun:test and remove jest. 2023-12-16 14:53:32 -03:00
nip21.ts just format 2023-08-31 13:42:15 -05:00
nip25.test.ts change tests and nips to use the new api. 2023-12-19 13:58:37 -03:00
nip25.ts change tests and nips to use the new api. 2023-12-19 13:58:37 -03:00
nip27.test.ts move to bun and bun:test and remove jest. 2023-12-16 14:53:32 -03:00
nip27.ts prettify and lint. 2023-12-16 12:39:24 -03:00
nip28.test.ts change tests and nips to use the new api. 2023-12-19 13:58:37 -03:00
nip28.ts change tests and nips to use the new api. 2023-12-19 13:58:37 -03:00
nip29.ts nip29: make relay property mandatory on Group. 2024-01-19 21:23:44 -03:00
nip30.test.ts move to bun and bun:test and remove jest. 2023-12-16 14:53:32 -03:00
nip30.ts prettify and lint. 2023-12-16 12:39:24 -03:00
nip39.test.ts move to bun and bun:test and remove jest. 2023-12-16 14:53:32 -03:00
nip39.ts just format 2023-08-31 13:42:15 -05:00
nip40.test.ts format with prettier 2024-01-18 11:51:13 -03:00
nip40.ts format with prettier 2024-01-18 11:51:13 -03:00
nip42.test.ts update nip42.test.ts with new mock relay class 2024-01-20 11:31:18 +03:30
nip42.ts import from core.ts instead of pure.ts whenever possible. 2023-12-21 17:27:32 -03:00
nip44.test.ts Add nip44 v2 2023-12-21 08:55:23 -03:00
nip44.ts Add nip44 v2 2023-12-21 08:55:23 -03:00
nip44.vectors.json Add nip44 v2 2023-12-21 08:55:23 -03:00
nip47.test.ts change tests and nips to use the new api. 2023-12-19 13:58:37 -03:00
nip47.ts change tests and nips to use the new api. 2023-12-19 13:58:37 -03:00
nip57.test.ts nip57: implement "P" tag for sender. 2024-01-01 11:39:22 -03:00
nip57.ts NIP-57: build lnurl in more secure way 2024-01-15 21:26:34 -03:00
nip98.test.ts refactor and add more test cases 2024-01-17 18:13:10 +03:30
nip98.ts fix some bugs, refactor to smaller parts, add docs 2024-01-17 17:50:48 +03:30
nip99.test.ts add test cases for nip99 2024-01-18 17:13:39 +03:30
nip99.ts remove un-used imports 2024-01-18 17:16:24 +03:30
package.json some beginnings of nip29 helpers. 2024-01-19 16:13:00 -03:00
pool.test.ts refactor pool.test.ts and update with new mock relay class 2024-01-20 11:29:46 +03:30
pool.ts unsplit, backwards-compatibility, wasm relay and pool must be configured manually from the abstract classes. 2023-12-21 19:57:28 -03:00
pure.ts change tests and nips to use the new api. 2023-12-19 13:58:37 -03:00
references.test.ts move to bun and bun:test and remove jest. 2023-12-16 14:53:32 -03:00
references.ts import from core.ts instead of pure.ts whenever possible. 2023-12-21 17:27:32 -03:00
relay.test.ts use new MockRelay class in relay.test.ts 2024-01-20 10:41:05 +03:30
relay.ts bring back relayConnect() as deprecated. 2023-12-21 19:59:12 -03:00
test-helpers.ts increase random range for mock relay urls 2024-01-20 11:21:29 +03:30
tsconfig.json import from core.ts instead of pure.ts whenever possible. 2023-12-21 17:27:32 -03:00
utils.test.ts import from core.ts instead of pure.ts whenever possible. 2023-12-21 17:27:32 -03:00
utils.ts normalizeURL prepends ws:// when necessary. 2024-01-20 12:48:28 -03:00
wasm.ts revamp core api + option to use nostr-wasm instead of noble-curves. 2023-12-19 12:20:42 -03:00

README.md

nostr-tools

Tools for developing Nostr clients.

Only depends on @scure and @noble packages.

This package is only providing lower-level functionality. 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 and @snort/system.

Installation

 npm install nostr-tools # or yarn add nostr-tools

If using TypeScript, this package requires TypeScript >= 5.0.

Usage

Generating a private key and a public key

import { generateSecretKey, getPublicKey } from 'nostr-tools'

let sk = generateSecretKey() // `sk` is a Uint8Array
let pk = getPublicKey(sk) // `pk` is a hex string

Creating, signing and verifying events

import { finalizeEvent, verifyEvent } from 'nostr-tools'

let event = finalizeEvent({
  kind: 1,
  created_at: Math.floor(Date.now() / 1000),
  tags: [],
  content: 'hello',
}, sk)

let isGood = verifyEvent(event)

Interacting with a relay

import { Relay, finalizeEvent, generateSecretKey, getPublicKey } from 'nostr-tools'

const relay = await Relay.connect('wss://relay.example.com')
console.log(`connected to ${relay.url}`)

// let's query for an event that exists
const sub = relay.subscribe([
  {
    ids: ['d7dd5eb3ab747e16f8d0212d53032ea2a7cadef53837e5a6c66d42849fcb9027'],
  },
], {
  onevent(event) {
    console.log('we got the event we wanted:', event)
  },
  oneose() {
    sub.close()
  }
})

// let's publish a new event while simultaneously monitoring the relay for it
let sk = generateSecretKey()
let pk = getPublicKey(sk)

relay.sub([
  {
    kinds: [1],
    authors: [pk],
  },
], {
  onevent(event) {
    console.log('got event:', event)
  }
})

let eventTemplate = {
  kind: 1,
  created_at: Math.floor(Date.now() / 1000),
  tags: [],
  content: 'hello world',
}

// this assigns the pubkey, calculates the event id and signs the event in a single step
const signedEvent = finalizeEvent(eventTemplate, sk)
await relay.publish(signedEvent)

relay.close()

To use this on Node.js you first must install websocket-polyfill and import it:

import 'websocket-polyfill'

Interacting with multiple relays

import { SimplePool } from 'nostr-tools'

const pool = new SimplePool()

let relays = ['wss://relay.example.com', 'wss://relay.example2.com']

let h = pool.subscribeMany(
  [...relays, 'wss://relay.example3.com'],
  [
    {
      authors: ['32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245'],
    },
  ],
  {
    onevent(event) {
      // this will only be called once the first time the event is received
      // ...
    },
    oneose() {
      h.close()
    }
  }
)

await Promise.any(pool.publish(relays, newEvent))
console.log('published to at least one relay!')

let events = await pool.querySync(relays, [{ kinds: [0, 1] }])
let event = await pool.get(relays, {
  ids: ['44e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245'],
})

Parsing references (mentions) from a content using NIP-10 and NIP-27

import { parseReferences } from 'nostr-tools'

let references = parseReferences(event)
let simpleAugmentedContent = event.content
for (let i = 0; i < references.length; i++) {
  let { text, profile, event, address } = references[i]
  let augmentedReference = profile
    ? `<strong>@${profilesCache[profile.pubkey].name}</strong>`
    : event
    ? `<em>${eventsCache[event.id].content.slice(0, 5)}</em>`
    : address
    ? `<a href="${text}">[link]</a>`
    : text
  simpleAugmentedContent.replaceAll(text, augmentedReference)
}

Querying profile data from a NIP-05 address

import { nip05 } from 'nostr-tools'

let profile = await nip05.queryProfile('jb55.com')
console.log(profile.pubkey)
// prints: 32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245
console.log(profile.relays)
// prints: [wss://relay.damus.io]

To use this on Node.js < v18, you first must install node-fetch@2 and call something like this:

nip05.useFetchImplementation(require('node-fetch'))

Encoding and decoding NIP-19 codes

import { nip19, generateSecretKey, getPublicKey } from 'nostr-tools'

let sk = generateSecretKey()
let nsec = nip19.nsecEncode(sk)
let { type, data } = nip19.decode(nsec)
assert(type === 'nsec')
assert(data === sk)

let pk = getPublicKey(generateSecretKey())
let npub = nip19.npubEncode(pk)
let { type, data } = nip19.decode(npub)
assert(type === 'npub')
assert(data === pk)

let pk = getPublicKey(generateSecretKey())
let relays = ['wss://relay.nostr.example.mydomain.example.com', 'wss://nostr.banana.com']
let nprofile = nip19.nprofileEncode({ pubkey: pk, relays })
let { type, data } = nip19.decode(nprofile)
assert(type === 'nprofile')
assert(data.pubkey === pk)
assert(data.relays.length === 2)

Import modes

Using just the packages you want

Importing the entirety of nostr-tools may bloat your build, so you should probably import individual packages instead:

import { generateSecretKey, finalizeEvent, verifyEvent } from 'nostr-tools/pure'
import { SimplePool } from 'nostr-tools/pool'
import { Relay, Subscription } from 'nostr-tools/relay'
import { matchFilter } from 'nostr-tools/filter'
import { decode, nprofileEncode, neventEncode, npubEncode } from 'nostr-tools/nip19'
// and so on and so forth

Using it with nostr-wasm

nostr-wasm is a thin wrapper over libsecp256k1 compiled to WASM just for hashing, signing and verifying Nostr events.

import { setNostrWasm, generateSecretKey, finalizeEvent, verifyEvent } from 'nostr-tools/wasm'
import { initNostrWasm } from 'nostr-wasm'

// make sure this promise resolves before your app starts calling finalizeEvent or verifyEvent
initNostrWasm().then(setNostrWasm)

// or use 'nostr-wasm/gzipped' or even 'nostr-wasm/headless',
// see https://www.npmjs.com/package/nostr-wasm for options

If you're going to use Relay and SimplePool you must also import nostr-tools/abstract-relay and/or nostr-tools/abstract-pool instead of the defaults and then instantiate them by passing the verifyEvent:

import { setNostrWasm, verifyEvent } from 'nostr-tools/wasm'
import { AbstractRelay } from 'nostr-tools/abstract-relay'
import { AbstractSimplePool } from 'nostr-tools/abstract-pool'
import { initNostrWasm } from 'nostr-wasm'

initNostrWasm().then(setNostrWasm)

const relay = AbstractRelay.connect('wss://relayable.org', { verifyEvent })
const pool = new AbstractSimplePool({ verifyEvent })

This may be faster than the pure-JS noble libraries used by default and in nostr-tools/pure. Benchmarks:

benchmark      time (avg)             (min … max)       p75       p99      p995
------------------------------------------------- -----------------------------
• relay read message and verify event (many events)
------------------------------------------------- -----------------------------
wasm        34.94 ms/iter   (34.61 ms … 35.73 ms)  35.07 ms  35.73 ms  35.73 ms
pure js     239.7 ms/iter (235.41 ms … 243.69 ms) 240.51 ms 243.69 ms 243.69 ms
trusted    402.71 µs/iter   (344.57 µs … 2.98 ms) 407.39 µs 745.62 µs 812.59 µs

summary for relay read message and verify event
  wasm
   86.77x slower than trusted
   6.86x faster than pure js

Using from the browser (if you don't want to use a bundler)

<script src="https://unpkg.com/nostr-tools/lib/nostr.bundle.js"></script>
<script>
  window.NostrTools.generateSecretKey('...') // and so on
</script>

Plumbing

To develop nostr-tools, install just and run just -l to see commands available.

License

This is free and unencumbered software released into the public domain. By submitting patches to this project, you agree to dedicate any and all copyright interest in this software to the public domain.