Compare commits

...

8 Commits

Author SHA1 Message Date
fiatjaf
cb29d62033 add links to jsr.io 2024-10-31 16:33:24 -03:00
Asai Toshiya
0d237405d9 fix lint error. 2024-10-31 20:43:03 +09:00
Asai Toshiya
659ad36b62 nip05: use stub to test queryProfile(). 2024-10-31 07:51:53 -03:00
Asai Toshiya
d062ab8afd make publish() timeout. 2024-10-30 11:55:04 -03:00
Fishcake
94f841f347 Fix fetch to work in the edge and node environments, cleanup type issues
- Fix "TypeError: Invalid redirect value, must be one of "follow" or "manual" ("error" won't be implemented since it does not make sense at the edge; use "manual" and check the response status code)." that is thrown when trying to use fetch in the edge environment  (e.g., workers)
- Cleanup types and variable definitions.
2024-10-28 14:56:10 -03:00
fiatjaf
c1d03cf00b nip46: only encrypt with nip44 (breaking). 2024-10-27 14:59:27 -03:00
fiatjaf
29ecdfc5ec fix slow types so we can publish to jsr.io 2024-10-26 14:23:28 -03:00
fiatjaf
d3fc4734b4 export missing modules. 2024-10-26 13:10:26 -03:00
11 changed files with 132 additions and 51 deletions

View File

@@ -1,4 +1,4 @@
# ![](https://img.shields.io/github/actions/workflow/status/nbd-wtf/nostr-tools/test.yml) nostr-tools
# ![](https://img.shields.io/github/actions/workflow/status/nbd-wtf/nostr-tools/test.yml) [![JSR](https://jsr.io/badges/@nostr/tools)](https://jsr.io/@nostr/tools) nostr-tools
Tools for developing [Nostr](https://github.com/fiatjaf/nostr) clients.
@@ -9,11 +9,19 @@ This package is only providing lower-level functionality. If you want more highe
## Installation
```bash
npm install nostr-tools # or yarn add nostr-tools
# npm
npm install --save nostr-tools
# jsr
npx jsr add @nostr/tools
```
If using TypeScript, this package requires TypeScript >= 5.0.
## Documentation
https://jsr.io/@nostr/tools/doc
## Usage
### Generating a private key and a public key

View File

@@ -23,7 +23,7 @@ export type SubscribeManyParams = Omit<SubscriptionParams, 'onclose' | 'id'> & {
}
export class AbstractSimplePool {
protected relays = new Map<string, AbstractRelay>()
protected relays: Map<string, AbstractRelay> = new Map()
public seenOn: Map<string, Set<AbstractRelay>> = new Map()
public trackRelays: boolean = false

View File

@@ -24,6 +24,7 @@ export class AbstractRelay {
public baseEoseTimeout: number = 4400
public connectionTimeout: number = 4400
public publishTimeout: number = 4400
public openSubs: Map<string, Subscription> = new Map()
private connectionTimeoutHandle: ReturnType<typeof setTimeout> | undefined
@@ -198,9 +199,11 @@ export class AbstractRelay {
const ok: boolean = data[2]
const reason: string = data[3]
const ep = this.openEventPublishes.get(id) as EventPublishResolver
if (ok) ep.resolve(reason)
else ep.reject(new Error(reason))
this.openEventPublishes.delete(id)
if (ep) {
if (ok) ep.resolve(reason)
else ep.reject(new Error(reason))
this.openEventPublishes.delete(id)
}
return
}
case 'CLOSED': {
@@ -248,6 +251,13 @@ export class AbstractRelay {
this.openEventPublishes.set(event.id, { resolve, reject })
})
this.send('["EVENT",' + JSON.stringify(event) + ']')
setTimeout(() => {
const ep = this.openEventPublishes.get(event.id) as EventPublishResolver
if (ep) {
ep.reject(new Error('publish timed out'))
this.openEventPublishes.delete(event.id)
}
}, this.publishTimeout)
return ret
}

View File

@@ -1,6 +1,6 @@
{
"name": "@nostr/tools",
"version": "2.3.2",
"version": "2.10.0",
"exports": {
".": "./index.ts",
"./core": "./core.ts",
@@ -20,6 +20,7 @@
"./nip10": "./nip10.ts",
"./nip11": "./nip11.ts",
"./nip13": "./nip13.ts",
"./nip17": "./nip17.ts",
"./nip18": "./nip18.ts",
"./nip19": "./nip19.ts",
"./nip21": "./nip21.ts",
@@ -34,6 +35,8 @@
"./nip46": "./nip46.ts",
"./nip49": "./nip49.ts",
"./nip57": "./nip57.ts",
"./nip58": "./nip58.ts",
"./nip59": "./nip59.ts",
"./nip75": "./nip75.ts",
"./nip94": "./nip94.ts",
"./nip96": "./nip96.ts",
@@ -42,4 +45,4 @@
"./fakejson": "./fakejson.ts",
"./utils": "./utils.ts"
}
}
}

View File

@@ -1,5 +1,4 @@
import { test, expect } from 'bun:test'
import fetch from 'node-fetch'
import { useFetchImplementation, queryProfile, NIP05_REGEX, isNip05 } from './nip05.ts'
@@ -16,7 +15,27 @@ test('validate NIP05_REGEX', () => {
})
test('fetch nip05 profiles', async () => {
useFetchImplementation(fetch)
const fetchStub = async (url: string) => ({
status: 200,
async json() {
return {
'https://compile-error.net/.well-known/nostr.json?name=_': {
names: { _: '2c7cc62a697ea3a7826521f3fd34f0cb273693cbe5e9310f35449f43622a5cdc' },
},
'https://fiatjaf.com/.well-known/nostr.json?name=_': {
names: { _: '3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d' },
relays: {
'3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d': [
'wss://pyramid.fiatjaf.com',
'wss://nos.lol',
],
},
},
}[url]
},
})
useFetchImplementation(fetchStub)
let p2 = await queryProfile('compile-error.net')
expect(p2!.pubkey).toEqual('2c7cc62a697ea3a7826521f3fd34f0cb273693cbe5e9310f35449f43622a5cdc')

View File

@@ -12,20 +12,26 @@ export type Nip05 = `${string}@${string}`
export const NIP05_REGEX = /^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/
export const isNip05 = (value?: string | null): value is Nip05 => NIP05_REGEX.test(value || '')
var _fetch: any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let _fetch: any
try {
_fetch = fetch
} catch {}
} catch (_) {
null
}
export function useFetchImplementation(fetchImplementation: any) {
export function useFetchImplementation(fetchImplementation: unknown) {
_fetch = fetchImplementation
}
export async function searchDomain(domain: string, query = ''): Promise<{ [name: string]: string }> {
try {
const url = `https://${domain}/.well-known/nostr.json?name=${query}`
const res = await _fetch(url, { redirect: 'error' })
const res = await _fetch(url, { redirect: 'manual' })
if (res.status !== 200) {
throw Error('Wrong response code')
}
const json = await res.json()
return json.names
} catch (_) {
@@ -37,20 +43,24 @@ export async function queryProfile(fullname: string): Promise<ProfilePointer | n
const match = fullname.match(NIP05_REGEX)
if (!match) return null
const [_, name = '_', domain] = match
const [, name = '_', domain] = match
try {
const url = `https://${domain}/.well-known/nostr.json?name=${name}`
const res = await (await _fetch(url, { redirect: 'error' })).json()
const res = await _fetch(url, { redirect: 'manual' })
if (res.status !== 200) {
throw Error('Wrong response code')
}
const json = await res.json()
let pubkey = res.names[name]
return pubkey ? { pubkey, relays: res.relays?.[pubkey] } : null
const pubkey = json.names[name]
return pubkey ? { pubkey, relays: json.relays?.[pubkey] } : null
} catch (_e) {
return null
}
}
export async function isValid(pubkey: string, nip05: Nip05): Promise<boolean> {
let res = await queryProfile(nip05)
const res = await queryProfile(nip05)
return res ? res.pubkey === pubkey : false
}

View File

@@ -1,5 +1,5 @@
import { PrivateDirectMessage } from './kinds.ts'
import { EventTemplate, getPublicKey } from './pure.ts'
import { EventTemplate, NostrEvent, getPublicKey } from './pure.ts'
import * as nip59 from './nip59.ts'
type Recipient = {
@@ -48,7 +48,7 @@ export function wrapEvent(
message: string,
conversationTitle?: string,
replyTo?: ReplyTo,
) {
): NostrEvent {
const event = createEvent(recipient, message, conversationTitle, replyTo)
return nip59.wrapEvent(event, senderPrivateKey, recipient.publicKey)
}
@@ -59,22 +59,17 @@ export function wrapManyEvents(
message: string,
conversationTitle?: string,
replyTo?: ReplyTo,
) {
): NostrEvent[] {
if (!recipients || recipients.length === 0) {
throw new Error('At least one recipient is required.')
}
const senderPublicKey = getPublicKey(senderPrivateKey)
// Initialize the wrappeds array with the sender's own wrapped event
const wrappeds = [wrapEvent(senderPrivateKey, { publicKey: senderPublicKey }, message, conversationTitle, replyTo)]
// Wrap the event for each recipient
recipients.forEach(recipient => {
wrappeds.push(wrapEvent(senderPrivateKey, recipient, message, conversationTitle, replyTo))
})
return wrappeds
// wrap the event for the sender and then for each recipient
return [{ publicKey: senderPublicKey }, ...recipients].map(recipient =>
wrapEvent(senderPrivateKey, recipient, message, conversationTitle, replyTo),
)
}
export const unwrapEvent = nip59.unwrapEvent

View File

@@ -1,8 +1,8 @@
import { NostrEvent, UnsignedEvent, VerifiedEvent } from './core.ts'
import { generateSecretKey, finalizeEvent, getPublicKey, verifyEvent } from './pure.ts'
import { AbstractSimplePool, SubCloser } from './abstract-pool.ts'
import { decrypt, encrypt } from './nip04.ts'
import { getConversationKey, decrypt as nip44decrypt } from './nip44.ts'
import { decrypt as legacyDecrypt } from './nip04.ts'
import { getConversationKey, decrypt, encrypt } from './nip44.ts'
import { NIP05_REGEX } from './nip05.ts'
import { SimplePool } from './pool.ts'
import { Handlerinformation, NostrConnect } from './kinds.ts'
@@ -86,6 +86,7 @@ export class BunkerSigner {
}
private waitingForAuth: { [id: string]: boolean }
private secretKey: Uint8Array
private conversationKey: Uint8Array
public bp: BunkerPointer
private cachedPubKey: string | undefined
@@ -103,6 +104,7 @@ export class BunkerSigner {
this.pool = params.pool || new SimplePool()
this.secretKey = clientSecretKey
this.conversationKey = getConversationKey(clientSecretKey, bp.pubkey)
this.bp = bp
this.isOpen = false
this.idPrefix = Math.random().toString(36).substring(7)
@@ -112,18 +114,18 @@ export class BunkerSigner {
const listeners = this.listeners
const waitingForAuth = this.waitingForAuth
const skBytes = this.secretKey
const convKey = this.conversationKey
this.subCloser = this.pool.subscribeMany(
this.bp.relays,
[{ kinds: [NostrConnect], '#p': [getPublicKey(this.secretKey)] }],
[{ kinds: [NostrConnect], authors: [bp.pubkey], '#p': [getPublicKey(this.secretKey)] }],
{
async onevent(event: NostrEvent) {
let o
try {
o = JSON.parse(await decrypt(clientSecretKey, event.pubkey, event.content))
o = JSON.parse(decrypt(event.content, convKey))
} catch (err) {
o = JSON.parse(nip44decrypt(event.content, getConversationKey(skBytes, event.pubkey)))
o = JSON.parse(await legacyDecrypt(event.content, event.pubkey, event.content))
}
const { id, result, error } = o
@@ -166,7 +168,7 @@ export class BunkerSigner {
this.serial++
const id = `${this.idPrefix}-${this.serial}`
const encryptedContent = await encrypt(this.secretKey, this.bp.pubkey, JSON.stringify({ id, method, params }))
const encryptedContent = encrypt(JSON.stringify({ id, method, params }), this.conversationKey)
// the request event
const verifiedEvent: VerifiedEvent = finalizeEvent(

View File

@@ -1,4 +1,4 @@
import { EventTemplate, UnsignedEvent, Event } from './core.ts'
import { EventTemplate, UnsignedEvent, NostrEvent } from './core.ts'
import { getConversationKey, decrypt, encrypt } from './nip44.ts'
import { getEventHash, generateSecretKey, finalizeEvent, getPublicKey } from './pure.ts'
import { Seal, GiftWrap } from './kinds.ts'
@@ -15,10 +15,10 @@ const nip44ConversationKey = (privateKey: Uint8Array, publicKey: string) => getC
const nip44Encrypt = (data: EventTemplate, privateKey: Uint8Array, publicKey: string) =>
encrypt(JSON.stringify(data), nip44ConversationKey(privateKey, publicKey))
const nip44Decrypt = (data: Event, privateKey: Uint8Array) =>
const nip44Decrypt = (data: NostrEvent, privateKey: Uint8Array) =>
JSON.parse(decrypt(data.content, nip44ConversationKey(privateKey, data.pubkey)))
export function createRumor(event: Partial<UnsignedEvent>, privateKey: Uint8Array) {
export function createRumor(event: Partial<UnsignedEvent>, privateKey: Uint8Array): Rumor {
const rumor = {
created_at: now(),
content: '',
@@ -32,7 +32,7 @@ export function createRumor(event: Partial<UnsignedEvent>, privateKey: Uint8Arra
return rumor as Rumor
}
export function createSeal(rumor: Rumor, privateKey: Uint8Array, recipientPublicKey: string) {
export function createSeal(rumor: Rumor, privateKey: Uint8Array, recipientPublicKey: string): NostrEvent {
return finalizeEvent(
{
kind: Seal,
@@ -41,10 +41,10 @@ export function createSeal(rumor: Rumor, privateKey: Uint8Array, recipientPublic
tags: [],
},
privateKey,
) as Event
)
}
export function createWrap(seal: Event, recipientPublicKey: string) {
export function createWrap(seal: NostrEvent, recipientPublicKey: string): NostrEvent {
const randomKey = generateSecretKey()
return finalizeEvent(
@@ -55,10 +55,14 @@ export function createWrap(seal: Event, recipientPublicKey: string) {
tags: [['p', recipientPublicKey]],
},
randomKey,
) as Event
) as NostrEvent
}
export function wrapEvent(event: Partial<UnsignedEvent>, senderPrivateKey: Uint8Array, recipientPublicKey: string) {
export function wrapEvent(
event: Partial<UnsignedEvent>,
senderPrivateKey: Uint8Array,
recipientPublicKey: string,
): NostrEvent {
const rumor = createRumor(event, senderPrivateKey)
const seal = createSeal(rumor, senderPrivateKey, recipientPublicKey)
@@ -69,7 +73,7 @@ export function wrapManyEvents(
event: Partial<UnsignedEvent>,
senderPrivateKey: Uint8Array,
recipientsPublicKeys: string[],
) {
): NostrEvent[] {
if (!recipientsPublicKeys || recipientsPublicKeys.length === 0) {
throw new Error('At least one recipient is required.')
}
@@ -85,12 +89,12 @@ export function wrapManyEvents(
return wrappeds
}
export function unwrapEvent(wrap: Event, recipientPrivateKey: Uint8Array): Rumor {
export function unwrapEvent(wrap: NostrEvent, recipientPrivateKey: Uint8Array): Rumor {
const unwrappedSeal = nip44Decrypt(wrap, recipientPrivateKey)
return nip44Decrypt(unwrappedSeal, recipientPrivateKey)
}
export function unwrapManyEvents(wrappedEvents: Event[], recipientPrivateKey: Uint8Array): Rumor[] {
export function unwrapManyEvents(wrappedEvents: NostrEvent[], recipientPrivateKey: Uint8Array): Rumor[] {
let unwrappedEvents: Rumor[] = []
wrappedEvents.forEach(e => {

View File

@@ -1,7 +1,7 @@
{
"type": "module",
"name": "nostr-tools",
"version": "2.9.3",
"version": "2.10.0",
"description": "Tools for making a Nostr client.",
"repository": {
"type": "git",
@@ -103,6 +103,11 @@
"require": "./lib/cjs/nip13.js",
"types": "./lib/types/nip13.d.ts"
},
"./nip17": {
"import": "./lib/esm/nip17.js",
"require": "./lib/cjs/nip17.js",
"types": "./lib/types/nip17.d.ts"
},
"./nip18": {
"import": "./lib/esm/nip18.js",
"require": "./lib/cjs/nip18.js",

View File

@@ -1,5 +1,5 @@
import { expect, test } from 'bun:test'
import { Server } from 'mock-socket'
import { finalizeEvent, generateSecretKey, getPublicKey } from './pure.ts'
import { Relay, useWebSocketImplementation } from './relay.ts'
import { MockRelay, MockWebSocketClient } from './test-helpers.ts'
@@ -92,3 +92,28 @@ test('listening and publishing and closing', async done => {
),
)
})
test('publish timeout', async () => {
const url = 'wss://relay.example.com'
new Server(url)
const relay = new Relay(url)
relay.publishTimeout = 100
await relay.connect()
setTimeout(() => relay.close(), 20000) // close the relay to fail the test on timeout
expect(
relay.publish(
finalizeEvent(
{
kind: 1,
created_at: Math.floor(Date.now() / 1000),
tags: [],
content: 'hello',
},
generateSecretKey(),
),
),
).rejects.toThrow('publish timed out')
})