mirror of
https://github.com/nbd-wtf/nostr-tools.git
synced 2025-12-08 16:28:49 +00:00
Compare commits
83 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
87a91c2daf | ||
|
|
4f1dc9ef1c | ||
|
|
faa1a9d556 | ||
|
|
97d838f254 | ||
|
|
260400b24d | ||
|
|
6e5ab34a54 | ||
|
|
9562c408b3 | ||
|
|
4f4de458e9 | ||
|
|
88454de628 | ||
|
|
9f5984d78d | ||
|
|
80df21d47f | ||
|
|
296e99d2a4 | ||
|
|
1cd9847ad5 | ||
|
|
fa31fdca78 | ||
|
|
5876acd67a | ||
|
|
44efd49bc0 | ||
|
|
f4f9bece6e | ||
|
|
e217f751da | ||
|
|
d0ae8b36a2 | ||
|
|
fd945757be | ||
|
|
c12ddd3c53 | ||
|
|
1e9f828e3e | ||
|
|
0a5eaac088 | ||
|
|
e858698cb9 | ||
|
|
b349ee577d | ||
|
|
849a2ac3f3 | ||
|
|
c18b94677c | ||
|
|
f306cec716 | ||
|
|
5c7e9c8f36 | ||
|
|
1d7620a057 | ||
|
|
88247e56c1 | ||
|
|
e5cda3509c | ||
|
|
02da1dc036 | ||
|
|
7aed747bb2 | ||
|
|
747a7944d7 | ||
|
|
9f8b7274b3 | ||
|
|
ee565db7f5 | ||
|
|
e9ee8258e7 | ||
|
|
ad07d260ab | ||
|
|
632184afb8 | ||
|
|
d7d5d30f41 | ||
|
|
387ce2c335 | ||
|
|
b62b8f88af | ||
|
|
6b43533f2e | ||
|
|
e30e08d8e2 | ||
|
|
59426d9f35 | ||
|
|
5429142858 | ||
|
|
564c9bca17 | ||
|
|
0190ae94a7 | ||
|
|
e1bde08ff3 | ||
|
|
71456feb20 | ||
|
|
ca928c697b | ||
|
|
7b98cae7fa | ||
|
|
db53f37161 | ||
|
|
1691f0b51d | ||
|
|
3b582a0206 | ||
|
|
8ed2c13c28 | ||
|
|
27a536f41d | ||
|
|
fbc82d0b73 | ||
|
|
9c0ade1329 | ||
|
|
63ccc8b4c8 | ||
|
|
7cf7df88db | ||
|
|
bded539122 | ||
|
|
3647bbd68a | ||
|
|
fb085ffdf7 | ||
|
|
280d483ef4 | ||
|
|
54b55b98f1 | ||
|
|
84f9881812 | ||
|
|
db6baf2e6b | ||
|
|
bb1e6f4356 | ||
|
|
5626d3048b | ||
|
|
058d0276e2 | ||
|
|
37b046c047 | ||
|
|
846654b449 | ||
|
|
b676dc0987 | ||
|
|
b1ce901555 | ||
|
|
62e5730965 | ||
|
|
01f13292bb | ||
|
|
7b0458db72 | ||
|
|
3aab7121f7 | ||
|
|
ce059d4608 | ||
|
|
b72b0dc1f0 | ||
|
|
29e5b71473 |
19
.devcontainer/Dockerfile
Executable file
19
.devcontainer/Dockerfile
Executable file
@@ -0,0 +1,19 @@
|
|||||||
|
FROM node:20
|
||||||
|
|
||||||
|
RUN npm install typescript -g
|
||||||
|
|
||||||
|
# Install bun
|
||||||
|
RUN curl -fsSL https://bun.sh/install | bash
|
||||||
|
|
||||||
|
# Install just
|
||||||
|
WORKDIR /usr/bin
|
||||||
|
RUN wget https://github.com/casey/just/releases/download/1.26.0/just-1.26.0-x86_64-unknown-linux-musl.tar.gz
|
||||||
|
RUN tar -xzf just-1.26.0-x86_64-unknown-linux-musl.tar.gz
|
||||||
|
RUN chmod +x ./just
|
||||||
|
RUN rm just-1.26.0-x86_64-unknown-linux-musl.tar.gz
|
||||||
|
|
||||||
|
WORKDIR /nostr-tools
|
||||||
|
ENV LANG C.UTF-8
|
||||||
|
|
||||||
|
# The run the start script
|
||||||
|
CMD [ "/bin/bash" ]
|
||||||
19
.devcontainer/devcontainer.json
Executable file
19
.devcontainer/devcontainer.json
Executable file
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"name": "Nostr Tools",
|
||||||
|
"dockerComposeFile": [
|
||||||
|
"docker-compose.yml"
|
||||||
|
],
|
||||||
|
"service": "nostr-tools-dev",
|
||||||
|
"workspaceFolder": "/nostr-tools",
|
||||||
|
"customizations": {
|
||||||
|
"vscode": {
|
||||||
|
"extensions": [
|
||||||
|
"ms-vscode.vscode-typescript-next",
|
||||||
|
"eamodio.gitlens",
|
||||||
|
"dbaeumer.vscode-eslint",
|
||||||
|
"manishsencha.readme-preview",
|
||||||
|
"wix.vscode-import-cost"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
13
.devcontainer/docker-compose.yml
Executable file
13
.devcontainer/docker-compose.yml
Executable file
@@ -0,0 +1,13 @@
|
|||||||
|
version: '3.9'
|
||||||
|
|
||||||
|
services:
|
||||||
|
nostr-tools-dev:
|
||||||
|
image: nostr-tools-dev
|
||||||
|
container_name: nostr-tools-dev
|
||||||
|
build:
|
||||||
|
context: ../.
|
||||||
|
dockerfile: ./.devcontainer/Dockerfile
|
||||||
|
working_dir: /nostr-tools
|
||||||
|
volumes:
|
||||||
|
- ..:/nostr-tools:cached
|
||||||
|
tty: true
|
||||||
98
README.md
98
README.md
@@ -19,16 +19,25 @@ If using TypeScript, this package requires TypeScript >= 5.0.
|
|||||||
### Generating a private key and a public key
|
### Generating a private key and a public key
|
||||||
|
|
||||||
```js
|
```js
|
||||||
import { generateSecretKey, getPublicKey } from 'nostr-tools'
|
import { generateSecretKey, getPublicKey } from 'nostr-tools/pure'
|
||||||
|
|
||||||
let sk = generateSecretKey() // `sk` is a Uint8Array
|
let sk = generateSecretKey() // `sk` is a Uint8Array
|
||||||
let pk = getPublicKey(sk) // `pk` is a hex string
|
let pk = getPublicKey(sk) // `pk` is a hex string
|
||||||
```
|
```
|
||||||
|
|
||||||
|
To get the secret key in hex format, use
|
||||||
|
|
||||||
|
```js
|
||||||
|
import { bytesToHex, hexToBytes } from '@noble/hashes/utils' // already an installed dependency
|
||||||
|
|
||||||
|
let skHex = bytesToHex(sk)
|
||||||
|
let backToBytes = hexToBytes(skHex)
|
||||||
|
```
|
||||||
|
|
||||||
### Creating, signing and verifying events
|
### Creating, signing and verifying events
|
||||||
|
|
||||||
```js
|
```js
|
||||||
import { finalizeEvent, verifyEvent } from 'nostr-tools'
|
import { finalizeEvent, verifyEvent } from 'nostr-tools/pure'
|
||||||
|
|
||||||
let event = finalizeEvent({
|
let event = finalizeEvent({
|
||||||
kind: 1,
|
kind: 1,
|
||||||
@@ -43,7 +52,8 @@ let isGood = verifyEvent(event)
|
|||||||
### Interacting with a relay
|
### Interacting with a relay
|
||||||
|
|
||||||
```js
|
```js
|
||||||
import { Relay, finalizeEvent, generateSecretKey, getPublicKey } from 'nostr-tools'
|
import { finalizeEvent, generateSecretKey, getPublicKey } from 'nostr-tools/pure'
|
||||||
|
import { Relay } from 'nostr-tools/relay'
|
||||||
|
|
||||||
const relay = await Relay.connect('wss://relay.example.com')
|
const relay = await Relay.connect('wss://relay.example.com')
|
||||||
console.log(`connected to ${relay.url}`)
|
console.log(`connected to ${relay.url}`)
|
||||||
@@ -91,16 +101,20 @@ await relay.publish(signedEvent)
|
|||||||
relay.close()
|
relay.close()
|
||||||
```
|
```
|
||||||
|
|
||||||
To use this on Node.js you first must install `websocket-polyfill` and import it:
|
To use this on Node.js you first must install `ws` and call something like this:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
import 'websocket-polyfill'
|
import { useWebSocketImplementation } from 'nostr-tools/pool'
|
||||||
|
// or import { useWebSocketImplementation } from 'nostr-tools/relay' if you're using the Relay directly
|
||||||
|
|
||||||
|
import WebSocket from 'ws'
|
||||||
|
useWebSocketImplementation(WebSocket)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Interacting with multiple relays
|
### Interacting with multiple relays
|
||||||
|
|
||||||
```js
|
```js
|
||||||
import { SimplePool } from 'nostr-tools'
|
import { SimplePool } from 'nostr-tools/pool'
|
||||||
|
|
||||||
const pool = new SimplePool()
|
const pool = new SimplePool()
|
||||||
|
|
||||||
@@ -127,7 +141,7 @@ let h = pool.subscribeMany(
|
|||||||
await Promise.any(pool.publish(relays, newEvent))
|
await Promise.any(pool.publish(relays, newEvent))
|
||||||
console.log('published to at least one relay!')
|
console.log('published to at least one relay!')
|
||||||
|
|
||||||
let events = await pool.querySync(relays, [{ kinds: [0, 1] }])
|
let events = await pool.querySync(relays, { kinds: [0, 1] })
|
||||||
let event = await pool.get(relays, {
|
let event = await pool.get(relays, {
|
||||||
ids: ['44e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245'],
|
ids: ['44e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245'],
|
||||||
})
|
})
|
||||||
@@ -136,7 +150,7 @@ let event = await pool.get(relays, {
|
|||||||
### Parsing references (mentions) from a content using NIP-10 and NIP-27
|
### Parsing references (mentions) from a content using NIP-10 and NIP-27
|
||||||
|
|
||||||
```js
|
```js
|
||||||
import { parseReferences } from 'nostr-tools'
|
import { parseReferences } from 'nostr-tools/references'
|
||||||
|
|
||||||
let references = parseReferences(event)
|
let references = parseReferences(event)
|
||||||
let simpleAugmentedContent = event.content
|
let simpleAugmentedContent = event.content
|
||||||
@@ -156,9 +170,9 @@ for (let i = 0; i < references.length; i++) {
|
|||||||
### Querying profile data from a NIP-05 address
|
### Querying profile data from a NIP-05 address
|
||||||
|
|
||||||
```js
|
```js
|
||||||
import { nip05 } from 'nostr-tools'
|
import { queryProfile } from 'nostr-tools/nip05'
|
||||||
|
|
||||||
let profile = await nip05.queryProfile('jb55.com')
|
let profile = await queryProfile('jb55.com')
|
||||||
console.log(profile.pubkey)
|
console.log(profile.pubkey)
|
||||||
// prints: 32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245
|
// prints: 32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245
|
||||||
console.log(profile.relays)
|
console.log(profile.relays)
|
||||||
@@ -168,13 +182,52 @@ console.log(profile.relays)
|
|||||||
To use this on Node.js < v18, you first must install `node-fetch@2` and call something like this:
|
To use this on Node.js < v18, you first must install `node-fetch@2` and call something like this:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
nip05.useFetchImplementation(require('node-fetch'))
|
import { useFetchImplementation } from 'nostr-tools/nip05'
|
||||||
|
useFetchImplementation(require('node-fetch'))
|
||||||
|
```
|
||||||
|
|
||||||
|
### Including NIP-07 types
|
||||||
|
```js
|
||||||
|
import type { WindowNostr } from 'nostr-tools/nip07'
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
interface Window {
|
||||||
|
nostr?: WindowNostr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### Generating NIP-06 keys
|
||||||
|
```js
|
||||||
|
import {
|
||||||
|
privateKeyFromSeedWords,
|
||||||
|
accountFromSeedWords,
|
||||||
|
extendedKeysFromSeedWords,
|
||||||
|
accountFromExtendedKey
|
||||||
|
} from 'nostr-tools/nip06'
|
||||||
|
|
||||||
|
const mnemonic = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong'
|
||||||
|
const passphrase = '123' // optional
|
||||||
|
const accountIndex = 0
|
||||||
|
const sk0 = privateKeyFromSeedWords(mnemonic, passphrase, accountIndex)
|
||||||
|
|
||||||
|
const { privateKey: sk1, publicKey: pk1 } = accountFromSeedWords(mnemonic, passphrase, accountIndex)
|
||||||
|
|
||||||
|
const extendedAccountIndex = 0
|
||||||
|
|
||||||
|
const { privateExtendedKey, publicExtendedKey } = extendedKeysFromSeedWords(mnemonic, passphrase, extendedAccountIndex)
|
||||||
|
|
||||||
|
const { privateKey: sk2, publicKey: pk2 } = accountFromExtendedKey(privateExtendedKey)
|
||||||
|
|
||||||
|
const { publicKey: pk3 } = accountFromExtendedKey(publicExtendedKey)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Encoding and decoding NIP-19 codes
|
### Encoding and decoding NIP-19 codes
|
||||||
|
|
||||||
```js
|
```js
|
||||||
import { nip19, generateSecretKey, getPublicKey } from 'nostr-tools'
|
import { generateSecretKey, getPublicKey } from 'nostr-tools/pure'
|
||||||
|
import * as nip19 from 'nostr-tools/nip19'
|
||||||
|
|
||||||
let sk = generateSecretKey()
|
let sk = generateSecretKey()
|
||||||
let nsec = nip19.nsecEncode(sk)
|
let nsec = nip19.nsecEncode(sk)
|
||||||
@@ -197,21 +250,6 @@ assert(data.pubkey === pk)
|
|||||||
assert(data.relays.length === 2)
|
assert(data.relays.length === 2)
|
||||||
```
|
```
|
||||||
|
|
||||||
## Import modes
|
|
||||||
|
|
||||||
### Using just the packages you want
|
|
||||||
|
|
||||||
Importing the entirety of `nostr-tools` may bloat your build, so you should probably import individual packages instead:
|
|
||||||
|
|
||||||
```js
|
|
||||||
import { generateSecretKey, finalizeEvent, verifyEvent } from 'nostr-tools/pure'
|
|
||||||
import { SimplePool } from 'nostr-tools/pool'
|
|
||||||
import { Relay, Subscription } from 'nostr-tools/relay'
|
|
||||||
import { matchFilter } from 'nostr-tools/filter'
|
|
||||||
import { decode, nprofileEncode, neventEncode, npubEncode } from 'nostr-tools/nip19'
|
|
||||||
// and so on and so forth
|
|
||||||
```
|
|
||||||
|
|
||||||
### Using it with `nostr-wasm`
|
### Using it with `nostr-wasm`
|
||||||
|
|
||||||
[`nostr-wasm`](https://github.com/fiatjaf/nostr-wasm) is a thin wrapper over [libsecp256k1](https://github.com/bitcoin-core/secp256k1) compiled to WASM just for hashing, signing and verifying Nostr events.
|
[`nostr-wasm`](https://github.com/fiatjaf/nostr-wasm) is a thin wrapper over [libsecp256k1](https://github.com/bitcoin-core/secp256k1) compiled to WASM just for hashing, signing and verifying Nostr events.
|
||||||
@@ -277,4 +315,8 @@ This is free and unencumbered software released into the public domain. By submi
|
|||||||
|
|
||||||
## Contributing to this repository
|
## Contributing to this repository
|
||||||
|
|
||||||
Use NIP-34 to send your patches to `naddr1qq9kummnw3ez6ar0dak8xqg5waehxw309aex2mrp0yhxummnw3ezucn8qyt8wumn8ghj7un9d3shjtnwdaehgu3wvfskueqpzemhxue69uhhyetvv9ujuurjd9kkzmpwdejhgq3q80cvv07tjdrrgpa0j7j7tmnyl2yr6yr7l8j4s3evf6u64th6gkwsxpqqqpmejdv00jq`.
|
Use NIP-34 to send your patches to:
|
||||||
|
|
||||||
|
```
|
||||||
|
naddr1qq9kummnw3ez6ar0dak8xqg5waehxw309aex2mrp0yhxummnw3ezucn8qyt8wumn8ghj7un9d3shjtnwdaehgu3wvfskueqpzemhxue69uhhyetvv9ujuurjd9kkzmpwdejhgq3q80cvv07tjdrrgpa0j7j7tmnyl2yr6yr7l8j4s3evf6u64th6gkwsxpqqqpmejdv00jq
|
||||||
|
```
|
||||||
|
|||||||
@@ -1,4 +1,11 @@
|
|||||||
import { AbstractRelay as AbstractRelay, SubscriptionParams, Subscription } from './abstract-relay.ts'
|
/* global WebSocket */
|
||||||
|
|
||||||
|
import {
|
||||||
|
AbstractRelay as AbstractRelay,
|
||||||
|
SubscriptionParams,
|
||||||
|
Subscription,
|
||||||
|
type AbstractRelayConstructorOptions,
|
||||||
|
} from './abstract-relay.ts'
|
||||||
import { normalizeURL } from './utils.ts'
|
import { normalizeURL } from './utils.ts'
|
||||||
|
|
||||||
import type { Event, Nostr } from './core.ts'
|
import type { Event, Nostr } from './core.ts'
|
||||||
@@ -7,6 +14,8 @@ import { alwaysTrue } from './helpers.ts'
|
|||||||
|
|
||||||
export type SubCloser = { close: () => void }
|
export type SubCloser = { close: () => void }
|
||||||
|
|
||||||
|
export type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {}
|
||||||
|
|
||||||
export type SubscribeManyParams = Omit<SubscriptionParams, 'onclose' | 'id'> & {
|
export type SubscribeManyParams = Omit<SubscriptionParams, 'onclose' | 'id'> & {
|
||||||
maxWait?: number
|
maxWait?: number
|
||||||
onclose?: (reasons: string[]) => void
|
onclose?: (reasons: string[]) => void
|
||||||
@@ -15,14 +24,17 @@ export type SubscribeManyParams = Omit<SubscriptionParams, 'onclose' | 'id'> & {
|
|||||||
|
|
||||||
export class AbstractSimplePool {
|
export class AbstractSimplePool {
|
||||||
private relays = new Map<string, AbstractRelay>()
|
private relays = new Map<string, AbstractRelay>()
|
||||||
public seenOn = new Map<string, Set<AbstractRelay>>()
|
public seenOn: Map<string, Set<AbstractRelay>> = new Map()
|
||||||
public trackRelays: boolean = false
|
public trackRelays: boolean = false
|
||||||
|
|
||||||
public verifyEvent: Nostr['verifyEvent']
|
public verifyEvent: Nostr['verifyEvent']
|
||||||
public trustedRelayURLs = new Set<string>()
|
public trustedRelayURLs: Set<string> = new Set()
|
||||||
|
|
||||||
constructor(opts: { verifyEvent: Nostr['verifyEvent'] }) {
|
private _WebSocket?: typeof WebSocket
|
||||||
|
|
||||||
|
constructor(opts: AbstractPoolConstructorOptions) {
|
||||||
this.verifyEvent = opts.verifyEvent
|
this.verifyEvent = opts.verifyEvent
|
||||||
|
this._WebSocket = opts.websocketImplementation
|
||||||
}
|
}
|
||||||
|
|
||||||
async ensureRelay(url: string, params?: { connectionTimeout?: number }): Promise<AbstractRelay> {
|
async ensureRelay(url: string, params?: { connectionTimeout?: number }): Promise<AbstractRelay> {
|
||||||
@@ -32,6 +44,7 @@ export class AbstractSimplePool {
|
|||||||
if (!relay) {
|
if (!relay) {
|
||||||
relay = new AbstractRelay(url, {
|
relay = new AbstractRelay(url, {
|
||||||
verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent,
|
verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent,
|
||||||
|
websocketImplementation: this._WebSocket,
|
||||||
})
|
})
|
||||||
if (params?.connectionTimeout) relay.connectionTimeout = params.connectionTimeout
|
if (params?.connectionTimeout) relay.connectionTimeout = params.connectionTimeout
|
||||||
this.relays.set(url, relay)
|
this.relays.set(url, relay)
|
||||||
@@ -48,6 +61,10 @@ export class AbstractSimplePool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
subscribeMany(relays: string[], filters: Filter[], params: SubscribeManyParams): SubCloser {
|
subscribeMany(relays: string[], filters: Filter[], params: SubscribeManyParams): SubCloser {
|
||||||
|
return this.subscribeManyMap(Object.fromEntries(relays.map(url => [url, filters])), params)
|
||||||
|
}
|
||||||
|
|
||||||
|
subscribeManyMap(requests: { [relay: string]: Filter[] }, params: SubscribeManyParams): SubCloser {
|
||||||
if (this.trackRelays) {
|
if (this.trackRelays) {
|
||||||
params.receivedEvent = (relay: AbstractRelay, id: string) => {
|
params.receivedEvent = (relay: AbstractRelay, id: string) => {
|
||||||
let set = this.seenOn.get(id)
|
let set = this.seenOn.get(id)
|
||||||
@@ -61,12 +78,13 @@ export class AbstractSimplePool {
|
|||||||
|
|
||||||
const _knownIds = new Set<string>()
|
const _knownIds = new Set<string>()
|
||||||
const subs: Subscription[] = []
|
const subs: Subscription[] = []
|
||||||
|
const relaysLength = Object.keys(requests).length
|
||||||
|
|
||||||
// batch all EOSEs into a single
|
// batch all EOSEs into a single
|
||||||
const eosesReceived: boolean[] = []
|
const eosesReceived: boolean[] = []
|
||||||
let handleEose = (i: number) => {
|
let handleEose = (i: number) => {
|
||||||
eosesReceived[i] = true
|
eosesReceived[i] = true
|
||||||
if (eosesReceived.filter(a => a).length === relays.length) {
|
if (eosesReceived.filter(a => a).length === relaysLength) {
|
||||||
params.oneose?.()
|
params.oneose?.()
|
||||||
handleEose = () => {}
|
handleEose = () => {}
|
||||||
}
|
}
|
||||||
@@ -76,7 +94,7 @@ export class AbstractSimplePool {
|
|||||||
let handleClose = (i: number, reason: string) => {
|
let handleClose = (i: number, reason: string) => {
|
||||||
handleEose(i)
|
handleEose(i)
|
||||||
closesReceived[i] = reason
|
closesReceived[i] = reason
|
||||||
if (closesReceived.filter(a => a).length === relays.length) {
|
if (closesReceived.filter(a => a).length === relaysLength) {
|
||||||
params.onclose?.(closesReceived)
|
params.onclose?.(closesReceived)
|
||||||
handleClose = () => {}
|
handleClose = () => {}
|
||||||
}
|
}
|
||||||
@@ -93,13 +111,16 @@ export class AbstractSimplePool {
|
|||||||
|
|
||||||
// open a subscription in all given relays
|
// open a subscription in all given relays
|
||||||
const allOpened = Promise.all(
|
const allOpened = Promise.all(
|
||||||
relays.map(normalizeURL).map(async (url, i, arr) => {
|
Object.entries(requests).map(async (req, i, arr) => {
|
||||||
if (arr.indexOf(url) !== i) {
|
if (arr.indexOf(req) !== i) {
|
||||||
// duplicate
|
// duplicate
|
||||||
handleClose(i, 'duplicate url')
|
handleClose(i, 'duplicate url')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let [url, filters] = req
|
||||||
|
url = normalizeURL(url)
|
||||||
|
|
||||||
let relay: AbstractRelay
|
let relay: AbstractRelay
|
||||||
try {
|
try {
|
||||||
relay = await this.ensureRelay(url, {
|
relay = await this.ensureRelay(url, {
|
||||||
|
|||||||
@@ -7,6 +7,11 @@ import { Queue, normalizeURL } from './utils.ts'
|
|||||||
import { makeAuthEvent } from './nip42.ts'
|
import { makeAuthEvent } from './nip42.ts'
|
||||||
import { yieldThread } from './helpers.ts'
|
import { yieldThread } from './helpers.ts'
|
||||||
|
|
||||||
|
export type AbstractRelayConstructorOptions = {
|
||||||
|
verifyEvent: Nostr['verifyEvent']
|
||||||
|
websocketImplementation?: typeof WebSocket
|
||||||
|
}
|
||||||
|
|
||||||
export class AbstractRelay {
|
export class AbstractRelay {
|
||||||
public readonly url: string
|
public readonly url: string
|
||||||
private _connected: boolean = false
|
private _connected: boolean = false
|
||||||
@@ -14,9 +19,12 @@ export class AbstractRelay {
|
|||||||
public onclose: (() => void) | null = null
|
public onclose: (() => void) | null = null
|
||||||
public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)
|
public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)
|
||||||
|
|
||||||
|
// this is exposed just to help in ndk migration, shouldn't be relied upon
|
||||||
|
public _onauth: ((challenge: string) => void) | null = null
|
||||||
|
|
||||||
public baseEoseTimeout: number = 4400
|
public baseEoseTimeout: number = 4400
|
||||||
public connectionTimeout: number = 4400
|
public connectionTimeout: number = 4400
|
||||||
public openSubs = new Map<string, Subscription>()
|
public openSubs: Map<string, Subscription> = new Map()
|
||||||
private connectionTimeoutHandle: ReturnType<typeof setTimeout> | undefined
|
private connectionTimeoutHandle: ReturnType<typeof setTimeout> | undefined
|
||||||
|
|
||||||
private connectionPromise: Promise<void> | undefined
|
private connectionPromise: Promise<void> | undefined
|
||||||
@@ -29,12 +37,15 @@ export class AbstractRelay {
|
|||||||
private serial: number = 0
|
private serial: number = 0
|
||||||
private verifyEvent: Nostr['verifyEvent']
|
private verifyEvent: Nostr['verifyEvent']
|
||||||
|
|
||||||
constructor(url: string, opts: { verifyEvent: Nostr['verifyEvent'] }) {
|
private _WebSocket: typeof WebSocket
|
||||||
|
|
||||||
|
constructor(url: string, opts: AbstractRelayConstructorOptions) {
|
||||||
this.url = normalizeURL(url)
|
this.url = normalizeURL(url)
|
||||||
this.verifyEvent = opts.verifyEvent
|
this.verifyEvent = opts.verifyEvent
|
||||||
|
this._WebSocket = opts.websocketImplementation || WebSocket
|
||||||
}
|
}
|
||||||
|
|
||||||
static async connect(url: string, opts: { verifyEvent: Nostr['verifyEvent'] }) {
|
static async connect(url: string, opts: AbstractRelayConstructorOptions): Promise<AbstractRelay> {
|
||||||
const relay = new AbstractRelay(url, opts)
|
const relay = new AbstractRelay(url, opts)
|
||||||
await relay.connect()
|
await relay.connect()
|
||||||
return relay
|
return relay
|
||||||
@@ -74,7 +85,7 @@ export class AbstractRelay {
|
|||||||
}, this.connectionTimeout)
|
}, this.connectionTimeout)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
this.ws = new WebSocket(this.url)
|
this.ws = new this._WebSocket(this.url)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
reject(err)
|
reject(err)
|
||||||
return
|
return
|
||||||
@@ -89,17 +100,20 @@ export class AbstractRelay {
|
|||||||
this.ws.onerror = ev => {
|
this.ws.onerror = ev => {
|
||||||
reject((ev as any).message)
|
reject((ev as any).message)
|
||||||
if (this._connected) {
|
if (this._connected) {
|
||||||
|
this._connected = false
|
||||||
|
this.connectionPromise = undefined
|
||||||
this.onclose?.()
|
this.onclose?.()
|
||||||
this.closeAllSubscriptions('relay connection errored')
|
this.closeAllSubscriptions('relay connection errored')
|
||||||
this._connected = false
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
this.ws.onclose = async () => {
|
this.ws.onclose = async () => {
|
||||||
this.connectionPromise = undefined
|
if (this._connected) {
|
||||||
this.onclose?.()
|
this._connected = false
|
||||||
this.closeAllSubscriptions('relay connection closed')
|
this.connectionPromise = undefined
|
||||||
this._connected = false
|
this.onclose?.()
|
||||||
|
this.closeAllSubscriptions('relay connection closed')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
this.ws.onmessage = this._onmessage.bind(this)
|
this.ws.onmessage = this._onmessage.bind(this)
|
||||||
@@ -202,6 +216,7 @@ export class AbstractRelay {
|
|||||||
return
|
return
|
||||||
case 'AUTH': {
|
case 'AUTH': {
|
||||||
this.challenge = data[1] as string
|
this.challenge = data[1] as string
|
||||||
|
this._onauth?.(data[1] as string)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -218,7 +233,7 @@ export class AbstractRelay {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
public async auth(signAuthEvent: (evt: EventTemplate) => Promise<VerifiedEvent>) {
|
public async auth(signAuthEvent: (evt: EventTemplate) => Promise<VerifiedEvent>): Promise<string> {
|
||||||
if (!this.challenge) throw new Error("can't perform auth, no challenge was received")
|
if (!this.challenge) throw new Error("can't perform auth, no challenge was received")
|
||||||
const evt = await signAuthEvent(makeAuthEvent(this.url, this.challenge))
|
const evt = await signAuthEvent(makeAuthEvent(this.url, this.challenge))
|
||||||
const ret = new Promise<string>((resolve, reject) => {
|
const ret = new Promise<string>((resolve, reject) => {
|
||||||
@@ -242,7 +257,7 @@ export class AbstractRelay {
|
|||||||
const ret = new Promise<number>((resolve, reject) => {
|
const ret = new Promise<number>((resolve, reject) => {
|
||||||
this.openCountRequests.set(id, { resolve, reject })
|
this.openCountRequests.set(id, { resolve, reject })
|
||||||
})
|
})
|
||||||
this.send('["COUNT","' + id + '",' + JSON.stringify(filters) + ']')
|
this.send('["COUNT","' + id + '",' + JSON.stringify(filters).substring(1))
|
||||||
return ret
|
return ret
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -328,7 +343,7 @@ export class Subscription {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public close(reason: string = 'closed by caller') {
|
public close(reason: string = 'closed by caller') {
|
||||||
if (!this.closed) {
|
if (!this.closed && this.relay.connected) {
|
||||||
// if the connection was closed by the user calling .close() we will send a CLOSE message
|
// if the connection was closed by the user calling .close() we will send a CLOSE message
|
||||||
// otherwise this._open will be already set to false so we will skip this
|
// otherwise this._open will be already set to false so we will skip this
|
||||||
this.relay.send('["CLOSE",' + JSON.stringify(this.id) + ']')
|
this.relay.send('["CLOSE",' + JSON.stringify(this.id) + ']')
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { run, bench, group, baseline } from 'mitata'
|
import { run, bench, group, baseline } from 'mitata'
|
||||||
import { initNostrWasm } from 'nostr-wasm'
|
import { initNostrWasm } from 'nostr-wasm'
|
||||||
import { NostrEvent } from './core'
|
import { NostrEvent } from './core.ts'
|
||||||
import { finalizeEvent, generateSecretKey } from './pure'
|
import { finalizeEvent, generateSecretKey } from './pure.ts'
|
||||||
import { setNostrWasm, verifyEvent } from './wasm'
|
import { setNostrWasm, verifyEvent } from './wasm.ts'
|
||||||
import { AbstractRelay } from './abstract-relay.ts'
|
import { AbstractRelay } from './abstract-relay.ts'
|
||||||
import { Relay as PureRelay } from './relay.ts'
|
import { Relay as PureRelay } from './relay.ts'
|
||||||
import { alwaysTrue } from './helpers.ts'
|
import { alwaysTrue } from './helpers.ts'
|
||||||
|
|||||||
306
core.test.ts
306
core.test.ts
@@ -1,293 +1,19 @@
|
|||||||
import { describe, test, expect } from 'bun:test'
|
import { test, expect } from 'bun:test'
|
||||||
|
|
||||||
import {
|
import { sortEvents } from './core.ts'
|
||||||
finalizeEvent,
|
|
||||||
serializeEvent,
|
|
||||||
getEventHash,
|
|
||||||
validateEvent,
|
|
||||||
verifyEvent,
|
|
||||||
verifiedSymbol,
|
|
||||||
getPublicKey,
|
|
||||||
generateSecretKey,
|
|
||||||
} from './pure.ts'
|
|
||||||
import { ShortTextNote } from './kinds.ts'
|
|
||||||
import { bytesToHex, hexToBytes } from '@noble/hashes/utils'
|
|
||||||
|
|
||||||
test('private key generation', () => {
|
test('sortEvents', () => {
|
||||||
expect(bytesToHex(generateSecretKey())).toMatch(/[a-f0-9]{64}/)
|
const events = [
|
||||||
})
|
{ id: 'abc123', pubkey: 'key1', created_at: 1610000000, kind: 1, tags: [], content: 'Hello', sig: 'sig1' },
|
||||||
|
{ id: 'abc124', pubkey: 'key2', created_at: 1620000000, kind: 1, tags: [], content: 'World', sig: 'sig2' },
|
||||||
test('public key generation', () => {
|
{ id: 'abc125', pubkey: 'key3', created_at: 1620000000, kind: 1, tags: [], content: '!', sig: 'sig3' },
|
||||||
expect(getPublicKey(generateSecretKey())).toMatch(/[a-f0-9]{64}/)
|
]
|
||||||
})
|
|
||||||
|
const sortedEvents = sortEvents(events)
|
||||||
test('public key from private key deterministic', () => {
|
|
||||||
let sk = generateSecretKey()
|
expect(sortedEvents).toEqual([
|
||||||
let pk = getPublicKey(sk)
|
{ id: 'abc124', pubkey: 'key2', created_at: 1620000000, kind: 1, tags: [], content: 'World', sig: 'sig2' },
|
||||||
|
{ id: 'abc125', pubkey: 'key3', created_at: 1620000000, kind: 1, tags: [], content: '!', sig: 'sig3' },
|
||||||
for (let i = 0; i < 5; i++) {
|
{ id: 'abc123', pubkey: 'key1', created_at: 1610000000, kind: 1, tags: [], content: 'Hello', sig: 'sig1' },
|
||||||
expect(getPublicKey(sk)).toEqual(pk)
|
])
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('finalizeEvent', () => {
|
|
||||||
test('should create a signed event from a template', () => {
|
|
||||||
const privateKey = hexToBytes('d217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf')
|
|
||||||
const publicKey = getPublicKey(privateKey)
|
|
||||||
|
|
||||||
const template = {
|
|
||||||
kind: ShortTextNote,
|
|
||||||
tags: [],
|
|
||||||
content: 'Hello, world!',
|
|
||||||
created_at: 1617932115,
|
|
||||||
}
|
|
||||||
|
|
||||||
const event = finalizeEvent(template, privateKey)
|
|
||||||
|
|
||||||
expect(event.kind).toEqual(template.kind)
|
|
||||||
expect(event.tags).toEqual(template.tags)
|
|
||||||
expect(event.content).toEqual(template.content)
|
|
||||||
expect(event.created_at).toEqual(template.created_at)
|
|
||||||
expect(event.pubkey).toEqual(publicKey)
|
|
||||||
expect(typeof event.id).toEqual('string')
|
|
||||||
expect(typeof event.sig).toEqual('string')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('serializeEvent', () => {
|
|
||||||
test('should serialize a valid event object', () => {
|
|
||||||
const privateKey = hexToBytes('d217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf')
|
|
||||||
const publicKey = getPublicKey(privateKey)
|
|
||||||
|
|
||||||
const unsignedEvent = {
|
|
||||||
pubkey: publicKey,
|
|
||||||
created_at: 1617932115,
|
|
||||||
kind: ShortTextNote,
|
|
||||||
tags: [],
|
|
||||||
content: 'Hello, world!',
|
|
||||||
}
|
|
||||||
|
|
||||||
const serializedEvent = serializeEvent(unsignedEvent)
|
|
||||||
|
|
||||||
expect(serializedEvent).toEqual(
|
|
||||||
JSON.stringify([
|
|
||||||
0,
|
|
||||||
publicKey,
|
|
||||||
unsignedEvent.created_at,
|
|
||||||
unsignedEvent.kind,
|
|
||||||
unsignedEvent.tags,
|
|
||||||
unsignedEvent.content,
|
|
||||||
]),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('should throw an error for an invalid event object', () => {
|
|
||||||
const privateKey = hexToBytes('d217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf')
|
|
||||||
const publicKey = getPublicKey(privateKey)
|
|
||||||
|
|
||||||
const invalidEvent = {
|
|
||||||
kind: ShortTextNote,
|
|
||||||
tags: [],
|
|
||||||
created_at: 1617932115,
|
|
||||||
pubkey: publicKey, // missing content
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(() => {
|
|
||||||
// @ts-expect-error
|
|
||||||
serializeEvent(invalidEvent)
|
|
||||||
}).toThrow("can't serialize event with wrong or missing properties")
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('getEventHash', () => {
|
|
||||||
test('should return the correct event hash', () => {
|
|
||||||
const privateKey = hexToBytes('d217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf')
|
|
||||||
const publicKey = getPublicKey(privateKey)
|
|
||||||
|
|
||||||
const unsignedEvent = {
|
|
||||||
kind: ShortTextNote,
|
|
||||||
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', () => {
|
|
||||||
test('should return true for a valid event object', () => {
|
|
||||||
const privateKey = hexToBytes('d217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf')
|
|
||||||
const publicKey = getPublicKey(privateKey)
|
|
||||||
|
|
||||||
const unsignedEvent = {
|
|
||||||
kind: ShortTextNote,
|
|
||||||
tags: [],
|
|
||||||
content: 'Hello, world!',
|
|
||||||
created_at: 1617932115,
|
|
||||||
pubkey: publicKey,
|
|
||||||
}
|
|
||||||
|
|
||||||
const isValid = validateEvent(unsignedEvent)
|
|
||||||
|
|
||||||
expect(isValid).toEqual(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('should return false for a non object event', () => {
|
|
||||||
const nonObjectEvent = ''
|
|
||||||
const isValid = validateEvent(nonObjectEvent)
|
|
||||||
expect(isValid).toEqual(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('should return false for an event object with missing properties', () => {
|
|
||||||
const invalidEvent = {
|
|
||||||
kind: ShortTextNote,
|
|
||||||
tags: [],
|
|
||||||
created_at: 1617932115, // missing content and pubkey
|
|
||||||
}
|
|
||||||
|
|
||||||
const isValid = validateEvent(invalidEvent)
|
|
||||||
|
|
||||||
expect(isValid).toEqual(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('should return false for an empty object', () => {
|
|
||||||
const emptyObj = {}
|
|
||||||
|
|
||||||
const isValid = validateEvent(emptyObj)
|
|
||||||
|
|
||||||
expect(isValid).toEqual(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('should return false for an object with invalid properties', () => {
|
|
||||||
const privateKey = hexToBytes('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)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('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)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('should return false for an object with invalid tags', () => {
|
|
||||||
const privateKey = hexToBytes('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('verifyEvent', () => {
|
|
||||||
test('should return true for a valid event signature', () => {
|
|
||||||
const privateKey = hexToBytes('d217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf')
|
|
||||||
const event = finalizeEvent(
|
|
||||||
{
|
|
||||||
kind: ShortTextNote,
|
|
||||||
tags: [],
|
|
||||||
content: 'Hello, world!',
|
|
||||||
created_at: 1617932115,
|
|
||||||
},
|
|
||||||
privateKey,
|
|
||||||
)
|
|
||||||
|
|
||||||
const isValid = verifyEvent(event)
|
|
||||||
expect(isValid).toEqual(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('should return false for an invalid event signature', () => {
|
|
||||||
const privateKey = hexToBytes('d217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf')
|
|
||||||
const { [verifiedSymbol]: _, ...event } = finalizeEvent(
|
|
||||||
{
|
|
||||||
kind: ShortTextNote,
|
|
||||||
tags: [],
|
|
||||||
content: 'Hello, world!',
|
|
||||||
created_at: 1617932115,
|
|
||||||
},
|
|
||||||
privateKey,
|
|
||||||
)
|
|
||||||
|
|
||||||
// tamper with the signature
|
|
||||||
event.sig = event.sig.replace(/^.{3}/g, '666')
|
|
||||||
|
|
||||||
const isValid = verifyEvent(event)
|
|
||||||
expect(isValid).toEqual(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('should return false when verifying an event with a different private key', () => {
|
|
||||||
const privateKey1 = hexToBytes('d217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf')
|
|
||||||
|
|
||||||
const privateKey2 = hexToBytes('5b4a34f4e4b23c63ad55a35e3f84a3b53d96dbf266edf521a8358f71d19cbf67')
|
|
||||||
const publicKey2 = getPublicKey(privateKey2)
|
|
||||||
|
|
||||||
const { [verifiedSymbol]: _, ...event } = finalizeEvent(
|
|
||||||
{
|
|
||||||
kind: ShortTextNote,
|
|
||||||
tags: [],
|
|
||||||
content: 'Hello, world!',
|
|
||||||
created_at: 1617932115,
|
|
||||||
},
|
|
||||||
privateKey1,
|
|
||||||
)
|
|
||||||
|
|
||||||
// verify with different private key
|
|
||||||
const isValid = verifyEvent({
|
|
||||||
...event,
|
|
||||||
pubkey: publicKey2,
|
|
||||||
})
|
|
||||||
expect(isValid).toEqual(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('should return false for an invalid event id', () => {
|
|
||||||
const privateKey = hexToBytes('d217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf')
|
|
||||||
|
|
||||||
const { [verifiedSymbol]: _, ...event } = finalizeEvent(
|
|
||||||
{
|
|
||||||
kind: 1,
|
|
||||||
tags: [],
|
|
||||||
content: 'Hello, world!',
|
|
||||||
created_at: 1617932115,
|
|
||||||
},
|
|
||||||
privateKey,
|
|
||||||
)
|
|
||||||
|
|
||||||
// tamper with the id
|
|
||||||
event.id = event.id.replace(/^.{3}/g, '666')
|
|
||||||
|
|
||||||
const isValid = verifyEvent(event)
|
|
||||||
expect(isValid).toEqual(false)
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|||||||
14
core.ts
14
core.ts
@@ -49,3 +49,17 @@ export function validateEvent<T>(event: T): event is T & UnsignedEvent {
|
|||||||
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sort events in reverse-chronological order by the `created_at` timestamp,
|
||||||
|
* and then by the event `id` (lexicographically) in case of ties.
|
||||||
|
* This mutates the array.
|
||||||
|
*/
|
||||||
|
export function sortEvents(events: Event[]): Event[] {
|
||||||
|
return events.sort((a: NostrEvent, b: NostrEvent): number => {
|
||||||
|
if (a.created_at !== b.created_at) {
|
||||||
|
return b.created_at - a.created_at
|
||||||
|
}
|
||||||
|
return a.id.localeCompare(b.id)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ describe('Filter', () => {
|
|||||||
until: 200,
|
until: 200,
|
||||||
'#tag': ['value'],
|
'#tag': ['value'],
|
||||||
}
|
}
|
||||||
|
|
||||||
const event = buildEvent({
|
const event = buildEvent({
|
||||||
id: '123',
|
id: '123',
|
||||||
kind: 1,
|
kind: 1,
|
||||||
@@ -21,39 +20,21 @@ describe('Filter', () => {
|
|||||||
created_at: 150,
|
created_at: 150,
|
||||||
tags: [['tag', 'value']],
|
tags: [['tag', 'value']],
|
||||||
})
|
})
|
||||||
|
|
||||||
const result = matchFilter(filter, event)
|
const result = matchFilter(filter, event)
|
||||||
|
|
||||||
expect(result).toEqual(true)
|
expect(result).toEqual(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('should return false when the event id is not in the filter', () => {
|
test('should return false when the event id is not in the filter', () => {
|
||||||
const filter = { ids: ['123', '456'] }
|
const filter = { ids: ['123', '456'] }
|
||||||
|
|
||||||
const event = buildEvent({ id: '789' })
|
const event = buildEvent({ id: '789' })
|
||||||
|
|
||||||
const result = matchFilter(filter, event)
|
const result = matchFilter(filter, event)
|
||||||
|
|
||||||
expect(result).toEqual(false)
|
expect(result).toEqual(false)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('should return true when the event id starts with a prefix', () => {
|
|
||||||
const filter = { ids: ['22', '00'] }
|
|
||||||
|
|
||||||
const event = buildEvent({ id: '001' })
|
|
||||||
|
|
||||||
const result = matchFilter(filter, event)
|
|
||||||
|
|
||||||
expect(result).toEqual(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('should return false when the event kind is not in the filter', () => {
|
test('should return false when the event kind is not in the filter', () => {
|
||||||
const filter = { kinds: [1, 2, 3] }
|
const filter = { kinds: [1, 2, 3] }
|
||||||
|
|
||||||
const event = buildEvent({ kind: 4 })
|
const event = buildEvent({ kind: 4 })
|
||||||
|
|
||||||
const result = matchFilter(filter, event)
|
const result = matchFilter(filter, event)
|
||||||
|
|
||||||
expect(result).toEqual(false)
|
expect(result).toEqual(false)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -154,25 +135,8 @@ describe('Filter', () => {
|
|||||||
{ ids: ['456'], kinds: [2], authors: ['def'] },
|
{ ids: ['456'], kinds: [2], authors: ['def'] },
|
||||||
{ ids: ['789'], kinds: [3], authors: ['ghi'] },
|
{ ids: ['789'], kinds: [3], authors: ['ghi'] },
|
||||||
]
|
]
|
||||||
|
|
||||||
const event = buildEvent({ id: '789', kind: 3, pubkey: 'ghi' })
|
const event = buildEvent({ id: '789', kind: 3, pubkey: 'ghi' })
|
||||||
|
|
||||||
const result = matchFilters(filters, event)
|
const result = matchFilters(filters, event)
|
||||||
|
|
||||||
expect(result).toEqual(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('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 = buildEvent({ id: '987', kind: 3, pubkey: 'ghi' })
|
|
||||||
|
|
||||||
const result = matchFilters(filters, event)
|
|
||||||
|
|
||||||
expect(result).toEqual(true)
|
expect(result).toEqual(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -201,11 +165,8 @@ describe('Filter', () => {
|
|||||||
{ ids: ['456'], kinds: [2], authors: ['def'] },
|
{ ids: ['456'], kinds: [2], authors: ['def'] },
|
||||||
{ ids: ['789'], kinds: [3], authors: ['ghi'] },
|
{ ids: ['789'], kinds: [3], authors: ['ghi'] },
|
||||||
]
|
]
|
||||||
|
|
||||||
const event = buildEvent({ id: '100', kind: 4, pubkey: 'jkl' })
|
const event = buildEvent({ id: '100', kind: 4, pubkey: 'jkl' })
|
||||||
|
|
||||||
const result = matchFilters(filters, event)
|
const result = matchFilters(filters, event)
|
||||||
|
|
||||||
expect(result).toEqual(false)
|
expect(result).toEqual(false)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -221,9 +182,7 @@ describe('Filter', () => {
|
|||||||
pubkey: 'def',
|
pubkey: 'def',
|
||||||
created_at: 200,
|
created_at: 200,
|
||||||
})
|
})
|
||||||
|
|
||||||
const result = matchFilters(filters, event)
|
const result = matchFilters(filters, event)
|
||||||
|
|
||||||
expect(result).toEqual(false)
|
expect(result).toEqual(false)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
16
filter.ts
16
filter.ts
@@ -14,15 +14,13 @@ export type Filter = {
|
|||||||
|
|
||||||
export function matchFilter(filter: Filter, event: Event): boolean {
|
export function matchFilter(filter: Filter, event: Event): boolean {
|
||||||
if (filter.ids && filter.ids.indexOf(event.id) === -1) {
|
if (filter.ids && filter.ids.indexOf(event.id) === -1) {
|
||||||
if (!filter.ids.some(prefix => event.id.startsWith(prefix))) {
|
return false
|
||||||
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) {
|
||||||
if (!filter.authors.some(prefix => event.pubkey.startsWith(prefix))) {
|
return false
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for (let f in filter) {
|
for (let f in filter) {
|
||||||
@@ -41,7 +39,9 @@ export function matchFilter(filter: Filter, event: Event): boolean {
|
|||||||
|
|
||||||
export function matchFilters(filters: Filter[], event: Event): boolean {
|
export function matchFilters(filters: Filter[], event: Event): 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
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|||||||
4
index.ts
4
index.ts
@@ -1,7 +1,7 @@
|
|||||||
export * from './pure.ts'
|
export * from './pure.ts'
|
||||||
export * from './relay.ts'
|
export { Relay } from './relay.ts'
|
||||||
export * from './filter.ts'
|
export * from './filter.ts'
|
||||||
export * from './pool.ts'
|
export { SimplePool } from './pool.ts'
|
||||||
export * from './references.ts'
|
export * from './references.ts'
|
||||||
|
|
||||||
export * as nip04 from './nip04.ts'
|
export * as nip04 from './nip04.ts'
|
||||||
|
|||||||
45
jsr.json
Normal file
45
jsr.json
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
{
|
||||||
|
"name": "@nostr/tools",
|
||||||
|
"version": "2.3.2",
|
||||||
|
"exports": {
|
||||||
|
".": "./index.ts",
|
||||||
|
"./core": "./core.ts",
|
||||||
|
"./pure": "./pure.ts",
|
||||||
|
"./wasm": "./wasm.ts",
|
||||||
|
"./kinds": "./kinds.ts",
|
||||||
|
"./filter": "./filter.ts",
|
||||||
|
"./abstract-relay": "./abstract-relay.ts",
|
||||||
|
"./relay": "./relay.ts",
|
||||||
|
"./abstract-pool": "./abstract-pool.ts",
|
||||||
|
"./pool": "./pool.ts",
|
||||||
|
"./references": "./references.ts",
|
||||||
|
"./nip04": "./nip04.ts",
|
||||||
|
"./nip05": "./nip05.ts",
|
||||||
|
"./nip06": "./nip06.ts",
|
||||||
|
"./nip07": "./nip07.ts",
|
||||||
|
"./nip10": "./nip10.ts",
|
||||||
|
"./nip11": "./nip11.ts",
|
||||||
|
"./nip13": "./nip13.ts",
|
||||||
|
"./nip18": "./nip18.ts",
|
||||||
|
"./nip19": "./nip19.ts",
|
||||||
|
"./nip21": "./nip21.ts",
|
||||||
|
"./nip25": "./nip25.ts",
|
||||||
|
"./nip27": "./nip27.ts",
|
||||||
|
"./nip28": "./nip28.ts",
|
||||||
|
"./nip29": "./nip29.ts",
|
||||||
|
"./nip30": "./nip30.ts",
|
||||||
|
"./nip39": "./nip39.ts",
|
||||||
|
"./nip42": "./nip42.ts",
|
||||||
|
"./nip44": "./nip44.ts",
|
||||||
|
"./nip46": "./nip46.ts",
|
||||||
|
"./nip49": "./nip49.ts",
|
||||||
|
"./nip57": "./nip57.ts",
|
||||||
|
"./nip75": "./nip75.ts",
|
||||||
|
"./nip94": "./nip94.ts",
|
||||||
|
"./nip96": "./nip96.ts",
|
||||||
|
"./nip98": "./nip98.ts",
|
||||||
|
"./nip99": "./nip99.ts",
|
||||||
|
"./fakejson": "./fakejson.ts",
|
||||||
|
"./utils": "./utils.ts"
|
||||||
|
}
|
||||||
|
}
|
||||||
9
kinds.ts
9
kinds.ts
@@ -1,20 +1,20 @@
|
|||||||
/** Events are **regular**, which means they're all expected to be stored by relays. */
|
/** Events are **regular**, which means they're all expected to be stored by relays. */
|
||||||
export function isRegularKind(kind: number) {
|
export function isRegularKind(kind: number): boolean {
|
||||||
return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)
|
return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */
|
/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */
|
||||||
export function isReplaceableKind(kind: number) {
|
export function isReplaceableKind(kind: number): boolean {
|
||||||
return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)
|
return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Events are **ephemeral**, which means they are not expected to be stored by relays. */
|
/** Events are **ephemeral**, which means they are not expected to be stored by relays. */
|
||||||
export function isEphemeralKind(kind: number) {
|
export function isEphemeralKind(kind: number): boolean {
|
||||||
return 20000 <= kind && kind < 30000
|
return 20000 <= kind && kind < 30000
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Events are **parameterized replaceable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */
|
/** Events are **parameterized replaceable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */
|
||||||
export function isParameterizedReplaceableKind(kind: number) {
|
export function isParameterizedReplaceableKind(kind: number): boolean {
|
||||||
return 30000 <= kind && kind < 40000
|
return 30000 <= kind && kind < 40000
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -78,7 +78,6 @@ export const ClientAuth = 22242
|
|||||||
export const NWCWalletRequest = 23194
|
export const NWCWalletRequest = 23194
|
||||||
export const NWCWalletResponse = 23195
|
export const NWCWalletResponse = 23195
|
||||||
export const NostrConnect = 24133
|
export const NostrConnect = 24133
|
||||||
export const NostrConnectAdmin = 24134
|
|
||||||
export const HTTPAuth = 27235
|
export const HTTPAuth = 27235
|
||||||
export const Followsets = 30000
|
export const Followsets = 30000
|
||||||
export const Genericlists = 30001
|
export const Genericlists = 30001
|
||||||
|
|||||||
@@ -1,18 +1,9 @@
|
|||||||
import { test, expect } from 'bun:test'
|
import { test, expect } from 'bun:test'
|
||||||
import crypto from 'node:crypto'
|
|
||||||
|
|
||||||
import { encrypt, decrypt } from './nip04.ts'
|
import { encrypt, decrypt } from './nip04.ts'
|
||||||
import { getPublicKey, generateSecretKey } from './pure.ts'
|
import { getPublicKey, generateSecretKey } from './pure.ts'
|
||||||
import { bytesToHex, hexToBytes } from '@noble/hashes/utils'
|
import { bytesToHex, hexToBytes } from '@noble/hashes/utils'
|
||||||
|
|
||||||
try {
|
|
||||||
// @ts-ignore
|
|
||||||
// eslint-disable-next-line no-undef
|
|
||||||
globalThis.crypto = crypto
|
|
||||||
} catch (err) {
|
|
||||||
/***/
|
|
||||||
}
|
|
||||||
|
|
||||||
test('encrypt and decrypt message', async () => {
|
test('encrypt and decrypt message', async () => {
|
||||||
let sk1 = generateSecretKey()
|
let sk1 = generateSecretKey()
|
||||||
let sk2 = generateSecretKey()
|
let sk2 = generateSecretKey()
|
||||||
|
|||||||
20
nip04.ts
20
nip04.ts
@@ -1,15 +1,10 @@
|
|||||||
import { bytesToHex, randomBytes } from '@noble/hashes/utils'
|
import { bytesToHex, randomBytes } from '@noble/hashes/utils'
|
||||||
import { secp256k1 } from '@noble/curves/secp256k1'
|
import { secp256k1 } from '@noble/curves/secp256k1'
|
||||||
|
import { cbc } from '@noble/ciphers/aes'
|
||||||
import { base64 } from '@scure/base'
|
import { base64 } from '@scure/base'
|
||||||
|
|
||||||
import { utf8Decoder, utf8Encoder } from './utils.ts'
|
import { utf8Decoder, utf8Encoder } from './utils.ts'
|
||||||
|
|
||||||
// @ts-ignore
|
|
||||||
if (typeof crypto !== 'undefined' && !crypto.subtle && crypto.webcrypto) {
|
|
||||||
// @ts-ignore
|
|
||||||
crypto.subtle = crypto.webcrypto.subtle
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function encrypt(secretKey: string | Uint8Array, pubkey: string, text: string): Promise<string> {
|
export async function encrypt(secretKey: string | Uint8Array, pubkey: string, text: string): Promise<string> {
|
||||||
const privkey: string = secretKey instanceof Uint8Array ? bytesToHex(secretKey) : secretKey
|
const privkey: string = secretKey instanceof Uint8Array ? bytesToHex(secretKey) : secretKey
|
||||||
const key = secp256k1.getSharedSecret(privkey, '02' + pubkey)
|
const key = secp256k1.getSharedSecret(privkey, '02' + pubkey)
|
||||||
@@ -17,8 +12,9 @@ export async function encrypt(secretKey: string | Uint8Array, pubkey: string, te
|
|||||||
|
|
||||||
let iv = Uint8Array.from(randomBytes(16))
|
let iv = Uint8Array.from(randomBytes(16))
|
||||||
let plaintext = utf8Encoder.encode(text)
|
let plaintext = utf8Encoder.encode(text)
|
||||||
let cryptoKey = await crypto.subtle.importKey('raw', normalizedKey, { name: 'AES-CBC' }, false, ['encrypt'])
|
|
||||||
let ciphertext = await crypto.subtle.encrypt({ name: 'AES-CBC', iv }, cryptoKey, plaintext)
|
let ciphertext = cbc(normalizedKey, iv).encrypt(plaintext)
|
||||||
|
|
||||||
let ctb64 = base64.encode(new Uint8Array(ciphertext))
|
let ctb64 = base64.encode(new Uint8Array(ciphertext))
|
||||||
let ivb64 = base64.encode(new Uint8Array(iv.buffer))
|
let ivb64 = base64.encode(new Uint8Array(iv.buffer))
|
||||||
|
|
||||||
@@ -31,14 +27,12 @@ export async function decrypt(secretKey: string | Uint8Array, pubkey: string, da
|
|||||||
let key = secp256k1.getSharedSecret(privkey, '02' + pubkey)
|
let key = secp256k1.getSharedSecret(privkey, '02' + pubkey)
|
||||||
let normalizedKey = getNormalizedX(key)
|
let normalizedKey = getNormalizedX(key)
|
||||||
|
|
||||||
let cryptoKey = await crypto.subtle.importKey('raw', normalizedKey, { name: 'AES-CBC' }, false, ['decrypt'])
|
|
||||||
let ciphertext = base64.decode(ctb64)
|
|
||||||
let iv = base64.decode(ivb64)
|
let iv = base64.decode(ivb64)
|
||||||
|
let ciphertext = base64.decode(ctb64)
|
||||||
|
|
||||||
let plaintext = await crypto.subtle.decrypt({ name: 'AES-CBC', iv }, cryptoKey, ciphertext)
|
let plaintext = cbc(normalizedKey, iv).decrypt(ciphertext)
|
||||||
|
|
||||||
let text = utf8Decoder.decode(plaintext)
|
return utf8Decoder.decode(plaintext)
|
||||||
return text
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function getNormalizedX(key: Uint8Array): Uint8Array {
|
function getNormalizedX(key: Uint8Array): Uint8Array {
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
import { test, expect } from 'bun:test'
|
import { test, expect } from 'bun:test'
|
||||||
import { privateKeyFromSeedWords } from './nip06.ts'
|
import {
|
||||||
|
privateKeyFromSeedWords,
|
||||||
|
accountFromSeedWords,
|
||||||
|
extendedKeysFromSeedWords,
|
||||||
|
accountFromExtendedKey,
|
||||||
|
} from './nip06.ts'
|
||||||
|
|
||||||
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'
|
||||||
@@ -26,3 +31,46 @@ test('generate private key for account 1 from a mnemonic and passphrase', async
|
|||||||
const privateKey = privateKeyFromSeedWords(mnemonic, passphrase, 1)
|
const privateKey = privateKeyFromSeedWords(mnemonic, passphrase, 1)
|
||||||
expect(privateKey).toEqual('2e0f7bd9e3c3ebcdff1a90fb49c913477e7c055eba1a415d571b6a8c714c7135')
|
expect(privateKey).toEqual('2e0f7bd9e3c3ebcdff1a90fb49c913477e7c055eba1a415d571b6a8c714c7135')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('generate private and public key for account 1 from a mnemonic and passphrase', async () => {
|
||||||
|
const mnemonic = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong'
|
||||||
|
const passphrase = '123'
|
||||||
|
const { privateKey, publicKey } = accountFromSeedWords(mnemonic, passphrase, 1)
|
||||||
|
expect(privateKey).toEqual('2e0f7bd9e3c3ebcdff1a90fb49c913477e7c055eba1a415d571b6a8c714c7135')
|
||||||
|
expect(publicKey).toEqual('13f55f4f01576570ea342eb7d2b611f9dc78f8dc601aeb512011e4e73b90cf0a')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('generate extended keys from mnemonic', () => {
|
||||||
|
const mnemonic = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'
|
||||||
|
const passphrase = ''
|
||||||
|
const extendedAccountIndex = 0
|
||||||
|
const { privateExtendedKey, publicExtendedKey } = extendedKeysFromSeedWords(
|
||||||
|
mnemonic,
|
||||||
|
passphrase,
|
||||||
|
extendedAccountIndex,
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(privateExtendedKey).toBe(
|
||||||
|
'xprv9z78fizET65qsCaRr1MSutTSGk1fcKfSt1sBqmuWShtkjRJJ4WCKcSnha6EmgNzFSsyom3MWtydHyPtJtSLZQUtictVQtM2vkPcguh6TQCH',
|
||||||
|
)
|
||||||
|
expect(publicExtendedKey).toBe(
|
||||||
|
'xpub6D6V5EX8HTe95getx2tTH2QApmrA1nPJFEnneAK813RjcDdSc3WaAF7BRNpTF7o7zXjVm3DD3VMX66jhQ7wLaZ9sS6NzyfiwfzqDZbxvpDN',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('generate account from extended private key', () => {
|
||||||
|
const xprv =
|
||||||
|
'xprv9z78fizET65qsCaRr1MSutTSGk1fcKfSt1sBqmuWShtkjRJJ4WCKcSnha6EmgNzFSsyom3MWtydHyPtJtSLZQUtictVQtM2vkPcguh6TQCH'
|
||||||
|
const { privateKey, publicKey } = accountFromExtendedKey(xprv)
|
||||||
|
|
||||||
|
expect(privateKey).toBe('5f29af3b9676180290e77a4efad265c4c2ff28a5302461f73597fda26bb25731')
|
||||||
|
expect(publicKey).toBe('e8bcf3823669444d0b49ad45d65088635d9fd8500a75b5f20b59abefa56a144f')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('generate account from extended public key', () => {
|
||||||
|
const xpub =
|
||||||
|
'xpub6D6V5EX8HTe95getx2tTH2QApmrA1nPJFEnneAK813RjcDdSc3WaAF7BRNpTF7o7zXjVm3DD3VMX66jhQ7wLaZ9sS6NzyfiwfzqDZbxvpDN'
|
||||||
|
const { publicKey } = accountFromExtendedKey(xpub)
|
||||||
|
|
||||||
|
expect(publicKey).toBe('e8bcf3823669444d0b49ad45d65088635d9fd8500a75b5f20b59abefa56a144f')
|
||||||
|
})
|
||||||
|
|||||||
58
nip06.ts
58
nip06.ts
@@ -3,13 +3,69 @@ import { wordlist } from '@scure/bip39/wordlists/english'
|
|||||||
import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39'
|
import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39'
|
||||||
import { HDKey } from '@scure/bip32'
|
import { HDKey } from '@scure/bip32'
|
||||||
|
|
||||||
|
const DERIVATION_PATH = `m/44'/1237'`
|
||||||
|
|
||||||
export function privateKeyFromSeedWords(mnemonic: string, passphrase?: string, accountIndex = 0): string {
|
export function privateKeyFromSeedWords(mnemonic: string, passphrase?: string, accountIndex = 0): string {
|
||||||
let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))
|
let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))
|
||||||
let privateKey = root.derive(`m/44'/1237'/${accountIndex}'/0/0`).privateKey
|
let privateKey = root.derive(`${DERIVATION_PATH}/${accountIndex}'/0/0`).privateKey
|
||||||
if (!privateKey) throw new Error('could not derive private key')
|
if (!privateKey) throw new Error('could not derive private key')
|
||||||
return bytesToHex(privateKey)
|
return bytesToHex(privateKey)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function accountFromSeedWords(
|
||||||
|
mnemonic: string,
|
||||||
|
passphrase?: string,
|
||||||
|
accountIndex = 0,
|
||||||
|
): {
|
||||||
|
privateKey: string
|
||||||
|
publicKey: string
|
||||||
|
} {
|
||||||
|
const root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))
|
||||||
|
const seed = root.derive(`${DERIVATION_PATH}/${accountIndex}'/0/0`)
|
||||||
|
const privateKey = bytesToHex(seed.privateKey!)
|
||||||
|
const publicKey = bytesToHex(seed.publicKey!.slice(1))
|
||||||
|
if (!privateKey && !publicKey) {
|
||||||
|
throw new Error('could not derive key pair')
|
||||||
|
}
|
||||||
|
return { privateKey, publicKey }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function extendedKeysFromSeedWords(
|
||||||
|
mnemonic: string,
|
||||||
|
passphrase?: string,
|
||||||
|
extendedAccountIndex = 0,
|
||||||
|
): {
|
||||||
|
privateExtendedKey: string
|
||||||
|
publicExtendedKey: string
|
||||||
|
} {
|
||||||
|
let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))
|
||||||
|
let seed = root.derive(`${DERIVATION_PATH}/${extendedAccountIndex}'`)
|
||||||
|
let privateExtendedKey = seed.privateExtendedKey
|
||||||
|
let publicExtendedKey = seed.publicExtendedKey
|
||||||
|
if (!privateExtendedKey && !publicExtendedKey) throw new Error('could not derive extended key pair')
|
||||||
|
return { privateExtendedKey, publicExtendedKey }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function accountFromExtendedKey(
|
||||||
|
base58key: string,
|
||||||
|
accountIndex = 0,
|
||||||
|
): {
|
||||||
|
privateKey?: string
|
||||||
|
publicKey: string
|
||||||
|
} {
|
||||||
|
let extendedKey = HDKey.fromExtendedKey(base58key)
|
||||||
|
let version = base58key.slice(0, 4)
|
||||||
|
let child = extendedKey.deriveChild(0).deriveChild(accountIndex)
|
||||||
|
let publicKey = bytesToHex(child.publicKey!.slice(1))
|
||||||
|
if (!publicKey) throw new Error('could not derive public key')
|
||||||
|
if (version === 'xprv') {
|
||||||
|
let privateKey = bytesToHex(child.privateKey!)
|
||||||
|
if (!privateKey) throw new Error('could not derive private key')
|
||||||
|
return { privateKey, publicKey }
|
||||||
|
}
|
||||||
|
return { publicKey }
|
||||||
|
}
|
||||||
|
|
||||||
export function generateSeedWords(): string {
|
export function generateSeedWords(): string {
|
||||||
return generateMnemonic(wordlist)
|
return generateMnemonic(wordlist)
|
||||||
}
|
}
|
||||||
|
|||||||
16
nip07.ts
Normal file
16
nip07.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import { EventTemplate, NostrEvent } from './core.ts'
|
||||||
|
import { RelayRecord } from './relay.ts'
|
||||||
|
|
||||||
|
export interface WindowNostr {
|
||||||
|
getPublicKey(): Promise<string>
|
||||||
|
signEvent(event: EventTemplate): Promise<NostrEvent>
|
||||||
|
getRelays(): Promise<RelayRecord>
|
||||||
|
nip04?: {
|
||||||
|
encrypt(pubkey: string, plaintext: string): Promise<string>
|
||||||
|
decrypt(pubkey: string, ciphertext: string): Promise<string>
|
||||||
|
}
|
||||||
|
nip44?: {
|
||||||
|
encrypt(pubkey: string, plaintext: string): Promise<string>
|
||||||
|
decrypt(pubkey: string, ciphertext: string): Promise<string>
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,17 +1,16 @@
|
|||||||
import { describe, test, expect } from 'bun:test'
|
import { describe, test, expect } from 'bun:test'
|
||||||
import fetch from 'node-fetch'
|
import fetch from 'node-fetch'
|
||||||
import { useFetchImplementation, fetchRelayInformation } from './nip11'
|
import { useFetchImplementation, fetchRelayInformation } from './nip11.ts'
|
||||||
|
|
||||||
// TODO: replace with a mock
|
// TODO: replace with a mock
|
||||||
describe('requesting relay as for NIP11', () => {
|
describe('requesting relay as for NIP11', () => {
|
||||||
useFetchImplementation(fetch)
|
useFetchImplementation(fetch)
|
||||||
|
|
||||||
test('testing a relay', async () => {
|
test('testing a relay', async () => {
|
||||||
const info = await fetchRelayInformation('wss://atlas.nostr.land')
|
const info = await fetchRelayInformation('wss://nos.lol')
|
||||||
expect(info.name).toEqual('nostr.land')
|
expect(info.name).toEqual('nos.lol')
|
||||||
expect(info.description).toEqual('nostr.land family of relays (us-or-01)')
|
expect(info.description).toContain('Generally accepts notes, except spammy ones.')
|
||||||
expect(info.fees).toBeTruthy()
|
|
||||||
expect(info.supported_nips).toEqual([1, 2, 4, 9, 11, 12, 16, 20, 22, 28, 33, 40])
|
expect(info.supported_nips).toEqual([1, 2, 4, 9, 11, 12, 16, 20, 22, 28, 33, 40])
|
||||||
expect(info.software).toEqual('custom')
|
expect(info.software).toEqual('git+https://github.com/hoytech/strfry.git')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
4
nip11.ts
4
nip11.ts
@@ -4,11 +4,11 @@ try {
|
|||||||
_fetch = fetch
|
_fetch = fetch
|
||||||
} catch {}
|
} catch {}
|
||||||
|
|
||||||
export function useFetchImplementation(fetchImplementation: any) {
|
export function useFetchImplementation(fetchImplementation: any): void {
|
||||||
_fetch = fetchImplementation
|
_fetch = fetchImplementation
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchRelayInformation(url: string) {
|
export async function fetchRelayInformation(url: string): Promise<RelayInformation> {
|
||||||
return (await (
|
return (await (
|
||||||
await fetch(url.replace('ws://', 'http://').replace('wss://', 'https://'), {
|
await fetch(url.replace('ws://', 'http://').replace('wss://', 'https://'), {
|
||||||
headers: { Accept: 'application/nostr+json' },
|
headers: { Accept: 'application/nostr+json' },
|
||||||
|
|||||||
2
nip21.ts
2
nip21.ts
@@ -1,7 +1,7 @@
|
|||||||
import { BECH32_REGEX, decode, type DecodeResult } from './nip19.ts'
|
import { BECH32_REGEX, decode, type DecodeResult } from './nip19.ts'
|
||||||
|
|
||||||
/** Nostr URI regex, eg `nostr:npub1...` */
|
/** Nostr URI regex, eg `nostr:npub1...` */
|
||||||
export const NOSTR_URI_REGEX = new RegExp(`nostr:(${BECH32_REGEX.source})`)
|
export const NOSTR_URI_REGEX: RegExp = new RegExp(`nostr:(${BECH32_REGEX.source})`)
|
||||||
|
|
||||||
/** Test whether the value is a Nostr URI. */
|
/** Test whether the value is a Nostr URI. */
|
||||||
export function test(value: unknown): value is `nostr:${string}` {
|
export function test(value: unknown): value is `nostr:${string}` {
|
||||||
|
|||||||
2
nip27.ts
2
nip27.ts
@@ -2,7 +2,7 @@ import { decode } from './nip19.ts'
|
|||||||
import { NOSTR_URI_REGEX, type NostrURI } from './nip21.ts'
|
import { NOSTR_URI_REGEX, type NostrURI } from './nip21.ts'
|
||||||
|
|
||||||
/** Regex to find NIP-21 URIs inside event content. */
|
/** Regex to find NIP-21 URIs inside event content. */
|
||||||
export const regex = () => new RegExp(`\\b${NOSTR_URI_REGEX.source}\\b`, 'g')
|
export const regex = (): RegExp => new RegExp(`\\b${NOSTR_URI_REGEX.source}\\b`, 'g')
|
||||||
|
|
||||||
/** Match result for a Nostr URI in event content. */
|
/** Match result for a Nostr URI in event content. */
|
||||||
export interface NostrURIMatch extends NostrURI {
|
export interface NostrURIMatch extends NostrURI {
|
||||||
|
|||||||
14
nip29.ts
14
nip29.ts
@@ -1,10 +1,10 @@
|
|||||||
import { AbstractSimplePool } from './abstract-pool'
|
import { AbstractSimplePool } from './abstract-pool.ts'
|
||||||
import { Subscription } from './abstract-relay'
|
import { Subscription } from './abstract-relay.ts'
|
||||||
import { decode } from './nip19'
|
import { decode } from './nip19.ts'
|
||||||
import type { Event } from './core'
|
import type { Event } from './core.ts'
|
||||||
import { fetchRelayInformation } from './nip11'
|
import { fetchRelayInformation } from './nip11.ts'
|
||||||
import { normalizeURL } from './utils'
|
import { normalizeURL } from './utils.ts'
|
||||||
import { AddressPointer } from './nip19'
|
import { AddressPointer } from './nip19.ts'
|
||||||
|
|
||||||
export function subscribeRelayGroups(
|
export function subscribeRelayGroups(
|
||||||
pool: AbstractSimplePool,
|
pool: AbstractSimplePool,
|
||||||
|
|||||||
2
nip30.ts
2
nip30.ts
@@ -2,7 +2,7 @@
|
|||||||
export const EMOJI_SHORTCODE_REGEX = /:(\w+):/
|
export const EMOJI_SHORTCODE_REGEX = /:(\w+):/
|
||||||
|
|
||||||
/** Regex to find emoji shortcodes in content. */
|
/** Regex to find emoji shortcodes in content. */
|
||||||
export const regex = () => new RegExp(`\\B${EMOJI_SHORTCODE_REGEX.source}\\B`, 'g')
|
export const regex = (): RegExp => new RegExp(`\\B${EMOJI_SHORTCODE_REGEX.source}\\B`, 'g')
|
||||||
|
|
||||||
/** Represents a Nostr custom emoji. */
|
/** Represents a Nostr custom emoji. */
|
||||||
export interface CustomEmoji {
|
export interface CustomEmoji {
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ const v2vec = vec.v2
|
|||||||
|
|
||||||
test('get_conversation_key', () => {
|
test('get_conversation_key', () => {
|
||||||
for (const v of v2vec.valid.get_conversation_key) {
|
for (const v of v2vec.valid.get_conversation_key) {
|
||||||
const key = v2.utils.getConversationKey(v.sec1, v.pub2)
|
const key = v2.utils.getConversationKey(hexToBytes(v.sec1), v.pub2)
|
||||||
expect(bytesToHex(key)).toEqual(v.conversation_key)
|
expect(bytesToHex(key)).toEqual(v.conversation_key)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -15,7 +15,7 @@ test('get_conversation_key', () => {
|
|||||||
test('encrypt_decrypt', () => {
|
test('encrypt_decrypt', () => {
|
||||||
for (const v of v2vec.valid.encrypt_decrypt) {
|
for (const v of v2vec.valid.encrypt_decrypt) {
|
||||||
const pub2 = bytesToHex(schnorr.getPublicKey(v.sec2))
|
const pub2 = bytesToHex(schnorr.getPublicKey(v.sec2))
|
||||||
const key = v2.utils.getConversationKey(v.sec1, pub2)
|
const key = v2.utils.getConversationKey(hexToBytes(v.sec1), pub2)
|
||||||
expect(bytesToHex(key)).toEqual(v.conversation_key)
|
expect(bytesToHex(key)).toEqual(v.conversation_key)
|
||||||
const ciphertext = v2.encrypt(v.plaintext, key, hexToBytes(v.nonce))
|
const ciphertext = v2.encrypt(v.plaintext, key, hexToBytes(v.nonce))
|
||||||
expect(ciphertext).toEqual(v.payload)
|
expect(ciphertext).toEqual(v.payload)
|
||||||
@@ -39,6 +39,8 @@ test('decrypt', async () => {
|
|||||||
|
|
||||||
test('get_conversation_key', async () => {
|
test('get_conversation_key', async () => {
|
||||||
for (const v of v2vec.invalid.get_conversation_key) {
|
for (const v of v2vec.invalid.get_conversation_key) {
|
||||||
expect(() => v2.utils.getConversationKey(v.sec1, v.pub2)).toThrow(/(Point is not on curve|Cannot find square root)/)
|
expect(() => v2.utils.getConversationKey(hexToBytes(v.sec1), v.pub2)).toThrow(
|
||||||
|
/(Point is not on curve|Cannot find square root)/,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
212
nip44.ts
212
nip44.ts
@@ -1,131 +1,127 @@
|
|||||||
import { chacha20 } from '@noble/ciphers/chacha'
|
import { chacha20 } from '@noble/ciphers/chacha'
|
||||||
import { ensureBytes, equalBytes } from '@noble/ciphers/utils'
|
import { equalBytes } from '@noble/ciphers/utils'
|
||||||
import { secp256k1 } from '@noble/curves/secp256k1'
|
import { secp256k1 } from '@noble/curves/secp256k1'
|
||||||
import { extract as hkdf_extract, expand as hkdf_expand } from '@noble/hashes/hkdf'
|
import { extract as hkdf_extract, expand as hkdf_expand } from '@noble/hashes/hkdf'
|
||||||
import { hmac } from '@noble/hashes/hmac'
|
import { hmac } from '@noble/hashes/hmac'
|
||||||
import { sha256 } from '@noble/hashes/sha256'
|
import { sha256 } from '@noble/hashes/sha256'
|
||||||
import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils'
|
import { concatBytes, randomBytes } from '@noble/hashes/utils'
|
||||||
import { base64 } from '@scure/base'
|
import { base64 } from '@scure/base'
|
||||||
|
|
||||||
const decoder = new TextDecoder()
|
import { utf8Decoder, utf8Encoder } from './utils.ts'
|
||||||
const u = {
|
|
||||||
minPlaintextSize: 0x0001, // 1b msg => padded to 32b
|
|
||||||
maxPlaintextSize: 0xffff, // 65535 (64kb-1) => padded to 64kb
|
|
||||||
|
|
||||||
utf8Encode: utf8ToBytes,
|
const minPlaintextSize = 0x0001 // 1b msg => padded to 32b
|
||||||
utf8Decode(bytes: Uint8Array) {
|
const maxPlaintextSize = 0xffff // 65535 (64kb-1) => padded to 64kb
|
||||||
return decoder.decode(bytes)
|
|
||||||
},
|
|
||||||
|
|
||||||
getConversationKey(privkeyA: string, pubkeyB: string): Uint8Array {
|
export function getConversationKey(privkeyA: Uint8Array, pubkeyB: string): Uint8Array {
|
||||||
const sharedX = secp256k1.getSharedSecret(privkeyA, '02' + pubkeyB).subarray(1, 33)
|
const sharedX = secp256k1.getSharedSecret(privkeyA, '02' + pubkeyB).subarray(1, 33)
|
||||||
return hkdf_extract(sha256, sharedX, 'nip44-v2')
|
return hkdf_extract(sha256, sharedX, 'nip44-v2')
|
||||||
},
|
|
||||||
|
|
||||||
getMessageKeys(conversationKey: Uint8Array, nonce: Uint8Array) {
|
|
||||||
ensureBytes(conversationKey, 32)
|
|
||||||
ensureBytes(nonce, 32)
|
|
||||||
const keys = hkdf_expand(sha256, conversationKey, nonce, 76)
|
|
||||||
return {
|
|
||||||
chacha_key: keys.subarray(0, 32),
|
|
||||||
chacha_nonce: keys.subarray(32, 44),
|
|
||||||
hmac_key: keys.subarray(44, 76),
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
calcPaddedLen(len: number): number {
|
|
||||||
if (!Number.isSafeInteger(len) || len < 1) throw new Error('expected positive integer')
|
|
||||||
if (len <= 32) return 32
|
|
||||||
const nextPower = 1 << (Math.floor(Math.log2(len - 1)) + 1)
|
|
||||||
const chunk = nextPower <= 256 ? 32 : nextPower / 8
|
|
||||||
return chunk * (Math.floor((len - 1) / chunk) + 1)
|
|
||||||
},
|
|
||||||
|
|
||||||
writeU16BE(num: number) {
|
|
||||||
if (!Number.isSafeInteger(num) || num < u.minPlaintextSize || num > u.maxPlaintextSize)
|
|
||||||
throw new Error('invalid plaintext size: must be between 1 and 65535 bytes')
|
|
||||||
const arr = new Uint8Array(2)
|
|
||||||
new DataView(arr.buffer).setUint16(0, num, false)
|
|
||||||
return arr
|
|
||||||
},
|
|
||||||
|
|
||||||
pad(plaintext: string): Uint8Array {
|
|
||||||
const unpadded = u.utf8Encode(plaintext)
|
|
||||||
const unpaddedLen = unpadded.length
|
|
||||||
const prefix = u.writeU16BE(unpaddedLen)
|
|
||||||
const suffix = new Uint8Array(u.calcPaddedLen(unpaddedLen) - unpaddedLen)
|
|
||||||
return concatBytes(prefix, unpadded, suffix)
|
|
||||||
},
|
|
||||||
|
|
||||||
unpad(padded: Uint8Array): string {
|
|
||||||
const unpaddedLen = new DataView(padded.buffer).getUint16(0)
|
|
||||||
const unpadded = padded.subarray(2, 2 + unpaddedLen)
|
|
||||||
if (
|
|
||||||
unpaddedLen < u.minPlaintextSize ||
|
|
||||||
unpaddedLen > u.maxPlaintextSize ||
|
|
||||||
unpadded.length !== unpaddedLen ||
|
|
||||||
padded.length !== 2 + u.calcPaddedLen(unpaddedLen)
|
|
||||||
)
|
|
||||||
throw new Error('invalid padding')
|
|
||||||
return u.utf8Decode(unpadded)
|
|
||||||
},
|
|
||||||
|
|
||||||
hmacAad(key: Uint8Array, message: Uint8Array, aad: Uint8Array) {
|
|
||||||
if (aad.length !== 32) throw new Error('AAD associated data must be 32 bytes')
|
|
||||||
const combined = concatBytes(aad, message)
|
|
||||||
return hmac(sha256, key, combined)
|
|
||||||
},
|
|
||||||
|
|
||||||
// metadata: always 65b (version: 1b, nonce: 32b, max: 32b)
|
|
||||||
// plaintext: 1b to 0xffff
|
|
||||||
// padded plaintext: 32b to 0xffff
|
|
||||||
// ciphertext: 32b+2 to 0xffff+2
|
|
||||||
// raw payload: 99 (65+32+2) to 65603 (65+0xffff+2)
|
|
||||||
// compressed payload (base64): 132b to 87472b
|
|
||||||
decodePayload(payload: string) {
|
|
||||||
if (typeof payload !== 'string') throw new Error('payload must be a valid string')
|
|
||||||
const plen = payload.length
|
|
||||||
if (plen < 132 || plen > 87472) throw new Error('invalid payload length: ' + plen)
|
|
||||||
if (payload[0] === '#') throw new Error('unknown encryption version')
|
|
||||||
let data: Uint8Array
|
|
||||||
try {
|
|
||||||
data = base64.decode(payload)
|
|
||||||
} catch (error) {
|
|
||||||
throw new Error('invalid base64: ' + (error as any).message)
|
|
||||||
}
|
|
||||||
const dlen = data.length
|
|
||||||
if (dlen < 99 || dlen > 65603) throw new Error('invalid data length: ' + dlen)
|
|
||||||
const vers = data[0]
|
|
||||||
if (vers !== 2) throw new Error('unknown encryption version ' + vers)
|
|
||||||
return {
|
|
||||||
nonce: data.subarray(1, 33),
|
|
||||||
ciphertext: data.subarray(33, -32),
|
|
||||||
mac: data.subarray(-32),
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function encrypt(plaintext: string, conversationKey: Uint8Array, nonce = randomBytes(32)): string {
|
function getMessageKeys(
|
||||||
const { chacha_key, chacha_nonce, hmac_key } = u.getMessageKeys(conversationKey, nonce)
|
conversationKey: Uint8Array,
|
||||||
const padded = u.pad(plaintext)
|
nonce: Uint8Array,
|
||||||
|
): { chacha_key: Uint8Array; chacha_nonce: Uint8Array; hmac_key: Uint8Array } {
|
||||||
|
const keys = hkdf_expand(sha256, conversationKey, nonce, 76)
|
||||||
|
return {
|
||||||
|
chacha_key: keys.subarray(0, 32),
|
||||||
|
chacha_nonce: keys.subarray(32, 44),
|
||||||
|
hmac_key: keys.subarray(44, 76),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function calcPaddedLen(len: number): number {
|
||||||
|
if (!Number.isSafeInteger(len) || len < 1) throw new Error('expected positive integer')
|
||||||
|
if (len <= 32) return 32
|
||||||
|
const nextPower = 1 << (Math.floor(Math.log2(len - 1)) + 1)
|
||||||
|
const chunk = nextPower <= 256 ? 32 : nextPower / 8
|
||||||
|
return chunk * (Math.floor((len - 1) / chunk) + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeU16BE(num: number): Uint8Array {
|
||||||
|
if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize)
|
||||||
|
throw new Error('invalid plaintext size: must be between 1 and 65535 bytes')
|
||||||
|
const arr = new Uint8Array(2)
|
||||||
|
new DataView(arr.buffer).setUint16(0, num, false)
|
||||||
|
return arr
|
||||||
|
}
|
||||||
|
|
||||||
|
function pad(plaintext: string): Uint8Array {
|
||||||
|
const unpadded = utf8Encoder.encode(plaintext)
|
||||||
|
const unpaddedLen = unpadded.length
|
||||||
|
const prefix = writeU16BE(unpaddedLen)
|
||||||
|
const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen)
|
||||||
|
return concatBytes(prefix, unpadded, suffix)
|
||||||
|
}
|
||||||
|
|
||||||
|
function unpad(padded: Uint8Array): string {
|
||||||
|
const unpaddedLen = new DataView(padded.buffer).getUint16(0)
|
||||||
|
const unpadded = padded.subarray(2, 2 + unpaddedLen)
|
||||||
|
if (
|
||||||
|
unpaddedLen < minPlaintextSize ||
|
||||||
|
unpaddedLen > maxPlaintextSize ||
|
||||||
|
unpadded.length !== unpaddedLen ||
|
||||||
|
padded.length !== 2 + calcPaddedLen(unpaddedLen)
|
||||||
|
)
|
||||||
|
throw new Error('invalid padding')
|
||||||
|
return utf8Decoder.decode(unpadded)
|
||||||
|
}
|
||||||
|
|
||||||
|
function hmacAad(key: Uint8Array, message: Uint8Array, aad: Uint8Array): Uint8Array {
|
||||||
|
if (aad.length !== 32) throw new Error('AAD associated data must be 32 bytes')
|
||||||
|
const combined = concatBytes(aad, message)
|
||||||
|
return hmac(sha256, key, combined)
|
||||||
|
}
|
||||||
|
|
||||||
|
// metadata: always 65b (version: 1b, nonce: 32b, max: 32b)
|
||||||
|
// plaintext: 1b to 0xffff
|
||||||
|
// padded plaintext: 32b to 0xffff
|
||||||
|
// ciphertext: 32b+2 to 0xffff+2
|
||||||
|
// raw payload: 99 (65+32+2) to 65603 (65+0xffff+2)
|
||||||
|
// compressed payload (base64): 132b to 87472b
|
||||||
|
function decodePayload(payload: string): { nonce: Uint8Array; ciphertext: Uint8Array; mac: Uint8Array } {
|
||||||
|
if (typeof payload !== 'string') throw new Error('payload must be a valid string')
|
||||||
|
const plen = payload.length
|
||||||
|
if (plen < 132 || plen > 87472) throw new Error('invalid payload length: ' + plen)
|
||||||
|
if (payload[0] === '#') throw new Error('unknown encryption version')
|
||||||
|
let data: Uint8Array
|
||||||
|
try {
|
||||||
|
data = base64.decode(payload)
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error('invalid base64: ' + (error as any).message)
|
||||||
|
}
|
||||||
|
const dlen = data.length
|
||||||
|
if (dlen < 99 || dlen > 65603) throw new Error('invalid data length: ' + dlen)
|
||||||
|
const vers = data[0]
|
||||||
|
if (vers !== 2) throw new Error('unknown encryption version ' + vers)
|
||||||
|
return {
|
||||||
|
nonce: data.subarray(1, 33),
|
||||||
|
ciphertext: data.subarray(33, -32),
|
||||||
|
mac: data.subarray(-32),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function encrypt(plaintext: string, conversationKey: Uint8Array, nonce: Uint8Array = randomBytes(32)): string {
|
||||||
|
const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)
|
||||||
|
const padded = pad(plaintext)
|
||||||
const ciphertext = chacha20(chacha_key, chacha_nonce, padded)
|
const ciphertext = chacha20(chacha_key, chacha_nonce, padded)
|
||||||
const mac = u.hmacAad(hmac_key, ciphertext, nonce)
|
const mac = hmacAad(hmac_key, ciphertext, nonce)
|
||||||
return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac))
|
return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac))
|
||||||
}
|
}
|
||||||
|
|
||||||
function decrypt(payload: string, conversationKey: Uint8Array): string {
|
export function decrypt(payload: string, conversationKey: Uint8Array): string {
|
||||||
const { nonce, ciphertext, mac } = u.decodePayload(payload)
|
const { nonce, ciphertext, mac } = decodePayload(payload)
|
||||||
const { chacha_key, chacha_nonce, hmac_key } = u.getMessageKeys(conversationKey, nonce)
|
const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce)
|
||||||
const calculatedMac = u.hmacAad(hmac_key, ciphertext, nonce)
|
const calculatedMac = hmacAad(hmac_key, ciphertext, nonce)
|
||||||
if (!equalBytes(calculatedMac, mac)) throw new Error('invalid MAC')
|
if (!equalBytes(calculatedMac, mac)) throw new Error('invalid MAC')
|
||||||
const padded = chacha20(chacha_key, chacha_nonce, ciphertext)
|
const padded = chacha20(chacha_key, chacha_nonce, ciphertext)
|
||||||
return u.unpad(padded)
|
return unpad(padded)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const v2 = {
|
export const v2 = {
|
||||||
utils: u,
|
utils: {
|
||||||
|
getConversationKey,
|
||||||
|
calcPaddedLen,
|
||||||
|
},
|
||||||
encrypt,
|
encrypt,
|
||||||
decrypt,
|
decrypt,
|
||||||
}
|
}
|
||||||
|
|
||||||
export default { v2 }
|
|
||||||
|
|||||||
126
nip46.ts
126
nip46.ts
@@ -1,10 +1,13 @@
|
|||||||
|
import { hexToBytes } from '@noble/hashes/utils'
|
||||||
import { NostrEvent, UnsignedEvent, VerifiedEvent } from './core.ts'
|
import { NostrEvent, UnsignedEvent, VerifiedEvent } from './core.ts'
|
||||||
import { generateSecretKey, finalizeEvent, getPublicKey, verifyEvent } from './pure.ts'
|
import { generateSecretKey, finalizeEvent, getPublicKey, verifyEvent } from './pure.ts'
|
||||||
import { AbstractSimplePool, SubCloser } from './abstract-pool.ts'
|
import { AbstractSimplePool, SubCloser } from './abstract-pool.ts'
|
||||||
import { decrypt, encrypt } from './nip04.ts'
|
import { decrypt, encrypt } from './nip04.ts'
|
||||||
|
import { getConversationKey, decrypt as nip44decrypt } from './nip44.ts'
|
||||||
import { NIP05_REGEX } from './nip05.ts'
|
import { NIP05_REGEX } from './nip05.ts'
|
||||||
import { SimplePool } from './pool.ts'
|
import { SimplePool } from './pool.ts'
|
||||||
import { Handlerinformation, NostrConnect, NostrConnectAdmin } from './kinds.ts'
|
import { Handlerinformation, NostrConnect } from './kinds.ts'
|
||||||
|
import type { RelayRecord } from './relay.ts'
|
||||||
|
|
||||||
var _fetch: any
|
var _fetch: any
|
||||||
|
|
||||||
@@ -16,7 +19,7 @@ export function useFetchImplementation(fetchImplementation: any) {
|
|||||||
_fetch = fetchImplementation
|
_fetch = fetchImplementation
|
||||||
}
|
}
|
||||||
|
|
||||||
export const BUNKER_REGEX = /^bunker:\/\/([0-9a-f]{64})\??([?\/\w:.=&%]*)$/
|
export const BUNKER_REGEX = /^bunker:\/\/([0-9a-f]{64})\??([?\/\w:.=&%-]*)$/
|
||||||
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||||
|
|
||||||
export type BunkerPointer = {
|
export type BunkerPointer = {
|
||||||
@@ -73,7 +76,6 @@ export type BunkerSignerParams = {
|
|||||||
export class BunkerSigner {
|
export class BunkerSigner {
|
||||||
private pool: AbstractSimplePool
|
private pool: AbstractSimplePool
|
||||||
private subCloser: SubCloser
|
private subCloser: SubCloser
|
||||||
private relays: string[]
|
|
||||||
private isOpen: boolean
|
private isOpen: boolean
|
||||||
private serial: number
|
private serial: number
|
||||||
private idPrefix: string
|
private idPrefix: string
|
||||||
@@ -83,9 +85,9 @@ export class BunkerSigner {
|
|||||||
reject: (_: string) => void
|
reject: (_: string) => void
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
private waitingForAuth: { [id: string]: boolean }
|
||||||
private secretKey: Uint8Array
|
private secretKey: Uint8Array
|
||||||
private connectionSecret: string
|
public bp: BunkerPointer
|
||||||
public remotePubkey: string
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new instance of the Nip46 class.
|
* Creates a new instance of the Nip46 class.
|
||||||
@@ -100,24 +102,34 @@ export class BunkerSigner {
|
|||||||
|
|
||||||
this.pool = params.pool || new SimplePool()
|
this.pool = params.pool || new SimplePool()
|
||||||
this.secretKey = clientSecretKey
|
this.secretKey = clientSecretKey
|
||||||
this.relays = bp.relays
|
this.bp = bp
|
||||||
this.remotePubkey = bp.pubkey
|
|
||||||
this.connectionSecret = bp.secret || ''
|
|
||||||
this.isOpen = false
|
this.isOpen = false
|
||||||
this.idPrefix = Math.random().toString(36).substring(7)
|
this.idPrefix = Math.random().toString(36).substring(7)
|
||||||
this.serial = 0
|
this.serial = 0
|
||||||
this.listeners = {}
|
this.listeners = {}
|
||||||
|
this.waitingForAuth = {}
|
||||||
|
|
||||||
const listeners = this.listeners
|
const listeners = this.listeners
|
||||||
|
const waitingForAuth = this.waitingForAuth
|
||||||
|
const skBytes = this.secretKey
|
||||||
|
|
||||||
this.subCloser = this.pool.subscribeMany(
|
this.subCloser = this.pool.subscribeMany(
|
||||||
this.relays,
|
this.bp.relays,
|
||||||
[{ kinds: [NostrConnect, NostrConnectAdmin], '#p': [getPublicKey(this.secretKey)] }],
|
[{ kinds: [NostrConnect], '#p': [getPublicKey(this.secretKey)] }],
|
||||||
{
|
{
|
||||||
async onevent(event: NostrEvent) {
|
async onevent(event: NostrEvent) {
|
||||||
const { id, result, error } = JSON.parse(await decrypt(clientSecretKey, event.pubkey, event.content))
|
let o
|
||||||
|
try {
|
||||||
|
o = JSON.parse(await decrypt(clientSecretKey, event.pubkey, event.content))
|
||||||
|
} catch (err) {
|
||||||
|
o = JSON.parse(nip44decrypt(event.content, getConversationKey(skBytes, event.pubkey)))
|
||||||
|
}
|
||||||
|
|
||||||
|
const { id, result, error } = o
|
||||||
|
|
||||||
|
if (result === 'auth_url' && waitingForAuth[id]) {
|
||||||
|
delete waitingForAuth[id]
|
||||||
|
|
||||||
if (result === 'auth_url') {
|
|
||||||
if (params.onauth) {
|
if (params.onauth) {
|
||||||
params.onauth(error)
|
params.onauth(error)
|
||||||
} else {
|
} else {
|
||||||
@@ -153,17 +165,13 @@ export class BunkerSigner {
|
|||||||
this.serial++
|
this.serial++
|
||||||
const id = `${this.idPrefix}-${this.serial}`
|
const id = `${this.idPrefix}-${this.serial}`
|
||||||
|
|
||||||
const encryptedContent = await encrypt(
|
const encryptedContent = await encrypt(this.secretKey, this.bp.pubkey, JSON.stringify({ id, method, params }))
|
||||||
this.secretKey,
|
|
||||||
this.remotePubkey,
|
|
||||||
JSON.stringify({ id, method, params }),
|
|
||||||
)
|
|
||||||
|
|
||||||
// the request event
|
// the request event
|
||||||
const verifiedEvent: VerifiedEvent = finalizeEvent(
|
const verifiedEvent: VerifiedEvent = finalizeEvent(
|
||||||
{
|
{
|
||||||
kind: method === 'create_account' ? NostrConnectAdmin : NostrConnect,
|
kind: NostrConnect,
|
||||||
tags: [['p', this.remotePubkey]],
|
tags: [['p', this.bp.pubkey]],
|
||||||
content: encryptedContent,
|
content: encryptedContent,
|
||||||
created_at: Math.floor(Date.now() / 1000),
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
},
|
},
|
||||||
@@ -172,9 +180,10 @@ export class BunkerSigner {
|
|||||||
|
|
||||||
// setup callback listener
|
// setup callback listener
|
||||||
this.listeners[id] = { resolve, reject }
|
this.listeners[id] = { resolve, reject }
|
||||||
|
this.waitingForAuth[id] = true
|
||||||
|
|
||||||
// publish the event
|
// publish the event
|
||||||
await Promise.any(this.pool.publish(this.relays, verifiedEvent))
|
await Promise.any(this.pool.publish(this.bp.relays, verifiedEvent))
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
reject(err)
|
reject(err)
|
||||||
}
|
}
|
||||||
@@ -182,9 +191,8 @@ export class BunkerSigner {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sends a ping request to the remote server.
|
* Calls the "connect" method on the bunker.
|
||||||
* Requires permission/access rights to bunker.
|
* The promise will be rejected if the response is not "pong".
|
||||||
* @returns "Pong" if successful. The promise will reject if the response is not "pong".
|
|
||||||
*/
|
*/
|
||||||
async ping(): Promise<void> {
|
async ping(): Promise<void> {
|
||||||
let resp = await this.sendRequest('ping', [])
|
let resp = await this.sendRequest('ping', [])
|
||||||
@@ -192,15 +200,25 @@ export class BunkerSigner {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Connects to a remote server using the provided keys and remote public key.
|
* Calls the "connect" method on the bunker.
|
||||||
* Optionally, a secret can be provided for additional authentication.
|
|
||||||
*
|
|
||||||
* @param remotePubkey - Optional the remote public key to connect to.
|
|
||||||
* @param secret - Optional secret for additional authentication.
|
|
||||||
* @returns "ack" if successful. The promise will reject if the response is not "ack".
|
|
||||||
*/
|
*/
|
||||||
async connect(): Promise<void> {
|
async connect(): Promise<void> {
|
||||||
await this.sendRequest('connect', [getPublicKey(this.secretKey), this.connectionSecret])
|
await this.sendRequest('connect', [this.bp.pubkey, this.bp.secret || ''])
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This was supposed to call the "get_public_key" method on the bunker,
|
||||||
|
* but instead we just returns the public key we already know.
|
||||||
|
*/
|
||||||
|
async getPublicKey(): Promise<string> {
|
||||||
|
return this.bp.pubkey
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calls the "get_relays" method on the bunker.
|
||||||
|
*/
|
||||||
|
async getRelays(): Promise<RelayRecord> {
|
||||||
|
return JSON.parse(await this.sendRequest('get_relays', []))
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -211,12 +229,33 @@ export class BunkerSigner {
|
|||||||
async signEvent(event: UnsignedEvent): Promise<VerifiedEvent> {
|
async signEvent(event: UnsignedEvent): Promise<VerifiedEvent> {
|
||||||
let resp = await this.sendRequest('sign_event', [JSON.stringify(event)])
|
let resp = await this.sendRequest('sign_event', [JSON.stringify(event)])
|
||||||
let signed: NostrEvent = JSON.parse(resp)
|
let signed: NostrEvent = JSON.parse(resp)
|
||||||
if (signed.pubkey === this.remotePubkey && verifyEvent(signed)) {
|
if (signed.pubkey === this.bp.pubkey && verifyEvent(signed)) {
|
||||||
return signed
|
return signed
|
||||||
} else {
|
} else {
|
||||||
throw new Error(`event returned from bunker is improperly signed: ${JSON.stringify(signed)}`)
|
throw new Error(`event returned from bunker is improperly signed: ${JSON.stringify(signed)}`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async nip04Encrypt(thirdPartyPubkey: string, plaintext: string): Promise<string> {
|
||||||
|
return await this.sendRequest('nip04_encrypt', [thirdPartyPubkey, plaintext])
|
||||||
|
}
|
||||||
|
|
||||||
|
async nip04Decrypt(thirdPartyPubkey: string, ciphertext: string): Promise<string> {
|
||||||
|
return await this.sendRequest('nip04_decrypt', [thirdPartyPubkey, ciphertext])
|
||||||
|
}
|
||||||
|
|
||||||
|
async nip44GetKey(thirdPartyPubkey: string): Promise<Uint8Array> {
|
||||||
|
let resp = await this.sendRequest('nip44_get_key', [thirdPartyPubkey])
|
||||||
|
return hexToBytes(resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
async nip44Encrypt(thirdPartyPubkey: string, plaintext: string): Promise<string> {
|
||||||
|
return await this.sendRequest('nip44_encrypt', [thirdPartyPubkey, plaintext])
|
||||||
|
}
|
||||||
|
|
||||||
|
async nip44Decrypt(thirdPartyPubkey: string, ciphertext: string): Promise<string> {
|
||||||
|
return await this.sendRequest('nip44_encrypt', [thirdPartyPubkey, ciphertext])
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -225,6 +264,8 @@ export class BunkerSigner {
|
|||||||
* @param username - The username for the account.
|
* @param username - The username for the account.
|
||||||
* @param domain - The domain for the account.
|
* @param domain - The domain for the account.
|
||||||
* @param email - The optional email for the account.
|
* @param email - The optional email for the account.
|
||||||
|
* @param localSecretKey - Optionally pass a local secret key that will be used to communicate with the bunker,
|
||||||
|
this will default to generating a random key.
|
||||||
* @throws Error if the email is present but invalid.
|
* @throws Error if the email is present but invalid.
|
||||||
* @returns A Promise that resolves to the auth_url that the client should follow to create an account.
|
* @returns A Promise that resolves to the auth_url that the client should follow to create an account.
|
||||||
*/
|
*/
|
||||||
@@ -234,38 +275,51 @@ export async function createAccount(
|
|||||||
username: string,
|
username: string,
|
||||||
domain: string,
|
domain: string,
|
||||||
email?: string,
|
email?: string,
|
||||||
|
localSecretKey: Uint8Array = generateSecretKey(),
|
||||||
): Promise<BunkerSigner> {
|
): Promise<BunkerSigner> {
|
||||||
if (email && !EMAIL_REGEX.test(email)) throw new Error('Invalid email')
|
if (email && !EMAIL_REGEX.test(email)) throw new Error('Invalid email')
|
||||||
|
|
||||||
let sk = generateSecretKey()
|
let rpc = new BunkerSigner(localSecretKey, bunker.bunkerPointer, params)
|
||||||
let rpc = new BunkerSigner(sk, bunker.bunkerPointer, params)
|
|
||||||
|
|
||||||
let pubkey = await rpc.sendRequest('create_account', [username, domain, email || ''])
|
let pubkey = await rpc.sendRequest('create_account', [username, domain, email || ''])
|
||||||
|
|
||||||
// once we get the newly created pubkey back, we hijack this signer instance
|
// once we get the newly created pubkey back, we hijack this signer instance
|
||||||
// and turn it into the main instance for this newly created pubkey
|
// and turn it into the main instance for this newly created pubkey
|
||||||
rpc.remotePubkey = pubkey
|
rpc.bp.pubkey = pubkey
|
||||||
await rpc.connect()
|
await rpc.connect()
|
||||||
|
|
||||||
return rpc
|
return rpc
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// @deprecated use fetchBunkerProviders instead
|
||||||
|
export const fetchCustodialBunkers = fetchBunkerProviders
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetches info on available providers that announce themselves using NIP-89 events.
|
* Fetches info on available providers that announce themselves using NIP-89 events.
|
||||||
* @returns A promise that resolves to an array of available bunker objects.
|
* @returns A promise that resolves to an array of available bunker objects.
|
||||||
*/
|
*/
|
||||||
export async function fetchCustodialbunkers(pool: AbstractSimplePool, relays: string[]): Promise<BunkerProfile[]> {
|
export async function fetchBunkerProviders(pool: AbstractSimplePool, relays: string[]): Promise<BunkerProfile[]> {
|
||||||
const events = await pool.querySync(relays, {
|
const events = await pool.querySync(relays, {
|
||||||
kinds: [Handlerinformation],
|
kinds: [Handlerinformation],
|
||||||
'#k': [NostrConnect.toString()],
|
'#k': [NostrConnect.toString()],
|
||||||
})
|
})
|
||||||
|
|
||||||
|
events.sort((a, b) => b.created_at - a.created_at)
|
||||||
|
|
||||||
// validate bunkers by checking their NIP-05 and pubkey
|
// validate bunkers by checking their NIP-05 and pubkey
|
||||||
// map to a more useful object
|
// map to a more useful object
|
||||||
const validatedBunkers = await Promise.all(
|
const validatedBunkers = await Promise.all(
|
||||||
events.map(async event => {
|
events.map(async (event, i) => {
|
||||||
try {
|
try {
|
||||||
const content = JSON.parse(event.content)
|
const content = JSON.parse(event.content)
|
||||||
|
|
||||||
|
// skip duplicates
|
||||||
|
try {
|
||||||
|
if (events.findIndex(ev => JSON.parse(ev.content).nip05 === content.nip05) !== i) return undefined
|
||||||
|
} catch (err) {
|
||||||
|
/***/
|
||||||
|
}
|
||||||
|
|
||||||
const bp = await queryBunkerProfile(content.nip05)
|
const bp = await queryBunkerProfile(content.nip05)
|
||||||
if (bp && bp.pubkey === event.pubkey && bp.relays.length) {
|
if (bp && bp.pubkey === event.pubkey && bp.relays.length) {
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -1,14 +1,9 @@
|
|||||||
import crypto from 'node:crypto'
|
|
||||||
import { describe, test, expect } from 'bun:test'
|
import { describe, test, expect } from 'bun:test'
|
||||||
import { hexToBytes } from '@noble/hashes/utils'
|
import { hexToBytes } from '@noble/hashes/utils'
|
||||||
import { makeNwcRequestEvent, parseConnectionString } from './nip47'
|
import { makeNwcRequestEvent, parseConnectionString } from './nip47.ts'
|
||||||
import { decrypt } from './nip04.ts'
|
import { decrypt } from './nip04.ts'
|
||||||
import { NWCWalletRequest } from './kinds.ts'
|
import { NWCWalletRequest } from './kinds.ts'
|
||||||
|
|
||||||
// @ts-ignore
|
|
||||||
// eslint-disable-next-line no-undef
|
|
||||||
globalThis.crypto = crypto
|
|
||||||
|
|
||||||
describe('parseConnectionString', () => {
|
describe('parseConnectionString', () => {
|
||||||
test('returns pubkey, relay, and secret if connection string is valid', () => {
|
test('returns pubkey, relay, and secret if connection string is valid', () => {
|
||||||
const connectionString =
|
const connectionString =
|
||||||
|
|||||||
16
nip47.ts
16
nip47.ts
@@ -1,8 +1,14 @@
|
|||||||
import { finalizeEvent } from './pure.ts'
|
import { type VerifiedEvent, finalizeEvent } from './pure.ts'
|
||||||
import { NWCWalletRequest } from './kinds.ts'
|
import { NWCWalletRequest } from './kinds.ts'
|
||||||
import { encrypt } from './nip04.ts'
|
import { encrypt } from './nip04.ts'
|
||||||
|
|
||||||
export function parseConnectionString(connectionString: string) {
|
interface NWCConnection {
|
||||||
|
pubkey: string
|
||||||
|
relay: string
|
||||||
|
secret: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseConnectionString(connectionString: string): NWCConnection {
|
||||||
const { pathname, searchParams } = new URL(connectionString)
|
const { pathname, searchParams } = new URL(connectionString)
|
||||||
const pubkey = pathname
|
const pubkey = pathname
|
||||||
const relay = searchParams.get('relay')
|
const relay = searchParams.get('relay')
|
||||||
@@ -15,7 +21,11 @@ export function parseConnectionString(connectionString: string) {
|
|||||||
return { pubkey, relay, secret }
|
return { pubkey, relay, secret }
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function makeNwcRequestEvent(pubkey: string, secretKey: Uint8Array, invoice: string) {
|
export async function makeNwcRequestEvent(
|
||||||
|
pubkey: string,
|
||||||
|
secretKey: Uint8Array,
|
||||||
|
invoice: string,
|
||||||
|
): Promise<VerifiedEvent> {
|
||||||
const content = {
|
const content = {
|
||||||
method: 'pay_invoice',
|
method: 'pay_invoice',
|
||||||
params: {
|
params: {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { test, expect } from 'bun:test'
|
import { test, expect } from 'bun:test'
|
||||||
import { decrypt, encrypt } from './nip49'
|
import { decrypt, encrypt } from './nip49.ts'
|
||||||
import { hexToBytes } from '@noble/hashes/utils'
|
import { hexToBytes } from '@noble/hashes/utils'
|
||||||
|
|
||||||
test('encrypt and decrypt', () => {
|
test('encrypt and decrypt', () => {
|
||||||
@@ -79,10 +79,17 @@ const vectors: [string, string, number, 0x00 | 0x01 | 0x02, string][] = [
|
|||||||
'ncryptsec1qgqnx59n7duv6ec3hhrvn33q25u2qfd7m69vv6plsg7spnw6d4r9hq0ayjsnlw99eghqqzj8ps7vfwx40nqp9gpw7yzyy09jmwkq3a3z8q0ph5jahs2hap5k6h2wfrme7w2nuek4jnwpzfht4q3u79ra',
|
'ncryptsec1qgqnx59n7duv6ec3hhrvn33q25u2qfd7m69vv6plsg7spnw6d4r9hq0ayjsnlw99eghqqzj8ps7vfwx40nqp9gpw7yzyy09jmwkq3a3z8q0ph5jahs2hap5k6h2wfrme7w2nuek4jnwpzfht4q3u79ra',
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
'',
|
'ÅΩẛ̣',
|
||||||
'11b25a101667dd9208db93c0827c6bdad66729a5b521156a7e9d3b22b3ae8944',
|
'11b25a101667dd9208db93c0827c6bdad66729a5b521156a7e9d3b22b3ae8944',
|
||||||
9,
|
9,
|
||||||
0x01,
|
0x01,
|
||||||
'ncryptsec1qgylzyeunu2j85au05ae0g0sly03xu54tgnjemr6g9w0eqwuuczya7k0f4juqve64vzsrlxqxmcekzrpvg2a8qu4q6wtjxe0dvy3xkjh5smmz4uy59jg0jay9vnf28e3rc6jq2kd26h6g3fejyw6cype',
|
'ncryptsec1qgy5kwr5v8p206vwaflp4g6r083kwts6q5sh8m4d0q56edpxwhrly78ema2z7jpdeldsz7u5wpxpyhs6m0405skdsep9n37uncw7xlc8q8meyw6d6ky47vcl0guhqpt5dx8ejxc8hvzf6y2gwsl5s0nw',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'ÅΩṩ',
|
||||||
|
'11b25a101667dd9208db93c0827c6bdad66729a5b521156a7e9d3b22b3ae8944',
|
||||||
|
9,
|
||||||
|
0x01,
|
||||||
|
'ncryptsec1qgy5f4lcx873yarkfpngaudarxfj4wj939xn4azmd66j6jrwcml6av87d6vnelzn70kszgkg4lj9rsdjlqz0wn7m7456sr2q5yjpy72ykgkdwckevl857hpcfnwzswj9lajxtln0tsr9h7xdwqm6pqzf',
|
||||||
],
|
],
|
||||||
]
|
]
|
||||||
|
|||||||
6
nip49.ts
6
nip49.ts
@@ -1,13 +1,13 @@
|
|||||||
import { scrypt } from '@noble/hashes/scrypt'
|
import { scrypt } from '@noble/hashes/scrypt'
|
||||||
import { xchacha20poly1305 } from '@noble/ciphers/chacha'
|
import { xchacha20poly1305 } from '@noble/ciphers/chacha'
|
||||||
import { concatBytes, randomBytes } from '@noble/hashes/utils'
|
import { concatBytes, randomBytes } from '@noble/hashes/utils'
|
||||||
import { Bech32MaxSize, encodeBytes } from './nip19'
|
import { Bech32MaxSize, encodeBytes } from './nip19.ts'
|
||||||
import { bech32 } from '@scure/base'
|
import { bech32 } from '@scure/base'
|
||||||
|
|
||||||
export function encrypt(sec: Uint8Array, password: string, logn: number = 16, ksb: 0x00 | 0x01 | 0x02 = 0x02): string {
|
export function encrypt(sec: Uint8Array, password: string, logn: number = 16, ksb: 0x00 | 0x01 | 0x02 = 0x02): string {
|
||||||
let salt = randomBytes(16)
|
let salt = randomBytes(16)
|
||||||
let n = 2 ** logn
|
let n = 2 ** logn
|
||||||
let key = scrypt(password, salt, { N: n, r: 8, p: 1, dkLen: 32 })
|
let key = scrypt(password.normalize('NFKC'), salt, { N: n, r: 8, p: 1, dkLen: 32 })
|
||||||
let nonce = randomBytes(24)
|
let nonce = randomBytes(24)
|
||||||
let aad = Uint8Array.from([ksb])
|
let aad = Uint8Array.from([ksb])
|
||||||
let xc2p1 = xchacha20poly1305(key, nonce, aad)
|
let xc2p1 = xchacha20poly1305(key, nonce, aad)
|
||||||
@@ -37,7 +37,7 @@ export function decrypt(ncryptsec: string, password: string): Uint8Array {
|
|||||||
let aad = Uint8Array.from([ksb])
|
let aad = Uint8Array.from([ksb])
|
||||||
let ciphertext = b.slice(2 + 16 + 24 + 1)
|
let ciphertext = b.slice(2 + 16 + 24 + 1)
|
||||||
|
|
||||||
let key = scrypt(password, salt, { N: n, r: 8, p: 1, dkLen: 32 })
|
let key = scrypt(password.normalize('NFKC'), salt, { N: n, r: 8, p: 1, dkLen: 32 })
|
||||||
let xc2p1 = xchacha20poly1305(key, nonce, aad)
|
let xc2p1 = xchacha20poly1305(key, nonce, aad)
|
||||||
let sec = xc2p1.decrypt(ciphertext)
|
let sec = xc2p1.decrypt(ciphertext)
|
||||||
|
|
||||||
|
|||||||
357
nip58.test.ts
Normal file
357
nip58.test.ts
Normal file
@@ -0,0 +1,357 @@
|
|||||||
|
import { expect, test } from 'bun:test'
|
||||||
|
|
||||||
|
import { EventTemplate } from './core.ts'
|
||||||
|
import {
|
||||||
|
BadgeAward as BadgeAwardKind,
|
||||||
|
BadgeDefinition as BadgeDefinitionKind,
|
||||||
|
ProfileBadges as ProfileBadgesKind,
|
||||||
|
} from './kinds.ts'
|
||||||
|
import { finalizeEvent, generateSecretKey } from './pure.ts'
|
||||||
|
|
||||||
|
import {
|
||||||
|
BadgeAward,
|
||||||
|
BadgeDefinition,
|
||||||
|
ProfileBadges,
|
||||||
|
generateBadgeAwardEventTemplate,
|
||||||
|
generateBadgeDefinitionEventTemplate,
|
||||||
|
generateProfileBadgesEventTemplate,
|
||||||
|
validateBadgeAwardEvent,
|
||||||
|
validateBadgeDefinitionEvent,
|
||||||
|
validateProfileBadgesEvent,
|
||||||
|
} from './nip58.ts'
|
||||||
|
|
||||||
|
test('BadgeDefinition has required property "d"', () => {
|
||||||
|
const badge: BadgeDefinition = {
|
||||||
|
d: 'badge-id',
|
||||||
|
}
|
||||||
|
expect(badge.d).toEqual('badge-id')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('BadgeDefinition has optional property "name"', () => {
|
||||||
|
const badge: BadgeDefinition = {
|
||||||
|
d: 'badge-id',
|
||||||
|
name: 'Badge Name',
|
||||||
|
}
|
||||||
|
expect(badge.name).toEqual('Badge Name')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('BadgeDefinition has optional property "description"', () => {
|
||||||
|
const badge: BadgeDefinition = {
|
||||||
|
d: 'badge-id',
|
||||||
|
description: 'Badge Description',
|
||||||
|
}
|
||||||
|
expect(badge.description).toEqual('Badge Description')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('BadgeDefinition has optional property "image"', () => {
|
||||||
|
const badge: BadgeDefinition = {
|
||||||
|
d: 'badge-id',
|
||||||
|
image: ['https://example.com/badge.png', '1024x1024'],
|
||||||
|
}
|
||||||
|
expect(badge.image).toEqual(['https://example.com/badge.png', '1024x1024'])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('BadgeDefinition has optional property "thumbs"', () => {
|
||||||
|
const badge: BadgeDefinition = {
|
||||||
|
d: 'badge-id',
|
||||||
|
thumbs: [
|
||||||
|
['https://example.com/thumb.png', '100x100'],
|
||||||
|
['https://example.com/thumb2.png', '200x200'],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
expect(badge.thumbs).toEqual([
|
||||||
|
['https://example.com/thumb.png', '100x100'],
|
||||||
|
['https://example.com/thumb2.png', '200x200'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('BadgeAward has required property "a"', () => {
|
||||||
|
const badgeAward: BadgeAward = {
|
||||||
|
a: 'badge-definition-address',
|
||||||
|
p: [
|
||||||
|
['pubkey1', 'relay1'],
|
||||||
|
['pubkey2', 'relay2'],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
expect(badgeAward.a).toEqual('badge-definition-address')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('BadgeAward has required property "p"', () => {
|
||||||
|
const badgeAward: BadgeAward = {
|
||||||
|
a: 'badge-definition-address',
|
||||||
|
p: [
|
||||||
|
['pubkey1', 'relay1'],
|
||||||
|
['pubkey2', 'relay2'],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
expect(badgeAward.p).toEqual([
|
||||||
|
['pubkey1', 'relay1'],
|
||||||
|
['pubkey2', 'relay2'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('ProfileBadges has required property "d"', () => {
|
||||||
|
const profileBadges: ProfileBadges = {
|
||||||
|
d: 'profile_badges',
|
||||||
|
badges: [],
|
||||||
|
}
|
||||||
|
expect(profileBadges.d).toEqual('profile_badges')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('ProfileBadges has required property "badges"', () => {
|
||||||
|
const profileBadges: ProfileBadges = {
|
||||||
|
d: 'profile_badges',
|
||||||
|
badges: [],
|
||||||
|
}
|
||||||
|
expect(profileBadges.badges).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('ProfileBadges badges array contains objects with required properties "a" and "e"', () => {
|
||||||
|
const profileBadges: ProfileBadges = {
|
||||||
|
d: 'profile_badges',
|
||||||
|
badges: [
|
||||||
|
{
|
||||||
|
a: 'badge-definition-address',
|
||||||
|
e: ['badge-award-event-id'],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
expect(profileBadges.badges[0].a).toEqual('badge-definition-address')
|
||||||
|
expect(profileBadges.badges[0].e).toEqual(['badge-award-event-id'])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('generateBadgeDefinitionEventTemplate generates EventTemplate with mandatory tags', () => {
|
||||||
|
const badge: BadgeDefinition = {
|
||||||
|
d: 'badge-id',
|
||||||
|
}
|
||||||
|
const eventTemplate = generateBadgeDefinitionEventTemplate(badge)
|
||||||
|
expect(eventTemplate.tags).toEqual([['d', 'badge-id']])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('generateBadgeDefinitionEventTemplate generates EventTemplate with optional tags', () => {
|
||||||
|
const badge: BadgeDefinition = {
|
||||||
|
d: 'badge-id',
|
||||||
|
name: 'Badge Name',
|
||||||
|
description: 'Badge Description',
|
||||||
|
image: ['https://example.com/badge.png', '1024x1024'],
|
||||||
|
thumbs: [
|
||||||
|
['https://example.com/thumb.png', '100x100'],
|
||||||
|
['https://example.com/thumb2.png', '200x200'],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const eventTemplate = generateBadgeDefinitionEventTemplate(badge)
|
||||||
|
expect(eventTemplate.tags).toEqual([
|
||||||
|
['d', 'badge-id'],
|
||||||
|
['name', 'Badge Name'],
|
||||||
|
['description', 'Badge Description'],
|
||||||
|
['image', 'https://example.com/badge.png', '1024x1024'],
|
||||||
|
['thumb', 'https://example.com/thumb.png', '100x100'],
|
||||||
|
['thumb', 'https://example.com/thumb2.png', '200x200'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('generateBadgeDefinitionEventTemplate generates EventTemplate without optional tags', () => {
|
||||||
|
const badge: BadgeDefinition = {
|
||||||
|
d: 'badge-id',
|
||||||
|
}
|
||||||
|
const eventTemplate = generateBadgeDefinitionEventTemplate(badge)
|
||||||
|
expect(eventTemplate.tags).toEqual([['d', 'badge-id']])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('validateBadgeDefinitionEvent returns true for valid BadgeDefinition event', () => {
|
||||||
|
const sk = generateSecretKey()
|
||||||
|
const eventTemplate: EventTemplate = {
|
||||||
|
content: '',
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
kind: BadgeDefinitionKind,
|
||||||
|
tags: [
|
||||||
|
['d', 'badge-id'],
|
||||||
|
['name', 'Badge Name'],
|
||||||
|
['description', 'Badge Description'],
|
||||||
|
['image', 'https://example.com/badge.png', '1024x1024'],
|
||||||
|
['thumb', 'https://example.com/thumb.png', '100x100'],
|
||||||
|
['thumb', 'https://example.com/thumb2.png', '200x200'],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const event = finalizeEvent(eventTemplate, sk)
|
||||||
|
const isValid = validateBadgeDefinitionEvent(event)
|
||||||
|
|
||||||
|
expect(isValid).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('validateBadgeDefinitionEvent returns false for invalid BadgeDefinition event', () => {
|
||||||
|
const sk = generateSecretKey()
|
||||||
|
const eventTemplate: EventTemplate = {
|
||||||
|
content: '',
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
kind: BadgeDefinitionKind,
|
||||||
|
tags: [],
|
||||||
|
}
|
||||||
|
const event = finalizeEvent(eventTemplate, sk)
|
||||||
|
const isValid = validateBadgeDefinitionEvent(event)
|
||||||
|
|
||||||
|
expect(isValid).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('generateBadgeAwardEventTemplate generates EventTemplate with mandatory tags', () => {
|
||||||
|
const badgeAward: BadgeAward = {
|
||||||
|
a: 'badge-definition-address',
|
||||||
|
p: [
|
||||||
|
['pubkey1', 'relay1'],
|
||||||
|
['pubkey2', 'relay2'],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const eventTemplate = generateBadgeAwardEventTemplate(badgeAward)
|
||||||
|
expect(eventTemplate.tags).toEqual([
|
||||||
|
['a', 'badge-definition-address'],
|
||||||
|
['p', 'pubkey1', 'relay1'],
|
||||||
|
['p', 'pubkey2', 'relay2'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('generateBadgeAwardEventTemplate generates EventTemplate without optional tags', () => {
|
||||||
|
const badgeAward: BadgeAward = {
|
||||||
|
a: 'badge-definition-address',
|
||||||
|
p: [
|
||||||
|
['pubkey1', 'relay1'],
|
||||||
|
['pubkey2', 'relay2'],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const eventTemplate = generateBadgeAwardEventTemplate(badgeAward)
|
||||||
|
expect(eventTemplate.tags).toEqual([
|
||||||
|
['a', 'badge-definition-address'],
|
||||||
|
['p', 'pubkey1', 'relay1'],
|
||||||
|
['p', 'pubkey2', 'relay2'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('generateBadgeAwardEventTemplate generates EventTemplate with optional tags', () => {
|
||||||
|
const badgeAward: BadgeAward = {
|
||||||
|
a: 'badge-definition-address',
|
||||||
|
p: [
|
||||||
|
['pubkey1', 'relay1'],
|
||||||
|
['pubkey2', 'relay2'],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const eventTemplate = generateBadgeAwardEventTemplate(badgeAward)
|
||||||
|
expect(eventTemplate.tags).toEqual([
|
||||||
|
['a', 'badge-definition-address'],
|
||||||
|
['p', 'pubkey1', 'relay1'],
|
||||||
|
['p', 'pubkey2', 'relay2'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('validateBadgeAwardEvent returns true for valid BadgeAward event', () => {
|
||||||
|
const sk = generateSecretKey()
|
||||||
|
const eventTemplate: EventTemplate = {
|
||||||
|
content: '',
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
kind: BadgeAwardKind,
|
||||||
|
tags: [
|
||||||
|
['a', 'badge-definition-address'],
|
||||||
|
['p', 'pubkey1', 'relay1'],
|
||||||
|
['p', 'pubkey2', 'relay2'],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const event = finalizeEvent(eventTemplate, sk)
|
||||||
|
const isValid = validateBadgeAwardEvent(event)
|
||||||
|
|
||||||
|
expect(isValid).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('validateBadgeAwardEvent returns false for invalid BadgeAward event', () => {
|
||||||
|
const sk = generateSecretKey()
|
||||||
|
const eventTemplate: EventTemplate = {
|
||||||
|
content: '',
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
kind: BadgeAwardKind,
|
||||||
|
tags: [],
|
||||||
|
}
|
||||||
|
const event = finalizeEvent(eventTemplate, sk)
|
||||||
|
const isValid = validateBadgeAwardEvent(event)
|
||||||
|
|
||||||
|
expect(isValid).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('generateProfileBadgesEventTemplate generates EventTemplate with mandatory tags', () => {
|
||||||
|
const profileBadges: ProfileBadges = {
|
||||||
|
d: 'profile_badges',
|
||||||
|
badges: [],
|
||||||
|
}
|
||||||
|
const eventTemplate = generateProfileBadgesEventTemplate(profileBadges)
|
||||||
|
expect(eventTemplate.tags).toEqual([['d', 'profile_badges']])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('generateProfileBadgesEventTemplate generates EventTemplate with optional tags', () => {
|
||||||
|
const profileBadges: ProfileBadges = {
|
||||||
|
d: 'profile_badges',
|
||||||
|
badges: [
|
||||||
|
{
|
||||||
|
a: 'badge-definition-address',
|
||||||
|
e: ['badge-award-event-id'],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const eventTemplate = generateProfileBadgesEventTemplate(profileBadges)
|
||||||
|
expect(eventTemplate.tags).toEqual([
|
||||||
|
['d', 'profile_badges'],
|
||||||
|
['a', 'badge-definition-address'],
|
||||||
|
['e', 'badge-award-event-id'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('generateProfileBadgesEventTemplate generates EventTemplate with multiple optional tags', () => {
|
||||||
|
const profileBadges: ProfileBadges = {
|
||||||
|
d: 'profile_badges',
|
||||||
|
badges: [
|
||||||
|
{
|
||||||
|
a: 'badge-definition-address1',
|
||||||
|
e: ['badge-award-event-id1', 'badge-award-event-id2'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
a: 'badge-definition-address2',
|
||||||
|
e: ['badge-award-event-id3'],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const eventTemplate = generateProfileBadgesEventTemplate(profileBadges)
|
||||||
|
expect(eventTemplate.tags).toEqual([
|
||||||
|
['d', 'profile_badges'],
|
||||||
|
['a', 'badge-definition-address1'],
|
||||||
|
['e', 'badge-award-event-id1', 'badge-award-event-id2'],
|
||||||
|
['a', 'badge-definition-address2'],
|
||||||
|
['e', 'badge-award-event-id3'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('validateProfileBadgesEvent returns true for valid ProfileBadges event', () => {
|
||||||
|
const sk = generateSecretKey()
|
||||||
|
const eventTemplate: EventTemplate = {
|
||||||
|
content: '',
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
kind: ProfileBadgesKind,
|
||||||
|
tags: [
|
||||||
|
['d', 'profile_badges'],
|
||||||
|
['a', 'badge-definition-address'],
|
||||||
|
['e', 'badge-award-event-id'],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const event = finalizeEvent(eventTemplate, sk)
|
||||||
|
const isValid = validateProfileBadgesEvent(event)
|
||||||
|
|
||||||
|
expect(isValid).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('validateProfileBadgesEvent returns false for invalid ProfileBadges event', () => {
|
||||||
|
const sk = generateSecretKey()
|
||||||
|
const eventTemplate: EventTemplate = {
|
||||||
|
content: '',
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
kind: ProfileBadgesKind,
|
||||||
|
tags: [],
|
||||||
|
}
|
||||||
|
const event = finalizeEvent(eventTemplate, sk)
|
||||||
|
const isValid = validateProfileBadgesEvent(event)
|
||||||
|
|
||||||
|
expect(isValid).toBe(false)
|
||||||
|
})
|
||||||
245
nip58.ts
Normal file
245
nip58.ts
Normal file
@@ -0,0 +1,245 @@
|
|||||||
|
import { Event, EventTemplate } from './core.ts'
|
||||||
|
import {
|
||||||
|
BadgeAward as BadgeAwardKind,
|
||||||
|
BadgeDefinition as BadgeDefinitionKind,
|
||||||
|
ProfileBadges as ProfileBadgesKind,
|
||||||
|
} from './kinds.ts'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents the structure for defining a badge within the Nostr network.
|
||||||
|
* This structure is used to create templates for badge definition events,
|
||||||
|
* facilitating the recognition and awarding of badges to users for various achievements.
|
||||||
|
*/
|
||||||
|
export type BadgeDefinition = {
|
||||||
|
/**
|
||||||
|
* A unique identifier for the badge. This is used to distinguish badges
|
||||||
|
* from one another and should be unique across all badge definitions.
|
||||||
|
* Typically, this could be a short, descriptive string.
|
||||||
|
*/
|
||||||
|
d: string
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An optional short name for the badge. This provides a human-readable
|
||||||
|
* title for the badge, making it easier to recognize and refer to.
|
||||||
|
*/
|
||||||
|
name?: string
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An optional description for the badge. This field can be used to
|
||||||
|
* provide more detailed information about the badge, such as the criteria
|
||||||
|
* for its awarding or its significance.
|
||||||
|
*/
|
||||||
|
description?: string
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An optional image URL and dimensions for the badge. The first element
|
||||||
|
* of the tuple is the URL pointing to a high-resolution image representing
|
||||||
|
* the badge, and the second element specifies the image's dimensions in
|
||||||
|
* the format "widthxheight". The recommended dimensions are 1024x1024 pixels.
|
||||||
|
*/
|
||||||
|
image?: [string, string]
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An optional list of thumbnail images for the badge. Each element in the
|
||||||
|
* array is a tuple, where the first element is the URL pointing to a thumbnail
|
||||||
|
* version of the badge image, and the second element specifies the thumbnail's
|
||||||
|
* dimensions in the format "widthxheight". Multiple thumbnails can be provided
|
||||||
|
* to support different display sizes.
|
||||||
|
*/
|
||||||
|
thumbs?: Array<[string, string]>
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents the structure for awarding a badge to one or more recipients
|
||||||
|
* within the Nostr network. This structure is used to create templates for
|
||||||
|
* badge award events, which are immutable and signify the recognition of
|
||||||
|
* individuals' achievements or contributions.
|
||||||
|
*/
|
||||||
|
export type BadgeAward = {
|
||||||
|
/**
|
||||||
|
* A reference to the Badge Definition event. This is typically composed
|
||||||
|
* of the event ID of the badge definition. It establishes a clear linkage
|
||||||
|
* between the badge being awarded and its original definition, ensuring
|
||||||
|
* that recipients are awarded the correct badge.
|
||||||
|
*/
|
||||||
|
a: string
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An array of p tags, each containing a pubkey and its associated relays.
|
||||||
|
*/
|
||||||
|
p: string[][]
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents the collection of badges a user chooses to display on their profile.
|
||||||
|
* This structure is crucial for applications that allow users to showcase achievements
|
||||||
|
* or recognitions in the form of badges, following the specifications of NIP-58.
|
||||||
|
*/
|
||||||
|
export type ProfileBadges = {
|
||||||
|
/**
|
||||||
|
* A unique identifier for the profile badges collection. According to NIP-58,
|
||||||
|
* this should be set to "profile_badges" to differentiate it from other event types.
|
||||||
|
*/
|
||||||
|
d: 'profile_badges'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A list of badges that the user has elected to display on their profile. Each item
|
||||||
|
* in the array represents a specific badge, including references to both its definition
|
||||||
|
* and the award event.
|
||||||
|
*/
|
||||||
|
badges: Array<{
|
||||||
|
/**
|
||||||
|
* The event address of the badge definition. This is a reference to the specific badge
|
||||||
|
* being displayed, linking back to the badge's original definition event. It allows
|
||||||
|
* clients to fetch and display the badge's details, such as its name, description,
|
||||||
|
* and image.
|
||||||
|
*/
|
||||||
|
a: string
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The event id of the badge award with corresponding relays. This references the event
|
||||||
|
* in which the badge was awarded to the user. It is crucial for verifying the
|
||||||
|
* authenticity of the badge display, ensuring that the user was indeed awarded the
|
||||||
|
* badge they are choosing to display.
|
||||||
|
*/
|
||||||
|
e: string[]
|
||||||
|
}>
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates an EventTemplate based on the provided BadgeDefinition.
|
||||||
|
*
|
||||||
|
* @param {BadgeDefinition} badgeDefinition - The BadgeDefinition object.
|
||||||
|
* @returns {EventTemplate} - The generated EventTemplate object.
|
||||||
|
*/
|
||||||
|
export function generateBadgeDefinitionEventTemplate({
|
||||||
|
d,
|
||||||
|
description,
|
||||||
|
image,
|
||||||
|
name,
|
||||||
|
thumbs,
|
||||||
|
}: BadgeDefinition): EventTemplate {
|
||||||
|
// Mandatory tags
|
||||||
|
const tags: string[][] = [['d', d]]
|
||||||
|
|
||||||
|
// Append optional tags
|
||||||
|
name && tags.push(['name', name])
|
||||||
|
description && tags.push(['description', description])
|
||||||
|
image && tags.push(['image', ...image])
|
||||||
|
if (thumbs) {
|
||||||
|
for (const thumb of thumbs) {
|
||||||
|
tags.push(['thumb', ...thumb])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Construct the EventTemplate object
|
||||||
|
const eventTemplate: EventTemplate = {
|
||||||
|
content: '',
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
kind: BadgeDefinitionKind,
|
||||||
|
tags,
|
||||||
|
}
|
||||||
|
|
||||||
|
return eventTemplate
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates a badge definition event.
|
||||||
|
*
|
||||||
|
* @param event - The event to validate.
|
||||||
|
* @returns A boolean indicating whether the event is a valid badge definition event.
|
||||||
|
*/
|
||||||
|
export function validateBadgeDefinitionEvent(event: Event): boolean {
|
||||||
|
if (event.kind !== BadgeDefinitionKind) return false
|
||||||
|
|
||||||
|
const requiredTags = ['d'] as const
|
||||||
|
for (const tag of requiredTags) {
|
||||||
|
if (!event.tags.find(([t]) => t == tag)) return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates an EventTemplate based on the provided BadgeAward.
|
||||||
|
*
|
||||||
|
* @param {BadgeAward} badgeAward - The BadgeAward object.
|
||||||
|
* @returns {EventTemplate} - The generated EventTemplate object.
|
||||||
|
*/
|
||||||
|
export function generateBadgeAwardEventTemplate({ a, p }: BadgeAward): EventTemplate {
|
||||||
|
// Mandatory tags
|
||||||
|
const tags: string[][] = [['a', a]]
|
||||||
|
for (const _p of p) {
|
||||||
|
tags.push(['p', ..._p])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Construct the EventTemplate object
|
||||||
|
const eventTemplate: EventTemplate = {
|
||||||
|
content: '',
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
kind: BadgeAwardKind,
|
||||||
|
tags,
|
||||||
|
}
|
||||||
|
|
||||||
|
return eventTemplate
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates a badge award event.
|
||||||
|
*
|
||||||
|
* @param event - The event to validate.
|
||||||
|
* @returns A boolean indicating whether the event is a valid badge award event.
|
||||||
|
*/
|
||||||
|
export function validateBadgeAwardEvent(event: Event): boolean {
|
||||||
|
if (event.kind !== BadgeAwardKind) return false
|
||||||
|
|
||||||
|
const requiredTags = ['a', 'p'] as const
|
||||||
|
for (const tag of requiredTags) {
|
||||||
|
if (!event.tags.find(([t]) => t == tag)) return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates an EventTemplate based on the provided ProfileBadges.
|
||||||
|
*
|
||||||
|
* @param {ProfileBadges} profileBadges - The ProfileBadges object.
|
||||||
|
* @returns {EventTemplate} - The generated EventTemplate object.
|
||||||
|
*/
|
||||||
|
export function generateProfileBadgesEventTemplate({ badges }: ProfileBadges): EventTemplate {
|
||||||
|
// Mandatory tags
|
||||||
|
const tags: string[][] = [['d', 'profile_badges']]
|
||||||
|
|
||||||
|
// Append optional tags
|
||||||
|
for (const badge of badges) {
|
||||||
|
tags.push(['a', badge.a], ['e', ...badge.e])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Construct the EventTemplate object
|
||||||
|
const eventTemplate: EventTemplate = {
|
||||||
|
content: '',
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
kind: ProfileBadgesKind,
|
||||||
|
tags,
|
||||||
|
}
|
||||||
|
|
||||||
|
return eventTemplate
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates a profile badges event.
|
||||||
|
*
|
||||||
|
* @param event - The event to validate.
|
||||||
|
* @returns A boolean indicating whether the event is a valid profile badges event.
|
||||||
|
*/
|
||||||
|
export function validateProfileBadgesEvent(event: Event): boolean {
|
||||||
|
if (event.kind !== ProfileBadgesKind) return false
|
||||||
|
|
||||||
|
const requiredTags = ['d'] as const
|
||||||
|
for (const tag of requiredTags) {
|
||||||
|
if (!event.tags.find(([t]) => t == tag)) return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
203
nip75.test.ts
Normal file
203
nip75.test.ts
Normal file
@@ -0,0 +1,203 @@
|
|||||||
|
import { describe, expect, it } from 'bun:test'
|
||||||
|
|
||||||
|
import { ZapGoal } from './kinds.ts'
|
||||||
|
import { Goal, generateGoalEventTemplate, validateZapGoalEvent } from './nip75.ts'
|
||||||
|
import { finalizeEvent, generateSecretKey } from './pure.ts'
|
||||||
|
|
||||||
|
describe('Goal Type', () => {
|
||||||
|
it('should create a proper Goal object', () => {
|
||||||
|
const goal: Goal = {
|
||||||
|
content: 'Fundraising for a new project',
|
||||||
|
amount: '100000000',
|
||||||
|
relays: ['wss://relay1.example.com', 'wss://relay2.example.com'],
|
||||||
|
closedAt: 1671150419,
|
||||||
|
image: 'https://example.com/goal-image.jpg',
|
||||||
|
summary: 'Help us reach our fundraising goal!',
|
||||||
|
r: 'https://example.com/additional-info',
|
||||||
|
a: 'fef2a50f7d9d3d5a5f38ee761bc087ec16198d3f0140df6d1e8193abf7c2b146',
|
||||||
|
zapTags: [
|
||||||
|
['zap', 'beneficiary1'],
|
||||||
|
['zap', 'beneficiary2'],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(goal.content).toBe('Fundraising for a new project')
|
||||||
|
expect(goal.amount).toBe('100000000')
|
||||||
|
expect(goal.relays).toEqual(['wss://relay1.example.com', 'wss://relay2.example.com'])
|
||||||
|
expect(goal.closedAt).toBe(1671150419)
|
||||||
|
expect(goal.image).toBe('https://example.com/goal-image.jpg')
|
||||||
|
expect(goal.summary).toBe('Help us reach our fundraising goal!')
|
||||||
|
expect(goal.r).toBe('https://example.com/additional-info')
|
||||||
|
expect(goal.a).toBe('fef2a50f7d9d3d5a5f38ee761bc087ec16198d3f0140df6d1e8193abf7c2b146')
|
||||||
|
expect(goal.zapTags).toEqual([
|
||||||
|
['zap', 'beneficiary1'],
|
||||||
|
['zap', 'beneficiary2'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('generateGoalEventTemplate', () => {
|
||||||
|
it('should generate an EventTemplate for a fundraising goal', () => {
|
||||||
|
const goal: Goal = {
|
||||||
|
content: 'Fundraising for a new project',
|
||||||
|
amount: '100000000',
|
||||||
|
relays: ['wss://relay1.example.com', 'wss://relay2.example.com'],
|
||||||
|
closedAt: 1671150419,
|
||||||
|
image: 'https://example.com/goal-image.jpg',
|
||||||
|
summary: 'Help us reach our fundraising goal!',
|
||||||
|
r: 'https://example.com/additional-info',
|
||||||
|
zapTags: [
|
||||||
|
['zap', 'beneficiary1'],
|
||||||
|
['zap', 'beneficiary2'],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
const eventTemplate = generateGoalEventTemplate(goal)
|
||||||
|
|
||||||
|
expect(eventTemplate.kind).toBe(ZapGoal)
|
||||||
|
expect(eventTemplate.content).toBe('Fundraising for a new project')
|
||||||
|
expect(eventTemplate.tags).toEqual([
|
||||||
|
['amount', '100000000'],
|
||||||
|
['relays', 'wss://relay1.example.com', 'wss://relay2.example.com'],
|
||||||
|
['closed_at', '1671150419'],
|
||||||
|
['image', 'https://example.com/goal-image.jpg'],
|
||||||
|
['summary', 'Help us reach our fundraising goal!'],
|
||||||
|
['r', 'https://example.com/additional-info'],
|
||||||
|
['zap', 'beneficiary1'],
|
||||||
|
['zap', 'beneficiary2'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should generate an EventTemplate for a fundraising goal without optional properties', () => {
|
||||||
|
const goal: Goal = {
|
||||||
|
content: 'Fundraising for a new project',
|
||||||
|
amount: '100000000',
|
||||||
|
relays: ['wss://relay1.example.com', 'wss://relay2.example.com'],
|
||||||
|
}
|
||||||
|
|
||||||
|
const eventTemplate = generateGoalEventTemplate(goal)
|
||||||
|
|
||||||
|
expect(eventTemplate.kind).toBe(ZapGoal)
|
||||||
|
expect(eventTemplate.content).toBe('Fundraising for a new project')
|
||||||
|
expect(eventTemplate.tags).toEqual([
|
||||||
|
['amount', '100000000'],
|
||||||
|
['relays', 'wss://relay1.example.com', 'wss://relay2.example.com'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should generate an EventTemplate that is valid', () => {
|
||||||
|
const sk = generateSecretKey()
|
||||||
|
const goal: Goal = {
|
||||||
|
content: 'Fundraising for a new project',
|
||||||
|
amount: '100000000',
|
||||||
|
relays: ['wss://relay1.example.com', 'wss://relay2.example.com'],
|
||||||
|
closedAt: 1671150419,
|
||||||
|
image: 'https://example.com/goal-image.jpg',
|
||||||
|
summary: 'Help us reach our fundraising goal!',
|
||||||
|
r: 'https://example.com/additional-info',
|
||||||
|
zapTags: [
|
||||||
|
['zap', 'beneficiary1'],
|
||||||
|
['zap', 'beneficiary2'],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const eventTemplate = generateGoalEventTemplate(goal)
|
||||||
|
const event = finalizeEvent(eventTemplate, sk)
|
||||||
|
const isValid = validateZapGoalEvent(event)
|
||||||
|
|
||||||
|
expect(isValid).toBe(true)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('validateZapGoalEvent', () => {
|
||||||
|
it('should validate a proper Goal event', () => {
|
||||||
|
const sk = generateSecretKey()
|
||||||
|
const eventTemplate = {
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
kind: ZapGoal,
|
||||||
|
content: 'Fundraising for a new project',
|
||||||
|
tags: [
|
||||||
|
['amount', '100000000'],
|
||||||
|
['relays', 'wss://relay1.example.com', 'wss://relay2.example.com'],
|
||||||
|
['closed_at', '1671150419'],
|
||||||
|
['image', 'https://example.com/goal-image.jpg'],
|
||||||
|
['summary', 'Help us reach our fundraising goal!'],
|
||||||
|
['r', 'https://example.com/additional-info'],
|
||||||
|
['zap', 'beneficiary1'],
|
||||||
|
['zap', 'beneficiary2'],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const event = finalizeEvent(eventTemplate, sk)
|
||||||
|
const isValid = validateZapGoalEvent(event)
|
||||||
|
|
||||||
|
expect(isValid).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should not validate an event with an incorrect kind', () => {
|
||||||
|
const sk = generateSecretKey()
|
||||||
|
const eventTemplate = {
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
kind: 0, // Incorrect kind
|
||||||
|
content: 'Fundraising for a new project',
|
||||||
|
tags: [
|
||||||
|
['amount', '100000000'],
|
||||||
|
['relays', 'wss://relay1.example.com', 'wss://relay2.example.com'],
|
||||||
|
['closed_at', '1671150419'],
|
||||||
|
['image', 'https://example.com/goal-image.jpg'],
|
||||||
|
['summary', 'Help us reach our fundraising goal!'],
|
||||||
|
['r', 'https://example.com/additional-info'],
|
||||||
|
['zap', 'beneficiary1'],
|
||||||
|
['zap', 'beneficiary2'],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const event = finalizeEvent(eventTemplate, sk)
|
||||||
|
const isValid = validateZapGoalEvent(event)
|
||||||
|
|
||||||
|
expect(isValid).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should not validate an event with missing required "amount" tag', () => {
|
||||||
|
const sk = generateSecretKey()
|
||||||
|
const eventTemplate = {
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
kind: ZapGoal,
|
||||||
|
content: 'Fundraising for a new project',
|
||||||
|
tags: [
|
||||||
|
// Missing "amount" tag
|
||||||
|
['relays', 'wss://relay1.example.com', 'wss://relay2.example.com'],
|
||||||
|
['closed_at', '1671150419'],
|
||||||
|
['image', 'https://example.com/goal-image.jpg'],
|
||||||
|
['summary', 'Help us reach our fundraising goal!'],
|
||||||
|
['r', 'https://example.com/additional-info'],
|
||||||
|
['zap', 'beneficiary1'],
|
||||||
|
['zap', 'beneficiary2'],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const event = finalizeEvent(eventTemplate, sk)
|
||||||
|
const isValid = validateZapGoalEvent(event)
|
||||||
|
|
||||||
|
expect(isValid).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should not validate an event with missing required "relays" tag', () => {
|
||||||
|
const sk = generateSecretKey()
|
||||||
|
const eventTemplate = {
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
kind: ZapGoal,
|
||||||
|
content: 'Fundraising for a new project',
|
||||||
|
tags: [
|
||||||
|
['amount', '100000000'],
|
||||||
|
// Missing "relays" tag
|
||||||
|
['closed_at', '1671150419'],
|
||||||
|
['image', 'https://example.com/goal-image.jpg'],
|
||||||
|
['summary', 'Help us reach our fundraising goal!'],
|
||||||
|
['r', 'https://example.com/additional-info'],
|
||||||
|
['zap', 'beneficiary1'],
|
||||||
|
['zap', 'beneficiary2'],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const event = finalizeEvent(eventTemplate, sk)
|
||||||
|
const isValid = validateZapGoalEvent(event)
|
||||||
|
|
||||||
|
expect(isValid).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
115
nip75.ts
Normal file
115
nip75.ts
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
import { Event, EventTemplate } from './core.ts'
|
||||||
|
import { ZapGoal } from './kinds.ts'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents a fundraising goal in the Nostr network as defined by NIP-75.
|
||||||
|
* This type is used to structure the information needed to create a goal event (`kind:9041`).
|
||||||
|
*/
|
||||||
|
export type Goal = {
|
||||||
|
/**
|
||||||
|
* A human-readable description of the fundraising goal.
|
||||||
|
* This content should provide clear information about the purpose of the fundraising.
|
||||||
|
*/
|
||||||
|
content: string
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The target amount for the fundraising goal in milisats.
|
||||||
|
* This defines the financial target that the fundraiser aims to reach.
|
||||||
|
*/
|
||||||
|
amount: string
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A list of relays where the zaps towards this goal will be sent to and tallied from.
|
||||||
|
* Each relay is represented by its WebSocket URL.
|
||||||
|
*/
|
||||||
|
relays: string[]
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An optional timestamp (in seconds, UNIX epoch) indicating when the fundraising goal is considered closed.
|
||||||
|
* Zaps published after this timestamp should not count towards the goal progress.
|
||||||
|
* If not provided, the goal remains open indefinitely or until manually closed.
|
||||||
|
*/
|
||||||
|
closedAt?: number
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An optional URL to an image related to the goal.
|
||||||
|
* This can be used to visually represent the goal on client interfaces.
|
||||||
|
*/
|
||||||
|
image?: string
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An optional brief description or summary of the goal.
|
||||||
|
* This can provide a quick overview of the goal, separate from the detailed `content`.
|
||||||
|
*/
|
||||||
|
summary?: string
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An optional URL related to the goal, providing additional information or actions through an 'r' tag.
|
||||||
|
* This is a single URL, as per NIP-75 specifications for linking additional resources.
|
||||||
|
*/
|
||||||
|
r?: string
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An optional parameterized replaceable event linked to the goal, specified through an 'a' tag.
|
||||||
|
* This is a single event id, aligning with NIP-75's allowance for linking to specific events.
|
||||||
|
*/
|
||||||
|
a?: string
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Optional tags specifying multiple beneficiary pubkeys or additional criteria for zapping,
|
||||||
|
* allowing contributions to be directed towards multiple recipients or according to specific conditions.
|
||||||
|
*/
|
||||||
|
zapTags?: string[][]
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates an EventTemplate for a fundraising goal based on the provided ZapGoal object.
|
||||||
|
* This function is tailored to fit the structure of EventTemplate as defined in the library.
|
||||||
|
* @param zapGoal The ZapGoal object containing the details of the fundraising goal.
|
||||||
|
* @returns An EventTemplate object structured for creating a Nostr event.
|
||||||
|
*/
|
||||||
|
export function generateGoalEventTemplate({
|
||||||
|
amount,
|
||||||
|
content,
|
||||||
|
relays,
|
||||||
|
a,
|
||||||
|
closedAt,
|
||||||
|
image,
|
||||||
|
r,
|
||||||
|
summary,
|
||||||
|
zapTags,
|
||||||
|
}: Goal): EventTemplate {
|
||||||
|
const tags: string[][] = [
|
||||||
|
['amount', amount],
|
||||||
|
['relays', ...relays],
|
||||||
|
]
|
||||||
|
|
||||||
|
// Append optional tags based on the presence of optional properties in zapGoal
|
||||||
|
closedAt && tags.push(['closed_at', closedAt.toString()])
|
||||||
|
image && tags.push(['image', image])
|
||||||
|
summary && tags.push(['summary', summary])
|
||||||
|
r && tags.push(['r', r])
|
||||||
|
a && tags.push(['a', a])
|
||||||
|
zapTags && tags.push(...zapTags)
|
||||||
|
|
||||||
|
// Construct the EventTemplate object
|
||||||
|
const eventTemplate: EventTemplate = {
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
kind: ZapGoal,
|
||||||
|
content,
|
||||||
|
tags,
|
||||||
|
}
|
||||||
|
|
||||||
|
return eventTemplate
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateZapGoalEvent(event: Event): boolean {
|
||||||
|
if (event.kind !== ZapGoal) return false
|
||||||
|
|
||||||
|
const requiredTags = ['amount', 'relays'] as const
|
||||||
|
for (const tag of requiredTags) {
|
||||||
|
if (!event.tags.find(([t]) => t == tag)) return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
2
nip94.ts
2
nip94.ts
@@ -1,4 +1,4 @@
|
|||||||
import { Event, EventTemplate } from './core'
|
import { Event, EventTemplate } from './core.ts'
|
||||||
import { FileMetadata as FileMetadataKind } from './kinds.ts'
|
import { FileMetadata as FileMetadataKind } from './kinds.ts'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
18
nip96.ts
18
nip96.ts
@@ -1,5 +1,7 @@
|
|||||||
import { EventTemplate } from './core'
|
import { sha256 } from '@noble/hashes/sha256'
|
||||||
import { FileServerPreference } from './kinds'
|
import { EventTemplate } from './core.ts'
|
||||||
|
import { FileServerPreference } from './kinds.ts'
|
||||||
|
import { bytesToHex } from '@noble/hashes/utils'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents the configuration for a server compliant with NIP-96.
|
* Represents the configuration for a server compliant with NIP-96.
|
||||||
@@ -576,15 +578,5 @@ export function generateFSPEventTemplate(serverUrls: string[]): EventTemplate {
|
|||||||
* @returns A promise that resolves to the SHA-256 hash of the file.
|
* @returns A promise that resolves to the SHA-256 hash of the file.
|
||||||
*/
|
*/
|
||||||
export async function calculateFileHash(file: Blob): Promise<string> {
|
export async function calculateFileHash(file: Blob): Promise<string> {
|
||||||
// Read the file as an ArrayBuffer
|
return bytesToHex(sha256(new Uint8Array(await file.arrayBuffer())))
|
||||||
const buffer = await file.arrayBuffer()
|
|
||||||
|
|
||||||
// Calculate the SHA-256 hash of the file
|
|
||||||
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer)
|
|
||||||
|
|
||||||
// Convert the hash to a hexadecimal string
|
|
||||||
const hashArray = Array.from(new Uint8Array(hashBuffer))
|
|
||||||
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('')
|
|
||||||
|
|
||||||
return hashHex
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { describe, expect, test } from 'bun:test'
|
import { describe, expect, test } from 'bun:test'
|
||||||
|
|
||||||
import { Event } from './core'
|
import { Event } from './core.ts'
|
||||||
import { ClassifiedListing, DraftClassifiedListing } from './kinds'
|
import { ClassifiedListing, DraftClassifiedListing } from './kinds.ts'
|
||||||
import { ClassifiedListingObject, generateEventTemplate, parseEvent, validateEvent } from './nip99'
|
import { ClassifiedListingObject, generateEventTemplate, parseEvent, validateEvent } from './nip99.ts'
|
||||||
import { finalizeEvent, generateSecretKey } from './pure'
|
import { finalizeEvent, generateSecretKey } from './pure.ts'
|
||||||
|
|
||||||
describe('validateEvent', () => {
|
describe('validateEvent', () => {
|
||||||
test('should return true for a valid classified listing event', () => {
|
test('should return true for a valid classified listing event', () => {
|
||||||
|
|||||||
17
package.json
17
package.json
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"name": "nostr-tools",
|
"name": "nostr-tools",
|
||||||
"version": "2.1.7",
|
"version": "2.7.0",
|
||||||
"description": "Tools for making a Nostr client.",
|
"description": "Tools for making a Nostr client.",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -85,6 +85,9 @@
|
|||||||
"require": "./lib/cjs/nip06.js",
|
"require": "./lib/cjs/nip06.js",
|
||||||
"types": "./lib/types/nip06.d.ts"
|
"types": "./lib/types/nip06.d.ts"
|
||||||
},
|
},
|
||||||
|
"./nip07": {
|
||||||
|
"types": "./lib/types/nip07.d.ts"
|
||||||
|
},
|
||||||
"./nip10": {
|
"./nip10": {
|
||||||
"import": "./lib/esm/nip10.js",
|
"import": "./lib/esm/nip10.js",
|
||||||
"require": "./lib/cjs/nip10.js",
|
"require": "./lib/cjs/nip10.js",
|
||||||
@@ -170,6 +173,16 @@
|
|||||||
"require": "./lib/cjs/nip57.js",
|
"require": "./lib/cjs/nip57.js",
|
||||||
"types": "./lib/types/nip57.d.ts"
|
"types": "./lib/types/nip57.d.ts"
|
||||||
},
|
},
|
||||||
|
"./nip58": {
|
||||||
|
"import": "./lib/esm/nip58.js",
|
||||||
|
"require": "./lib/cjs/nip58.js",
|
||||||
|
"types": "./lib/types/nip58.d.ts"
|
||||||
|
},
|
||||||
|
"./nip75": {
|
||||||
|
"import": "./lib/esm/nip75.js",
|
||||||
|
"require": "./lib/cjs/nip75.js",
|
||||||
|
"types": "./lib/types/nip75.d.ts"
|
||||||
|
},
|
||||||
"./nip94": {
|
"./nip94": {
|
||||||
"import": "./lib/esm/nip94.js",
|
"import": "./lib/esm/nip94.js",
|
||||||
"require": "./lib/cjs/nip94.js",
|
"require": "./lib/cjs/nip94.js",
|
||||||
@@ -203,7 +216,7 @@
|
|||||||
},
|
},
|
||||||
"license": "Unlicense",
|
"license": "Unlicense",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@noble/ciphers": "0.2.0",
|
"@noble/ciphers": "^0.5.1",
|
||||||
"@noble/curves": "1.2.0",
|
"@noble/curves": "1.2.0",
|
||||||
"@noble/hashes": "1.3.1",
|
"@noble/hashes": "1.3.1",
|
||||||
"@scure/base": "1.1.1",
|
"@scure/base": "1.1.1",
|
||||||
|
|||||||
87
pool.test.ts
87
pool.test.ts
@@ -1,8 +1,11 @@
|
|||||||
import { afterEach, beforeEach, expect, test } from 'bun:test'
|
import { afterEach, beforeEach, expect, test } from 'bun:test'
|
||||||
|
|
||||||
import { SimplePool } from './pool.ts'
|
import { SimplePool, useWebSocketImplementation } from './pool.ts'
|
||||||
import { finalizeEvent, generateSecretKey, getPublicKey, type Event } from './pure.ts'
|
import { finalizeEvent, generateSecretKey, getPublicKey, type Event } from './pure.ts'
|
||||||
import { MockRelay } from './test-helpers.ts'
|
import { MockRelay, MockWebSocketClient } from './test-helpers.ts'
|
||||||
|
import { hexToBytes } from '@noble/hashes/utils'
|
||||||
|
|
||||||
|
useWebSocketImplementation(MockWebSocketClient)
|
||||||
|
|
||||||
let pool: SimplePool
|
let pool: SimplePool
|
||||||
let mockRelays: MockRelay[]
|
let mockRelays: MockRelay[]
|
||||||
@@ -81,6 +84,86 @@ test('same with double subs', async () => {
|
|||||||
expect(received).toHaveLength(2)
|
expect(received).toHaveLength(2)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('subscribe many map', async () => {
|
||||||
|
let priv = hexToBytes('8ea002840d413ccdd5be98df5dd89d799eaa566355ede83ca0bbdbb4b145e0d3')
|
||||||
|
let pub = getPublicKey(priv)
|
||||||
|
|
||||||
|
let received: Event[] = []
|
||||||
|
let event1 = finalizeEvent(
|
||||||
|
{
|
||||||
|
created_at: Math.round(Date.now() / 1000),
|
||||||
|
content: 'test1',
|
||||||
|
kind: 20001,
|
||||||
|
tags: [],
|
||||||
|
},
|
||||||
|
priv,
|
||||||
|
)
|
||||||
|
let event2 = finalizeEvent(
|
||||||
|
{
|
||||||
|
created_at: Math.round(Date.now() / 1000),
|
||||||
|
content: 'test2',
|
||||||
|
kind: 20002,
|
||||||
|
tags: [['t', 'biloba']],
|
||||||
|
},
|
||||||
|
priv,
|
||||||
|
)
|
||||||
|
let event3 = finalizeEvent(
|
||||||
|
{
|
||||||
|
created_at: Math.round(Date.now() / 1000),
|
||||||
|
content: 'test3',
|
||||||
|
kind: 20003,
|
||||||
|
tags: [['t', 'biloba']],
|
||||||
|
},
|
||||||
|
priv,
|
||||||
|
)
|
||||||
|
|
||||||
|
const [relayA, relayB, relayC] = relayURLs
|
||||||
|
|
||||||
|
pool.subscribeManyMap(
|
||||||
|
{
|
||||||
|
[relayA]: [{ authors: [pub], kinds: [20001] }],
|
||||||
|
[relayB]: [{ authors: [pub], kinds: [20002] }],
|
||||||
|
[relayC]: [{ kinds: [20003], '#t': ['biloba'] }],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
onevent(event: Event) {
|
||||||
|
received.push(event)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
// publish the first
|
||||||
|
await Promise.all(pool.publish([relayA, relayB], event1))
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 100))
|
||||||
|
|
||||||
|
expect(received).toHaveLength(1)
|
||||||
|
expect(received[0]).toEqual(event1)
|
||||||
|
|
||||||
|
// publish the second
|
||||||
|
await pool.publish([relayB], event2)[0]
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 100))
|
||||||
|
|
||||||
|
expect(received).toHaveLength(2)
|
||||||
|
expect(received[1]).toEqual(event2)
|
||||||
|
|
||||||
|
// publish a events that shouldn't match our filters
|
||||||
|
await Promise.all([
|
||||||
|
...pool.publish([relayA, relayB], event3),
|
||||||
|
...pool.publish([relayA, relayB, relayC], event1),
|
||||||
|
pool.publish([relayA, relayB, relayC], event2),
|
||||||
|
])
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 100))
|
||||||
|
|
||||||
|
expect(received).toHaveLength(2)
|
||||||
|
|
||||||
|
// publsih the third
|
||||||
|
await pool.publish([relayC], event3)[0]
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 100))
|
||||||
|
|
||||||
|
expect(received).toHaveLength(3)
|
||||||
|
expect(received[2]).toEqual(event3)
|
||||||
|
})
|
||||||
|
|
||||||
test('query a bunch of events and cancel on eose', async () => {
|
test('query a bunch of events and cancel on eose', async () => {
|
||||||
let events = new Set<string>()
|
let events = new Set<string>()
|
||||||
|
|
||||||
|
|||||||
14
pool.ts
14
pool.ts
@@ -1,9 +1,21 @@
|
|||||||
|
/* global WebSocket */
|
||||||
|
|
||||||
import { verifyEvent } from './pure.ts'
|
import { verifyEvent } from './pure.ts'
|
||||||
import { AbstractSimplePool } from './abstract-pool.ts'
|
import { AbstractSimplePool } from './abstract-pool.ts'
|
||||||
|
|
||||||
|
var _WebSocket: typeof WebSocket
|
||||||
|
|
||||||
|
try {
|
||||||
|
_WebSocket = WebSocket
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
export function useWebSocketImplementation(websocketImplementation: any) {
|
||||||
|
_WebSocket = websocketImplementation
|
||||||
|
}
|
||||||
|
|
||||||
export class SimplePool extends AbstractSimplePool {
|
export class SimplePool extends AbstractSimplePool {
|
||||||
constructor() {
|
constructor() {
|
||||||
super({ verifyEvent })
|
super({ verifyEvent, websocketImplementation: _WebSocket })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
293
pure.test.ts
Normal file
293
pure.test.ts
Normal file
@@ -0,0 +1,293 @@
|
|||||||
|
import { describe, test, expect } from 'bun:test'
|
||||||
|
|
||||||
|
import {
|
||||||
|
finalizeEvent,
|
||||||
|
serializeEvent,
|
||||||
|
getEventHash,
|
||||||
|
validateEvent,
|
||||||
|
verifyEvent,
|
||||||
|
verifiedSymbol,
|
||||||
|
getPublicKey,
|
||||||
|
generateSecretKey,
|
||||||
|
} from './pure.ts'
|
||||||
|
import { ShortTextNote } from './kinds.ts'
|
||||||
|
import { bytesToHex, hexToBytes } from '@noble/hashes/utils'
|
||||||
|
|
||||||
|
test('private key generation', () => {
|
||||||
|
expect(bytesToHex(generateSecretKey())).toMatch(/[a-f0-9]{64}/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('public key generation', () => {
|
||||||
|
expect(getPublicKey(generateSecretKey())).toMatch(/[a-f0-9]{64}/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('public key from private key deterministic', () => {
|
||||||
|
let sk = generateSecretKey()
|
||||||
|
let pk = getPublicKey(sk)
|
||||||
|
|
||||||
|
for (let i = 0; i < 5; i++) {
|
||||||
|
expect(getPublicKey(sk)).toEqual(pk)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('finalizeEvent', () => {
|
||||||
|
test('should create a signed event from a template', () => {
|
||||||
|
const privateKey = hexToBytes('d217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf')
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const template = {
|
||||||
|
kind: ShortTextNote,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115,
|
||||||
|
}
|
||||||
|
|
||||||
|
const event = finalizeEvent(template, privateKey)
|
||||||
|
|
||||||
|
expect(event.kind).toEqual(template.kind)
|
||||||
|
expect(event.tags).toEqual(template.tags)
|
||||||
|
expect(event.content).toEqual(template.content)
|
||||||
|
expect(event.created_at).toEqual(template.created_at)
|
||||||
|
expect(event.pubkey).toEqual(publicKey)
|
||||||
|
expect(typeof event.id).toEqual('string')
|
||||||
|
expect(typeof event.sig).toEqual('string')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('serializeEvent', () => {
|
||||||
|
test('should serialize a valid event object', () => {
|
||||||
|
const privateKey = hexToBytes('d217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf')
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const unsignedEvent = {
|
||||||
|
pubkey: publicKey,
|
||||||
|
created_at: 1617932115,
|
||||||
|
kind: ShortTextNote,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
}
|
||||||
|
|
||||||
|
const serializedEvent = serializeEvent(unsignedEvent)
|
||||||
|
|
||||||
|
expect(serializedEvent).toEqual(
|
||||||
|
JSON.stringify([
|
||||||
|
0,
|
||||||
|
publicKey,
|
||||||
|
unsignedEvent.created_at,
|
||||||
|
unsignedEvent.kind,
|
||||||
|
unsignedEvent.tags,
|
||||||
|
unsignedEvent.content,
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should throw an error for an invalid event object', () => {
|
||||||
|
const privateKey = hexToBytes('d217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf')
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const invalidEvent = {
|
||||||
|
kind: ShortTextNote,
|
||||||
|
tags: [],
|
||||||
|
created_at: 1617932115,
|
||||||
|
pubkey: publicKey, // missing content
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(() => {
|
||||||
|
// @ts-expect-error
|
||||||
|
serializeEvent(invalidEvent)
|
||||||
|
}).toThrow("can't serialize event with wrong or missing properties")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('getEventHash', () => {
|
||||||
|
test('should return the correct event hash', () => {
|
||||||
|
const privateKey = hexToBytes('d217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf')
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const unsignedEvent = {
|
||||||
|
kind: ShortTextNote,
|
||||||
|
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', () => {
|
||||||
|
test('should return true for a valid event object', () => {
|
||||||
|
const privateKey = hexToBytes('d217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf')
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const unsignedEvent = {
|
||||||
|
kind: ShortTextNote,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115,
|
||||||
|
pubkey: publicKey,
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValid = validateEvent(unsignedEvent)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should return false for a non object event', () => {
|
||||||
|
const nonObjectEvent = ''
|
||||||
|
const isValid = validateEvent(nonObjectEvent)
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should return false for an event object with missing properties', () => {
|
||||||
|
const invalidEvent = {
|
||||||
|
kind: ShortTextNote,
|
||||||
|
tags: [],
|
||||||
|
created_at: 1617932115, // missing content and pubkey
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValid = validateEvent(invalidEvent)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should return false for an empty object', () => {
|
||||||
|
const emptyObj = {}
|
||||||
|
|
||||||
|
const isValid = validateEvent(emptyObj)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should return false for an object with invalid properties', () => {
|
||||||
|
const privateKey = hexToBytes('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)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('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)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should return false for an object with invalid tags', () => {
|
||||||
|
const privateKey = hexToBytes('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('verifyEvent', () => {
|
||||||
|
test('should return true for a valid event signature', () => {
|
||||||
|
const privateKey = hexToBytes('d217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf')
|
||||||
|
const event = finalizeEvent(
|
||||||
|
{
|
||||||
|
kind: ShortTextNote,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115,
|
||||||
|
},
|
||||||
|
privateKey,
|
||||||
|
)
|
||||||
|
|
||||||
|
const isValid = verifyEvent(event)
|
||||||
|
expect(isValid).toEqual(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should return false for an invalid event signature', () => {
|
||||||
|
const privateKey = hexToBytes('d217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf')
|
||||||
|
const { [verifiedSymbol]: _, ...event } = finalizeEvent(
|
||||||
|
{
|
||||||
|
kind: ShortTextNote,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115,
|
||||||
|
},
|
||||||
|
privateKey,
|
||||||
|
)
|
||||||
|
|
||||||
|
// tamper with the signature
|
||||||
|
event.sig = event.sig.replace(/^.{3}/g, '666')
|
||||||
|
|
||||||
|
const isValid = verifyEvent(event)
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should return false when verifying an event with a different private key', () => {
|
||||||
|
const privateKey1 = hexToBytes('d217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf')
|
||||||
|
|
||||||
|
const privateKey2 = hexToBytes('5b4a34f4e4b23c63ad55a35e3f84a3b53d96dbf266edf521a8358f71d19cbf67')
|
||||||
|
const publicKey2 = getPublicKey(privateKey2)
|
||||||
|
|
||||||
|
const { [verifiedSymbol]: _, ...event } = finalizeEvent(
|
||||||
|
{
|
||||||
|
kind: ShortTextNote,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115,
|
||||||
|
},
|
||||||
|
privateKey1,
|
||||||
|
)
|
||||||
|
|
||||||
|
// verify with different private key
|
||||||
|
const isValid = verifyEvent({
|
||||||
|
...event,
|
||||||
|
pubkey: publicKey2,
|
||||||
|
})
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should return false for an invalid event id', () => {
|
||||||
|
const privateKey = hexToBytes('d217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf')
|
||||||
|
|
||||||
|
const { [verifiedSymbol]: _, ...event } = finalizeEvent(
|
||||||
|
{
|
||||||
|
kind: 1,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115,
|
||||||
|
},
|
||||||
|
privateKey,
|
||||||
|
)
|
||||||
|
|
||||||
|
// tamper with the id
|
||||||
|
event.id = event.id.replace(/^.{3}/g, '666')
|
||||||
|
|
||||||
|
const isValid = verifyEvent(event)
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
2
pure.ts
2
pure.ts
@@ -50,7 +50,7 @@ export function getEventHash(event: UnsignedEvent): string {
|
|||||||
return bytesToHex(eventHash)
|
return bytesToHex(eventHash)
|
||||||
}
|
}
|
||||||
|
|
||||||
const i = new JS()
|
const i: JS = new JS()
|
||||||
|
|
||||||
export const generateSecretKey = i.generateSecretKey
|
export const generateSecretKey = i.generateSecretKey
|
||||||
export const getPublicKey = i.getPublicKey
|
export const getPublicKey = i.getPublicKey
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import { expect, test } from 'bun:test'
|
import { expect, test } from 'bun:test'
|
||||||
|
|
||||||
import { finalizeEvent, generateSecretKey, getPublicKey } from './pure.ts'
|
import { finalizeEvent, generateSecretKey, getPublicKey } from './pure.ts'
|
||||||
import { Relay } from './relay.ts'
|
import { Relay, useWebSocketImplementation } from './relay.ts'
|
||||||
import { MockRelay } from './test-helpers.ts'
|
import { MockRelay, MockWebSocketClient } from './test-helpers.ts'
|
||||||
|
|
||||||
|
useWebSocketImplementation(MockWebSocketClient)
|
||||||
|
|
||||||
test('connectivity', async () => {
|
test('connectivity', async () => {
|
||||||
const mockRelay = new MockRelay()
|
const mockRelay = new MockRelay()
|
||||||
|
|||||||
18
relay.ts
18
relay.ts
@@ -1,3 +1,5 @@
|
|||||||
|
/* global WebSocket */
|
||||||
|
|
||||||
import { verifyEvent } from './pure.ts'
|
import { verifyEvent } from './pure.ts'
|
||||||
import { AbstractRelay } from './abstract-relay.ts'
|
import { AbstractRelay } from './abstract-relay.ts'
|
||||||
|
|
||||||
@@ -8,16 +10,28 @@ export function relayConnect(url: string): Promise<Relay> {
|
|||||||
return Relay.connect(url)
|
return Relay.connect(url)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var _WebSocket: typeof WebSocket
|
||||||
|
|
||||||
|
try {
|
||||||
|
_WebSocket = WebSocket
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
export function useWebSocketImplementation(websocketImplementation: any) {
|
||||||
|
_WebSocket = websocketImplementation
|
||||||
|
}
|
||||||
|
|
||||||
export class Relay extends AbstractRelay {
|
export class Relay extends AbstractRelay {
|
||||||
constructor(url: string) {
|
constructor(url: string) {
|
||||||
super(url, { verifyEvent })
|
super(url, { verifyEvent, websocketImplementation: _WebSocket })
|
||||||
}
|
}
|
||||||
|
|
||||||
static async connect(url: string) {
|
static async connect(url: string): Promise<Relay> {
|
||||||
const relay = new Relay(url)
|
const relay = new Relay(url)
|
||||||
await relay.connect()
|
await relay.connect()
|
||||||
return relay
|
return relay
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type RelayRecord = Record<string, { read: boolean; write: boolean }>
|
||||||
|
|
||||||
export * from './abstract-relay.ts'
|
export * from './abstract-relay.ts'
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import { Server } from 'mock-socket'
|
import { Server, WebSocket } from 'mock-socket'
|
||||||
|
|
||||||
import { finalizeEvent, type Event, getPublicKey, generateSecretKey } from './pure.ts'
|
import { finalizeEvent, type Event, getPublicKey, generateSecretKey } from './pure.ts'
|
||||||
import { matchFilters, type Filter } from './filter.ts'
|
import { matchFilters, type Filter } from './filter.ts'
|
||||||
|
|
||||||
|
export const MockWebSocketClient = WebSocket
|
||||||
|
|
||||||
export function buildEvent(params: Partial<Event>): Event {
|
export function buildEvent(params: Partial<Event>): Event {
|
||||||
return {
|
return {
|
||||||
id: '',
|
id: '',
|
||||||
@@ -33,9 +35,9 @@ export class MockRelay {
|
|||||||
finalizeEvent(
|
finalizeEvent(
|
||||||
{
|
{
|
||||||
kind: 1,
|
kind: 1,
|
||||||
content: '',
|
content: 'autogenerated by relay',
|
||||||
created_at: Math.floor(Date.now() / 1000),
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
tags: [],
|
tags: [['t', 'auto']],
|
||||||
},
|
},
|
||||||
sk,
|
sk,
|
||||||
),
|
),
|
||||||
@@ -66,9 +68,9 @@ export class MockRelay {
|
|||||||
const event = finalizeEvent(
|
const event = finalizeEvent(
|
||||||
{
|
{
|
||||||
kind,
|
kind,
|
||||||
content: '',
|
content: 'kind-aware autogenerated by relay',
|
||||||
created_at: Math.floor(Date.now() / 1000),
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
tags: [],
|
tags: [['t', 'auto']],
|
||||||
},
|
},
|
||||||
sk,
|
sk,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"module": "esnext",
|
"module": "NodeNext",
|
||||||
"target": "esnext",
|
"target": "esnext",
|
||||||
"lib": ["dom", "dom.iterable", "esnext"],
|
"lib": ["dom", "dom.iterable", "esnext"],
|
||||||
"declaration": true,
|
"declaration": true,
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"moduleResolution": "node",
|
"moduleResolution": "NodeNext",
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
"esModuleInterop": true,
|
"esModuleInterop": true,
|
||||||
"emitDeclarationOnly": true,
|
"emitDeclarationOnly": true,
|
||||||
|
|||||||
8
utils.ts
8
utils.ts
@@ -1,7 +1,7 @@
|
|||||||
import type { Event } from './core.ts'
|
import type { Event } from './core.ts'
|
||||||
|
|
||||||
export const utf8Decoder = new TextDecoder('utf-8')
|
export const utf8Decoder: TextDecoder = new TextDecoder('utf-8')
|
||||||
export const utf8Encoder = new TextEncoder()
|
export const utf8Encoder: TextEncoder = new TextEncoder()
|
||||||
|
|
||||||
export function normalizeURL(url: string): string {
|
export function normalizeURL(url: string): string {
|
||||||
if (url.indexOf('://') === -1) url = 'wss://' + url
|
if (url.indexOf('://') === -1) url = 'wss://' + url
|
||||||
@@ -14,7 +14,7 @@ export function normalizeURL(url: string): string {
|
|||||||
return p.toString()
|
return p.toString()
|
||||||
}
|
}
|
||||||
|
|
||||||
export function insertEventIntoDescendingList(sortedArray: Event[], event: Event) {
|
export function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {
|
||||||
const [idx, found] = binarySearch(sortedArray, b => {
|
const [idx, found] = binarySearch(sortedArray, b => {
|
||||||
if (event.id === b.id) return 0
|
if (event.id === b.id) return 0
|
||||||
if (event.created_at === b.created_at) return -1
|
if (event.created_at === b.created_at) return -1
|
||||||
@@ -26,7 +26,7 @@ export function insertEventIntoDescendingList(sortedArray: Event[], event: Event
|
|||||||
return sortedArray
|
return sortedArray
|
||||||
}
|
}
|
||||||
|
|
||||||
export function insertEventIntoAscendingList(sortedArray: Event[], event: Event) {
|
export function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {
|
||||||
const [idx, found] = binarySearch(sortedArray, b => {
|
const [idx, found] = binarySearch(sortedArray, b => {
|
||||||
if (event.id === b.id) return 0
|
if (event.id === b.id) return 0
|
||||||
if (event.created_at === b.created_at) return -1
|
if (event.created_at === b.created_at) return -1
|
||||||
|
|||||||
4
wasm.ts
4
wasm.ts
@@ -1,6 +1,6 @@
|
|||||||
import { bytesToHex } from '@noble/hashes/utils'
|
import { bytesToHex } from '@noble/hashes/utils'
|
||||||
import { Nostr as NostrWasm } from 'nostr-wasm'
|
import { Nostr as NostrWasm } from 'nostr-wasm'
|
||||||
import { EventTemplate, Event, Nostr, VerifiedEvent, verifiedSymbol } from './core'
|
import { EventTemplate, Event, Nostr, VerifiedEvent, verifiedSymbol } from './core.ts'
|
||||||
|
|
||||||
let nw: NostrWasm
|
let nw: NostrWasm
|
||||||
|
|
||||||
@@ -30,7 +30,7 @@ class Wasm implements Nostr {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const i = new Wasm()
|
const i: Wasm = new Wasm()
|
||||||
export const generateSecretKey = i.generateSecretKey
|
export const generateSecretKey = i.generateSecretKey
|
||||||
export const getPublicKey = i.getPublicKey
|
export const getPublicKey = i.getPublicKey
|
||||||
export const finalizeEvent = i.finalizeEvent
|
export const finalizeEvent = i.finalizeEvent
|
||||||
|
|||||||
Reference in New Issue
Block a user