mirror of
https://github.com/nbd-wtf/nostr-tools.git
synced 2025-12-08 16:28:49 +00:00
Compare commits
81 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf7e00d32a | ||
|
|
9241089997 | ||
|
|
32c47e9bd8 | ||
|
|
6e58fe371c | ||
|
|
26e35d50e0 | ||
|
|
ef3184a6e0 | ||
|
|
56fe3dd5dd | ||
|
|
f1bb5030c8 | ||
|
|
ac212cb5c8 | ||
|
|
204ae0eff1 | ||
|
|
f17ab41d72 | ||
|
|
f6f5ee8223 | ||
|
|
a05506468d | ||
|
|
674ff66b6f | ||
|
|
731705047a | ||
|
|
94b382a49f | ||
|
|
199411a971 | ||
|
|
a1dc6f41b9 | ||
|
|
5b59b93d86 | ||
|
|
12acd7bdca | ||
|
|
3bdb68020d | ||
|
|
b0a58e2ca4 | ||
|
|
b063be76ae | ||
|
|
e3cea5db16 | ||
|
|
9ee58bd6c7 | ||
|
|
f1eb9a3bc7 | ||
|
|
ce081bb4cb | ||
|
|
7413072e9f | ||
|
|
4c464b39cf | ||
|
|
11ef43abdc | ||
|
|
3e67f9b014 | ||
|
|
0933fba6d5 | ||
|
|
51b8f42529 | ||
|
|
24d885aaeb | ||
|
|
74c77a2e9f | ||
|
|
ce73b96565 | ||
|
|
8818e4f88a | ||
|
|
5a63c75f24 | ||
|
|
60e01a9006 | ||
|
|
687f387385 | ||
|
|
6d116a2f7f | ||
|
|
51c3aec788 | ||
|
|
613b2c177f | ||
|
|
24f5068fdb | ||
|
|
5733f9c4e4 | ||
|
|
6b73bbf8a3 | ||
|
|
d244b62c7a | ||
|
|
b00af9a30a | ||
|
|
be7c981c14 | ||
|
|
5539e5cf89 | ||
|
|
73decbc8e0 | ||
|
|
b3d95cecdd | ||
|
|
82228036ef | ||
|
|
01435ab9f5 | ||
|
|
63cbc4133a | ||
|
|
049f183d27 | ||
|
|
f9e3119ab4 | ||
|
|
f992c9c967 | ||
|
|
dbf625d6ac | ||
|
|
8622bd11dd | ||
|
|
0970eee70f | ||
|
|
086f8830e3 | ||
|
|
e48d722227 | ||
|
|
0d77013aab | ||
|
|
4c415280aa | ||
|
|
4188aaf7c8 | ||
|
|
673f4abab8 | ||
|
|
bcefaa0757 | ||
|
|
649af36a86 | ||
|
|
96a6f7af87 | ||
|
|
a4c713efcb | ||
|
|
9d345a8f01 | ||
|
|
c362212778 | ||
|
|
a8938a3a0f | ||
|
|
a21329da3f | ||
|
|
63f4a49a69 | ||
|
|
27749d91b8 | ||
|
|
9530849f0a | ||
|
|
b8aa75b6e1 | ||
|
|
344762820c | ||
|
|
f43d23d344 |
9
.editorconfig
Normal file
9
.editorconfig
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
root = true
|
||||||
|
|
||||||
|
[*]
|
||||||
|
indent_style = space
|
||||||
|
indent_size = 2
|
||||||
|
end_of_line = lf
|
||||||
|
charset = utf-8
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
insert_final_newline = true
|
||||||
1
.github/workflows/npm-publish.yml
vendored
1
.github/workflows/npm-publish.yml
vendored
@@ -16,6 +16,7 @@ jobs:
|
|||||||
- run: just install-dependencies
|
- run: just install-dependencies
|
||||||
- run: just build
|
- run: just build
|
||||||
- run: just test
|
- run: just test
|
||||||
|
- run: just emit-types
|
||||||
- uses: JS-DevTools/npm-publish@v1
|
- uses: JS-DevTools/npm-publish@v1
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.NPM_TOKEN }}
|
token: ${{ secrets.NPM_TOKEN }}
|
||||||
|
|||||||
2
.github/workflows/test.yml
vendored
2
.github/workflows/test.yml
vendored
@@ -9,7 +9,7 @@ jobs:
|
|||||||
test:
|
test:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-node@v3
|
- uses: actions/setup-node@v3
|
||||||
with:
|
with:
|
||||||
node-version: 18
|
node-version: 18
|
||||||
|
|||||||
53
README.md
53
README.md
@@ -10,7 +10,6 @@ Only depends on _@scure_ and _@noble_ packages.
|
|||||||
npm install nostr-tools # or yarn add nostr-tools
|
npm install nostr-tools # or yarn add nostr-tools
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
### Generating a private key and a public key
|
### Generating a private key and a public key
|
||||||
@@ -138,25 +137,27 @@ const pool = new SimplePool()
|
|||||||
|
|
||||||
let relays = ['wss://relay.example.com', 'wss://relay.example2.com']
|
let relays = ['wss://relay.example.com', 'wss://relay.example2.com']
|
||||||
|
|
||||||
let relay = await pool.ensureRelay('wss://relay.example3.com')
|
let sub = pool.sub(
|
||||||
|
[...relays, 'wss://relay.example3.com'],
|
||||||
|
[
|
||||||
|
{
|
||||||
|
authors: [
|
||||||
|
'32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245'
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
let subs = pool.sub([...relays, relay], {
|
sub.on('event', event => {
|
||||||
authors: ['32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245']
|
// this will only be called once the first time the event is received
|
||||||
|
// ...
|
||||||
})
|
})
|
||||||
|
|
||||||
subs.forEach(sub =>
|
|
||||||
sub.on('event', event => {
|
|
||||||
// this will only be called once the first time the event is received
|
|
||||||
// ...
|
|
||||||
})
|
|
||||||
)
|
|
||||||
|
|
||||||
let pubs = pool.publish(relays, newEvent)
|
let pubs = pool.publish(relays, newEvent)
|
||||||
pubs.forEach(pub =>
|
pubs.on('ok', () => {
|
||||||
pub.on('ok', () => {
|
// this may be called multiple times, once for every relay that accepts the event
|
||||||
// ...
|
// ...
|
||||||
})
|
})
|
||||||
)
|
|
||||||
|
|
||||||
let events = await pool.list(relays, [{kinds: [0, 1]}])
|
let events = await pool.list(relays, [{kinds: [0, 1]}])
|
||||||
let event = await pool.get(relays, {
|
let event = await pool.get(relays, {
|
||||||
@@ -169,6 +170,26 @@ let relaysForEvent = pool.seenOn(
|
|||||||
// relaysForEvent will be an array of URLs from relays a given event was seen on
|
// relaysForEvent will be an array of URLs from relays a given event was seen on
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Parsing references (mentions) from a content using NIP-10 and NIP-27
|
||||||
|
|
||||||
|
```js
|
||||||
|
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
|
### Querying profile data from a NIP-05 address
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
2
build.js
2
build.js
@@ -17,7 +17,7 @@ esbuild
|
|||||||
packages: 'external'
|
packages: 'external'
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
const packageJson = JSON.stringify({ type: 'module' })
|
const packageJson = JSON.stringify({type: 'module'})
|
||||||
fs.writeFileSync(`${__dirname}/lib/esm/package.json`, packageJson, 'utf8')
|
fs.writeFileSync(`${__dirname}/lib/esm/package.json`, packageJson, 'utf8')
|
||||||
|
|
||||||
console.log('esm build success.')
|
console.log('esm build success.')
|
||||||
|
|||||||
368
event.test.js
368
event.test.js
@@ -1,48 +1,340 @@
|
|||||||
/* eslint-env jest */
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
|
getBlankEvent,
|
||||||
|
finishEvent,
|
||||||
|
serializeEvent,
|
||||||
|
getEventHash,
|
||||||
validateEvent,
|
validateEvent,
|
||||||
verifySignature,
|
verifySignature,
|
||||||
signEvent,
|
signEvent,
|
||||||
getPublicKey
|
getPublicKey,
|
||||||
|
Kind
|
||||||
} = require('./lib/nostr.cjs')
|
} = require('./lib/nostr.cjs')
|
||||||
|
|
||||||
const event = {
|
describe('Event', () => {
|
||||||
id: 'd7dd5eb3ab747e16f8d0212d53032ea2a7cadef53837e5a6c66d42849fcb9027',
|
describe('getBlankEvent', () => {
|
||||||
kind: 1,
|
it('should return a blank event object', () => {
|
||||||
pubkey: '22a12a128a3be27cd7fb250cbe796e692896398dc1440ae3fa567812c8107c1c',
|
expect(getBlankEvent()).toEqual({
|
||||||
created_at: 1670869179,
|
kind: 255,
|
||||||
content:
|
content: '',
|
||||||
'NOSTR "WINE-ACCOUNT" WITH HARVEST DATE STAMPED\n\n\n"The older the wine, the greater its reputation"\n\n\n22a12a128a3be27cd7fb250cbe796e692896398dc1440ae3fa567812c8107c1c\n\n\nNWA 2022-12-12\nAA',
|
tags: [],
|
||||||
tags: [['client', 'astral']],
|
created_at: 0
|
||||||
sig: 'f110e4fdf67835fb07abc72469933c40bdc7334615610cade9554bf00945a1cebf84f8d079ec325d26fefd76fe51cb589bdbe208ac9cdbd63351ddad24a57559'
|
})
|
||||||
}
|
})
|
||||||
|
})
|
||||||
|
|
||||||
const unsigned = {
|
describe('finishEvent', () => {
|
||||||
created_at: 1671217411,
|
it('should create a signed event from a template', () => {
|
||||||
kind: 0,
|
const privateKey =
|
||||||
tags: [],
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
content:
|
const publicKey = getPublicKey(privateKey)
|
||||||
'{"name":"fiatjaf","about":"buy my merch at fiatjaf store","picture":"https://fiatjaf.com/static/favicon.jpg","nip05":"_@fiatjaf.com"}'
|
|
||||||
}
|
|
||||||
|
|
||||||
const privateKey =
|
const template = {
|
||||||
'5c6c25b7ef18d8633e97512159954e1aa22809c6b763e94b9f91071836d00217'
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115
|
||||||
|
}
|
||||||
|
|
||||||
test('validate event', () => {
|
const event = finishEvent(template, privateKey)
|
||||||
expect(validateEvent(event)).toBeTruthy()
|
|
||||||
})
|
expect(event.kind).toEqual(template.kind)
|
||||||
|
expect(event.tags).toEqual(template.tags)
|
||||||
test('check signature', async () => {
|
expect(event.content).toEqual(template.content)
|
||||||
expect(verifySignature(event)).toBeTruthy()
|
expect(event.created_at).toEqual(template.created_at)
|
||||||
})
|
expect(event.pubkey).toEqual(publicKey)
|
||||||
|
expect(typeof event.id).toEqual('string')
|
||||||
test('sign event', async () => {
|
expect(typeof event.sig).toEqual('string')
|
||||||
let pubkey = getPublicKey(privateKey)
|
})
|
||||||
let authored = {...unsigned, pubkey}
|
})
|
||||||
|
|
||||||
let sig = signEvent(authored, privateKey)
|
describe('serializeEvent', () => {
|
||||||
let signed = {...authored, sig}
|
it('should serialize a valid event object', () => {
|
||||||
|
const privateKey =
|
||||||
expect(verifySignature(signed)).toBeTruthy()
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const unsignedEvent = {
|
||||||
|
pubkey: publicKey,
|
||||||
|
created_at: 1617932115,
|
||||||
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!'
|
||||||
|
}
|
||||||
|
|
||||||
|
const serializedEvent = serializeEvent(unsignedEvent)
|
||||||
|
|
||||||
|
expect(serializedEvent).toEqual(
|
||||||
|
JSON.stringify([
|
||||||
|
0,
|
||||||
|
publicKey,
|
||||||
|
unsignedEvent.created_at,
|
||||||
|
unsignedEvent.kind,
|
||||||
|
unsignedEvent.tags,
|
||||||
|
unsignedEvent.content
|
||||||
|
])
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should throw an error for an invalid event object', () => {
|
||||||
|
const privateKey =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const invalidEvent = {
|
||||||
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
created_at: 1617932115,
|
||||||
|
pubkey: publicKey // missing content
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(() => {
|
||||||
|
serializeEvent(invalidEvent)
|
||||||
|
}).toThrow("can't serialize event with wrong or missing properties")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('getEventHash', () => {
|
||||||
|
it('should return the correct event hash', () => {
|
||||||
|
const privateKey =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const unsignedEvent = {
|
||||||
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115,
|
||||||
|
pubkey: publicKey
|
||||||
|
}
|
||||||
|
|
||||||
|
const eventHash = getEventHash(unsignedEvent)
|
||||||
|
|
||||||
|
expect(typeof eventHash).toEqual('string')
|
||||||
|
expect(eventHash.length).toEqual(64)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('validateEvent', () => {
|
||||||
|
it('should return true for a valid event object', () => {
|
||||||
|
const privateKey =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const unsignedEvent = {
|
||||||
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115,
|
||||||
|
pubkey: publicKey
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValid = validateEvent(unsignedEvent)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false for a non object event', () => {
|
||||||
|
const nonObjectEvent = ''
|
||||||
|
|
||||||
|
const isValid = validateEvent(nonObjectEvent)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false for an event object with missing properties', () => {
|
||||||
|
const invalidEvent = {
|
||||||
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
created_at: 1617932115 // missing content and pubkey
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValid = validateEvent(invalidEvent)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false for an empty object', () => {
|
||||||
|
const emptyObj = {}
|
||||||
|
|
||||||
|
const isValid = validateEvent(emptyObj)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false for an object with invalid properties', () => {
|
||||||
|
const privateKey =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const invalidEvent = {
|
||||||
|
kind: 1,
|
||||||
|
tags: [],
|
||||||
|
created_at: '1617932115', // should be a number
|
||||||
|
pubkey: publicKey
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValid = validateEvent(invalidEvent)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false for an object with an invalid public key', () => {
|
||||||
|
const invalidEvent = {
|
||||||
|
kind: 1,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115,
|
||||||
|
pubkey: 'invalid_pubkey'
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValid = validateEvent(invalidEvent)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false for an object with invalid tags', () => {
|
||||||
|
const privateKey =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const invalidEvent = {
|
||||||
|
kind: 1,
|
||||||
|
tags: {}, // should be an array
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115,
|
||||||
|
pubkey: publicKey
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValid = validateEvent(invalidEvent)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('verifySignature', () => {
|
||||||
|
it('should return true for a valid event signature', () => {
|
||||||
|
const privateKey =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
|
||||||
|
const event = finishEvent(
|
||||||
|
{
|
||||||
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115
|
||||||
|
},
|
||||||
|
privateKey
|
||||||
|
)
|
||||||
|
|
||||||
|
const isValid = verifySignature(event)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false for an invalid event signature', () => {
|
||||||
|
const privateKey =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
|
||||||
|
const event = finishEvent(
|
||||||
|
{
|
||||||
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115
|
||||||
|
},
|
||||||
|
privateKey
|
||||||
|
)
|
||||||
|
|
||||||
|
// tamper with the signature
|
||||||
|
event.sig = event.sig.replace(/0/g, '1')
|
||||||
|
|
||||||
|
const isValid = verifySignature(event)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false when verifying an event with a different private key', () => {
|
||||||
|
const privateKey1 =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
|
||||||
|
const privateKey2 =
|
||||||
|
'5b4a34f4e4b23c63ad55a35e3f84a3b53d96dbf266edf521a8358f71d19cbf67'
|
||||||
|
const publicKey2 = getPublicKey(privateKey2)
|
||||||
|
|
||||||
|
const event = finishEvent(
|
||||||
|
{
|
||||||
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115
|
||||||
|
},
|
||||||
|
privateKey1
|
||||||
|
)
|
||||||
|
|
||||||
|
// verify with different private key
|
||||||
|
const isValid = verifySignature({
|
||||||
|
...event,
|
||||||
|
pubkey: publicKey2
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('signEvent', () => {
|
||||||
|
it('should sign an event object', () => {
|
||||||
|
const privateKey =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const unsignedEvent = {
|
||||||
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115,
|
||||||
|
pubkey: publicKey
|
||||||
|
}
|
||||||
|
|
||||||
|
const sig = signEvent(unsignedEvent, privateKey)
|
||||||
|
|
||||||
|
// verify the signature
|
||||||
|
const isValid = verifySignature({
|
||||||
|
...unsignedEvent,
|
||||||
|
sig
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(typeof sig).toEqual('string')
|
||||||
|
expect(sig.length).toEqual(128)
|
||||||
|
expect(isValid).toEqual(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should not sign an event with different private key', () => {
|
||||||
|
const privateKey =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const wrongPrivateKey =
|
||||||
|
'a91e2a9d9e0f70f0877bea0dbf034e8f95d7392a27a7f07da0d14b9e9d456be7'
|
||||||
|
|
||||||
|
const unsignedEvent = {
|
||||||
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115,
|
||||||
|
pubkey: publicKey
|
||||||
|
}
|
||||||
|
|
||||||
|
const sig = signEvent(unsignedEvent, wrongPrivateKey)
|
||||||
|
|
||||||
|
// verify the signature
|
||||||
|
const isValid = verifySignature({
|
||||||
|
...unsignedEvent,
|
||||||
|
sig
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(typeof sig).toEqual('string')
|
||||||
|
expect(sig.length).toEqual(128)
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
12
event.ts
12
event.ts
@@ -13,6 +13,7 @@ export enum Kind {
|
|||||||
EncryptedDirectMessage = 4,
|
EncryptedDirectMessage = 4,
|
||||||
EventDeletion = 5,
|
EventDeletion = 5,
|
||||||
Reaction = 7,
|
Reaction = 7,
|
||||||
|
BadgeAward = 8,
|
||||||
ChannelCreation = 40,
|
ChannelCreation = 40,
|
||||||
ChannelMetadata = 41,
|
ChannelMetadata = 41,
|
||||||
ChannelMessage = 42,
|
ChannelMessage = 42,
|
||||||
@@ -23,6 +24,8 @@ export enum Kind {
|
|||||||
Zap = 9735,
|
Zap = 9735,
|
||||||
RelayList = 10002,
|
RelayList = 10002,
|
||||||
ClientAuth = 22242,
|
ClientAuth = 22242,
|
||||||
|
BadgeDefinition = 30008,
|
||||||
|
ProfileBadge = 30009,
|
||||||
Article = 30023
|
Article = 30023
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -78,8 +81,11 @@ export function getEventHash(event: UnsignedEvent): string {
|
|||||||
return secp256k1.utils.bytesToHex(eventHash)
|
return secp256k1.utils.bytesToHex(eventHash)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function validateEvent(event: UnsignedEvent): boolean {
|
const isRecord = (obj: unknown): obj is Record<string, unknown> => obj instanceof Object
|
||||||
if (typeof event !== 'object') return false
|
|
||||||
|
export function validateEvent<T>(event: T): event is T & UnsignedEvent {
|
||||||
|
if (!isRecord(event)) return false
|
||||||
|
if (typeof event.kind !== 'number') return false
|
||||||
if (typeof event.content !== 'string') return false
|
if (typeof event.content !== 'string') return false
|
||||||
if (typeof event.created_at !== 'number') return false
|
if (typeof event.created_at !== 'number') return false
|
||||||
if (typeof event.pubkey !== 'string') return false
|
if (typeof event.pubkey !== 'string') return false
|
||||||
@@ -97,7 +103,7 @@ export function validateEvent(event: UnsignedEvent): boolean {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
export function verifySignature(event: Event & {sig: string}): boolean {
|
export function verifySignature(event: Event): boolean {
|
||||||
return secp256k1.schnorr.verifySync(
|
return secp256k1.schnorr.verifySync(
|
||||||
event.sig,
|
event.sig,
|
||||||
getEventHash(event),
|
getEventHash(event),
|
||||||
|
|||||||
228
filter.test.js
228
filter.test.js
@@ -1,42 +1,200 @@
|
|||||||
/* eslint-env jest */
|
/* eslint-env jest */
|
||||||
|
|
||||||
const {matchFilters} = require('./lib/nostr.cjs')
|
const {matchFilter, matchFilters} = require('./lib/nostr.cjs.js')
|
||||||
|
|
||||||
test('test if filters match', () => {
|
describe('Filter', () => {
|
||||||
;[
|
describe('matchFilter', () => {
|
||||||
{
|
it('should return true when all filter conditions are met', () => {
|
||||||
filters: [{ids: ['i']}],
|
const filter = {
|
||||||
good: [{id: 'i'}],
|
ids: ['123', '456'],
|
||||||
bad: [{id: 'j'}]
|
kinds: [1, 2, 3],
|
||||||
},
|
authors: ['abc'],
|
||||||
{
|
since: 100,
|
||||||
filters: [{authors: ['abc']}, {kinds: [1, 3]}],
|
until: 200,
|
||||||
good: [
|
'#tag': ['value']
|
||||||
{pubkey: 'xyz', kind: 3},
|
}
|
||||||
{pubkey: 'abc', kind: 12},
|
|
||||||
{pubkey: 'abc', kind: 1}
|
const event = {
|
||||||
],
|
id: '123',
|
||||||
bad: [{pubkey: 'hhh', kind: 12}]
|
kind: 1,
|
||||||
},
|
pubkey: 'abc',
|
||||||
{
|
created_at: 150,
|
||||||
filters: [{'#e': ['yyy'], since: 444}],
|
tags: [['tag', 'value']]
|
||||||
good: [
|
}
|
||||||
{
|
|
||||||
tags: [
|
const result = matchFilter(filter, event)
|
||||||
['e', 'uuu'],
|
|
||||||
['e', 'yyy']
|
expect(result).toEqual(true)
|
||||||
],
|
|
||||||
created_at: 555
|
|
||||||
}
|
|
||||||
],
|
|
||||||
bad: [{tags: [['e', 'uuu']], created_at: 111}]
|
|
||||||
}
|
|
||||||
].forEach(({filters, good, bad}) => {
|
|
||||||
good.forEach(ev => {
|
|
||||||
expect(matchFilters(filters, ev)).toBeTruthy()
|
|
||||||
})
|
})
|
||||||
bad.forEach(ev => {
|
|
||||||
expect(matchFilters(filters, ev)).toBeFalsy()
|
it('should return false when the event id is not in the filter', () => {
|
||||||
|
const filter = {ids: ['123', '456']}
|
||||||
|
|
||||||
|
const event = {id: '789'}
|
||||||
|
|
||||||
|
const result = matchFilter(filter, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return true when the event id starts with a prefix', () => {
|
||||||
|
const filter = {ids: ['22', '00']}
|
||||||
|
|
||||||
|
const event = {id: '001'}
|
||||||
|
|
||||||
|
const result = matchFilter(filter, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false when the event kind is not in the filter', () => {
|
||||||
|
const filter = {kinds: [1, 2, 3]}
|
||||||
|
|
||||||
|
const event = {kind: 4}
|
||||||
|
|
||||||
|
const result = matchFilter(filter, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false when the event author is not in the filter', () => {
|
||||||
|
const filter = {authors: ['abc', 'def']}
|
||||||
|
|
||||||
|
const event = {pubkey: 'ghi'}
|
||||||
|
|
||||||
|
const result = matchFilter(filter, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false when a tag is not present in the event', () => {
|
||||||
|
const filter = {'#tag': ['value1', 'value2']}
|
||||||
|
|
||||||
|
const event = {tags: [['not_tag', 'value1']]}
|
||||||
|
|
||||||
|
const result = matchFilter(filter, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false when a tag value is not present in the event', () => {
|
||||||
|
const filter = {'#tag': ['value1', 'value2']}
|
||||||
|
|
||||||
|
const event = {tags: [['tag', 'value3']]}
|
||||||
|
|
||||||
|
const result = matchFilter(filter, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return true when filter has tags that is present in the event', () => {
|
||||||
|
const filter = {'#tag1': ['foo']}
|
||||||
|
|
||||||
|
const event = {
|
||||||
|
id: '123',
|
||||||
|
kind: 1,
|
||||||
|
pubkey: 'abc',
|
||||||
|
created_at: 150,
|
||||||
|
tags: [
|
||||||
|
['tag1', 'foo'],
|
||||||
|
['tag2', 'bar']
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = matchFilter(filter, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false when the event is before the filter since value', () => {
|
||||||
|
const filter = {since: 100}
|
||||||
|
|
||||||
|
const event = {created_at: 50}
|
||||||
|
|
||||||
|
const result = matchFilter(filter, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false when the event is after the filter until value', () => {
|
||||||
|
const filter = {until: 100}
|
||||||
|
|
||||||
|
const event = {created_at: 150}
|
||||||
|
|
||||||
|
const result = matchFilter(filter, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('matchFilters', () => {
|
||||||
|
it('should return true when at least one filter matches the event', () => {
|
||||||
|
const filters = [
|
||||||
|
{ids: ['123'], kinds: [1], authors: ['abc']},
|
||||||
|
{ids: ['456'], kinds: [2], authors: ['def']},
|
||||||
|
{ids: ['789'], kinds: [3], authors: ['ghi']}
|
||||||
|
]
|
||||||
|
|
||||||
|
const event = {id: '789', kind: 3, pubkey: 'ghi'}
|
||||||
|
|
||||||
|
const result = matchFilters(filters, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return true when at least one prefix matches the event', () => {
|
||||||
|
const filters = [
|
||||||
|
{ids: ['1'], kinds: [1], authors: ['a']},
|
||||||
|
{ids: ['4'], kinds: [2], authors: ['d']},
|
||||||
|
{ids: ['9'], kinds: [3], authors: ['g']}
|
||||||
|
]
|
||||||
|
|
||||||
|
const event = {id: '987', kind: 3, pubkey: 'ghi'}
|
||||||
|
|
||||||
|
const result = matchFilters(filters, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return true when event matches one or more filters and some have limit set', () => {
|
||||||
|
const filters = [
|
||||||
|
{ids: ['123'], limit: 1},
|
||||||
|
{kinds: [1], limit: 2},
|
||||||
|
{authors: ['abc'], limit: 3}
|
||||||
|
]
|
||||||
|
|
||||||
|
const event = {id: '123', kind: 1, pubkey: 'abc', created_at: 150}
|
||||||
|
|
||||||
|
const result = matchFilters(filters, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false when no filters match the event', () => {
|
||||||
|
const filters = [
|
||||||
|
{ids: ['123'], kinds: [1], authors: ['abc']},
|
||||||
|
{ids: ['456'], kinds: [2], authors: ['def']},
|
||||||
|
{ids: ['789'], kinds: [3], authors: ['ghi']}
|
||||||
|
]
|
||||||
|
|
||||||
|
const event = {id: '100', kind: 4, pubkey: 'jkl'}
|
||||||
|
|
||||||
|
const result = matchFilters(filters, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false when event matches none of the filters and some have limit set', () => {
|
||||||
|
const filters = [
|
||||||
|
{ids: ['123'], limit: 1},
|
||||||
|
{kinds: [1], limit: 2},
|
||||||
|
{authors: ['abc'], limit: 3}
|
||||||
|
]
|
||||||
|
const event = {id: '456', kind: 2, pubkey: 'def', created_at: 200}
|
||||||
|
|
||||||
|
const result = matchFilters(filters, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(false)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
18
filter.ts
18
filter.ts
@@ -7,17 +7,25 @@ export type Filter = {
|
|||||||
since?: number
|
since?: number
|
||||||
until?: number
|
until?: number
|
||||||
limit?: number
|
limit?: number
|
||||||
|
search?: string
|
||||||
[key: `#${string}`]: string[]
|
[key: `#${string}`]: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export function matchFilter(
|
export function matchFilter(
|
||||||
filter: Filter,
|
filter: Filter,
|
||||||
event: Event & {id: string}
|
event: Event
|
||||||
): boolean {
|
): boolean {
|
||||||
if (filter.ids && filter.ids.indexOf(event.id) === -1) return false
|
if (filter.ids && filter.ids.indexOf(event.id) === -1) {
|
||||||
|
if (!filter.ids.some(prefix => event.id.startsWith(prefix))) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) return false
|
if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) return false
|
||||||
if (filter.authors && filter.authors.indexOf(event.pubkey) === -1)
|
if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {
|
||||||
return false
|
if (!filter.authors.some(prefix => event.pubkey.startsWith(prefix))) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
for (let f in filter) {
|
for (let f in filter) {
|
||||||
if (f[0] === '#') {
|
if (f[0] === '#') {
|
||||||
@@ -41,7 +49,7 @@ export function matchFilter(
|
|||||||
|
|
||||||
export function matchFilters(
|
export function matchFilters(
|
||||||
filters: Filter[],
|
filters: Filter[],
|
||||||
event: Event & {id: string}
|
event: Event
|
||||||
): boolean {
|
): boolean {
|
||||||
for (let i = 0; i < filters.length; i++) {
|
for (let i = 0; i < filters.length; i++) {
|
||||||
if (matchFilter(filters[i], event)) return true
|
if (matchFilter(filters[i], event)) return true
|
||||||
|
|||||||
5
index.ts
5
index.ts
@@ -3,12 +3,17 @@ export * from './relay'
|
|||||||
export * from './event'
|
export * from './event'
|
||||||
export * from './filter'
|
export * from './filter'
|
||||||
export * from './pool'
|
export * from './pool'
|
||||||
|
export * from './references'
|
||||||
|
|
||||||
export * as nip04 from './nip04'
|
export * as nip04 from './nip04'
|
||||||
export * as nip05 from './nip05'
|
export * as nip05 from './nip05'
|
||||||
export * as nip06 from './nip06'
|
export * as nip06 from './nip06'
|
||||||
|
export * as nip10 from './nip10'
|
||||||
|
export * as nip13 from './nip13'
|
||||||
export * as nip19 from './nip19'
|
export * as nip19 from './nip19'
|
||||||
export * as nip26 from './nip26'
|
export * as nip26 from './nip26'
|
||||||
|
export * as nip39 from './nip39'
|
||||||
|
export * as nip42 from './nip42'
|
||||||
export * as nip57 from './nip57'
|
export * as nip57 from './nip57'
|
||||||
|
|
||||||
export * as fj from './fakejson'
|
export * as fj from './fakejson'
|
||||||
|
|||||||
11
justfile
11
justfile
@@ -4,13 +4,20 @@ install-dependencies:
|
|||||||
yarn --ignore-engines
|
yarn --ignore-engines
|
||||||
|
|
||||||
build:
|
build:
|
||||||
|
rm -rf lib
|
||||||
node build.js
|
node build.js
|
||||||
|
|
||||||
test: build
|
test: build
|
||||||
jest
|
jest
|
||||||
|
|
||||||
testOnly file: build
|
test-only file: build
|
||||||
jest {{file}}
|
jest {{file}}
|
||||||
|
|
||||||
publish: build
|
emit-types:
|
||||||
|
tsc # see tsconfig.json
|
||||||
|
|
||||||
|
publish: build emit-types
|
||||||
npm publish
|
npm publish
|
||||||
|
|
||||||
|
format:
|
||||||
|
prettier --plugin-search-dir . --write .
|
||||||
|
|||||||
140
magic.ts
140
magic.ts
@@ -1,140 +0,0 @@
|
|||||||
import {Relay, relayInit} from './relay'
|
|
||||||
import {Event} from './event'
|
|
||||||
import {normalizeURL} from './utils'
|
|
||||||
|
|
||||||
export default function (
|
|
||||||
writeableRelays: string[],
|
|
||||||
fallbackRelays: string[],
|
|
||||||
safeRelays: string[]
|
|
||||||
) {
|
|
||||||
return new MagicPool(fallbackRelays, writeableRelays, safeRelays)
|
|
||||||
}
|
|
||||||
|
|
||||||
class MagicPool {
|
|
||||||
private _conn: {[url: string]: Relay}
|
|
||||||
private _fallback: {[url: string]: Relay}
|
|
||||||
private _write: {[url: string]: Relay}
|
|
||||||
private _safe: {[url: string]: Relay}
|
|
||||||
|
|
||||||
private _profileRelays: {[pubkey: string]: RelayTableScore}
|
|
||||||
private _tempCache: {[id: string]: Event}
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
fallbackRelays: string[],
|
|
||||||
writeableRelays: string[],
|
|
||||||
safeRelays: string[] = [
|
|
||||||
'wss://eden.nostr.land',
|
|
||||||
'wss://nostr.milou.lol',
|
|
||||||
'wss://relay.minds.com/nostr/v1/ws'
|
|
||||||
]
|
|
||||||
) {
|
|
||||||
this._conn = {}
|
|
||||||
this._write = {}
|
|
||||||
this._fallback = {}
|
|
||||||
this._profileRelays = {}
|
|
||||||
this._tempCache = {}
|
|
||||||
|
|
||||||
const hasEventId = (id: string): boolean => id in this._tempCache
|
|
||||||
const init = (url: string) => {
|
|
||||||
this._conn[normalizeURL(url)] = relayInit(normalizeURL(url), hasEventId)
|
|
||||||
}
|
|
||||||
|
|
||||||
fallbackRelays.forEach(init)
|
|
||||||
writeableRelays.forEach(init)
|
|
||||||
safeRelays.forEach(init)
|
|
||||||
|
|
||||||
this._write = Object.fromEntries(
|
|
||||||
writeableRelays.map(url => [
|
|
||||||
normalizeURL(url),
|
|
||||||
this._conn[normalizeURL(url)]
|
|
||||||
])
|
|
||||||
)
|
|
||||||
this._fallback = Object.fromEntries(
|
|
||||||
fallbackRelays.map(url => [
|
|
||||||
normalizeURL(url),
|
|
||||||
this._conn[normalizeURL(url)]
|
|
||||||
])
|
|
||||||
)
|
|
||||||
this._safe = Object.fromEntries(
|
|
||||||
safeRelays.map(url => [normalizeURL(url), this._conn[normalizeURL(url)]])
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
publish(event: Event) {
|
|
||||||
return Promise.all(
|
|
||||||
Object.entries(this._write).map(
|
|
||||||
([url, relay]) =>
|
|
||||||
new Promise(async resolve => {
|
|
||||||
await relay.connect()
|
|
||||||
let pub = relay.publish(event)
|
|
||||||
let to = setTimeout(() => {
|
|
||||||
let end = setTimeout(() => {
|
|
||||||
resolve({url, success: false, reason: 'timeout'})
|
|
||||||
}, 2500)
|
|
||||||
pub.on('seen', () => {
|
|
||||||
clearTimeout(end)
|
|
||||||
resolve({url, success: true, reason: 'seen'})
|
|
||||||
})
|
|
||||||
}, 2500)
|
|
||||||
pub.on('ok', () => {
|
|
||||||
clearTimeout(to)
|
|
||||||
resolve({url, success: true, reason: 'ok'})
|
|
||||||
})
|
|
||||||
pub.on('failed', (reason: string) => {
|
|
||||||
clearTimeout(to)
|
|
||||||
resolve({url, success: false, reason})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
profile(
|
|
||||||
pubkey: string,
|
|
||||||
onUpdate: (events: Event[]) => void
|
|
||||||
): {
|
|
||||||
page(n: number): void
|
|
||||||
} {
|
|
||||||
var relays = new Set()
|
|
||||||
let rts = this._profileRelays[pubkey]
|
|
||||||
if (rts) {
|
|
||||||
relays = rts.get(3)
|
|
||||||
}
|
|
||||||
|
|
||||||
let fallback = Object.values(this._fallback)
|
|
||||||
for (let i = 0; i < fallback.length; i++) {
|
|
||||||
if (relays.size < 3) {
|
|
||||||
relays.add(fallback[Math.floor(Math.random() * fallback.length)])
|
|
||||||
} else break
|
|
||||||
}
|
|
||||||
|
|
||||||
// start subscription
|
|
||||||
for (let r in relays) {
|
|
||||||
r.
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
page(n: number) {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class RelayTableScore {
|
|
||||||
seen: string[] = []
|
|
||||||
hinted: string[] = []
|
|
||||||
explicit: string[] = []
|
|
||||||
|
|
||||||
get(n: number): Set<string> {
|
|
||||||
let relays = new Set<string>()
|
|
||||||
for (let i = 0; i < n; i++) {
|
|
||||||
for (let j = 0; j < 3; j++) {
|
|
||||||
let v = [this.seen, this.explicit, this.hinted][j][i]
|
|
||||||
if (v) {
|
|
||||||
relays.add(v)
|
|
||||||
if (relays.size >= n) return relays
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return relays
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -17,4 +17,9 @@ test('fetch nip05 profiles', async () => {
|
|||||||
'32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245'
|
'32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245'
|
||||||
)
|
)
|
||||||
expect(p2.relays).toEqual(['wss://relay.damus.io'])
|
expect(p2.relays).toEqual(['wss://relay.damus.io'])
|
||||||
|
|
||||||
|
let p3 = await nip05.queryProfile('channel.ninja@channel.ninja')
|
||||||
|
expect(p3.pubkey).toEqual(
|
||||||
|
'36e65b503eba8a6b698e724a59137603101166a1cddb45ddc704247fc8aa0fce'
|
||||||
|
)
|
||||||
})
|
})
|
||||||
|
|||||||
14
nip05.ts
14
nip05.ts
@@ -36,11 +36,17 @@ export async function queryProfile(
|
|||||||
name = '_'
|
name = '_'
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!name.match(/^[A-Za-z0-9-_]+$/)) return null
|
if (!name.match(/^[A-Za-z0-9-_.]+$/)) return null
|
||||||
|
if (!domain.includes('.')) return null
|
||||||
|
|
||||||
let res = await (
|
let res
|
||||||
await _fetch(`https://${domain}/.well-known/nostr.json?name=${name}`)
|
try {
|
||||||
).json()
|
res = await (
|
||||||
|
await _fetch(`https://${domain}/.well-known/nostr.json?name=${name}`)
|
||||||
|
).json()
|
||||||
|
} catch (err) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
if (!res?.names?.[name]) return null
|
if (!res?.names?.[name]) return null
|
||||||
|
|
||||||
|
|||||||
@@ -4,12 +4,16 @@ const {nip06} = require('./lib/nostr.cjs')
|
|||||||
test('generate private key from a mnemonic', async () => {
|
test('generate private key from a mnemonic', async () => {
|
||||||
const mnemonic = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong'
|
const mnemonic = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong'
|
||||||
const privateKey = nip06.privateKeyFromSeedWords(mnemonic)
|
const privateKey = nip06.privateKeyFromSeedWords(mnemonic)
|
||||||
expect(privateKey).toEqual('c26cf31d8ba425b555ca27d00ca71b5008004f2f662470f8c8131822ec129fe2')
|
expect(privateKey).toEqual(
|
||||||
|
'c26cf31d8ba425b555ca27d00ca71b5008004f2f662470f8c8131822ec129fe2'
|
||||||
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('generate private key from a mnemonic and passphrase', async () => {
|
test('generate private key from a mnemonic and passphrase', async () => {
|
||||||
const mnemonic = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong'
|
const mnemonic = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong'
|
||||||
const passphrase = '123'
|
const passphrase = '123'
|
||||||
const privateKey = nip06.privateKeyFromSeedWords(mnemonic, passphrase)
|
const privateKey = nip06.privateKeyFromSeedWords(mnemonic, passphrase)
|
||||||
expect(privateKey).toEqual('55a22b8203273d0aaf24c22c8fbe99608e70c524b17265641074281c8b978ae4')
|
expect(privateKey).toEqual(
|
||||||
|
'55a22b8203273d0aaf24c22c8fbe99608e70c524b17265641074281c8b978ae4'
|
||||||
|
)
|
||||||
})
|
})
|
||||||
|
|||||||
5
nip06.ts
5
nip06.ts
@@ -7,7 +7,10 @@ import {
|
|||||||
} from '@scure/bip39'
|
} from '@scure/bip39'
|
||||||
import {HDKey} from '@scure/bip32'
|
import {HDKey} from '@scure/bip32'
|
||||||
|
|
||||||
export function privateKeyFromSeedWords(mnemonic: string, passphrase?: string): string {
|
export function privateKeyFromSeedWords(
|
||||||
|
mnemonic: string,
|
||||||
|
passphrase?: string
|
||||||
|
): string {
|
||||||
let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))
|
let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))
|
||||||
let privateKey = root.derive(`m/44'/1237'/0'/0/0`).privateKey
|
let privateKey = root.derive(`m/44'/1237'/0'/0/0`).privateKey
|
||||||
if (!privateKey) throw new Error('could not derive private key')
|
if (!privateKey) throw new Error('could not derive private key')
|
||||||
|
|||||||
353
nip10.test.js
Normal file
353
nip10.test.js
Normal file
@@ -0,0 +1,353 @@
|
|||||||
|
/* eslint-env jest */
|
||||||
|
|
||||||
|
const {nip10} = require('./lib/nostr.cjs')
|
||||||
|
|
||||||
|
describe('parse NIP10-referenced events', () => {
|
||||||
|
test('legacy + a lot of events', () => {
|
||||||
|
let event = {
|
||||||
|
tags: [
|
||||||
|
[
|
||||||
|
'e',
|
||||||
|
'b857504288c18a15950dd05b9e8772c62ca6289d5aac373c0a8ee5b132e94e7c'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'e',
|
||||||
|
'bbd72f0ae14374aa8fb166b483cfcf99b57d7f4cf1600ccbf17c350040834631'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'e',
|
||||||
|
'5e081ebb19153357d7c31e8a10b9ceeef29313f58dc8d701f66727fab02aef64'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'e',
|
||||||
|
'49aff7ae6daeaaa2777931b90f9bb29f6cb01c5a3d7d88c8ba82d890f264afb4'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'e',
|
||||||
|
'567b7c11f0fe582361e3cea6fcc7609a8942dfe196ee1b98d5604c93fbeea976'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'e',
|
||||||
|
'090c037b2e399ee74d9f134758928948dd9154413ca1a1acb37155046e03a051'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'e',
|
||||||
|
'89f220b63465c93542b1a78caa3a952cf4f196e91a50596493c8093c533ebc4d'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'p',
|
||||||
|
'77ce56f89d1228f7ff3743ce1ad1b254857b9008564727ebd5a1f317362f6ca7'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'p',
|
||||||
|
'534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'p',
|
||||||
|
'4ca4f5533e40da5e0508796d409e6bb35a50b26fc304345617ab017183d83ac0'
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(nip10.parse(event)).toEqual({
|
||||||
|
mentions: [
|
||||||
|
{
|
||||||
|
id: 'bbd72f0ae14374aa8fb166b483cfcf99b57d7f4cf1600ccbf17c350040834631',
|
||||||
|
relays: []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '5e081ebb19153357d7c31e8a10b9ceeef29313f58dc8d701f66727fab02aef64',
|
||||||
|
relays: []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '49aff7ae6daeaaa2777931b90f9bb29f6cb01c5a3d7d88c8ba82d890f264afb4',
|
||||||
|
relays: []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '567b7c11f0fe582361e3cea6fcc7609a8942dfe196ee1b98d5604c93fbeea976',
|
||||||
|
relays: []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '090c037b2e399ee74d9f134758928948dd9154413ca1a1acb37155046e03a051',
|
||||||
|
relays: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
profiles: [
|
||||||
|
{
|
||||||
|
pubkey:
|
||||||
|
'77ce56f89d1228f7ff3743ce1ad1b254857b9008564727ebd5a1f317362f6ca7',
|
||||||
|
relays: []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pubkey:
|
||||||
|
'534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec',
|
||||||
|
relays: []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pubkey:
|
||||||
|
'4ca4f5533e40da5e0508796d409e6bb35a50b26fc304345617ab017183d83ac0',
|
||||||
|
relays: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
reply: {
|
||||||
|
id: '89f220b63465c93542b1a78caa3a952cf4f196e91a50596493c8093c533ebc4d',
|
||||||
|
relays: []
|
||||||
|
},
|
||||||
|
root: {
|
||||||
|
id: 'b857504288c18a15950dd05b9e8772c62ca6289d5aac373c0a8ee5b132e94e7c',
|
||||||
|
relays: []
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('legacy + 3 events', () => {
|
||||||
|
let event = {
|
||||||
|
tags: [
|
||||||
|
[
|
||||||
|
'e',
|
||||||
|
'b857504288c18a15950dd05b9e8772c62ca6289d5aac373c0a8ee5b132e94e7c'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'e',
|
||||||
|
'bbd72f0ae14374aa8fb166b483cfcf99b57d7f4cf1600ccbf17c350040834631'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'e',
|
||||||
|
'5e081ebb19153357d7c31e8a10b9ceeef29313f58dc8d701f66727fab02aef64'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'p',
|
||||||
|
'77ce56f89d1228f7ff3743ce1ad1b254857b9008564727ebd5a1f317362f6ca7'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'p',
|
||||||
|
'534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'p',
|
||||||
|
'4ca4f5533e40da5e0508796d409e6bb35a50b26fc304345617ab017183d83ac0'
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(nip10.parse(event)).toEqual({
|
||||||
|
mentions: [
|
||||||
|
{
|
||||||
|
id: 'bbd72f0ae14374aa8fb166b483cfcf99b57d7f4cf1600ccbf17c350040834631',
|
||||||
|
relays: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
profiles: [
|
||||||
|
{
|
||||||
|
pubkey:
|
||||||
|
'77ce56f89d1228f7ff3743ce1ad1b254857b9008564727ebd5a1f317362f6ca7',
|
||||||
|
relays: []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pubkey:
|
||||||
|
'534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec',
|
||||||
|
relays: []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pubkey:
|
||||||
|
'4ca4f5533e40da5e0508796d409e6bb35a50b26fc304345617ab017183d83ac0',
|
||||||
|
relays: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
reply: {
|
||||||
|
id: '5e081ebb19153357d7c31e8a10b9ceeef29313f58dc8d701f66727fab02aef64',
|
||||||
|
relays: []
|
||||||
|
},
|
||||||
|
root: {
|
||||||
|
id: 'b857504288c18a15950dd05b9e8772c62ca6289d5aac373c0a8ee5b132e94e7c',
|
||||||
|
relays: []
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('legacy + 2 events', () => {
|
||||||
|
let event = {
|
||||||
|
tags: [
|
||||||
|
[
|
||||||
|
'e',
|
||||||
|
'b857504288c18a15950dd05b9e8772c62ca6289d5aac373c0a8ee5b132e94e7c'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'e',
|
||||||
|
'bbd72f0ae14374aa8fb166b483cfcf99b57d7f4cf1600ccbf17c350040834631'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'p',
|
||||||
|
'77ce56f89d1228f7ff3743ce1ad1b254857b9008564727ebd5a1f317362f6ca7'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'p',
|
||||||
|
'534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'p',
|
||||||
|
'4ca4f5533e40da5e0508796d409e6bb35a50b26fc304345617ab017183d83ac0'
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(nip10.parse(event)).toEqual({
|
||||||
|
mentions: [],
|
||||||
|
profiles: [
|
||||||
|
{
|
||||||
|
pubkey:
|
||||||
|
'77ce56f89d1228f7ff3743ce1ad1b254857b9008564727ebd5a1f317362f6ca7',
|
||||||
|
relays: []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pubkey:
|
||||||
|
'534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec',
|
||||||
|
relays: []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pubkey:
|
||||||
|
'4ca4f5533e40da5e0508796d409e6bb35a50b26fc304345617ab017183d83ac0',
|
||||||
|
relays: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
reply: {
|
||||||
|
id: 'bbd72f0ae14374aa8fb166b483cfcf99b57d7f4cf1600ccbf17c350040834631',
|
||||||
|
relays: []
|
||||||
|
},
|
||||||
|
root: {
|
||||||
|
id: 'b857504288c18a15950dd05b9e8772c62ca6289d5aac373c0a8ee5b132e94e7c',
|
||||||
|
relays: []
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('legacy + 1 event', () => {
|
||||||
|
let event = {
|
||||||
|
tags: [
|
||||||
|
[
|
||||||
|
'e',
|
||||||
|
'9abbfd9b9ac5ecdab45d14b8bf8d746139ea039e931a1b376d19a239f1946590'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'p',
|
||||||
|
'534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec'
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(nip10.parse(event)).toEqual({
|
||||||
|
mentions: [],
|
||||||
|
profiles: [
|
||||||
|
{
|
||||||
|
pubkey:
|
||||||
|
'534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec',
|
||||||
|
relays: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
reply: undefined,
|
||||||
|
root: {
|
||||||
|
id: '9abbfd9b9ac5ecdab45d14b8bf8d746139ea039e931a1b376d19a239f1946590',
|
||||||
|
relays: []
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test.todo('recommended + a lot of events')
|
||||||
|
test.todo('recommended + 3 events')
|
||||||
|
test.todo('recommended + 2 events')
|
||||||
|
|
||||||
|
test('recommended + 1 event', () => {
|
||||||
|
let event = {
|
||||||
|
tags: [
|
||||||
|
[
|
||||||
|
'p',
|
||||||
|
'a8c21fcd8aa1f4befba14d72fc7a012397732d30d8b3131af912642f3c726f52',
|
||||||
|
'wss://relay.mostr.pub'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'p',
|
||||||
|
'003d7fd21fd09ff7f6f63a75daf194dd99feefbe6919cc376b7359d5090aa9a6',
|
||||||
|
'wss://relay.mostr.pub'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'p',
|
||||||
|
'2f6fbe452edd3987d3c67f3b034c03ec5bcf4d054c521c3a954686f89f03212e',
|
||||||
|
'wss://relay.mostr.pub'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'p',
|
||||||
|
'44c7c74668ff222b0e0b30579c49fc6e22dafcdeaad091036c947f9856590f1e',
|
||||||
|
'wss://relay.mostr.pub'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'p',
|
||||||
|
'c5cf39149caebda4cdd61771c51f6ba91ef5645919004e5c4998a4ea69f00512',
|
||||||
|
'wss://relay.mostr.pub'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'p',
|
||||||
|
'094d44bb1e812696c57f57ad1c0c707812dedbe72c07e538b80639032c236a9e',
|
||||||
|
'wss://relay.mostr.pub'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'p',
|
||||||
|
'a1ba0ac9b6ec098f726a3c11ec654df4a32cbb84b5377e8788395e9c27d9ecda',
|
||||||
|
'wss://relay.mostr.pub'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'e',
|
||||||
|
'f9472913904ab7e9da008dcb2d85fd4af2d2993ada483d00c646d0c4481d031d',
|
||||||
|
'wss://relay.mostr.pub',
|
||||||
|
'reply'
|
||||||
|
],
|
||||||
|
['mostr', 'https://poa.st/objects/dc50684b-6364-4264-ab16-49f4622f05ea']
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(nip10.parse(event)).toEqual({
|
||||||
|
mentions: [],
|
||||||
|
profiles: [
|
||||||
|
{
|
||||||
|
pubkey:
|
||||||
|
'a8c21fcd8aa1f4befba14d72fc7a012397732d30d8b3131af912642f3c726f52',
|
||||||
|
relays: ['wss://relay.mostr.pub']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pubkey:
|
||||||
|
'003d7fd21fd09ff7f6f63a75daf194dd99feefbe6919cc376b7359d5090aa9a6',
|
||||||
|
relays: ['wss://relay.mostr.pub']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pubkey:
|
||||||
|
'2f6fbe452edd3987d3c67f3b034c03ec5bcf4d054c521c3a954686f89f03212e',
|
||||||
|
relays: ['wss://relay.mostr.pub']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pubkey:
|
||||||
|
'44c7c74668ff222b0e0b30579c49fc6e22dafcdeaad091036c947f9856590f1e',
|
||||||
|
relays: ['wss://relay.mostr.pub']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pubkey:
|
||||||
|
'c5cf39149caebda4cdd61771c51f6ba91ef5645919004e5c4998a4ea69f00512',
|
||||||
|
relays: ['wss://relay.mostr.pub']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pubkey:
|
||||||
|
'094d44bb1e812696c57f57ad1c0c707812dedbe72c07e538b80639032c236a9e',
|
||||||
|
relays: ['wss://relay.mostr.pub']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pubkey:
|
||||||
|
'a1ba0ac9b6ec098f726a3c11ec654df4a32cbb84b5377e8788395e9c27d9ecda',
|
||||||
|
relays: ['wss://relay.mostr.pub']
|
||||||
|
}
|
||||||
|
],
|
||||||
|
reply: {
|
||||||
|
id: 'f9472913904ab7e9da008dcb2d85fd4af2d2993ada483d00c646d0c4481d031d',
|
||||||
|
relays: ['wss://relay.mostr.pub']
|
||||||
|
},
|
||||||
|
root: undefined
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
96
nip10.ts
Normal file
96
nip10.ts
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
import type {Event} from './event'
|
||||||
|
import type {EventPointer, ProfilePointer} from './nip19'
|
||||||
|
|
||||||
|
export type NIP10Result = {
|
||||||
|
/**
|
||||||
|
* Pointer to the root of the thread.
|
||||||
|
*/
|
||||||
|
root: EventPointer | undefined
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pointer to a "parent" event that parsed event replies to (responded to).
|
||||||
|
*/
|
||||||
|
reply: EventPointer | undefined
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pointers to events which may or may not be in the reply chain.
|
||||||
|
*/
|
||||||
|
mentions: EventPointer[]
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List of pubkeys that are involved in the thread in no particular order.
|
||||||
|
*/
|
||||||
|
profiles: ProfilePointer[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parse(event: Pick<Event, 'tags'>): NIP10Result {
|
||||||
|
const result: NIP10Result = {
|
||||||
|
reply: undefined,
|
||||||
|
root: undefined,
|
||||||
|
mentions: [],
|
||||||
|
profiles: []
|
||||||
|
}
|
||||||
|
|
||||||
|
const eTags: string[][] = []
|
||||||
|
|
||||||
|
for (const tag of event.tags) {
|
||||||
|
if (tag[0] === 'e' && tag[1]) {
|
||||||
|
eTags.push(tag)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tag[0] === 'p' && tag[1]) {
|
||||||
|
result.profiles.push({
|
||||||
|
pubkey: tag[1],
|
||||||
|
relays: tag[2] ? [tag[2]] : []
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let eTagIndex = 0; eTagIndex < eTags.length; eTagIndex++) {
|
||||||
|
const eTag = eTags[eTagIndex]
|
||||||
|
|
||||||
|
const [_, eTagEventId, eTagRelayUrl, eTagMarker] = eTag as [
|
||||||
|
string,
|
||||||
|
string,
|
||||||
|
undefined | string,
|
||||||
|
undefined | string
|
||||||
|
]
|
||||||
|
|
||||||
|
const eventPointer: EventPointer = {
|
||||||
|
id: eTagEventId,
|
||||||
|
relays: eTagRelayUrl ? [eTagRelayUrl] : []
|
||||||
|
}
|
||||||
|
|
||||||
|
const isFirstETag = eTagIndex === 0
|
||||||
|
const isLastETag = eTagIndex === eTags.length - 1
|
||||||
|
|
||||||
|
if (eTagMarker === 'root') {
|
||||||
|
result.root = eventPointer
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if (eTagMarker === 'reply') {
|
||||||
|
result.reply = eventPointer
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if (eTagMarker === 'mention') {
|
||||||
|
result.mentions.push(eventPointer)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isFirstETag) {
|
||||||
|
result.root = eventPointer
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isLastETag) {
|
||||||
|
result.reply = eventPointer
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
result.mentions.push(eventPointer)
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
8
nip13.test.js
Normal file
8
nip13.test.js
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
/* eslint-env jest */
|
||||||
|
const {nip13} = require('./lib/nostr.cjs')
|
||||||
|
|
||||||
|
test('identifies proof-of-work difficulty', async () => {
|
||||||
|
const id = '000006d8c378af1779d2feebc7603a125d99eca0ccf1085959b307f64e5dd358'
|
||||||
|
const difficulty = nip13.getPow(id)
|
||||||
|
expect(difficulty).toEqual(21)
|
||||||
|
})
|
||||||
42
nip13.ts
Normal file
42
nip13.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import * as secp256k1 from '@noble/secp256k1'
|
||||||
|
|
||||||
|
/** Get POW difficulty from a Nostr hex ID. */
|
||||||
|
export function getPow(id: string): number {
|
||||||
|
return getLeadingZeroBits(secp256k1.utils.hexToBytes(id))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get number of leading 0 bits. Adapted from nostream.
|
||||||
|
* https://github.com/Cameri/nostream/blob/fb6948fd83ca87ce552f39f9b5eb780ea07e272e/src/utils/proof-of-work.ts
|
||||||
|
*/
|
||||||
|
function getLeadingZeroBits(hash: Uint8Array): number {
|
||||||
|
let total: number, i: number, bits: number
|
||||||
|
|
||||||
|
for (i = 0, total = 0; i < hash.length; i++) {
|
||||||
|
bits = msb(hash[i])
|
||||||
|
total += bits
|
||||||
|
if (bits !== 8) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return total
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adapted from nostream.
|
||||||
|
* https://github.com/Cameri/nostream/blob/fb6948fd83ca87ce552f39f9b5eb780ea07e272e/src/utils/proof-of-work.ts
|
||||||
|
*/
|
||||||
|
function msb(b: number) {
|
||||||
|
let n = 0
|
||||||
|
|
||||||
|
if (b === 0) {
|
||||||
|
return 8
|
||||||
|
}
|
||||||
|
|
||||||
|
// eslint-disable-next-line no-cond-assign
|
||||||
|
while (b >>= 1) {
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
|
||||||
|
return 7 - n
|
||||||
|
}
|
||||||
@@ -35,6 +35,21 @@ test('encode and decode nprofile', () => {
|
|||||||
expect(data.relays).toContain(relays[1])
|
expect(data.relays).toContain(relays[1])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('decode nprofile without relays', () => {
|
||||||
|
expect(
|
||||||
|
nip19.decode(
|
||||||
|
nip19.nprofileEncode({
|
||||||
|
pubkey:
|
||||||
|
'97c70a44366a6535c145b333f973ea86dfdc2d7a99da618c40c64705ad98e322',
|
||||||
|
relays: []
|
||||||
|
})
|
||||||
|
).data
|
||||||
|
).toHaveProperty(
|
||||||
|
'pubkey',
|
||||||
|
'97c70a44366a6535c145b333f973ea86dfdc2d7a99da618c40c64705ad98e322'
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
test('encode and decode naddr', () => {
|
test('encode and decode naddr', () => {
|
||||||
let pk = getPublicKey(generatePrivateKey())
|
let pk = getPublicKey(generatePrivateKey())
|
||||||
let relays = [
|
let relays = [
|
||||||
@@ -56,3 +71,41 @@ test('encode and decode naddr', () => {
|
|||||||
expect(data.kind).toEqual(30023)
|
expect(data.kind).toEqual(30023)
|
||||||
expect(data.identifier).toEqual('banana')
|
expect(data.identifier).toEqual('banana')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('decode naddr from habla.news', () => {
|
||||||
|
let {type, data} = nip19.decode(
|
||||||
|
'naddr1qq98yetxv4ex2mnrv4esygrl54h466tz4v0re4pyuavvxqptsejl0vxcmnhfl60z3rth2xkpjspsgqqqw4rsf34vl5'
|
||||||
|
)
|
||||||
|
expect(type).toEqual('naddr')
|
||||||
|
expect(data.pubkey).toEqual(
|
||||||
|
'7fa56f5d6962ab1e3cd424e758c3002b8665f7b0d8dcee9fe9e288d7751ac194'
|
||||||
|
)
|
||||||
|
expect(data.kind).toEqual(30023)
|
||||||
|
expect(data.identifier).toEqual('references')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('decode naddr from go-nostr with different TLV ordering', () => {
|
||||||
|
let {type, data} = nip19.decode(
|
||||||
|
'naddr1qqrxyctwv9hxzq3q80cvv07tjdrrgpa0j7j7tmnyl2yr6yr7l8j4s3evf6u64th6gkwsxpqqqp65wqfwwaehxw309aex2mrp0yhxummnw3ezuetcv9khqmr99ekhjer0d4skjm3wv4uxzmtsd3jjucm0d5q3vamnwvaz7tmwdaehgu3wvfskuctwvyhxxmmd0zfmwx'
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(type).toEqual('naddr')
|
||||||
|
expect(data.pubkey).toEqual(
|
||||||
|
'3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d'
|
||||||
|
)
|
||||||
|
expect(data.relays).toContain(
|
||||||
|
'wss://relay.nostr.example.mydomain.example.com'
|
||||||
|
)
|
||||||
|
expect(data.relays).toContain('wss://nostr.banana.com')
|
||||||
|
expect(data.kind).toEqual(30023)
|
||||||
|
expect(data.identifier).toEqual('banana')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('encode and decode nrelay', () => {
|
||||||
|
let url = "wss://relay.nostr.example"
|
||||||
|
let nrelay = nip19.nrelayEncode(url)
|
||||||
|
expect(nrelay).toMatch(/nrelay1\w+/)
|
||||||
|
let {type, data} = nip19.decode(nrelay)
|
||||||
|
expect(type).toEqual('nrelay')
|
||||||
|
expect(data).toEqual(url)
|
||||||
|
})
|
||||||
|
|||||||
47
nip19.ts
47
nip19.ts
@@ -13,6 +13,7 @@ export type ProfilePointer = {
|
|||||||
export type EventPointer = {
|
export type EventPointer = {
|
||||||
id: string // hex
|
id: string // hex
|
||||||
relays?: string[]
|
relays?: string[]
|
||||||
|
author?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AddressPointer = {
|
export type AddressPointer = {
|
||||||
@@ -22,10 +23,16 @@ export type AddressPointer = {
|
|||||||
relays?: string[]
|
relays?: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export function decode(nip19: string): {
|
export type DecodeResult =
|
||||||
type: string
|
| {type: 'nprofile'; data: ProfilePointer}
|
||||||
data: ProfilePointer | EventPointer | AddressPointer | string
|
| {type: 'nrelay'; data: string}
|
||||||
} {
|
| {type: 'nevent'; data: EventPointer}
|
||||||
|
| {type: 'naddr'; data: AddressPointer}
|
||||||
|
| {type: 'nsec'; data: string}
|
||||||
|
| {type: 'npub'; data: string}
|
||||||
|
| {type: 'note'; data: string}
|
||||||
|
|
||||||
|
export function decode(nip19: string): DecodeResult {
|
||||||
let {prefix, words} = bech32.decode(nip19, Bech32MaxSize)
|
let {prefix, words} = bech32.decode(nip19, Bech32MaxSize)
|
||||||
let data = new Uint8Array(bech32.fromWords(words))
|
let data = new Uint8Array(bech32.fromWords(words))
|
||||||
|
|
||||||
@@ -39,7 +46,7 @@ export function decode(nip19: string): {
|
|||||||
type: 'nprofile',
|
type: 'nprofile',
|
||||||
data: {
|
data: {
|
||||||
pubkey: secp256k1.utils.bytesToHex(tlv[0][0]),
|
pubkey: secp256k1.utils.bytesToHex(tlv[0][0]),
|
||||||
relays: tlv[1].map(d => utf8Decoder.decode(d))
|
relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : []
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -47,12 +54,17 @@ export function decode(nip19: string): {
|
|||||||
let tlv = parseTLV(data)
|
let tlv = parseTLV(data)
|
||||||
if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nevent')
|
if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nevent')
|
||||||
if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')
|
if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')
|
||||||
|
if (tlv[2] && tlv[2][0].length !== 32)
|
||||||
|
throw new Error('TLV 2 should be 32 bytes')
|
||||||
|
|
||||||
return {
|
return {
|
||||||
type: 'nevent',
|
type: 'nevent',
|
||||||
data: {
|
data: {
|
||||||
id: secp256k1.utils.bytesToHex(tlv[0][0]),
|
id: secp256k1.utils.bytesToHex(tlv[0][0]),
|
||||||
relays: tlv[1].map(d => utf8Decoder.decode(d))
|
relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],
|
||||||
|
author: tlv[2]?.[0]
|
||||||
|
? secp256k1.utils.bytesToHex(tlv[2][0])
|
||||||
|
: undefined
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -71,11 +83,21 @@ export function decode(nip19: string): {
|
|||||||
identifier: utf8Decoder.decode(tlv[0][0]),
|
identifier: utf8Decoder.decode(tlv[0][0]),
|
||||||
pubkey: secp256k1.utils.bytesToHex(tlv[2][0]),
|
pubkey: secp256k1.utils.bytesToHex(tlv[2][0]),
|
||||||
kind: parseInt(secp256k1.utils.bytesToHex(tlv[3][0]), 16),
|
kind: parseInt(secp256k1.utils.bytesToHex(tlv[3][0]), 16),
|
||||||
relays: tlv[1].map(d => utf8Decoder.decode(d))
|
relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : []
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case 'nrelay': {
|
||||||
|
let tlv = parseTLV(data)
|
||||||
|
if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nrelay')
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: 'nrelay',
|
||||||
|
data: utf8Decoder.decode(tlv[0][0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
case 'nsec':
|
case 'nsec':
|
||||||
case 'npub':
|
case 'npub':
|
||||||
case 'note':
|
case 'note':
|
||||||
@@ -133,7 +155,8 @@ export function nprofileEncode(profile: ProfilePointer): string {
|
|||||||
export function neventEncode(event: EventPointer): string {
|
export function neventEncode(event: EventPointer): string {
|
||||||
let data = encodeTLV({
|
let data = encodeTLV({
|
||||||
0: [secp256k1.utils.hexToBytes(event.id)],
|
0: [secp256k1.utils.hexToBytes(event.id)],
|
||||||
1: (event.relays || []).map(url => utf8Encoder.encode(url))
|
1: (event.relays || []).map(url => utf8Encoder.encode(url)),
|
||||||
|
2: event.author ? [secp256k1.utils.hexToBytes(event.author)] : []
|
||||||
})
|
})
|
||||||
let words = bech32.toWords(data)
|
let words = bech32.toWords(data)
|
||||||
return bech32.encode('nevent', words, Bech32MaxSize)
|
return bech32.encode('nevent', words, Bech32MaxSize)
|
||||||
@@ -153,6 +176,14 @@ export function naddrEncode(addr: AddressPointer): string {
|
|||||||
return bech32.encode('naddr', words, Bech32MaxSize)
|
return bech32.encode('naddr', words, Bech32MaxSize)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function nrelayEncode(url: string): string {
|
||||||
|
let data = encodeTLV({
|
||||||
|
0: [utf8Encoder.encode(url)]
|
||||||
|
})
|
||||||
|
let words = bech32.toWords(data)
|
||||||
|
return bech32.encode('nrelay', words, Bech32MaxSize)
|
||||||
|
}
|
||||||
|
|
||||||
function encodeTLV(tlv: TLV): Uint8Array {
|
function encodeTLV(tlv: TLV): Uint8Array {
|
||||||
let entries: Uint8Array[] = []
|
let entries: Uint8Array[] = []
|
||||||
|
|
||||||
|
|||||||
15
nip39.test.js
Normal file
15
nip39.test.js
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
/* eslint-env jest */
|
||||||
|
|
||||||
|
const fetch = require('node-fetch')
|
||||||
|
const {nip39} = require('./lib/nostr.cjs.js')
|
||||||
|
|
||||||
|
test('validate github claim', async () => {
|
||||||
|
nip39.useFetchImplementation(fetch)
|
||||||
|
|
||||||
|
let result = await nip39.validateGithub(
|
||||||
|
'npub1gcxzte5zlkncx26j68ez60fzkvtkm9e0vrwdcvsjakxf9mu9qewqlfnj5z',
|
||||||
|
'vitorpamplona',
|
||||||
|
'cf19e2d1d7f8dac6348ad37b35ec8421'
|
||||||
|
)
|
||||||
|
expect(result).toBe(true)
|
||||||
|
})
|
||||||
27
nip39.ts
Normal file
27
nip39.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
var _fetch: any
|
||||||
|
|
||||||
|
try {
|
||||||
|
_fetch = fetch
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
export function useFetchImplementation(fetchImplementation: any) {
|
||||||
|
_fetch = fetchImplementation
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function validateGithub(
|
||||||
|
pubkey: string,
|
||||||
|
username: string,
|
||||||
|
proof: string
|
||||||
|
): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
let res = await (
|
||||||
|
await _fetch(`https://gist.github.com/${username}/${proof}/raw`)
|
||||||
|
).text()
|
||||||
|
return (
|
||||||
|
res ===
|
||||||
|
`Verifying that I control the following Nostr public key: ${pubkey}`
|
||||||
|
)
|
||||||
|
} catch (_) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
27
nip42.test.js
Normal file
27
nip42.test.js
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
/* eslint-env jest */
|
||||||
|
|
||||||
|
require('websocket-polyfill')
|
||||||
|
const {
|
||||||
|
relayInit,
|
||||||
|
generatePrivateKey,
|
||||||
|
finishEvent,
|
||||||
|
nip42
|
||||||
|
} = require('./lib/nostr.cjs')
|
||||||
|
|
||||||
|
test('auth flow', done => {
|
||||||
|
const relay = relayInit('wss://nostr.kollider.xyz')
|
||||||
|
relay.connect()
|
||||||
|
const sk = generatePrivateKey()
|
||||||
|
|
||||||
|
relay.on('auth', async challenge => {
|
||||||
|
await expect(
|
||||||
|
nip42.authenticate({
|
||||||
|
challenge,
|
||||||
|
relay,
|
||||||
|
sign: e => finishEvent(e, sk)
|
||||||
|
})
|
||||||
|
).rejects.toBeTruthy()
|
||||||
|
relay.close()
|
||||||
|
done()
|
||||||
|
})
|
||||||
|
})
|
||||||
42
nip42.ts
Normal file
42
nip42.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import {EventTemplate, Event, Kind} from './event'
|
||||||
|
import {Relay} from './relay'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authenticate via NIP-42 flow.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const sign = window.nostr.signEvent
|
||||||
|
* relay.on('auth', challenge =>
|
||||||
|
* authenticate({ relay, sign, challenge })
|
||||||
|
* )
|
||||||
|
*/
|
||||||
|
export const authenticate = async ({
|
||||||
|
challenge,
|
||||||
|
relay,
|
||||||
|
sign
|
||||||
|
}: {
|
||||||
|
challenge: string
|
||||||
|
relay: Relay
|
||||||
|
sign: (e: EventTemplate) => Promise<Event>
|
||||||
|
}): Promise<void> => {
|
||||||
|
const e: EventTemplate = {
|
||||||
|
kind: Kind.ClientAuth,
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
tags: [
|
||||||
|
['relay', relay.url],
|
||||||
|
['challenge', challenge]
|
||||||
|
],
|
||||||
|
content: ''
|
||||||
|
}
|
||||||
|
const pub = relay.auth(await sign(e))
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
pub.on('ok', function ok() {
|
||||||
|
pub.off('ok', ok)
|
||||||
|
resolve()
|
||||||
|
})
|
||||||
|
pub.on('failed', function fail(reason: string) {
|
||||||
|
pub.off('failed', fail)
|
||||||
|
reject(reason)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
335
nip57.test.js
Normal file
335
nip57.test.js
Normal file
@@ -0,0 +1,335 @@
|
|||||||
|
const {bech32} = require('@scure/base')
|
||||||
|
const {
|
||||||
|
nip57,
|
||||||
|
generatePrivateKey,
|
||||||
|
getPublicKey,
|
||||||
|
finishEvent
|
||||||
|
} = require('./lib/nostr.cjs')
|
||||||
|
|
||||||
|
describe('getZapEndpoint', () => {
|
||||||
|
test('returns null if neither lud06 nor lud16 is present', async () => {
|
||||||
|
const metadata = {content: '{}'}
|
||||||
|
const result = await nip57.getZapEndpoint(metadata)
|
||||||
|
|
||||||
|
expect(result).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('returns null if fetch fails', async () => {
|
||||||
|
const fetchImplementation = jest.fn(() => Promise.reject(new Error()))
|
||||||
|
nip57.useFetchImplementation(fetchImplementation)
|
||||||
|
|
||||||
|
const metadata = {content: '{"lud16": "name@domain"}'}
|
||||||
|
const result = await nip57.getZapEndpoint(metadata)
|
||||||
|
|
||||||
|
expect(result).toBeNull()
|
||||||
|
expect(fetchImplementation).toHaveBeenCalledWith(
|
||||||
|
'https://domain/.well-known/lnurlp/name'
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('returns null if the response does not allow Nostr payments', async () => {
|
||||||
|
const fetchImplementation = jest.fn(() =>
|
||||||
|
Promise.resolve({json: () => ({allowsNostr: false})})
|
||||||
|
)
|
||||||
|
nip57.useFetchImplementation(fetchImplementation)
|
||||||
|
|
||||||
|
const metadata = {content: '{"lud16": "name@domain"}'}
|
||||||
|
const result = await nip57.getZapEndpoint(metadata)
|
||||||
|
|
||||||
|
expect(result).toBeNull()
|
||||||
|
expect(fetchImplementation).toHaveBeenCalledWith(
|
||||||
|
'https://domain/.well-known/lnurlp/name'
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('returns the callback URL if the response allows Nostr payments', async () => {
|
||||||
|
const fetchImplementation = jest.fn(() =>
|
||||||
|
Promise.resolve({
|
||||||
|
json: () => ({
|
||||||
|
allowsNostr: true,
|
||||||
|
nostrPubkey: 'pubkey',
|
||||||
|
callback: 'callback'
|
||||||
|
})
|
||||||
|
})
|
||||||
|
)
|
||||||
|
nip57.useFetchImplementation(fetchImplementation)
|
||||||
|
|
||||||
|
const metadata = {content: '{"lud16": "name@domain"}'}
|
||||||
|
const result = await nip57.getZapEndpoint(metadata)
|
||||||
|
|
||||||
|
expect(result).toBe('callback')
|
||||||
|
expect(fetchImplementation).toHaveBeenCalledWith(
|
||||||
|
'https://domain/.well-known/lnurlp/name'
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('makeZapRequest', () => {
|
||||||
|
test('throws an error if amount is not given', () => {
|
||||||
|
expect(() =>
|
||||||
|
nip57.makeZapRequest({
|
||||||
|
profile: 'profile',
|
||||||
|
event: null,
|
||||||
|
relays: [],
|
||||||
|
comment: ''
|
||||||
|
})
|
||||||
|
).toThrow()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('throws an error if profile is not given', () => {
|
||||||
|
expect(() =>
|
||||||
|
nip57.makeZapRequest({
|
||||||
|
event: null,
|
||||||
|
amount: 100,
|
||||||
|
relays: [],
|
||||||
|
comment: ''
|
||||||
|
})
|
||||||
|
).toThrow()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('returns a valid Zap request', () => {
|
||||||
|
const result = nip57.makeZapRequest({
|
||||||
|
profile: 'profile',
|
||||||
|
event: 'event',
|
||||||
|
amount: 100,
|
||||||
|
relays: ['relay1', 'relay2'],
|
||||||
|
comment: 'comment'
|
||||||
|
})
|
||||||
|
expect(result.kind).toBe(9734)
|
||||||
|
expect(result.created_at).toBeCloseTo(Date.now() / 1000, 0)
|
||||||
|
expect(result.content).toBe('comment')
|
||||||
|
expect(result.tags).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
['p', 'profile'],
|
||||||
|
['amount', '100'],
|
||||||
|
['relays', 'relay1', 'relay2']
|
||||||
|
])
|
||||||
|
)
|
||||||
|
expect(result.tags).toContainEqual(['e', 'event'])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('validateZapRequest', () => {
|
||||||
|
test('returns an error message for invalid JSON', () => {
|
||||||
|
expect(nip57.validateZapRequest('invalid JSON')).toBe(
|
||||||
|
'Invalid zap request JSON.'
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('returns an error message if the Zap request is not a valid Nostr event', () => {
|
||||||
|
const zapRequest = {
|
||||||
|
kind: 1234,
|
||||||
|
created_at: Date.now() / 1000,
|
||||||
|
content: 'content',
|
||||||
|
tags: [
|
||||||
|
['p', 'profile'],
|
||||||
|
['amount', '100'],
|
||||||
|
['relays', 'relay1', 'relay2']
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(nip57.validateZapRequest(JSON.stringify(zapRequest))).toBe(
|
||||||
|
'Zap request is not a valid Nostr event.'
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('returns an error message if the signature on the Zap request is invalid', () => {
|
||||||
|
const privateKey = generatePrivateKey()
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const zapRequest = {
|
||||||
|
pubkey: publicKey,
|
||||||
|
kind: 9734,
|
||||||
|
created_at: Date.now() / 1000,
|
||||||
|
content: 'content',
|
||||||
|
tags: [
|
||||||
|
['p', publicKey],
|
||||||
|
['amount', '100'],
|
||||||
|
['relays', 'relay1', 'relay2']
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(nip57.validateZapRequest(JSON.stringify(zapRequest))).toBe(
|
||||||
|
'Invalid signature on zap request.'
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('returns an error message if the Zap request does not have a "p" tag', () => {
|
||||||
|
const privateKey = generatePrivateKey()
|
||||||
|
|
||||||
|
const zapRequest = finishEvent(
|
||||||
|
{
|
||||||
|
kind: 9734,
|
||||||
|
created_at: Date.now() / 1000,
|
||||||
|
content: 'content',
|
||||||
|
tags: [
|
||||||
|
['amount', '100'],
|
||||||
|
['relays', 'relay1', 'relay2']
|
||||||
|
]
|
||||||
|
},
|
||||||
|
privateKey
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(nip57.validateZapRequest(JSON.stringify(zapRequest))).toBe(
|
||||||
|
"Zap request doesn't have a 'p' tag."
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('returns an error message if the "p" tag on the Zap request is not valid hex', () => {
|
||||||
|
const privateKey = generatePrivateKey()
|
||||||
|
|
||||||
|
const zapRequest = finishEvent(
|
||||||
|
{
|
||||||
|
kind: 9734,
|
||||||
|
created_at: Date.now() / 1000,
|
||||||
|
content: 'content',
|
||||||
|
tags: [
|
||||||
|
['p', 'invalid hex'],
|
||||||
|
['amount', '100'],
|
||||||
|
['relays', 'relay1', 'relay2']
|
||||||
|
]
|
||||||
|
},
|
||||||
|
privateKey
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(nip57.validateZapRequest(JSON.stringify(zapRequest))).toBe(
|
||||||
|
"Zap request 'p' tag is not valid hex."
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('returns an error message if the "e" tag on the Zap request is not valid hex', () => {
|
||||||
|
const privateKey = generatePrivateKey()
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const zapRequest = finishEvent(
|
||||||
|
{
|
||||||
|
kind: 9734,
|
||||||
|
created_at: Date.now() / 1000,
|
||||||
|
content: 'content',
|
||||||
|
tags: [
|
||||||
|
['p', publicKey],
|
||||||
|
['e', 'invalid hex'],
|
||||||
|
['amount', '100'],
|
||||||
|
['relays', 'relay1', 'relay2']
|
||||||
|
]
|
||||||
|
},
|
||||||
|
privateKey
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(nip57.validateZapRequest(JSON.stringify(zapRequest))).toBe(
|
||||||
|
"Zap request 'e' tag is not valid hex."
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('returns an error message if the Zap request does not have a relays tag', () => {
|
||||||
|
const privateKey = generatePrivateKey()
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const zapRequest = finishEvent(
|
||||||
|
{
|
||||||
|
kind: 9734,
|
||||||
|
created_at: Date.now() / 1000,
|
||||||
|
content: 'content',
|
||||||
|
tags: [
|
||||||
|
['p', publicKey],
|
||||||
|
['amount', '100']
|
||||||
|
]
|
||||||
|
},
|
||||||
|
privateKey
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(nip57.validateZapRequest(JSON.stringify(zapRequest))).toBe(
|
||||||
|
"Zap request doesn't have a 'relays' tag."
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('returns null for a valid Zap request', () => {
|
||||||
|
const privateKey = generatePrivateKey()
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const zapRequest = finishEvent(
|
||||||
|
{
|
||||||
|
kind: 9734,
|
||||||
|
created_at: Date.now() / 1000,
|
||||||
|
content: 'content',
|
||||||
|
tags: [
|
||||||
|
['p', publicKey],
|
||||||
|
['amount', '100'],
|
||||||
|
['relays', 'relay1', 'relay2']
|
||||||
|
]
|
||||||
|
},
|
||||||
|
privateKey
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(nip57.validateZapRequest(JSON.stringify(zapRequest))).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('makeZapReceipt', () => {
|
||||||
|
test('returns a valid Zap receipt with a preimage', () => {
|
||||||
|
const privateKey = generatePrivateKey()
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const zapRequest = JSON.stringify(
|
||||||
|
finishEvent(
|
||||||
|
{
|
||||||
|
kind: 9734,
|
||||||
|
created_at: Date.now() / 1000,
|
||||||
|
content: 'content',
|
||||||
|
tags: [
|
||||||
|
['p', publicKey],
|
||||||
|
['amount', '100'],
|
||||||
|
['relays', 'relay1', 'relay2']
|
||||||
|
]
|
||||||
|
},
|
||||||
|
privateKey
|
||||||
|
)
|
||||||
|
)
|
||||||
|
const preimage = 'preimage'
|
||||||
|
const bolt11 = 'bolt11'
|
||||||
|
const paidAt = new Date()
|
||||||
|
|
||||||
|
const result = nip57.makeZapReceipt({zapRequest, preimage, bolt11, paidAt})
|
||||||
|
|
||||||
|
expect(result.kind).toBe(9735)
|
||||||
|
expect(result.created_at).toBeCloseTo(paidAt.getTime() / 1000, 0)
|
||||||
|
expect(result.content).toBe('')
|
||||||
|
expect(result.tags).toContainEqual(['bolt11', bolt11])
|
||||||
|
expect(result.tags).toContainEqual(['description', zapRequest])
|
||||||
|
expect(result.tags).toContainEqual(['p', publicKey])
|
||||||
|
expect(result.tags).toContainEqual(['preimage', preimage])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('returns a valid Zap receipt without a preimage', () => {
|
||||||
|
const privateKey = generatePrivateKey()
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const zapRequest = JSON.stringify(
|
||||||
|
finishEvent(
|
||||||
|
{
|
||||||
|
kind: 9734,
|
||||||
|
created_at: Date.now() / 1000,
|
||||||
|
content: 'content',
|
||||||
|
tags: [
|
||||||
|
['p', publicKey],
|
||||||
|
['amount', '100'],
|
||||||
|
['relays', 'relay1', 'relay2']
|
||||||
|
]
|
||||||
|
},
|
||||||
|
privateKey
|
||||||
|
)
|
||||||
|
)
|
||||||
|
const bolt11 = 'bolt11'
|
||||||
|
const paidAt = new Date()
|
||||||
|
|
||||||
|
const result = nip57.makeZapReceipt({zapRequest, bolt11, paidAt})
|
||||||
|
|
||||||
|
expect(result.kind).toBe(9735)
|
||||||
|
expect(result.created_at).toBeCloseTo(paidAt.getTime() / 1000, 0)
|
||||||
|
expect(result.content).toBe('')
|
||||||
|
expect(result.tags).toContainEqual(['bolt11', bolt11])
|
||||||
|
expect(result.tags).toContainEqual(['description', zapRequest])
|
||||||
|
expect(result.tags).toContainEqual(['p', publicKey])
|
||||||
|
expect(result.tags).not.toContain('preimage')
|
||||||
|
})
|
||||||
|
})
|
||||||
26
package.json
26
package.json
@@ -1,24 +1,28 @@
|
|||||||
{
|
{
|
||||||
"name": "nostr-tools",
|
"name": "nostr-tools",
|
||||||
"version": "1.6.0",
|
"version": "1.10.0",
|
||||||
"description": "Tools for making a Nostr client.",
|
"description": "Tools for making a Nostr client.",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://github.com/fiatjaf/nostr-tools.git"
|
"url": "https://github.com/nbd-wtf/nostr-tools.git"
|
||||||
},
|
},
|
||||||
|
"files": [
|
||||||
|
"./lib/**/*"
|
||||||
|
],
|
||||||
|
"types": "./lib/index.d.ts",
|
||||||
"main": "lib/nostr.cjs.js",
|
"main": "lib/nostr.cjs.js",
|
||||||
"module": "lib/esm/nostr.mjs",
|
"module": "lib/esm/nostr.mjs",
|
||||||
"exports": {
|
"exports": {
|
||||||
"import": "./lib/esm/nostr.mjs",
|
"import": "./lib/esm/nostr.mjs",
|
||||||
"require": "./lib/nostr.cjs.js"
|
"require": "./lib/nostr.cjs.js"
|
||||||
},
|
},
|
||||||
|
"license": "Public domain",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@noble/hashes": "1.0.0",
|
"@noble/hashes": "1.2.0",
|
||||||
"@noble/secp256k1": "^1.7.1",
|
"@noble/secp256k1": "1.7.1",
|
||||||
"@scure/base": "^1.1.1",
|
"@scure/base": "1.1.1",
|
||||||
"@scure/bip32": "^1.1.5",
|
"@scure/bip32": "1.1.4",
|
||||||
"@scure/bip39": "^1.1.1",
|
"@scure/bip39": "1.1.1"
|
||||||
"prettier": "^2.8.4"
|
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"decentralization",
|
"decentralization",
|
||||||
@@ -27,6 +31,11 @@
|
|||||||
"client",
|
"client",
|
||||||
"nostr"
|
"nostr"
|
||||||
],
|
],
|
||||||
|
"scripts": {
|
||||||
|
"build": "node build",
|
||||||
|
"format": "prettier --plugin-search-dir . --write .",
|
||||||
|
"test": "node build && jest"
|
||||||
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^18.13.0",
|
"@types/node": "^18.13.0",
|
||||||
"@typescript-eslint/eslint-plugin": "^5.51.0",
|
"@typescript-eslint/eslint-plugin": "^5.51.0",
|
||||||
@@ -39,6 +48,7 @@
|
|||||||
"events": "^3.3.0",
|
"events": "^3.3.0",
|
||||||
"jest": "^29.4.2",
|
"jest": "^29.4.2",
|
||||||
"node-fetch": "^2.6.9",
|
"node-fetch": "^2.6.9",
|
||||||
|
"prettier": "^2.8.4",
|
||||||
"ts-jest": "^29.0.5",
|
"ts-jest": "^29.0.5",
|
||||||
"tsd": "^0.22.0",
|
"tsd": "^0.22.0",
|
||||||
"typescript": "^4.9.5",
|
"typescript": "^4.9.5",
|
||||||
|
|||||||
@@ -12,17 +12,17 @@ const {
|
|||||||
let pool = new SimplePool()
|
let pool = new SimplePool()
|
||||||
|
|
||||||
let relays = [
|
let relays = [
|
||||||
'wss://nostr-dev.wellorder.net/',
|
'wss://relay.damus.io/',
|
||||||
'wss://relay.nostr.bg/',
|
'wss://relay.nostr.bg/',
|
||||||
'wss://nostr.fmt.wiz.biz/',
|
'wss://nostr.fmt.wiz.biz/',
|
||||||
'wss://relay.nostr.band/',
|
'wss://relay.nostr.band/',
|
||||||
'wss://nostr.zebedee.cloud/'
|
'wss://nos.lol/'
|
||||||
]
|
]
|
||||||
|
|
||||||
afterAll(() => {
|
afterAll(() => {
|
||||||
pool.close([
|
pool.close([
|
||||||
...relays,
|
...relays,
|
||||||
'wss://nostr-relay.untethr.me',
|
'wss://nostr.wine',
|
||||||
'wss://offchain.pub',
|
'wss://offchain.pub',
|
||||||
'wss://eden.nostr.land'
|
'wss://eden.nostr.land'
|
||||||
])
|
])
|
||||||
|
|||||||
116
pool.ts
116
pool.ts
@@ -2,40 +2,50 @@ import {Relay, relayInit} from './relay'
|
|||||||
import {normalizeURL} from './utils'
|
import {normalizeURL} from './utils'
|
||||||
import {Filter} from './filter'
|
import {Filter} from './filter'
|
||||||
import {Event} from './event'
|
import {Event} from './event'
|
||||||
import {SubscriptionOptions, Sub, Pub} from './relay'
|
import {SubscriptionOptions, Sub, Pub, CountPayload} from './relay'
|
||||||
|
|
||||||
export class SimplePool {
|
export class SimplePool {
|
||||||
private _conn: {[url: string]: Relay}
|
private _conn: {[url: string]: Relay}
|
||||||
private _seenOn: {[id: string]: Set<string>} = {} // a map of all events we've seen in each relay
|
private _seenOn: {[id: string]: Set<string>} = {} // a map of all events we've seen in each relay
|
||||||
|
|
||||||
constructor() {
|
private eoseSubTimeout: number
|
||||||
|
private getTimeout: number
|
||||||
|
|
||||||
|
constructor(options: {eoseSubTimeout?: number; getTimeout?: number} = {}) {
|
||||||
this._conn = {}
|
this._conn = {}
|
||||||
|
this.eoseSubTimeout = options.eoseSubTimeout || 3400
|
||||||
|
this.getTimeout = options.getTimeout || 3400
|
||||||
}
|
}
|
||||||
|
|
||||||
close(relays: string[]): void {
|
close(relays: string[]): void {
|
||||||
relays.map(url => {
|
relays.forEach(url => {
|
||||||
let relay = this._conn[normalizeURL(url)]
|
let relay = this._conn[normalizeURL(url)]
|
||||||
if (relay) relay.close()
|
if (relay) relay.close()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async ensureRelay(url: string): Promise<Relay> {
|
async ensureRelay(url: string): Promise<Relay> {
|
||||||
const nm = normalizeURL(url)
|
const nm = normalizeURL(url)
|
||||||
const existing = this._conn[nm]
|
|
||||||
if (existing) return existing
|
|
||||||
|
|
||||||
const relay = relayInit(nm)
|
if (!this._conn[nm]) {
|
||||||
this._conn[nm] = relay
|
this._conn[nm] = relayInit(nm, {
|
||||||
|
getTimeout: this.getTimeout * 0.9,
|
||||||
|
listTimeout: this.getTimeout * 0.9
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const relay = this._conn[nm]
|
||||||
await relay.connect()
|
await relay.connect()
|
||||||
|
|
||||||
return relay
|
return relay
|
||||||
}
|
}
|
||||||
|
|
||||||
sub(relays: string[], filters: Filter[], opts?: SubscriptionOptions): Sub {
|
sub(relays: string[], filters: Filter[], opts?: SubscriptionOptions): Sub {
|
||||||
let _knownIds: Set<string> = new Set()
|
let _knownIds: Set<string> = new Set()
|
||||||
let modifiedOpts = opts || {}
|
let modifiedOpts = {...(opts || {})}
|
||||||
modifiedOpts.alreadyHaveEvent = (id, url) => {
|
modifiedOpts.alreadyHaveEvent = (id, url) => {
|
||||||
|
if (opts?.alreadyHaveEvent?.(id, url)) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
let set = this._seenOn[id] || new Set()
|
let set = this._seenOn[id] || new Set()
|
||||||
set.add(url)
|
set.add(url)
|
||||||
this._seenOn[id] = set
|
this._seenOn[id] = set
|
||||||
@@ -43,7 +53,7 @@ export class SimplePool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let subs: Sub[] = []
|
let subs: Sub[] = []
|
||||||
let eventListeners: Set<(event: Event) => void> = new Set()
|
let eventListeners: Set<any> = new Set()
|
||||||
let eoseListeners: Set<() => void> = new Set()
|
let eoseListeners: Set<() => void> = new Set()
|
||||||
let eosesMissing = relays.length
|
let eosesMissing = relays.length
|
||||||
|
|
||||||
@@ -51,10 +61,16 @@ export class SimplePool {
|
|||||||
let eoseTimeout = setTimeout(() => {
|
let eoseTimeout = setTimeout(() => {
|
||||||
eoseSent = true
|
eoseSent = true
|
||||||
for (let cb of eoseListeners.values()) cb()
|
for (let cb of eoseListeners.values()) cb()
|
||||||
}, 2400)
|
}, this.eoseSubTimeout)
|
||||||
|
|
||||||
relays.forEach(async relay => {
|
relays.forEach(async relay => {
|
||||||
let r = await this.ensureRelay(relay)
|
let r
|
||||||
|
try {
|
||||||
|
r = await this.ensureRelay(relay)
|
||||||
|
} catch (err) {
|
||||||
|
handleEose()
|
||||||
|
return
|
||||||
|
}
|
||||||
if (!r) return
|
if (!r) return
|
||||||
let s = r.sub(filters, modifiedOpts)
|
let s = r.sub(filters, modifiedOpts)
|
||||||
s.on('event', (event: Event) => {
|
s.on('event', (event: Event) => {
|
||||||
@@ -63,14 +79,17 @@ export class SimplePool {
|
|||||||
})
|
})
|
||||||
s.on('eose', () => {
|
s.on('eose', () => {
|
||||||
if (eoseSent) return
|
if (eoseSent) return
|
||||||
|
handleEose()
|
||||||
|
})
|
||||||
|
subs.push(s)
|
||||||
|
|
||||||
|
function handleEose() {
|
||||||
eosesMissing--
|
eosesMissing--
|
||||||
if (eosesMissing === 0) {
|
if (eosesMissing === 0) {
|
||||||
clearTimeout(eoseTimeout)
|
clearTimeout(eoseTimeout)
|
||||||
for (let cb of eoseListeners.values()) cb()
|
for (let cb of eoseListeners.values()) cb()
|
||||||
}
|
}
|
||||||
})
|
}
|
||||||
subs.push(s)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
let greaterSub: Sub = {
|
let greaterSub: Sub = {
|
||||||
@@ -82,19 +101,17 @@ export class SimplePool {
|
|||||||
subs.forEach(sub => sub.unsub())
|
subs.forEach(sub => sub.unsub())
|
||||||
},
|
},
|
||||||
on(type, cb) {
|
on(type, cb) {
|
||||||
switch (type) {
|
if (type === 'event') {
|
||||||
case 'event':
|
eventListeners.add(cb)
|
||||||
eventListeners.add(cb)
|
} else if (type === 'eose') {
|
||||||
break
|
eoseListeners.add(cb as () => void | Promise<void>)
|
||||||
case 'eose':
|
|
||||||
eoseListeners.add(cb)
|
|
||||||
break
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
off(type, cb) {
|
off(type, cb) {
|
||||||
if (type === 'event') {
|
if (type === 'event') {
|
||||||
eventListeners.delete(cb)
|
eventListeners.delete(cb)
|
||||||
} else if (type === 'eose') eoseListeners.delete(cb)
|
} else if (type === 'eose')
|
||||||
|
eoseListeners.delete(cb as () => void | Promise<void>)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,7 +128,7 @@ export class SimplePool {
|
|||||||
let timeout = setTimeout(() => {
|
let timeout = setTimeout(() => {
|
||||||
sub.unsub()
|
sub.unsub()
|
||||||
resolve(null)
|
resolve(null)
|
||||||
}, 1500)
|
}, this.getTimeout)
|
||||||
sub.on('event', (event: Event) => {
|
sub.on('event', (event: Event) => {
|
||||||
resolve(event)
|
resolve(event)
|
||||||
clearTimeout(timeout)
|
clearTimeout(timeout)
|
||||||
@@ -141,25 +158,42 @@ export class SimplePool {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
publish(relays: string[], event: Event): Pub[] {
|
publish(relays: string[], event: Event): Pub {
|
||||||
return relays.map(relay => {
|
const pubPromises: Promise<Pub>[] = relays.map(async relay => {
|
||||||
let r = this._conn[normalizeURL(relay)]
|
let r
|
||||||
if (!r) return badPub(relay)
|
try {
|
||||||
let s = r.publish(event)
|
r = await this.ensureRelay(relay)
|
||||||
return s
|
return r.publish(event)
|
||||||
|
} catch (_) {
|
||||||
|
return {on() {}, off() {}}
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const callbackMap = new Map()
|
||||||
|
|
||||||
|
return {
|
||||||
|
on(type, cb) {
|
||||||
|
relays.forEach(async (relay, i) => {
|
||||||
|
let pub = await pubPromises[i]
|
||||||
|
let callback = () => cb(relay)
|
||||||
|
callbackMap.set(cb, callback)
|
||||||
|
pub.on(type, callback)
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
off(type, cb) {
|
||||||
|
relays.forEach(async (_, i) => {
|
||||||
|
let callback = callbackMap.get(cb)
|
||||||
|
if (callback) {
|
||||||
|
let pub = await pubPromises[i]
|
||||||
|
pub.off(type, callback)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
seenOn(id: string): string[] {
|
seenOn(id: string): string[] {
|
||||||
return Array.from(this._seenOn[id]?.values?.() || [])
|
return Array.from(this._seenOn[id]?.values?.() || [])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function badPub(relay: string): Pub {
|
|
||||||
return {
|
|
||||||
on(typ, cb) {
|
|
||||||
if (typ === 'failed') cb(`relay ${relay} not connected`)
|
|
||||||
},
|
|
||||||
off() {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
62
references.test.js
Normal file
62
references.test.js
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
/* eslint-env jest */
|
||||||
|
|
||||||
|
const {parseReferences} = require('./lib/nostr.cjs')
|
||||||
|
|
||||||
|
test('parse mentions', () => {
|
||||||
|
let evt = {
|
||||||
|
tags: [
|
||||||
|
[
|
||||||
|
'p',
|
||||||
|
'c9d556c6d3978d112d30616d0d20aaa81410e3653911dd67787b5aaf9b36ade8',
|
||||||
|
'wss://nostr.com'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'e',
|
||||||
|
'a84c5de86efc2ec2cff7bad077c4171e09146b633b7ad117fffe088d9579ac33',
|
||||||
|
'wss://other.com',
|
||||||
|
'reply'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'e',
|
||||||
|
'31d7c2875b5fc8e6f9c8f9dc1f84de1b6b91d1947ea4c59225e55c325d330fa8',
|
||||||
|
''
|
||||||
|
]
|
||||||
|
],
|
||||||
|
content:
|
||||||
|
'hello #[0], have you seen #[2]? it was made by nostr:nprofile1qqsvc6ulagpn7kwrcwdqgp797xl7usumqa6s3kgcelwq6m75x8fe8yc5usxdg on nostr:nevent1qqsvc6ulagpn7kwrcwdqgp797xl7usumqa6s3kgcelwq6m75x8fe8ychxp5v4! broken #[3]'
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(parseReferences(evt)).toEqual([
|
||||||
|
{
|
||||||
|
text: '#[0]',
|
||||||
|
profile: {
|
||||||
|
pubkey:
|
||||||
|
'c9d556c6d3978d112d30616d0d20aaa81410e3653911dd67787b5aaf9b36ade8',
|
||||||
|
relays: ['wss://nostr.com']
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
text: '#[2]',
|
||||||
|
event: {
|
||||||
|
id: '31d7c2875b5fc8e6f9c8f9dc1f84de1b6b91d1947ea4c59225e55c325d330fa8',
|
||||||
|
relays: []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
text: 'nostr:nprofile1qqsvc6ulagpn7kwrcwdqgp797xl7usumqa6s3kgcelwq6m75x8fe8yc5usxdg',
|
||||||
|
profile: {
|
||||||
|
pubkey:
|
||||||
|
'cc6b9fea033f59c3c39a0407c5f1bfee439b077508d918cfdc0d6fd431d39393',
|
||||||
|
relays: []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
text: 'nostr:nevent1qqsvc6ulagpn7kwrcwdqgp797xl7usumqa6s3kgcelwq6m75x8fe8ychxp5v4',
|
||||||
|
event: {
|
||||||
|
id: 'cc6b9fea033f59c3c39a0407c5f1bfee439b077508d918cfdc0d6fd431d39393',
|
||||||
|
relays: [],
|
||||||
|
author: undefined
|
||||||
|
}
|
||||||
|
}
|
||||||
|
])
|
||||||
|
})
|
||||||
104
references.ts
Normal file
104
references.ts
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
import {Event} from './event'
|
||||||
|
import {decode, AddressPointer, ProfilePointer, EventPointer} from './nip19'
|
||||||
|
|
||||||
|
type Reference = {
|
||||||
|
text: string
|
||||||
|
profile?: ProfilePointer
|
||||||
|
event?: EventPointer
|
||||||
|
address?: AddressPointer
|
||||||
|
}
|
||||||
|
|
||||||
|
const mentionRegex =
|
||||||
|
/\bnostr:((note|npub|naddr|nevent|nprofile)1\w+)\b|#\[(\d+)\]/g
|
||||||
|
|
||||||
|
export function parseReferences(evt: Event): Reference[] {
|
||||||
|
let references: Reference[] = []
|
||||||
|
for (let ref of evt.content.matchAll(mentionRegex)) {
|
||||||
|
if (ref[2]) {
|
||||||
|
// it's a NIP-27 mention
|
||||||
|
try {
|
||||||
|
let {type, data} = decode(ref[1])
|
||||||
|
switch (type) {
|
||||||
|
case 'npub': {
|
||||||
|
references.push({
|
||||||
|
text: ref[0],
|
||||||
|
profile: {pubkey: data as string, relays: []}
|
||||||
|
})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case 'nprofile': {
|
||||||
|
references.push({
|
||||||
|
text: ref[0],
|
||||||
|
profile: data as ProfilePointer
|
||||||
|
})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case 'note': {
|
||||||
|
references.push({
|
||||||
|
text: ref[0],
|
||||||
|
event: {id: data as string, relays: []}
|
||||||
|
})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case 'nevent': {
|
||||||
|
references.push({
|
||||||
|
text: ref[0],
|
||||||
|
event: data as EventPointer
|
||||||
|
})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case 'naddr': {
|
||||||
|
references.push({
|
||||||
|
text: ref[0],
|
||||||
|
address: data as AddressPointer
|
||||||
|
})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
/***/
|
||||||
|
}
|
||||||
|
} else if (ref[3]) {
|
||||||
|
// it's a NIP-10 mention
|
||||||
|
let idx = parseInt(ref[3], 10)
|
||||||
|
let tag = evt.tags[idx]
|
||||||
|
if (!tag) continue
|
||||||
|
|
||||||
|
switch (tag[0]) {
|
||||||
|
case 'p': {
|
||||||
|
references.push({
|
||||||
|
text: ref[0],
|
||||||
|
profile: {pubkey: tag[1], relays: tag[2] ? [tag[2]] : []}
|
||||||
|
})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case 'e': {
|
||||||
|
references.push({
|
||||||
|
text: ref[0],
|
||||||
|
event: {id: tag[1], relays: tag[2] ? [tag[2]] : []}
|
||||||
|
})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case 'a': {
|
||||||
|
try {
|
||||||
|
let [kind, pubkey, identifier] = tag[1].split(':')
|
||||||
|
references.push({
|
||||||
|
text: ref[0],
|
||||||
|
address: {
|
||||||
|
identifier,
|
||||||
|
pubkey,
|
||||||
|
kind: parseInt(kind, 10),
|
||||||
|
relays: tag[2] ? [tag[2]] : []
|
||||||
|
}
|
||||||
|
})
|
||||||
|
} catch (err) {
|
||||||
|
/***/
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return references
|
||||||
|
}
|
||||||
@@ -9,7 +9,7 @@ const {
|
|||||||
signEvent
|
signEvent
|
||||||
} = require('./lib/nostr.cjs')
|
} = require('./lib/nostr.cjs')
|
||||||
|
|
||||||
let relay = relayInit('wss://nostr-dev.wellorder.net/')
|
let relay = relayInit('wss://relay.damus.io/')
|
||||||
|
|
||||||
beforeAll(() => {
|
beforeAll(() => {
|
||||||
relay.connect()
|
relay.connect()
|
||||||
|
|||||||
222
relay.ts
222
relay.ts
@@ -4,8 +4,21 @@ import {Event, verifySignature, validateEvent} from './event'
|
|||||||
import {Filter, matchFilters} from './filter'
|
import {Filter, matchFilters} from './filter'
|
||||||
import {getHex64, getSubscriptionId} from './fakejson'
|
import {getHex64, getSubscriptionId} from './fakejson'
|
||||||
|
|
||||||
type RelayEvent = 'connect' | 'disconnect' | 'error' | 'notice'
|
type RelayEvent = {
|
||||||
|
connect: () => void | Promise<void>
|
||||||
|
disconnect: () => void | Promise<void>
|
||||||
|
error: () => void | Promise<void>
|
||||||
|
notice: (msg: string) => void | Promise<void>
|
||||||
|
auth: (challenge: string) => void | Promise<void>
|
||||||
|
}
|
||||||
|
export type CountPayload = {
|
||||||
|
count: number
|
||||||
|
}
|
||||||
|
type SubEvent = {
|
||||||
|
event: (event: Event) => void | Promise<void>
|
||||||
|
count: (payload: CountPayload) => void | Promise<void>
|
||||||
|
eose: () => void | Promise<void>
|
||||||
|
}
|
||||||
export type Relay = {
|
export type Relay = {
|
||||||
url: string
|
url: string
|
||||||
status: number
|
status: number
|
||||||
@@ -14,9 +27,20 @@ export type Relay = {
|
|||||||
sub: (filters: Filter[], opts?: SubscriptionOptions) => Sub
|
sub: (filters: Filter[], opts?: SubscriptionOptions) => Sub
|
||||||
list: (filters: Filter[], opts?: SubscriptionOptions) => Promise<Event[]>
|
list: (filters: Filter[], opts?: SubscriptionOptions) => Promise<Event[]>
|
||||||
get: (filter: Filter, opts?: SubscriptionOptions) => Promise<Event | null>
|
get: (filter: Filter, opts?: SubscriptionOptions) => Promise<Event | null>
|
||||||
|
count: (
|
||||||
|
filters: Filter[],
|
||||||
|
opts?: SubscriptionOptions
|
||||||
|
) => Promise<CountPayload | null>
|
||||||
publish: (event: Event) => Pub
|
publish: (event: Event) => Pub
|
||||||
on: (type: RelayEvent, cb: any) => void
|
auth: (event: Event) => Pub
|
||||||
off: (type: RelayEvent, cb: any) => void
|
off: <T extends keyof RelayEvent, U extends RelayEvent[T]>(
|
||||||
|
event: T,
|
||||||
|
listener: U
|
||||||
|
) => void
|
||||||
|
on: <T extends keyof RelayEvent, U extends RelayEvent[T]>(
|
||||||
|
event: T,
|
||||||
|
listener: U
|
||||||
|
) => void
|
||||||
}
|
}
|
||||||
export type Pub = {
|
export type Pub = {
|
||||||
on: (type: 'ok' | 'failed', cb: any) => void
|
on: (type: 'ok' | 'failed', cb: any) => void
|
||||||
@@ -25,35 +49,46 @@ export type Pub = {
|
|||||||
export type Sub = {
|
export type Sub = {
|
||||||
sub: (filters: Filter[], opts: SubscriptionOptions) => Sub
|
sub: (filters: Filter[], opts: SubscriptionOptions) => Sub
|
||||||
unsub: () => void
|
unsub: () => void
|
||||||
on: (type: 'event' | 'eose', cb: any) => void
|
on: <T extends keyof SubEvent, U extends SubEvent[T]>(
|
||||||
off: (type: 'event' | 'eose', cb: any) => void
|
event: T,
|
||||||
|
listener: U
|
||||||
|
) => void
|
||||||
|
off: <T extends keyof SubEvent, U extends SubEvent[T]>(
|
||||||
|
event: T,
|
||||||
|
listener: U
|
||||||
|
) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
export type SubscriptionOptions = {
|
export type SubscriptionOptions = {
|
||||||
id?: string
|
id?: string
|
||||||
|
verb?: 'REQ' | 'COUNT'
|
||||||
skipVerification?: boolean
|
skipVerification?: boolean
|
||||||
alreadyHaveEvent?: null | ((id: string, relay: string) => boolean)
|
alreadyHaveEvent?: null | ((id: string, relay: string) => boolean)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function relayInit(url: string): Relay {
|
const newListeners = (): {[TK in keyof RelayEvent]: RelayEvent[TK][]} => ({
|
||||||
|
connect: [],
|
||||||
|
disconnect: [],
|
||||||
|
error: [],
|
||||||
|
notice: [],
|
||||||
|
auth: []
|
||||||
|
})
|
||||||
|
|
||||||
|
export function relayInit(
|
||||||
|
url: string,
|
||||||
|
options: {
|
||||||
|
getTimeout?: number
|
||||||
|
listTimeout?: number
|
||||||
|
countTimeout?: number
|
||||||
|
} = {}
|
||||||
|
): Relay {
|
||||||
|
let {listTimeout = 3000, getTimeout = 3000, countTimeout = 3000} = options
|
||||||
|
|
||||||
var ws: WebSocket
|
var ws: WebSocket
|
||||||
var openSubs: {[id: string]: {filters: Filter[]} & SubscriptionOptions} = {}
|
var openSubs: {[id: string]: {filters: Filter[]} & SubscriptionOptions} = {}
|
||||||
var listeners: {
|
var listeners = newListeners()
|
||||||
connect: Array<() => void>
|
|
||||||
disconnect: Array<() => void>
|
|
||||||
error: Array<() => void>
|
|
||||||
notice: Array<(msg: string) => void>
|
|
||||||
} = {
|
|
||||||
connect: [],
|
|
||||||
disconnect: [],
|
|
||||||
error: [],
|
|
||||||
notice: []
|
|
||||||
}
|
|
||||||
var subListeners: {
|
var subListeners: {
|
||||||
[subid: string]: {
|
[subid: string]: {[TK in keyof SubEvent]: SubEvent[TK][]}
|
||||||
event: Array<(event: Event) => void>
|
|
||||||
eose: Array<() => void>
|
|
||||||
}
|
|
||||||
} = {}
|
} = {}
|
||||||
var pubListeners: {
|
var pubListeners: {
|
||||||
[eventid: string]: {
|
[eventid: string]: {
|
||||||
@@ -63,19 +98,27 @@ export function relayInit(url: string): Relay {
|
|||||||
}
|
}
|
||||||
} = {}
|
} = {}
|
||||||
|
|
||||||
|
var connectionPromise: Promise<void> | undefined
|
||||||
async function connectRelay(): Promise<void> {
|
async function connectRelay(): Promise<void> {
|
||||||
return new Promise((resolve, reject) => {
|
if (connectionPromise) return connectionPromise
|
||||||
ws = new WebSocket(url)
|
connectionPromise = new Promise((resolve, reject) => {
|
||||||
|
try {
|
||||||
|
ws = new WebSocket(url)
|
||||||
|
} catch (err) {
|
||||||
|
reject(err)
|
||||||
|
}
|
||||||
|
|
||||||
ws.onopen = () => {
|
ws.onopen = () => {
|
||||||
listeners.connect.forEach(cb => cb())
|
listeners.connect.forEach(cb => cb())
|
||||||
resolve()
|
resolve()
|
||||||
}
|
}
|
||||||
ws.onerror = () => {
|
ws.onerror = () => {
|
||||||
|
connectionPromise = undefined
|
||||||
listeners.error.forEach(cb => cb())
|
listeners.error.forEach(cb => cb())
|
||||||
reject()
|
reject()
|
||||||
}
|
}
|
||||||
ws.onclose = async () => {
|
ws.onclose = async () => {
|
||||||
|
connectionPromise = undefined
|
||||||
listeners.disconnect.forEach(cb => cb())
|
listeners.disconnect.forEach(cb => cb())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,7 +161,7 @@ export function relayInit(url: string): Relay {
|
|||||||
// will naturally be caught by the encompassing try..catch block
|
// will naturally be caught by the encompassing try..catch block
|
||||||
|
|
||||||
switch (data[0]) {
|
switch (data[0]) {
|
||||||
case 'EVENT':
|
case 'EVENT': {
|
||||||
let id = data[1]
|
let id = data[1]
|
||||||
let event = data[2]
|
let event = data[2]
|
||||||
if (
|
if (
|
||||||
@@ -131,6 +174,14 @@ export function relayInit(url: string): Relay {
|
|||||||
;(subListeners[id]?.event || []).forEach(cb => cb(event))
|
;(subListeners[id]?.event || []).forEach(cb => cb(event))
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
|
}
|
||||||
|
case 'COUNT':
|
||||||
|
let id = data[1]
|
||||||
|
let payload = data[2]
|
||||||
|
if (openSubs[id]) {
|
||||||
|
;(subListeners[id]?.count || []).forEach(cb => cb(payload))
|
||||||
|
}
|
||||||
|
return
|
||||||
case 'EOSE': {
|
case 'EOSE': {
|
||||||
let id = data[1]
|
let id = data[1]
|
||||||
if (id in subListeners) {
|
if (id in subListeners) {
|
||||||
@@ -155,22 +206,38 @@ export function relayInit(url: string): Relay {
|
|||||||
let notice = data[1]
|
let notice = data[1]
|
||||||
listeners.notice.forEach(cb => cb(notice))
|
listeners.notice.forEach(cb => cb(notice))
|
||||||
return
|
return
|
||||||
|
case 'AUTH': {
|
||||||
|
let challenge = data[1]
|
||||||
|
listeners.auth?.forEach(cb => cb(challenge))
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
return connectionPromise
|
||||||
|
}
|
||||||
|
|
||||||
|
function connected() {
|
||||||
|
return ws?.readyState === 1
|
||||||
}
|
}
|
||||||
|
|
||||||
async function connect(): Promise<void> {
|
async function connect(): Promise<void> {
|
||||||
if (ws?.readyState && ws.readyState === 1) return // ws already open
|
if (connected()) return // ws already open
|
||||||
await connectRelay()
|
await connectRelay()
|
||||||
}
|
}
|
||||||
|
|
||||||
async function trySend(params: [string, ...any]) {
|
async function trySend(params: [string, ...any]) {
|
||||||
let msg = JSON.stringify(params)
|
let msg = JSON.stringify(params)
|
||||||
|
if (!connected()) {
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 1000))
|
||||||
|
if (!connected()) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
ws.send(msg)
|
ws.send(msg)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -181,6 +248,7 @@ export function relayInit(url: string): Relay {
|
|||||||
const sub = (
|
const sub = (
|
||||||
filters: Filter[],
|
filters: Filter[],
|
||||||
{
|
{
|
||||||
|
verb = 'REQ',
|
||||||
skipVerification = false,
|
skipVerification = false,
|
||||||
alreadyHaveEvent = null,
|
alreadyHaveEvent = null,
|
||||||
id = Math.random().toString().slice(2)
|
id = Math.random().toString().slice(2)
|
||||||
@@ -194,7 +262,7 @@ export function relayInit(url: string): Relay {
|
|||||||
skipVerification,
|
skipVerification,
|
||||||
alreadyHaveEvent
|
alreadyHaveEvent
|
||||||
}
|
}
|
||||||
trySend(['REQ', subid, ...filters])
|
trySend([verb, subid, ...filters])
|
||||||
|
|
||||||
return {
|
return {
|
||||||
sub: (newFilters, newOpts = {}) =>
|
sub: (newFilters, newOpts = {}) =>
|
||||||
@@ -208,14 +276,21 @@ export function relayInit(url: string): Relay {
|
|||||||
delete subListeners[subid]
|
delete subListeners[subid]
|
||||||
trySend(['CLOSE', subid])
|
trySend(['CLOSE', subid])
|
||||||
},
|
},
|
||||||
on: (type: 'event' | 'eose', cb: any): void => {
|
on: <T extends keyof SubEvent, U extends SubEvent[T]>(
|
||||||
|
type: T,
|
||||||
|
cb: U
|
||||||
|
): void => {
|
||||||
subListeners[subid] = subListeners[subid] || {
|
subListeners[subid] = subListeners[subid] || {
|
||||||
event: [],
|
event: [],
|
||||||
|
count: [],
|
||||||
eose: []
|
eose: []
|
||||||
}
|
}
|
||||||
subListeners[subid][type].push(cb)
|
subListeners[subid][type].push(cb)
|
||||||
},
|
},
|
||||||
off: (type: 'event' | 'eose', cb: any): void => {
|
off: <T extends keyof SubEvent, U extends SubEvent[T]>(
|
||||||
|
type: T,
|
||||||
|
cb: U
|
||||||
|
): void => {
|
||||||
let listeners = subListeners[subid]
|
let listeners = subListeners[subid]
|
||||||
let idx = listeners[type].indexOf(cb)
|
let idx = listeners[type].indexOf(cb)
|
||||||
if (idx >= 0) listeners[type].splice(idx, 1)
|
if (idx >= 0) listeners[type].splice(idx, 1)
|
||||||
@@ -223,16 +298,46 @@ export function relayInit(url: string): Relay {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function _publishEvent(event: Event, type: string) {
|
||||||
|
if (!event.id) throw new Error(`event ${event} has no id`)
|
||||||
|
let id = event.id
|
||||||
|
|
||||||
|
trySend([type, event])
|
||||||
|
|
||||||
|
return {
|
||||||
|
on: (type: 'ok' | 'failed', cb: any) => {
|
||||||
|
pubListeners[id] = pubListeners[id] || {
|
||||||
|
ok: [],
|
||||||
|
failed: []
|
||||||
|
}
|
||||||
|
pubListeners[id][type].push(cb)
|
||||||
|
},
|
||||||
|
off: (type: 'ok' | 'failed', cb: any) => {
|
||||||
|
let listeners = pubListeners[id]
|
||||||
|
if (!listeners) return
|
||||||
|
let idx = listeners[type].indexOf(cb)
|
||||||
|
if (idx >= 0) listeners[type].splice(idx, 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
url,
|
url,
|
||||||
sub,
|
sub,
|
||||||
on: (type: RelayEvent, cb: any): void => {
|
on: <T extends keyof RelayEvent, U extends RelayEvent[T]>(
|
||||||
|
type: T,
|
||||||
|
cb: U
|
||||||
|
): void => {
|
||||||
listeners[type].push(cb)
|
listeners[type].push(cb)
|
||||||
if (type === 'connect' && ws?.readyState === 1) {
|
if (type === 'connect' && ws?.readyState === 1) {
|
||||||
cb()
|
// i would love to know why we need this
|
||||||
|
;(cb as () => void)()
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
off: (type: RelayEvent, cb: any): void => {
|
off: <T extends keyof RelayEvent, U extends RelayEvent[T]>(
|
||||||
|
type: T,
|
||||||
|
cb: U
|
||||||
|
): void => {
|
||||||
let index = listeners[type].indexOf(cb)
|
let index = listeners[type].indexOf(cb)
|
||||||
if (index !== -1) listeners[type].splice(index, 1)
|
if (index !== -1) listeners[type].splice(index, 1)
|
||||||
},
|
},
|
||||||
@@ -243,7 +348,7 @@ export function relayInit(url: string): Relay {
|
|||||||
let timeout = setTimeout(() => {
|
let timeout = setTimeout(() => {
|
||||||
s.unsub()
|
s.unsub()
|
||||||
resolve(events)
|
resolve(events)
|
||||||
}, 1500)
|
}, listTimeout)
|
||||||
s.on('eose', () => {
|
s.on('eose', () => {
|
||||||
s.unsub()
|
s.unsub()
|
||||||
clearTimeout(timeout)
|
clearTimeout(timeout)
|
||||||
@@ -259,43 +364,40 @@ export function relayInit(url: string): Relay {
|
|||||||
let timeout = setTimeout(() => {
|
let timeout = setTimeout(() => {
|
||||||
s.unsub()
|
s.unsub()
|
||||||
resolve(null)
|
resolve(null)
|
||||||
}, 1500)
|
}, getTimeout)
|
||||||
s.on('event', (event: Event) => {
|
s.on('event', (event: Event) => {
|
||||||
s.unsub()
|
s.unsub()
|
||||||
clearTimeout(timeout)
|
clearTimeout(timeout)
|
||||||
resolve(event)
|
resolve(event)
|
||||||
})
|
})
|
||||||
}),
|
}),
|
||||||
publish(event: Event): Pub {
|
count: (filters: Filter[]): Promise<CountPayload | null> =>
|
||||||
if (!event.id) throw new Error(`event ${event} has no id`)
|
new Promise(resolve => {
|
||||||
let id = event.id
|
let s = sub(filters, {...sub, verb: 'COUNT'})
|
||||||
|
let timeout = setTimeout(() => {
|
||||||
trySend(['EVENT', event])
|
s.unsub()
|
||||||
|
resolve(null)
|
||||||
return {
|
}, countTimeout)
|
||||||
on: (type: 'ok' | 'failed', cb: any) => {
|
s.on('count', (event: CountPayload) => {
|
||||||
pubListeners[id] = pubListeners[id] || {
|
s.unsub()
|
||||||
ok: [],
|
clearTimeout(timeout)
|
||||||
failed: []
|
resolve(event)
|
||||||
}
|
})
|
||||||
pubListeners[id][type].push(cb)
|
}),
|
||||||
},
|
publish(event): Pub {
|
||||||
off: (type: 'ok' | 'failed', cb: any) => {
|
return _publishEvent(event, 'EVENT')
|
||||||
let listeners = pubListeners[id]
|
},
|
||||||
if (!listeners) return
|
auth(event): Pub {
|
||||||
let idx = listeners[type].indexOf(cb)
|
return _publishEvent(event, 'AUTH')
|
||||||
if (idx >= 0) listeners[type].splice(idx, 1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
connect,
|
connect,
|
||||||
close(): void {
|
close(): void {
|
||||||
listeners = {connect: [], disconnect: [], error: [], notice: []}
|
listeners = newListeners()
|
||||||
subListeners = {}
|
subListeners = {}
|
||||||
pubListeners = {}
|
pubListeners = {}
|
||||||
|
if (ws.readyState === WebSocket.OPEN) {
|
||||||
if (ws.readyState > 1) return
|
ws?.close()
|
||||||
ws.close()
|
}
|
||||||
},
|
},
|
||||||
get status() {
|
get status() {
|
||||||
return ws?.readyState ?? 3
|
return ws?.readyState ?? 3
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
"esModuleInterop": true,
|
"esModuleInterop": true,
|
||||||
"emitDeclarationOnly": true,
|
"emitDeclarationOnly": true,
|
||||||
"outDir": "dist",
|
"outDir": "lib",
|
||||||
"rootDir": "."
|
"rootDir": "."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user