GithubHelp home page GithubHelp logo

nbd-wtf / nostr-tools Goto Github PK

View Code? Open in Web Editor NEW
667.0 667.0 185.0 1.03 MB

Tools for developing Nostr clients.

License: The Unlicense

JavaScript 0.38% TypeScript 99.32% Just 0.16% Dockerfile 0.14%
nostr

nostr-tools's People

Contributors

adamritter avatar airtune avatar akiomik avatar alexgleason avatar anderson-juhasc avatar antonioconselheiro avatar arejula27 avatar asaitoshiya avatar billigsteruser avatar chmac avatar egge21m avatar eosxx avatar fernandolguevara avatar fiatjaf avatar franzaps avatar futpib avatar jaonoctus avatar jiftechnify avatar mmalmi avatar monlovesmango avatar npub1zenn0 avatar paulmillr avatar rkfg avatar rolznz avatar rsbondi avatar sepehr-safari avatar susumuota avatar syusui-s avatar t4t5 avatar verbiricha avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nostr-tools's Issues

Unsecure signature scheme

Hi pointing out 2 security issues here around the signature

  1. implementation:
    https://github.com/fiatjaf/nostr-tools/blob/master/event.ts#L67
    If you give to the function a fake id (of another event), it opens to an attack where a user can sign another message. I would compute again the hash of the event only instead. Even for the whole protocol, i would completely get rid-off the id in the transmission to force recomputing the hash on reception.
  2. protocol wise:
    It is not a good practice to blindly sign a hash, it could be used for some pre-image attacks scheme. It is usually a good practice to prefix with the "meaning" of the signature. That way it can't be reused for another purpose.

For instance here it could be hash("nostr-nip01" | hash(event)). This way even in blind signature (it can happens in some uses cases like hardware when you can't verify the meaning of the event) can be secured

Usage Documentation and Test Support

Hi, I'm working on implementing a NIP06 key generator for the Passport cold wallet, and would like to run your reference implementation via CLI. I'm currently unable to run tests due this error:
jest_error
Would it be possible to add install and usage instructions to the README? It would be helpful to mention the just and yarn dependencies early on as well. I've never used JS so it took some time for me to find the dependencies I needed in order to run "just install-dependencies"
Thanks!

nip06 passphrase

I think users should be able to use passphrases, since it's part of BIP39.

A user may decide to protect their mnemonic with a passphrase.

I did it on my own package, nip06

feature request: implement nip-13 (pow)

one idea is for signEvent to take an optional difficulty arg:

/**
 * if difficulty is a non-negative integer, signEvent inserts the 'nonce'
 * tag, if none is present, performs proof of work and signs the event only if
 * the difficulty is reached within the specified timeout, in milliseconds.
 * a zero timeout makes signEvent mine indefinitely.
 */
function signEvent(event, privkey, difficulty, timeout)

but then i realized it wouldn't work with nip-07 (window.nostr) where signEvent has a fixed number of args. so maybe add a new function here, in nostr-tools? something like this:

/**
 * run proof of work until at least the specified difficulty.
 * if succcessful, the returned event contains the 'nonce' tag
 * and the updated created_at timestamp.
 *
 * mineEvent throws an error if the funtion runs for longer than timeout.
 * a zero timeout makes mineEvent run without a time limit.
 */
async function mineEvent(event, difficulty, timeout)

Interest in TypeScript definitions?

I'm starting to work on a new Nostr client and generally prefer to do my JS-ecosystem work in TypeScript from the start. Would y'all be interested in a contributed set of TS declarations for this library?

I know things are moving fast in Nostr-land and I don't want to create a ton of extra hassle around API changes, but it would also be cool to not "miss the boat" on TS support (i.e., wait until the API footprint + quantity of existing loosely-typed code is just too huge to retrofit TS everywhere) as SSB, Dat, and others have sadly done over the years.

To be clear: I don't mean to imply that this project is doomed or not "serious" simply because you're using vanilla JS. I'm just an old, forgetful dev who likes to have my compiler + editor remind me what's ok/not-ok when I come back to code I haven't looked at in a while. :)

How to work with existing public key

Hello, it's clear from the docs how to work with public/private keys when generating them from scratch. I'm trying to figure out how to use the existing public key to pass the validateEvent check.

I went through the nostr-tools and @noble/secp256k1 packages and tried to simulate the creating of the keys.

import * as secp256k1 from '@noble/secp256k1'
import { utf8Encoder } from 'nostr-tools/utils'

const pubkey = secp256k1.utils.bytesToHex(
  utf8Encoder.encode('npub1yrmj7fe0t5tjffv8e28et7ur27zvrmucmeqytt3w2wdp2tp3la3shpy9pf')
) 

// 6e7075623179726d6a376665307435746a66667638653238657437757232377a76726d75636d6571797474337732776470327470336c613373687079397066

Such constructed pubkey fails the validation pubkey.match(/^[a-f0-9]{64}$/).

How should I work with existing public key? Thank you!

As a PHP developer who has not used node.js before, how can I quickly get started with this project?

As a PHP developer who has not used node.js before, how can I quickly get started with this project?

I have installed cygwin64 and just. Then I ran just build and a directory of lib appeared with some files "nostr.bundle.js, nostr.cjs.js, nostr.esm.js, etc." I created a file "1.js" in the root directory and wrote the following code in it:

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

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

Then I ran node 1.js and got some error messages. I know it's because I don't understand node.js, but I just want to quickly start using this library for development and don't want to spend too much time learning node.js.

Filtering by tags

Can nostr-tools filter by tags? I currently don't see a way to query for reactions to a particular event. Thanks!

Usage of `fetch` unclear

I get the following error whenever I simply require/import nostr-tools:

[...]\node_modules\nostr-tools\lib\nostr.cjs.js:438
var _fetch = fetch;
             ^

ReferenceError: fetch is not defined

I'm using Windows and I installed node-fetch. I'm pretty sure I'm missing something obvious.

Unit-test: FAIL ./nip04.test.js ● encrypt and decrypt message

  1. Checking out master
  2. yarn
  3. yarn test

Gives me:

Test Suites: 1 failed, 7 passed, 8 total
Tests:       1 failed, 17 passed, 18 total
Snapshots:   0 total
Time:        4.634 s

Failing test:

 FAIL  ./nip04.test.js
  ● encrypt and decrypt message

    TypeError: Cannot read property 'importKey' of undefined

      392 |   let iv = Uint8Array.from((0, import_utils2.randomBytes)(16));
      393 |   let plaintext = utf8Encoder.encode(text);
    > 394 |   let cryptoKey = await crypto.subtle.importKey(
          |                                       ^
      395 |     "raw",
      396 |     normalizedKey,
      397 |     { name: "AES-CBC" },

      at Object.importKey (lib/nostr.cjs.js:394:39)
      at Object.encrypt (nip04.test.js:13:47)

Does this work for you?
A github action running the tests could help with that. Happy to create a PR if this is wanted.

Vanilla repo clone, failing test in `nip04.test.js`

Hello 👋🏻 checking out these tools, looks great!

Problem

After a vanilla repo clone and yarn, 17/18 tests pass, one test fails.

Steps to reproduce

  1. git clone the repo into clean userspace.
  2. Run yarn to bring everything in.
  3. run npm test and observe (see screen capture below)

2022-12-23_21-02-55

signEvent generating incorrect signature

I've got a really baffling problem that I've been staring at for days to no avail. It seems that signEvent is generating an incorrect signature in one instance, and I can't determine why. Here is my signing function:

async function signEvent_(event) {
    event = JSON.parse(JSON.stringify(event));
    let privKey = await getPrivKey();
    console.log('signing with privkey ', privKey);
    console.log('signing with id: ', event.id);
    event.sig = signEvent(event, privKey);
    console.log('event sig: ', event.sig);
    console.log(JSON.stringify(event));
    return event;
}

Here is the logged data:

[Log] signing with privkey  – "0991e6969e8c65a6e732ec526d8733a71c20d041389d427475ac6ae1700e2422" (background.build.js, line 7514)
[Log] signing with id:  – "5b9b3770279b1171e6a25e04e152b23992ea6b6ec8835996ab1105425dd5b713" (background.build.js, line 7515)
[Log] event sig:  – "4331926865a4500b8ab873df56051d8548fa7d07561d7e54b0f77f22f026f39061ba7f36b75d8da7883df40999bfef96cebff363d2d4e34b3e670764e6af8f7c" (background.build.js, line 7517)
[Log] {"id":"5b9b3770279b1171e6a25e04e152b23992ea6b6ec8835996ab1105425dd5b713","kind":1,"pubkey":"00c899bce030cb9eeba4032bfbca4147b6d5d854a9db97f89faf7635848c5a6c","tags":[["delegation","7a346f6e715d7d6aabb4cea0726865edc94169c2268560692b8ef462c9d01579","created_at<1676510630&created_at>1675905829","8b9cd1e9db4361922b6f2e28631264535ac555bc40305441c37e36f0daafa50ea7a253e102bb104f33adc972918f071c8cb3696bb8132a7340ff6629742be672"]],"content":"test","created_at":1675912531,"sig":"4331926865a4500b8ab873df56051d8548fa7d07561d7e54b0f77f22f026f39061ba7f36b75d8da7883df40999bfef96cebff363d2d4e34b3e670764e6af8f7c"} (background.build.js, line 7518)

Now, that is the incorrect signature!

I thought I was taking crazy pills. In a different project, I wrote this following script:

import nostr from "nostr-tools";
const { nip19, nip26, getEventHash, signEvent } = nostr;

let event =
  '{"id":"5b9b3770279b1171e6a25e04e152b23992ea6b6ec8835996ab1105425dd5b713","kind":1,"pubkey":"00c899bce030cb9eeba4032bfbca4147b6d5d854a9db97f89faf7635848c5a6c","tags":[["delegation","7a346f6e715d7d6aabb4cea0726865edc94169c2268560692b8ef462c9d01579","created_at<1676510630&created_at>1675905829","8b9cd1e9db4361922b6f2e28631264535ac555bc40305441c37e36f0daafa50ea7a253e102bb104f33adc972918f071c8cb3696bb8132a7340ff6629742be672"]],"content":"test","created_at":1675912531,"sig":"4331926865a4500b8ab873df56051d8548fa7d07561d7e54b0f77f22f026f39061ba7f36b75d8da7883df40999bfef96cebff363d2d4e34b3e670764e6af8f7c"}';
event = JSON.parse(event);

console.log(event);

let expectedId = getEventHash(event);

console.log("Expected ID: ", expectedId);
console.log("Actual ID:   ", event.id);

let delegateSk =
  "nsec1pxg7d95733j6deeja3fxmpen5uwzp5zp8zw5yar4434wzuqwys3q8mxsl8";
delegateSk = nip19.decode(delegateSk).data;
console.log("delegate SK: ", delegateSk);

let expectedSig = signEvent(event, delegateSk);

console.log("Expected sig: ", expectedSig);
console.log("Actual sig:   ", event.sig);

As you can see, I just copied the logged JSON from the javascript console, and plugged it into the event string, then parsed it, generated a new ID from it, and signed it. Then I output the values I calculated fresh, against the ones from my signed event, and the ids match, but the signatures do not! This script is calculating the correct signature, but the one in the other script is not. Here is the output:

{
  id: '5b9b3770279b1171e6a25e04e152b23992ea6b6ec8835996ab1105425dd5b713',
  kind: 1,
  pubkey: '00c899bce030cb9eeba4032bfbca4147b6d5d854a9db97f89faf7635848c5a6c',
  tags: [
    [
      'delegation',
      '7a346f6e715d7d6aabb4cea0726865edc94169c2268560692b8ef462c9d01579',
      'created_at<1676510630&created_at>1675905829',
      '8b9cd1e9db4361922b6f2e28631264535ac555bc40305441c37e36f0daafa50ea7a253e102bb104f33adc972918f071c8cb3696bb8132a7340ff6629742be672'
    ]
  ],
  content: 'test',
  created_at: 1675912531,
  sig: '4331926865a4500b8ab873df56051d8548fa7d07561d7e54b0f77f22f026f39061ba7f36b75d8da7883df40999bfef96cebff363d2d4e34b3e670764e6af8f7c'
}
Expected ID:  5b9b3770279b1171e6a25e04e152b23992ea6b6ec8835996ab1105425dd5b713
Actual ID:    5b9b3770279b1171e6a25e04e152b23992ea6b6ec8835996ab1105425dd5b713
delegate SK:  0991e6969e8c65a6e732ec526d8733a71c20d041389d427475ac6ae1700e2422
Expected sig:  d33bfe7b3e468cb9bd9e1d6a2a384a03f185fe4cb586069662106c1b8490bb7dd0398d8bc48af67f8bfe95583cec594bd7c179c6e663f09e0767178a361ad7e1
Actual sig:    4331926865a4500b8ab873df56051d8548fa7d07561d7e54b0f77f22f026f39061ba7f36b75d8da7883df40999bfef96cebff363d2d4e34b3e670764e6af8f7c

You see here in the output, the ids are the same, the privkey is the same as the one from the console output, and yet the signature is different!

Please tell me I'm missing something obvious here. It is really confusing.

cross-fetch is not available in service workers

I'm trying to use nip05.js and run into this issue.

import crossFetch from 'cross-fetch'

const f = (typeof XMLHttpRequest == 'function')
  ? crossFetch
  : fetch

using f instead of fetch makes it fetch stuff in my service worker but I haven't tested this enough to make a PR yet.

Support for key extension

We can add a few functions which obtain the keys from nos2x o albby. Do you think will be a nostr-tool or not?

close never resolves if existing connection status is not 1

ISSUE

Calling the close function on the relay will hang forever.

This can be mitigated by validating the status is 1 before calling close.

EXPECTED BEHAVIOR

I'm expecting the .close() function to easily handle any current connection status and simply return when connection is closed.

Filter Logical Operation AND

Looks like the filter works as OR operation:
events with kind 4 OR authors in [...]
Is there a way for treat them as AND?

react-native support

I have tried to polyfill my react-native app so it could use the crypto native module, but then I realized that this library is meant to be used by clients, a lot of which doesn't support node's native crypto module.

May I suggest using some library instead, like https://github.com/entronad/crypto-es ?
Do you think it would be possible?

nostr-tools and electron

For anyone trying to get nostr-tools working with electron, I have started a repo which is a fork of electron-react-boilerplate in which I am testing out basic nostr-tools functionality. So far, I'm getting at least some of it to work. I'm going to post problems that I encounter either on my repo's README or over here (or both) in the hopes it may be useful to others using electron. (I should mention that electron-react-boilerplate is fairly well fleshed out with bells and whistles, so some of the issues I encounter may stem from interactions with them.)

So far there are two issues that I will summarize briefly:

The first is already fixed in the code and I presume the fix will be in v0.24.2, but it's still a problem in the most recent version which is still v0.24.1. I was getting a type error:

Cannot read properties of undefined (reading 'call')

with any function that called getEventHash, which is in event.ts. To fix this I had to dig into that file in node_modules/nostr-tools after installation, add:

import {sha256} from '@noble/hashes/sha256'

and update getEventHash to

export function getEventHash(event: Event): string {
  let eventHash = sha256(Buffer.from(serializeEvent(event)))
  return Buffer.from(eventHash).toString('hex')
}

Like I said - already addressed in the upcoming version, although I don't know when that will be ready.

The second issue relates to the topic of native modules, which is something I still haven't wrapped my head around. By my understanding, nostr-tools is not a native module, but its dependency tree includes bufferutil and utf-8-validate, both of which are native. So for me to get nostr-tools to work in electron, I had to install it as a devDependency, not a dependency; otherwise, npm install throws an error. More specifically, this file throws an error when the postinstall script is called. So far I have it working in dev mode, not yet in the packaged app. (I know I need to install nostr-tools in release/app, although I haven't gotten it fully working yet.)

I don't know whether cleaning up the dependency tree to remove the above two native modules is feasible or not. If it is feasible, it might save some headaches for anyone working with electron.

Proper doc

The project is growing and more people would like to use kt. It is a interesting idea to have a proper doc deployed via gh actions, what about Astro? I can try to do it for Christmas. People would find more usable the API if there is a good documentation instead just a read.me

importing nostr-tools results in bundle exporting it as default

I know this might be a long shot but as the issue happens with this import and not with others, I'll leave the issue here in case others ran into the same ...

I'm using the svelte bundler and when I import nostr-tools in service-worker.ts, svelte bundles it, including a default export which I think is the full nostr-tools import.

If I import anything else, Dexie for example, no export is generated in my bundle.

$ cat src/service-worker.ts 
import { relayPool } from 'nostr-tools'
$ npm run build
...
  Wrote site to "build"
  ✔ done
$ grep '^export' build/service-worker.js 
export default Fl();

Is this a bug in nostr-tools or in the svelte bundler or not a bug at all?? I'm confused.

fix import statements in readme

Looks like the recently updated examples in readme need import statements to be fixed, e.g. change:

const {matchFilters} = require('./cjs')

to

import {matchFilters} from 'nostr-tools'

I'll see if I can get a pull request going for that.

TypeError: resolveClose is not a function

Uncaught (in promise) TypeError: resolveClose is not a function
Ember 10
onclose
NostrTools
connectRelay
connect

Seeing this error quite a lot. Looks like scope error.

ReferenceError: fetch is not defined

I just need to publish some notes to a few relays, not much else.
Trying to use this on serverless api endpoint with next.js on vercel and it gives this error

import { relayInit } from 'nostr-tools';

ReferenceError: fetch is not defined

I did npm i node-fetch@2 but still same error.

Best way to validate public key

Finding the need to validate public keys. Due to the two formats, curious if there is an existing, fool-proof (or suggested) method for validating pubkeys before I write my own.

NIP-26

matchFilters checks if returned events are compatible with the filters. This is not currently compatible with delegation NIP-26, as those events generally have a different pubkey than the one requested.

resolveClose is not a function - Error connecting to relay

When trying to connect to wss://nostr.rocks it hangs first and then returns this error. Other relays work without issues.

TypeError: resolveClose is not a function
    at ws.onclose (node_modules/nostr-tools/lib/nostr.cjs.js:173:7)
    at WebSocket.EventTarget.dispatchEvent (node_modules/websocket-polyfill/lib/events/EventTarget.js:33:17)
    at WebSocket._Handle_close (node_modules/websocket-polyfill/lib/WebSocket.js:208:14)
    at WebSocketConnection.emit (node:events:513:28)
    at WebSocketConnection.handleSocketClose (node_modules/websocket/lib/WebSocketConnection.js:389:14)
    at TLSSocket.emit (node:events:525:35)
    at node:net:757:14
    at TCP.done (node:_tls_wrap:584:7)
    at TCP.callbackTrampoline (node:internal/async_hooks:130:17)

Version: 1.0.0-beta2
Environment: Node v16.17.0

Example code for validateEvent and verifySignature not working from README.md

const {
  generatePrivateKey,
  getPublicKey,
  getEventHash,
  signEvent,
  verifySignature,
  validateEvent,
} = require("nostr-tools");

let privateKey = generatePrivateKey();
let publicKey = getPublicKey(privateKey);

console.log(privateKey);
console.log(publicKey);

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

event.id = getEventHash(event);
event.pubkey = publicKey;
event.sig = signEvent(event, privateKey);

console.log(event);

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

console.log(ok);
console.log(veryOk);

Output:

0bd69cf6b8bd9d62afee43459e40e86480bc672ddd4e8480fa54cb96eb6d62ee
85ed964a4e4df125c7555a0d6f6a303d33748ffded8569717d33b3bd76a21ab5
{
  kind: 1,
  created_at: 1672835523,
  tags: [],
  content: 'hello',
  id: 'e29442be3ac948f08c7225849cd1131507952e28a91145a87ea352cdac487b4b',
  pubkey: '85ed964a4e4df125c7555a0d6f6a303d33748ffded8569717d33b3bd76a21ab5',
  sig: '9a46319ed0724903e024f0e963aac8e3ec8ac6b64842def549f97965dc85f1adedde69b5f123ebce1b43abf9fdd72217b03222c15ad6e646289ef2e8785f0721'
}
false
false

Any idea why the console.log for validateEvent and verifySignature isn't working?

I'm using NodeJS 18 btw

tsc fails with errors

Compile is failing with these errors. I can try to look at them at some point.

tsc --noEmit --pretty

node_modules/nostr-tools/filter.ts:28:43 - error TS2532: Object is possibly 'undefined'.

28           ([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1
                                             ~~~~~~

node_modules/nostr-tools/filter.ts:28:58 - error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
  Type 'undefined' is not assignable to type 'string'.

28           ([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1
                                                            ~

node_modules/nostr-tools/filter.ts:46:21 - error TS2345: Argument of type 'Filter | undefined' is not assignable to parameter of type 'Filter'.
  Type 'undefined' is not assignable to type 'Filter'.

46     if (matchFilter(filters[i], event)) return true
                       ~~~~~~~~~~

node_modules/nostr-tools/nip04.ts:51:30 - error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
  Type 'undefined' is not assignable to type 'string'.

51   let ciphertext = b64decode(ctb64)
                                ~~~~~

node_modules/nostr-tools/nip04.ts:52:22 - error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
  Type 'undefined' is not assignable to type 'string'.

52   let iv = b64decode(ivb64)
                        ~~~~~

node_modules/nostr-tools/nip05.ts:39:21 - error TS2538: Type 'undefined' cannot be used as an index type.

39   if (!res?.names?.[name]) return null
                       ~~~~

node_modules/nostr-tools/nip05.ts:41:26 - error TS2538: Type 'undefined' cannot be used as an index type.

41   let pubkey = res.names[name] as string
                            ~~~~

node_modules/nostr-tools/nip19.ts:32:17 - error TS2532: Object is possibly 'undefined'.

32         relays: tlv[1].map(d => utf8Decoder.decode(d))
                   ~~~~~~

node_modules/nostr-tools/nip19.ts:46:17 - error TS2532: Object is possibly 'undefined'.

46         relays: tlv[1].map(d => utf8Decoder.decode(d))
                   ~~~~~~

node_modules/nostr-tools/nip19.ts:66:31 - error TS2532: Object is possibly 'undefined'.

66     let v = rest.slice(2, 2 + l)
                                 ~

node_modules/nostr-tools/nip19.ts:67:27 - error TS2532: Object is possibly 'undefined'.

67     rest = rest.slice(2 + l)
                             ~

node_modules/nostr-tools/nip19.ts:68:20 - error TS2532: Object is possibly 'undefined'.

68     if (v.length < l) continue
                      ~

node_modules/nostr-tools/nip19.ts:69:12 - error TS2538: Type 'undefined' cannot be used as an index type.

69     result[t] = result[t] || []
              ~

node_modules/nostr-tools/nip19.ts:69:24 - error TS2538: Type 'undefined' cannot be used as an index type.

69     result[t] = result[t] || []
                          ~

node_modules/nostr-tools/nip19.ts:70:12 - error TS2538: Type 'undefined' cannot be used as an index type.

70     result[t].push(v)
              ~

node_modules/nostr-tools/relay.ts:94:16 - error TS2532: Object is possibly 'undefined'.

94               (openSubs[id].skipVerification || verifySignature(event)) &&
                  ~~~~~~~~~~~~

node_modules/nostr-tools/relay.ts:95:28 - error TS2532: Object is possibly 'undefined'.

95               matchFilters(openSubs[id].filters, event)
                              ~~~~~~~~~~~~

node_modules/nostr-tools/relay.ts:170:9 - error TS2532: Object is possibly 'undefined'.

170         subListeners[subid][type].push(cb)
            ~~~~~~~~~~~~~~~~~~~

node_modules/nostr-tools/relay.ts:173:19 - error TS2532: Object is possibly 'undefined'.

173         let idx = subListeners[subid][type].indexOf(cb)
                      ~~~~~~~~~~~~~~~~~~~

node_modules/nostr-tools/relay.ts:174:23 - error TS2532: Object is possibly 'undefined'.

174         if (idx >= 0) subListeners[subid][type].splice(idx, 1)
                          ~~~~~~~~~~~~~~~~~~~

node_modules/nostr-tools/relay.ts:220:11 - error TS2532: Object is possibly 'undefined'.

220           pubListeners[id].failed.forEach(cb =>
              ~~~~~~~~~~~~~~~~

node_modules/nostr-tools/relay.ts:227:11 - error TS2532: Object is possibly 'undefined'.

227           pubListeners[id].seen.forEach(cb => cb())
              ~~~~~~~~~~~~~~~~

node_modules/nostr-tools/relay.ts:238:11 - error TS2532: Object is possibly 'undefined'.

238           pubListeners[id][type].push(cb)
              ~~~~~~~~~~~~~~~~

node_modules/nostr-tools/relay.ts:246:21 - error TS2532: Object is possibly 'undefined'.

246           let idx = pubListeners[id][type].indexOf(cb)
                        ~~~~~~~~~~~~~~~~

node_modules/nostr-tools/relay.ts:247:25 - error TS2532: Object is possibly 'undefined'.

247           if (idx >= 0) pubListeners[id][type].splice(idx, 1)
                            ~~~~~~~~~~~~~~~~


Found 25 errors.

Make Relay test not dependent on external service

I made nostr-relaypool-ts tests more deterministic by not depending on external service / internet connection by using an in memory relay pool implementation as a dev dependency. It's just a small improvement (also makes tests run much faster, which can help with development). Feel free to take it if you want:

https://github.com/adamritter/nostr-relaypool-ts/blob/main/in-memory-relay-server.ts

The relay test in nostr-relaypool-ts repo is here:

https://github.com/adamritter/nostr-relaypool-ts/blob/main/relay.test.ts

Readme has erroneous code

Under "Creating, signing and verifying events"

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

event.id = getEventHash(event.id)

getEventHash(event.id) -> getEventHash(event)

The event must be signed before or after getting the id

For verifying uses the whole event, where is also the id so i think it could be a problem because for signing is needed the id but for the id is needed the whole event (id,signature, content, etc..). Should be modify the validateEvent function ?

Idea: Adding support for nip11 relay info

Firstly, thanks for nostr-tools, it makes building on nostr super easy in the browser. 🧡 🧡 🧡

My idea is to add nip11 support to nostr-tools. The back story is that I was pushing parameterised replaceable events to several relays, until I realised they don't support them (nip33). Then checking nostr.watch it seems that there's only a small subset of relays who support nip33.

My thought was that I'd like my nostr client to automatically reject messages I try to post to relays which don't support those features. Of course I'd also like to be able to override said protections.

Before I go too far down the rabbit hole and start writing PRs, I wanted to check in with the maintainers first. Is this something you think would make sense to add to nostr-tools?

Edit: I can think of lots of different ways nip11 support could be added. The scenario described above is just one of those. I wanted to open the discussion on the whole topic rather than just the idea of rejecting events to relays which won't support them.

Question about status 'ok' vs 'seen' when publishing new event

Hi there.

I have a small question regarding the state of a newly published event.

It seems that after publishing a new event, it will first become in an 'ok' state where it "has been accepted by relay", then it'll become in a 'seen' state where it has been "seen on the relay"

But I'm not really sure about the different between the two.
Could an event be accepted by a relay but not "seen" on it??

When I'm building a user journey where there I show a loading spinner while publishing an event, should I end the loading state when I receive the 'ok' state or when I receive the 'seen' state??


Another related question.
I noticed that after publishing an event, there will be 2 events returned.
One is the same event that we published, and another that has a monitor-${id.slice()} value & also contains the published event.
What is the difference between the two?

Should I care about one and ignore the other or what??

Thanks 🙏

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.