Tools for developing Nostr clients.
Go to file
fiatjaf 1357642575
adjust packages exported.
2023-12-16 13:08:37 -03:00
.github/workflows ci: ensure `just` is available to the runner 2023-08-31 13:52:56 -05:00
.editorconfig Add .editorconfig 2023-04-01 08:18:57 -03:00
.eslintrc.json just format 2023-08-31 13:42:15 -05:00
.gitignore better publishing built files. 2022-12-20 16:56:05 -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 adjust packages exported. 2023-12-16 13:08:37 -03:00
build.js Organize build, allow one entrypoint per file (#305) 2023-10-01 18:20:53 -03:00
event.test.ts remove the kind type parameter from events and filters. 2023-12-16 10:10:37 -03:00
event.ts remove the kind type parameter from events and filters. 2023-12-16 10:10:37 -03:00
fakejson.test.ts just format 2023-08-31 13:42:15 -05:00
fakejson.ts fakejson match subscription id. 2023-02-08 14:15:54 -03:00
filter.test.ts just format 2023-08-31 13:42:15 -05:00
filter.ts remove the kind type parameter from events and filters. 2023-12-16 10:10:37 -03:00
index.ts adjust packages exported. 2023-12-16 13:08:37 -03:00
jest.config.js Convert nip05 test to typescript 2023-05-10 21:20:27 -03:00
justfile apply prettier. 2023-09-26 12:19:01 -03:00
keys.test.ts just format 2023-08-31 13:42:15 -05:00
keys.ts just format 2023-08-31 13:42:15 -05:00
kinds.test.ts just format 2023-08-31 13:42:15 -05:00
kinds.ts remove the kind type parameter from events and filters. 2023-12-16 10:10:37 -03:00
nip04.test.ts nip04: augment tests with cross-compatibility vectors. 2023-12-02 13:13:16 -03:00
nip04.ts just format 2023-08-31 13:42:15 -05:00
nip05.test.ts fix nip05 test. 2023-12-16 08:51:33 -03:00
nip05.ts just format 2023-08-31 13:42:15 -05:00
nip06.test.ts prettify and lint. 2023-12-16 12:39:24 -03:00
nip06.ts prettify and lint. 2023-12-16 12:39:24 -03:00
nip10.test.ts just format 2023-08-31 13:42:15 -05:00
nip10.ts just format 2023-08-31 13:42:15 -05:00
nip11.test.ts cleanup nip-11. 2023-12-16 11:00:46 -03:00
nip11.ts cleanup nip-11. 2023-12-16 11:00:46 -03:00
nip13.test.ts apply prettier. 2023-09-26 12:19:01 -03:00
nip13.ts remove the kind type parameter from events and filters. 2023-12-16 10:10:37 -03:00
nip18.test.ts remove the kind type parameter from events and filters. 2023-12-16 10:10:37 -03:00
nip18.ts remove the kind type parameter from events and filters. 2023-12-16 10:10:37 -03:00
nip19.test.ts Add kind to nevent decode and encode (#304) 2023-09-26 12:20:17 -03:00
nip19.ts prettify and lint. 2023-12-16 12:39:24 -03:00
nip21.test.ts just format 2023-08-31 13:42:15 -05:00
nip21.ts just format 2023-08-31 13:42:15 -05:00
nip25.test.ts remove the kind type parameter from events and filters. 2023-12-16 10:10:37 -03:00
nip25.ts remove the kind type parameter from events and filters. 2023-12-16 10:10:37 -03:00
nip27.test.ts just format 2023-08-31 13:42:15 -05:00
nip27.ts prettify and lint. 2023-12-16 12:39:24 -03:00
nip28.test.ts remove the kind type parameter from events and filters. 2023-12-16 10:10:37 -03:00
nip28.ts remove the kind type parameter from events and filters. 2023-12-16 10:10:37 -03:00
nip30.test.ts prettify and lint. 2023-12-16 12:39:24 -03:00
nip30.ts prettify and lint. 2023-12-16 12:39:24 -03:00
nip39.test.ts just format 2023-08-31 13:42:15 -05:00
nip39.ts just format 2023-08-31 13:42:15 -05:00
nip42.test.ts simplify nip-42. 2023-12-16 11:21:49 -03:00
nip42.ts simplify nip-42. 2023-12-16 11:21:49 -03:00
nip47.test.ts fix nip-47 by removing some useless time checks. 2023-12-16 11:08:51 -03:00
nip47.ts remove the kind type parameter from events and filters. 2023-12-16 10:10:37 -03:00
nip57.test.ts just format 2023-08-31 13:42:15 -05:00
nip57.ts remove the kind type parameter from events and filters. 2023-12-16 10:10:37 -03:00
nip98.test.ts remove the kind type parameter from events and filters. 2023-12-16 10:10:37 -03:00
nip98.ts remove the kind type parameter from events and filters. 2023-12-16 10:10:37 -03:00
package.json adjust packages exported. 2023-12-16 13:08:37 -03:00
pool.test.ts clean up test with a minor refactor to delete the ts-ignore 2023-10-24 08:41:40 -03:00
pool.ts remove the kind type parameter from events and filters. 2023-12-16 10:10:37 -03:00
references.test.ts just format 2023-08-31 13:42:15 -05:00
references.ts just format 2023-08-31 13:42:15 -05:00
relay.test.ts relay: `sub.events` async iterator 2023-09-09 19:05:21 -03:00
relay.ts remove the kind type parameter from events and filters. 2023-12-16 10:10:37 -03:00
test-helpers.ts remove the kind type parameter from events and filters. 2023-12-16 10:10:37 -03:00
tsconfig.json Organize build, allow one entrypoint per file (#305) 2023-10-01 18:20:53 -03:00
utils.test.ts just format 2023-08-31 13:42:15 -05:00
utils.ts remove the kind type parameter from events and filters. 2023-12-16 10:10:37 -03:00
yarn.lock update dependencies. 2023-12-16 08:51:43 -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 { generatePrivateKey, getPublicKey } from 'nostr-tools'

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

Creating, signing and verifying events

import { validateEvent, verifySignature, getSignature, getEventHash, getPublicKey } from 'nostr-tools'

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

event.id = getEventHash(event)
event.sig = getSignature(event, privateKey)

let ok = validateEvent(event)
let veryOk = verifySignature(event)

Interacting with a relay

import { relayInit, finishEvent, generatePrivateKey, getPublicKey } from 'nostr-tools'

const relay = relayInit('wss://relay.example.com')
relay.on('connect', () => {
  console.log(`connected to ${relay.url}`)
})
relay.on('error', () => {
  console.log(`failed to connect to ${relay.url}`)
})

await relay.connect()

// let's query for an event that exists
let sub = relay.sub([
  {
    ids: ['d7dd5eb3ab747e16f8d0212d53032ea2a7cadef53837e5a6c66d42849fcb9027'],
  },
])
sub.on('event', event => {
  console.log('we got the event we wanted:', event)
})
sub.on('eose', () => {
  sub.unsub()
})

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

let sub = relay.sub([
  {
    kinds: [1],
    authors: [pk],
  },
])

sub.on('event', event => {
  console.log('got event:', event)
})

let event = {
  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 = finishEvent(event, sk)
await relay.publish(signedEvent)

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

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 sub = pool.sub(
  [...relays, 'wss://relay.example3.com'],
  [
    {
      authors: ['32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245'],
    },
  ],
)

sub.on('event', event => {
  // this will only be called once the first time the event is received
  // ...
})

let pubs = pool.publish(relays, newEvent)
await Promise.all(pubs)

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

let batchedEvents = await pool.batchedList('notes', relays, [{ kinds: [1] }])
// `batchedList` will wait for other function calls with the same `batchKey`
// (e.g. 'notes', 'authors', etc) within a fixed amount of time (default: `100ms`) before sending
// next ws request, and batch all requests with similar `batchKey`s together in a single request.

let relaysForEvent = pool.seenOn('44e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245')
// relaysForEvent will be an array of URLs from relays a given event was seen on

pool.close()

read more details about batchedList on this pr: https://github.com/nbd-wtf/nostr-tools/pull/279

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, generatePrivateKey, getPublicKey } from 'nostr-tools'

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

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

let pk = getPublicKey(generatePrivateKey())
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)

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.generatePrivateKey('...') // and so on
</script>

Plumbing

  1. Install just
  2. just -l

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.