mirror of
https://github.com/nbd-wtf/nostr-tools.git
synced 2025-12-08 16:28:49 +00:00
Compare commits
60 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5a55c670fb | ||
|
|
bf0c4d4988 | ||
|
|
50fe7c2a8b | ||
|
|
29270c8c9d | ||
|
|
cb29d62033 | ||
|
|
0d237405d9 | ||
|
|
659ad36b62 | ||
|
|
d062ab8afd | ||
|
|
94f841f347 | ||
|
|
c1d03cf00b | ||
|
|
29ecdfc5ec | ||
|
|
d3fc4734b4 | ||
|
|
66d0b8a4e1 | ||
|
|
e2ec7a4b55 | ||
|
|
a72e47135a | ||
|
|
de7bbfc6a2 | ||
|
|
f2d421fa4f | ||
|
|
cae06fc4fe | ||
|
|
5c538efa38 | ||
|
|
013daae91b | ||
|
|
75660e7ff1 | ||
|
|
4c2d2b5ce6 | ||
|
|
aba266b8e6 | ||
|
|
d7dcc75ebe | ||
|
|
b18510b460 | ||
|
|
b04e0d16c0 | ||
|
|
633696bf46 | ||
|
|
bf975c9a87 | ||
|
|
7aa4f09769 | ||
|
|
f646fcd889 | ||
|
|
1d89038375 | ||
|
|
0b5b35714c | ||
|
|
e398617fdc | ||
|
|
1b236faa7b | ||
|
|
7064e0b828 | ||
|
|
4f6976f6f8 | ||
|
|
a61cde77ea | ||
|
|
23d95acb26 | ||
|
|
13ac04b8f8 | ||
|
|
45b25c5bf5 | ||
|
|
ee76d69b4b | ||
|
|
21433049b8 | ||
|
|
e8ff68f0b3 | ||
|
|
1b77d6e080 | ||
|
|
76d3a91600 | ||
|
|
6f334f31a7 | ||
|
|
9c009ac543 | ||
|
|
a87099fa5c | ||
|
|
475a22a95f | ||
|
|
54e352d8e2 | ||
|
|
235a1c50cb | ||
|
|
dfc2107569 | ||
|
|
986b9d0cce | ||
|
|
753ff323ea | ||
|
|
f8c3e20f3d | ||
|
|
87a91c2daf | ||
|
|
4f1dc9ef1c | ||
|
|
faa1a9d556 | ||
|
|
97d838f254 | ||
|
|
260400b24d |
@@ -1,6 +1,6 @@
|
|||||||
FROM node:20
|
FROM node:20
|
||||||
|
|
||||||
RUN npm install typescript -g
|
RUN npm install typescript eslint prettier -g
|
||||||
|
|
||||||
# Install bun
|
# Install bun
|
||||||
RUN curl -fsSL https://bun.sh/install | bash
|
RUN curl -fsSL https://bun.sh/install | bash
|
||||||
|
|||||||
@@ -116,7 +116,8 @@
|
|||||||
"no-unexpected-multiline": 2,
|
"no-unexpected-multiline": 2,
|
||||||
"no-unneeded-ternary": [2, { "defaultAssignment": false }],
|
"no-unneeded-ternary": [2, { "defaultAssignment": false }],
|
||||||
"no-unreachable": 2,
|
"no-unreachable": 2,
|
||||||
"no-unused-vars": [2, { "vars": "local", "args": "none", "varsIgnorePattern": "^_" }],
|
"no-unused-vars": "off",
|
||||||
|
"@typescript-eslint/no-unused-vars": [2, { "vars": "local", "args": "none", "varsIgnorePattern": "^_" }],
|
||||||
"no-useless-call": 2,
|
"no-useless-call": 2,
|
||||||
"no-useless-constructor": 2,
|
"no-useless-constructor": 2,
|
||||||
"no-with": 2,
|
"no-with": 2,
|
||||||
|
|||||||
49
README.md
49
README.md
@@ -1,19 +1,27 @@
|
|||||||
#  nostr-tools
|
#  [](https://jsr.io/@nostr/tools) nostr-tools
|
||||||
|
|
||||||
Tools for developing [Nostr](https://github.com/fiatjaf/nostr) clients.
|
Tools for developing [Nostr](https://github.com/fiatjaf/nostr) clients.
|
||||||
|
|
||||||
Only depends on _@scure_ and _@noble_ packages.
|
Only depends on _@scure_ and _@noble_ packages.
|
||||||
|
|
||||||
This package is only providing lower-level functionality. If you want an easy-to-use fully-fledged solution that abstracts the hard parts of Nostr and makes decisions on your behalf, take a look at [NDK](https://github.com/nostr-dev-kit/ndk) and [@snort/system](https://www.npmjs.com/package/@snort/system).
|
This package is only providing lower-level functionality. If you want more higher-level features, take a look at [Nostrify](https://nostrify.dev), or if you want an easy-to-use fully-fledged solution that abstracts the hard parts of Nostr and makes decisions on your behalf, take a look at [NDK](https://github.com/nostr-dev-kit/ndk) and [@snort/system](https://www.npmjs.com/package/@snort/system).
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
```bash
|
```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.
|
If using TypeScript, this package requires TypeScript >= 5.0.
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
https://jsr.io/@nostr/tools/doc
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
### Generating a private key and a public key
|
### Generating a private key and a public key
|
||||||
@@ -76,7 +84,7 @@ const sub = relay.subscribe([
|
|||||||
let sk = generateSecretKey()
|
let sk = generateSecretKey()
|
||||||
let pk = getPublicKey(sk)
|
let pk = getPublicKey(sk)
|
||||||
|
|
||||||
relay.sub([
|
relay.subscribe([
|
||||||
{
|
{
|
||||||
kinds: [1],
|
kinds: [1],
|
||||||
authors: [pk],
|
authors: [pk],
|
||||||
@@ -104,8 +112,11 @@ relay.close()
|
|||||||
To use this on Node.js you first must install `ws` and call something like this:
|
To use this on Node.js you first must install `ws` and call something like this:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
import { useWebSocketImplementation } from 'nostr-tools/relay'
|
import { useWebSocketImplementation } from 'nostr-tools/pool'
|
||||||
useWebSocketImplementation(require('ws'))
|
// 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
|
||||||
@@ -194,6 +205,32 @@ declare global {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### 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
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -14,15 +23,18 @@ export type SubscribeManyParams = Omit<SubscriptionParams, 'onclose' | 'id'> & {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class AbstractSimplePool {
|
export class AbstractSimplePool {
|
||||||
private relays = new Map<string, AbstractRelay>()
|
protected relays: Map<string, AbstractRelay> = new Map()
|
||||||
public seenOn: Map<string, Set<AbstractRelay>> = new Map()
|
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: Set<string> = new Set()
|
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)
|
||||||
@@ -192,7 +205,29 @@ export class AbstractSimplePool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let r = await this.ensureRelay(url)
|
let r = await this.ensureRelay(url)
|
||||||
return r.publish(event)
|
return r.publish(event).then(reason => {
|
||||||
|
if (this.trackRelays) {
|
||||||
|
let set = this.seenOn.get(event.id)
|
||||||
|
if (!set) {
|
||||||
|
set = new Set()
|
||||||
|
this.seenOn.set(event.id, set)
|
||||||
|
}
|
||||||
|
set.add(r)
|
||||||
|
}
|
||||||
|
return reason
|
||||||
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
listConnectionStatus(): Map<string, boolean> {
|
||||||
|
const map = new Map<string, boolean>()
|
||||||
|
this.relays.forEach((relay, url) => map.set(url, relay.connected))
|
||||||
|
|
||||||
|
return map
|
||||||
|
}
|
||||||
|
|
||||||
|
destroy(): void {
|
||||||
|
this.relays.forEach(conn => conn.close())
|
||||||
|
this.relays = new Map()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,14 +7,9 @@ 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'
|
||||||
|
|
||||||
var _WebSocket: typeof WebSocket
|
export type AbstractRelayConstructorOptions = {
|
||||||
|
verifyEvent: Nostr['verifyEvent']
|
||||||
try {
|
websocketImplementation?: typeof WebSocket
|
||||||
_WebSocket = WebSocket
|
|
||||||
} catch {}
|
|
||||||
|
|
||||||
export function useWebSocketImplementation(websocketImplementation: any) {
|
|
||||||
_WebSocket = websocketImplementation
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export class AbstractRelay {
|
export class AbstractRelay {
|
||||||
@@ -29,6 +24,7 @@ export class AbstractRelay {
|
|||||||
|
|
||||||
public baseEoseTimeout: number = 4400
|
public baseEoseTimeout: number = 4400
|
||||||
public connectionTimeout: number = 4400
|
public connectionTimeout: number = 4400
|
||||||
|
public publishTimeout: number = 4400
|
||||||
public openSubs: Map<string, Subscription> = new Map()
|
public openSubs: Map<string, Subscription> = new Map()
|
||||||
private connectionTimeoutHandle: ReturnType<typeof setTimeout> | undefined
|
private connectionTimeoutHandle: ReturnType<typeof setTimeout> | undefined
|
||||||
|
|
||||||
@@ -42,12 +38,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'] }): Promise<AbstractRelay> {
|
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
|
||||||
@@ -87,7 +86,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
|
||||||
@@ -100,7 +99,7 @@ export class AbstractRelay {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.ws.onerror = ev => {
|
this.ws.onerror = ev => {
|
||||||
reject((ev as any).message)
|
reject((ev as any).message || 'websocket error')
|
||||||
if (this._connected) {
|
if (this._connected) {
|
||||||
this._connected = false
|
this._connected = false
|
||||||
this.connectionPromise = undefined
|
this.connectionPromise = undefined
|
||||||
@@ -200,9 +199,11 @@ export class AbstractRelay {
|
|||||||
const ok: boolean = data[2]
|
const ok: boolean = data[2]
|
||||||
const reason: string = data[3]
|
const reason: string = data[3]
|
||||||
const ep = this.openEventPublishes.get(id) as EventPublishResolver
|
const ep = this.openEventPublishes.get(id) as EventPublishResolver
|
||||||
if (ok) ep.resolve(reason)
|
if (ep) {
|
||||||
else ep.reject(new Error(reason))
|
if (ok) ep.resolve(reason)
|
||||||
this.openEventPublishes.delete(id)
|
else ep.reject(new Error(reason))
|
||||||
|
this.openEventPublishes.delete(id)
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
case 'CLOSED': {
|
case 'CLOSED': {
|
||||||
@@ -250,6 +251,13 @@ export class AbstractRelay {
|
|||||||
this.openEventPublishes.set(event.id, { resolve, reject })
|
this.openEventPublishes.set(event.id, { resolve, reject })
|
||||||
})
|
})
|
||||||
this.send('["EVENT",' + JSON.stringify(event) + ']')
|
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
|
return ret
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -263,7 +271,7 @@ export class AbstractRelay {
|
|||||||
return ret
|
return ret
|
||||||
}
|
}
|
||||||
|
|
||||||
public subscribe(filters: Filter[], params: Partial<SubscriptionParams>): Subscription {
|
public subscribe(filters: Filter[], params: Partial<SubscriptionParams> & { id?: string }): Subscription {
|
||||||
const subscription = this.prepareSubscription(filters, params)
|
const subscription = this.prepareSubscription(filters, params)
|
||||||
subscription.fire()
|
subscription.fire()
|
||||||
return subscription
|
return subscription
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { test, expect } from 'bun:test'
|
import { test, expect } from 'bun:test'
|
||||||
|
|
||||||
import { sortEvents } from './core.ts'
|
import { sortEvents } from './core.ts'
|
||||||
|
|
||||||
test('sortEvents', () => {
|
test('sortEvents', () => {
|
||||||
|
|||||||
@@ -215,6 +215,16 @@ describe('Filter', () => {
|
|||||||
expect(getFilterLimit({ kinds: [0, 3], authors: ['alex', 'fiatjaf'] })).toEqual(4)
|
expect(getFilterLimit({ kinds: [0, 3], authors: ['alex', 'fiatjaf'] })).toEqual(4)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('should handle parameterized replaceable events', () => {
|
||||||
|
expect(getFilterLimit({ kinds: [30078], authors: ['alex'] })).toEqual(Infinity)
|
||||||
|
expect(getFilterLimit({ kinds: [30078], authors: ['alex'], '#d': ['ditto'] })).toEqual(1)
|
||||||
|
expect(getFilterLimit({ kinds: [30078], authors: ['alex'], '#d': ['ditto', 'soapbox'] })).toEqual(2)
|
||||||
|
expect(getFilterLimit({ kinds: [30078], authors: ['alex', 'fiatjaf'], '#d': ['ditto', 'soapbox'] })).toEqual(4)
|
||||||
|
expect(
|
||||||
|
getFilterLimit({ kinds: [30000, 30078], authors: ['alex', 'fiatjaf'], '#d': ['ditto', 'soapbox'] }),
|
||||||
|
).toEqual(8)
|
||||||
|
})
|
||||||
|
|
||||||
test('should return Infinity for authors with regular kinds', () => {
|
test('should return Infinity for authors with regular kinds', () => {
|
||||||
expect(getFilterLimit({ kinds: [1], authors: ['alex'] })).toEqual(Infinity)
|
expect(getFilterLimit({ kinds: [1], authors: ['alex'] })).toEqual(Infinity)
|
||||||
})
|
})
|
||||||
@@ -222,5 +232,9 @@ describe('Filter', () => {
|
|||||||
test('should return Infinity for empty filters', () => {
|
test('should return Infinity for empty filters', () => {
|
||||||
expect(getFilterLimit({})).toEqual(Infinity)
|
expect(getFilterLimit({})).toEqual(Infinity)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('empty tags return 0', () => {
|
||||||
|
expect(getFilterLimit({ '#p': [] })).toEqual(0)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
21
filter.ts
21
filter.ts
@@ -1,5 +1,5 @@
|
|||||||
import { Event } from './core.ts'
|
import { Event } from './core.ts'
|
||||||
import { isReplaceableKind } from './kinds.ts'
|
import { isParameterizedReplaceableKind, isReplaceableKind } from './kinds.ts'
|
||||||
|
|
||||||
export type Filter = {
|
export type Filter = {
|
||||||
ids?: string[]
|
ids?: string[]
|
||||||
@@ -72,17 +72,34 @@ export function mergeFilters(...filters: Filter[]): Filter {
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Calculate the intrinsic limit of a filter. This function may return `Infinity`. */
|
/**
|
||||||
|
* Calculate the intrinsic limit of a filter.
|
||||||
|
* This function returns a positive integer, or `Infinity` if there is no intrinsic limit.
|
||||||
|
*/
|
||||||
export function getFilterLimit(filter: Filter): number {
|
export function getFilterLimit(filter: Filter): number {
|
||||||
if (filter.ids && !filter.ids.length) return 0
|
if (filter.ids && !filter.ids.length) return 0
|
||||||
if (filter.kinds && !filter.kinds.length) return 0
|
if (filter.kinds && !filter.kinds.length) return 0
|
||||||
if (filter.authors && !filter.authors.length) return 0
|
if (filter.authors && !filter.authors.length) return 0
|
||||||
|
|
||||||
|
for (const [key, value] of Object.entries(filter)) {
|
||||||
|
if (key[0] === '#' && Array.isArray(value) && !value.length) return 0
|
||||||
|
}
|
||||||
|
|
||||||
return Math.min(
|
return Math.min(
|
||||||
|
// The `limit` property creates an artificial limit.
|
||||||
Math.max(0, filter.limit ?? Infinity),
|
Math.max(0, filter.limit ?? Infinity),
|
||||||
|
|
||||||
|
// There can only be one event per `id`.
|
||||||
filter.ids?.length ?? Infinity,
|
filter.ids?.length ?? Infinity,
|
||||||
|
|
||||||
|
// Replaceable events are limited by the number of authors and kinds.
|
||||||
filter.authors?.length && filter.kinds?.every(kind => isReplaceableKind(kind))
|
filter.authors?.length && filter.kinds?.every(kind => isReplaceableKind(kind))
|
||||||
? filter.authors.length * filter.kinds.length
|
? filter.authors.length * filter.kinds.length
|
||||||
: Infinity,
|
: Infinity,
|
||||||
|
|
||||||
|
// Parameterized replaceable events are limited by the number of authors, kinds, and "d" tags.
|
||||||
|
filter.authors?.length && filter.kinds?.every(kind => isParameterizedReplaceableKind(kind)) && filter['#d']?.length
|
||||||
|
? filter.authors.length * filter.kinds.length * filter['#d'].length
|
||||||
|
: Infinity,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
5
index.ts
5
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'
|
||||||
@@ -21,6 +21,7 @@ export * as nip42 from './nip42.ts'
|
|||||||
export * as nip44 from './nip44.ts'
|
export * as nip44 from './nip44.ts'
|
||||||
export * as nip47 from './nip47.ts'
|
export * as nip47 from './nip47.ts'
|
||||||
export * as nip57 from './nip57.ts'
|
export * as nip57 from './nip57.ts'
|
||||||
|
export * as nip59 from './nip59.ts'
|
||||||
export * as nip98 from './nip98.ts'
|
export * as nip98 from './nip98.ts'
|
||||||
|
|
||||||
export * as kinds from './kinds.ts'
|
export * as kinds from './kinds.ts'
|
||||||
|
|||||||
7
jsr.json
7
jsr.json
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@nostr/tools",
|
"name": "@nostr/tools",
|
||||||
"version": "2.3.2",
|
"version": "2.10.3",
|
||||||
"exports": {
|
"exports": {
|
||||||
".": "./index.ts",
|
".": "./index.ts",
|
||||||
"./core": "./core.ts",
|
"./core": "./core.ts",
|
||||||
@@ -20,6 +20,7 @@
|
|||||||
"./nip10": "./nip10.ts",
|
"./nip10": "./nip10.ts",
|
||||||
"./nip11": "./nip11.ts",
|
"./nip11": "./nip11.ts",
|
||||||
"./nip13": "./nip13.ts",
|
"./nip13": "./nip13.ts",
|
||||||
|
"./nip17": "./nip17.ts",
|
||||||
"./nip18": "./nip18.ts",
|
"./nip18": "./nip18.ts",
|
||||||
"./nip19": "./nip19.ts",
|
"./nip19": "./nip19.ts",
|
||||||
"./nip21": "./nip21.ts",
|
"./nip21": "./nip21.ts",
|
||||||
@@ -34,6 +35,8 @@
|
|||||||
"./nip46": "./nip46.ts",
|
"./nip46": "./nip46.ts",
|
||||||
"./nip49": "./nip49.ts",
|
"./nip49": "./nip49.ts",
|
||||||
"./nip57": "./nip57.ts",
|
"./nip57": "./nip57.ts",
|
||||||
|
"./nip58": "./nip58.ts",
|
||||||
|
"./nip59": "./nip59.ts",
|
||||||
"./nip75": "./nip75.ts",
|
"./nip75": "./nip75.ts",
|
||||||
"./nip94": "./nip94.ts",
|
"./nip94": "./nip94.ts",
|
||||||
"./nip96": "./nip96.ts",
|
"./nip96": "./nip96.ts",
|
||||||
@@ -42,4 +45,4 @@
|
|||||||
"./fakejson": "./fakejson.ts",
|
"./fakejson": "./fakejson.ts",
|
||||||
"./utils": "./utils.ts"
|
"./utils": "./utils.ts"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
3
justfile
3
justfile
@@ -13,6 +13,9 @@ test-only file:
|
|||||||
|
|
||||||
publish: build
|
publish: build
|
||||||
npm publish
|
npm publish
|
||||||
|
perl -i -0pe "s/},\n \"optionalDependencies\": {\n/,/" package.json
|
||||||
|
jsr publish --allow-dirty
|
||||||
|
git checkout -- package.json
|
||||||
|
|
||||||
format:
|
format:
|
||||||
eslint --ext .ts --fix *.ts
|
eslint --ext .ts --fix *.ts
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { test, expect } from 'bun:test'
|
import { expect, test } from 'bun:test'
|
||||||
import { classifyKind } from './kinds.ts'
|
import { classifyKind, isKind, Repost, ShortTextNote } from './kinds.ts'
|
||||||
|
import { finalizeEvent, generateSecretKey } from './pure.ts'
|
||||||
|
|
||||||
test('kind classification', () => {
|
test('kind classification', () => {
|
||||||
expect(classifyKind(1)).toBe('regular')
|
expect(classifyKind(1)).toBe('regular')
|
||||||
@@ -19,3 +20,22 @@ test('kind classification', () => {
|
|||||||
expect(classifyKind(40000)).toBe('unknown')
|
expect(classifyKind(40000)).toBe('unknown')
|
||||||
expect(classifyKind(255)).toBe('unknown')
|
expect(classifyKind(255)).toBe('unknown')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('kind type guard', () => {
|
||||||
|
const privateKey = generateSecretKey()
|
||||||
|
const repostedEvent = finalizeEvent(
|
||||||
|
{
|
||||||
|
kind: ShortTextNote,
|
||||||
|
tags: [
|
||||||
|
['e', 'replied event id'],
|
||||||
|
['p', 'replied event pubkey'],
|
||||||
|
],
|
||||||
|
content: 'Replied to a post',
|
||||||
|
created_at: 1617932115,
|
||||||
|
},
|
||||||
|
privateKey,
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(isKind(repostedEvent, ShortTextNote)).toBeTrue()
|
||||||
|
expect(isKind(repostedEvent, Repost)).toBeFalse()
|
||||||
|
})
|
||||||
|
|||||||
89
kinds.ts
89
kinds.ts
@@ -1,3 +1,5 @@
|
|||||||
|
import { NostrEvent, validateEvent } from './pure.ts'
|
||||||
|
|
||||||
/** 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): boolean {
|
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)
|
||||||
@@ -30,77 +32,162 @@ export function classifyKind(kind: number): KindClassification {
|
|||||||
return 'unknown'
|
return 'unknown'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function isKind<T extends number>(event: unknown, kind: T | Array<T>): event is NostrEvent & { kind: T } {
|
||||||
|
const kindAsArray: number[] = kind instanceof Array ? kind : [kind]
|
||||||
|
return (validateEvent(event) && kindAsArray.includes(event.kind)) || false
|
||||||
|
}
|
||||||
|
|
||||||
export const Metadata = 0
|
export const Metadata = 0
|
||||||
|
export type Metadata = typeof Metadata
|
||||||
export const ShortTextNote = 1
|
export const ShortTextNote = 1
|
||||||
|
export type ShortTextNote = typeof ShortTextNote
|
||||||
export const RecommendRelay = 2
|
export const RecommendRelay = 2
|
||||||
|
export type RecommendRelay = typeof RecommendRelay
|
||||||
export const Contacts = 3
|
export const Contacts = 3
|
||||||
|
export type Contacts = typeof Contacts
|
||||||
export const EncryptedDirectMessage = 4
|
export const EncryptedDirectMessage = 4
|
||||||
export const EncryptedDirectMessages = 4
|
export type EncryptedDirectMessage = typeof EncryptedDirectMessage
|
||||||
export const EventDeletion = 5
|
export const EventDeletion = 5
|
||||||
|
export type EventDeletion = typeof EventDeletion
|
||||||
export const Repost = 6
|
export const Repost = 6
|
||||||
|
export type Repost = typeof Repost
|
||||||
export const Reaction = 7
|
export const Reaction = 7
|
||||||
|
export type Reaction = typeof Reaction
|
||||||
export const BadgeAward = 8
|
export const BadgeAward = 8
|
||||||
|
export type BadgeAward = typeof BadgeAward
|
||||||
|
export const Seal = 13
|
||||||
|
export type Seal = typeof Seal
|
||||||
|
export const PrivateDirectMessage = 14
|
||||||
|
export type PrivateDirectMessage = typeof PrivateDirectMessage
|
||||||
export const GenericRepost = 16
|
export const GenericRepost = 16
|
||||||
|
export type GenericRepost = typeof GenericRepost
|
||||||
export const ChannelCreation = 40
|
export const ChannelCreation = 40
|
||||||
|
export type ChannelCreation = typeof ChannelCreation
|
||||||
export const ChannelMetadata = 41
|
export const ChannelMetadata = 41
|
||||||
|
export type ChannelMetadata = typeof ChannelMetadata
|
||||||
export const ChannelMessage = 42
|
export const ChannelMessage = 42
|
||||||
|
export type ChannelMessage = typeof ChannelMessage
|
||||||
export const ChannelHideMessage = 43
|
export const ChannelHideMessage = 43
|
||||||
|
export type ChannelHideMessage = typeof ChannelHideMessage
|
||||||
export const ChannelMuteUser = 44
|
export const ChannelMuteUser = 44
|
||||||
|
export type ChannelMuteUser = typeof ChannelMuteUser
|
||||||
export const OpenTimestamps = 1040
|
export const OpenTimestamps = 1040
|
||||||
|
export type OpenTimestamps = typeof OpenTimestamps
|
||||||
|
export const GiftWrap = 1059
|
||||||
|
export type GiftWrap = typeof GiftWrap
|
||||||
export const FileMetadata = 1063
|
export const FileMetadata = 1063
|
||||||
|
export type FileMetadata = typeof FileMetadata
|
||||||
export const LiveChatMessage = 1311
|
export const LiveChatMessage = 1311
|
||||||
|
export type LiveChatMessage = typeof LiveChatMessage
|
||||||
export const ProblemTracker = 1971
|
export const ProblemTracker = 1971
|
||||||
|
export type ProblemTracker = typeof ProblemTracker
|
||||||
export const Report = 1984
|
export const Report = 1984
|
||||||
|
export type Report = typeof Report
|
||||||
export const Reporting = 1984
|
export const Reporting = 1984
|
||||||
|
export type Reporting = typeof Reporting
|
||||||
export const Label = 1985
|
export const Label = 1985
|
||||||
|
export type Label = typeof Label
|
||||||
export const CommunityPostApproval = 4550
|
export const CommunityPostApproval = 4550
|
||||||
|
export type CommunityPostApproval = typeof CommunityPostApproval
|
||||||
export const JobRequest = 5999
|
export const JobRequest = 5999
|
||||||
|
export type JobRequest = typeof JobRequest
|
||||||
export const JobResult = 6999
|
export const JobResult = 6999
|
||||||
|
export type JobResult = typeof JobResult
|
||||||
export const JobFeedback = 7000
|
export const JobFeedback = 7000
|
||||||
|
export type JobFeedback = typeof JobFeedback
|
||||||
export const ZapGoal = 9041
|
export const ZapGoal = 9041
|
||||||
|
export type ZapGoal = typeof ZapGoal
|
||||||
export const ZapRequest = 9734
|
export const ZapRequest = 9734
|
||||||
|
export type ZapRequest = typeof ZapRequest
|
||||||
export const Zap = 9735
|
export const Zap = 9735
|
||||||
|
export type Zap = typeof Zap
|
||||||
export const Highlights = 9802
|
export const Highlights = 9802
|
||||||
|
export type Highlights = typeof Highlights
|
||||||
export const Mutelist = 10000
|
export const Mutelist = 10000
|
||||||
|
export type Mutelist = typeof Mutelist
|
||||||
export const Pinlist = 10001
|
export const Pinlist = 10001
|
||||||
|
export type Pinlist = typeof Pinlist
|
||||||
export const RelayList = 10002
|
export const RelayList = 10002
|
||||||
|
export type RelayList = typeof RelayList
|
||||||
export const BookmarkList = 10003
|
export const BookmarkList = 10003
|
||||||
|
export type BookmarkList = typeof BookmarkList
|
||||||
export const CommunitiesList = 10004
|
export const CommunitiesList = 10004
|
||||||
|
export type CommunitiesList = typeof CommunitiesList
|
||||||
export const PublicChatsList = 10005
|
export const PublicChatsList = 10005
|
||||||
|
export type PublicChatsList = typeof PublicChatsList
|
||||||
export const BlockedRelaysList = 10006
|
export const BlockedRelaysList = 10006
|
||||||
|
export type BlockedRelaysList = typeof BlockedRelaysList
|
||||||
export const SearchRelaysList = 10007
|
export const SearchRelaysList = 10007
|
||||||
|
export type SearchRelaysList = typeof SearchRelaysList
|
||||||
export const InterestsList = 10015
|
export const InterestsList = 10015
|
||||||
|
export type InterestsList = typeof InterestsList
|
||||||
export const UserEmojiList = 10030
|
export const UserEmojiList = 10030
|
||||||
|
export type UserEmojiList = typeof UserEmojiList
|
||||||
|
export const DirectMessageRelaysList = 10050
|
||||||
|
export type DirectMessageRelaysList = typeof DirectMessageRelaysList
|
||||||
export const FileServerPreference = 10096
|
export const FileServerPreference = 10096
|
||||||
|
export type FileServerPreference = typeof FileServerPreference
|
||||||
export const NWCWalletInfo = 13194
|
export const NWCWalletInfo = 13194
|
||||||
|
export type NWCWalletInfo = typeof NWCWalletInfo
|
||||||
export const LightningPubRPC = 21000
|
export const LightningPubRPC = 21000
|
||||||
|
export type LightningPubRPC = typeof LightningPubRPC
|
||||||
export const ClientAuth = 22242
|
export const ClientAuth = 22242
|
||||||
|
export type ClientAuth = typeof ClientAuth
|
||||||
export const NWCWalletRequest = 23194
|
export const NWCWalletRequest = 23194
|
||||||
|
export type NWCWalletRequest = typeof NWCWalletRequest
|
||||||
export const NWCWalletResponse = 23195
|
export const NWCWalletResponse = 23195
|
||||||
|
export type NWCWalletResponse = typeof NWCWalletResponse
|
||||||
export const NostrConnect = 24133
|
export const NostrConnect = 24133
|
||||||
|
export type NostrConnect = typeof NostrConnect
|
||||||
export const HTTPAuth = 27235
|
export const HTTPAuth = 27235
|
||||||
|
export type HTTPAuth = typeof HTTPAuth
|
||||||
export const Followsets = 30000
|
export const Followsets = 30000
|
||||||
|
export type Followsets = typeof Followsets
|
||||||
export const Genericlists = 30001
|
export const Genericlists = 30001
|
||||||
|
export type Genericlists = typeof Genericlists
|
||||||
export const Relaysets = 30002
|
export const Relaysets = 30002
|
||||||
|
export type Relaysets = typeof Relaysets
|
||||||
export const Bookmarksets = 30003
|
export const Bookmarksets = 30003
|
||||||
|
export type Bookmarksets = typeof Bookmarksets
|
||||||
export const Curationsets = 30004
|
export const Curationsets = 30004
|
||||||
|
export type Curationsets = typeof Curationsets
|
||||||
export const ProfileBadges = 30008
|
export const ProfileBadges = 30008
|
||||||
|
export type ProfileBadges = typeof ProfileBadges
|
||||||
export const BadgeDefinition = 30009
|
export const BadgeDefinition = 30009
|
||||||
|
export type BadgeDefinition = typeof BadgeDefinition
|
||||||
export const Interestsets = 30015
|
export const Interestsets = 30015
|
||||||
|
export type Interestsets = typeof Interestsets
|
||||||
export const CreateOrUpdateStall = 30017
|
export const CreateOrUpdateStall = 30017
|
||||||
|
export type CreateOrUpdateStall = typeof CreateOrUpdateStall
|
||||||
export const CreateOrUpdateProduct = 30018
|
export const CreateOrUpdateProduct = 30018
|
||||||
|
export type CreateOrUpdateProduct = typeof CreateOrUpdateProduct
|
||||||
export const LongFormArticle = 30023
|
export const LongFormArticle = 30023
|
||||||
|
export type LongFormArticle = typeof LongFormArticle
|
||||||
export const DraftLong = 30024
|
export const DraftLong = 30024
|
||||||
|
export type DraftLong = typeof DraftLong
|
||||||
export const Emojisets = 30030
|
export const Emojisets = 30030
|
||||||
|
export type Emojisets = typeof Emojisets
|
||||||
export const Application = 30078
|
export const Application = 30078
|
||||||
|
export type Application = typeof Application
|
||||||
export const LiveEvent = 30311
|
export const LiveEvent = 30311
|
||||||
|
export type LiveEvent = typeof LiveEvent
|
||||||
export const UserStatuses = 30315
|
export const UserStatuses = 30315
|
||||||
|
export type UserStatuses = typeof UserStatuses
|
||||||
export const ClassifiedListing = 30402
|
export const ClassifiedListing = 30402
|
||||||
|
export type ClassifiedListing = typeof ClassifiedListing
|
||||||
export const DraftClassifiedListing = 30403
|
export const DraftClassifiedListing = 30403
|
||||||
|
export type DraftClassifiedListing = typeof DraftClassifiedListing
|
||||||
export const Date = 31922
|
export const Date = 31922
|
||||||
|
export type Date = typeof Date
|
||||||
export const Time = 31923
|
export const Time = 31923
|
||||||
|
export type Time = typeof Time
|
||||||
export const Calendar = 31924
|
export const Calendar = 31924
|
||||||
|
export type Calendar = typeof Calendar
|
||||||
export const CalendarEventRSVP = 31925
|
export const CalendarEventRSVP = 31925
|
||||||
|
export type CalendarEventRSVP = typeof CalendarEventRSVP
|
||||||
export const Handlerrecommendation = 31989
|
export const Handlerrecommendation = 31989
|
||||||
|
export type Handlerrecommendation = typeof Handlerrecommendation
|
||||||
export const Handlerinformation = 31990
|
export const Handlerinformation = 31990
|
||||||
|
export type Handlerinformation = typeof Handlerinformation
|
||||||
export const CommunityDefinition = 34550
|
export const CommunityDefinition = 34550
|
||||||
|
export type CommunityDefinition = typeof CommunityDefinition
|
||||||
|
|||||||
@@ -1,18 +1,44 @@
|
|||||||
import { test, expect } from 'bun:test'
|
import { test, expect } from 'bun:test'
|
||||||
import fetch from 'node-fetch'
|
|
||||||
|
|
||||||
import { useFetchImplementation, queryProfile } from './nip05.ts'
|
import { useFetchImplementation, queryProfile, NIP05_REGEX, isNip05 } from './nip05.ts'
|
||||||
|
|
||||||
|
test('validate NIP05_REGEX', () => {
|
||||||
|
expect(NIP05_REGEX.test('_@bob.com.br')).toBeTrue()
|
||||||
|
expect(NIP05_REGEX.test('bob@bob.com.br')).toBeTrue()
|
||||||
|
expect(NIP05_REGEX.test('b&b@bob.com.br')).toBeFalse()
|
||||||
|
|
||||||
|
expect('b&b@bob.com.br'.match(NIP05_REGEX)).toBeNull()
|
||||||
|
expect(Array.from('bob@bob.com.br'.match(NIP05_REGEX) || [])).toEqual(['bob@bob.com.br', 'bob', 'bob.com.br', '.br'])
|
||||||
|
|
||||||
|
expect(isNip05('bob@bob.com.br')).toBeTrue()
|
||||||
|
expect(isNip05('b&b@bob.com.br')).toBeFalse()
|
||||||
|
})
|
||||||
|
|
||||||
test('fetch nip05 profiles', async () => {
|
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]
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
let p1 = await queryProfile('jb55.com')
|
useFetchImplementation(fetchStub)
|
||||||
expect(p1!.pubkey).toEqual('32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245')
|
|
||||||
expect(p1!.relays).toEqual(['wss://relay.damus.io'])
|
|
||||||
|
|
||||||
let p2 = await queryProfile('jb55@jb55.com')
|
let p2 = await queryProfile('compile-error.net')
|
||||||
expect(p2!.pubkey).toEqual('32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245')
|
expect(p2!.pubkey).toEqual('2c7cc62a697ea3a7826521f3fd34f0cb273693cbe5e9310f35449f43622a5cdc')
|
||||||
expect(p2!.relays).toEqual(['wss://relay.damus.io'])
|
|
||||||
|
|
||||||
let p3 = await queryProfile('_@fiatjaf.com')
|
let p3 = await queryProfile('_@fiatjaf.com')
|
||||||
expect(p3!.pubkey).toEqual('3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d')
|
expect(p3!.pubkey).toEqual('3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d')
|
||||||
|
|||||||
33
nip05.ts
33
nip05.ts
@@ -1,5 +1,7 @@
|
|||||||
import { ProfilePointer } from './nip19.ts'
|
import { ProfilePointer } from './nip19.ts'
|
||||||
|
|
||||||
|
export type Nip05 = `${string}@${string}`
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* NIP-05 regex. The localpart is optional, and should be assumed to be `_` otherwise.
|
* NIP-05 regex. The localpart is optional, and should be assumed to be `_` otherwise.
|
||||||
*
|
*
|
||||||
@@ -8,21 +10,28 @@ import { ProfilePointer } from './nip19.ts'
|
|||||||
* - 2: domain
|
* - 2: domain
|
||||||
*/
|
*/
|
||||||
export const NIP05_REGEX = /^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/
|
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 {
|
try {
|
||||||
_fetch = fetch
|
_fetch = fetch
|
||||||
} catch {}
|
} catch (_) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
export function useFetchImplementation(fetchImplementation: any) {
|
export function useFetchImplementation(fetchImplementation: unknown) {
|
||||||
_fetch = fetchImplementation
|
_fetch = fetchImplementation
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function searchDomain(domain: string, query = ''): Promise<{ [name: string]: string }> {
|
export async function searchDomain(domain: string, query = ''): Promise<{ [name: string]: string }> {
|
||||||
try {
|
try {
|
||||||
const url = `https://${domain}/.well-known/nostr.json?name=${query}`
|
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()
|
const json = await res.json()
|
||||||
return json.names
|
return json.names
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
@@ -34,20 +43,24 @@ export async function queryProfile(fullname: string): Promise<ProfilePointer | n
|
|||||||
const match = fullname.match(NIP05_REGEX)
|
const match = fullname.match(NIP05_REGEX)
|
||||||
if (!match) return null
|
if (!match) return null
|
||||||
|
|
||||||
const [_, name = '_', domain] = match
|
const [, name = '_', domain] = match
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const url = `https://${domain}/.well-known/nostr.json?name=${name}`
|
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]
|
const pubkey = json.names[name]
|
||||||
return pubkey ? { pubkey, relays: res.relays?.[pubkey] } : null
|
return pubkey ? { pubkey, relays: json.relays?.[pubkey] } : null
|
||||||
} catch (_e) {
|
} catch (_e) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function isValid(pubkey: string, nip05: string): Promise<boolean> {
|
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
|
return res ? res.pubkey === pubkey : false
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,40 +3,41 @@ import {
|
|||||||
privateKeyFromSeedWords,
|
privateKeyFromSeedWords,
|
||||||
accountFromSeedWords,
|
accountFromSeedWords,
|
||||||
extendedKeysFromSeedWords,
|
extendedKeysFromSeedWords,
|
||||||
accountFromExtendedKey
|
accountFromExtendedKey,
|
||||||
} from './nip06.ts'
|
} from './nip06.ts'
|
||||||
|
import { hexToBytes } from '@noble/hashes/utils'
|
||||||
|
|
||||||
test('generate private key from a mnemonic', async () => {
|
test('generate private key from a mnemonic', async () => {
|
||||||
const mnemonic = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong'
|
const mnemonic = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong'
|
||||||
const privateKey = privateKeyFromSeedWords(mnemonic)
|
const privateKey = privateKeyFromSeedWords(mnemonic)
|
||||||
expect(privateKey).toEqual('c26cf31d8ba425b555ca27d00ca71b5008004f2f662470f8c8131822ec129fe2')
|
expect(privateKey).toEqual(hexToBytes('c26cf31d8ba425b555ca27d00ca71b5008004f2f662470f8c8131822ec129fe2'))
|
||||||
})
|
})
|
||||||
|
|
||||||
test('generate private key for account 1 from a mnemonic', async () => {
|
test('generate private key for account 1 from a mnemonic', async () => {
|
||||||
const mnemonic = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong'
|
const mnemonic = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong'
|
||||||
const privateKey = privateKeyFromSeedWords(mnemonic, undefined, 1)
|
const privateKey = privateKeyFromSeedWords(mnemonic, undefined, 1)
|
||||||
expect(privateKey).toEqual('b5fc7f229de3fb5c189063e3b3fc6c921d8f4366cff5bd31c6f063493665eb2b')
|
expect(privateKey).toEqual(hexToBytes('b5fc7f229de3fb5c189063e3b3fc6c921d8f4366cff5bd31c6f063493665eb2b'))
|
||||||
})
|
})
|
||||||
|
|
||||||
test('generate private key from a mnemonic and passphrase', async () => {
|
test('generate private key from a mnemonic and passphrase', async () => {
|
||||||
const mnemonic = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong'
|
const mnemonic = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong'
|
||||||
const passphrase = '123'
|
const passphrase = '123'
|
||||||
const privateKey = privateKeyFromSeedWords(mnemonic, passphrase)
|
const privateKey = privateKeyFromSeedWords(mnemonic, passphrase)
|
||||||
expect(privateKey).toEqual('55a22b8203273d0aaf24c22c8fbe99608e70c524b17265641074281c8b978ae4')
|
expect(privateKey).toEqual(hexToBytes('55a22b8203273d0aaf24c22c8fbe99608e70c524b17265641074281c8b978ae4'))
|
||||||
})
|
})
|
||||||
|
|
||||||
test('generate private key for account 1 from a mnemonic and passphrase', async () => {
|
test('generate private 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 mnemonic = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong'
|
||||||
const passphrase = '123'
|
const passphrase = '123'
|
||||||
const privateKey = privateKeyFromSeedWords(mnemonic, passphrase, 1)
|
const privateKey = privateKeyFromSeedWords(mnemonic, passphrase, 1)
|
||||||
expect(privateKey).toEqual('2e0f7bd9e3c3ebcdff1a90fb49c913477e7c055eba1a415d571b6a8c714c7135')
|
expect(privateKey).toEqual(hexToBytes('2e0f7bd9e3c3ebcdff1a90fb49c913477e7c055eba1a415d571b6a8c714c7135'))
|
||||||
})
|
})
|
||||||
|
|
||||||
test('generate private and public key for account 1 from a mnemonic and passphrase', async () => {
|
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 mnemonic = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong'
|
||||||
const passphrase = '123'
|
const passphrase = '123'
|
||||||
const { privateKey, publicKey } = accountFromSeedWords(mnemonic, passphrase, 1)
|
const { privateKey, publicKey } = accountFromSeedWords(mnemonic, passphrase, 1)
|
||||||
expect(privateKey).toEqual('2e0f7bd9e3c3ebcdff1a90fb49c913477e7c055eba1a415d571b6a8c714c7135')
|
expect(privateKey).toEqual(hexToBytes('2e0f7bd9e3c3ebcdff1a90fb49c913477e7c055eba1a415d571b6a8c714c7135'))
|
||||||
expect(publicKey).toEqual('13f55f4f01576570ea342eb7d2b611f9dc78f8dc601aeb512011e4e73b90cf0a')
|
expect(publicKey).toEqual('13f55f4f01576570ea342eb7d2b611f9dc78f8dc601aeb512011e4e73b90cf0a')
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -44,22 +45,32 @@ test('generate extended keys from mnemonic', () => {
|
|||||||
const mnemonic = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'
|
const mnemonic = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'
|
||||||
const passphrase = ''
|
const passphrase = ''
|
||||||
const extendedAccountIndex = 0
|
const extendedAccountIndex = 0
|
||||||
const { privateExtendedKey, publicExtendedKey } = extendedKeysFromSeedWords(mnemonic, passphrase, extendedAccountIndex)
|
const { privateExtendedKey, publicExtendedKey } = extendedKeysFromSeedWords(
|
||||||
|
mnemonic,
|
||||||
|
passphrase,
|
||||||
|
extendedAccountIndex,
|
||||||
|
)
|
||||||
|
|
||||||
expect(privateExtendedKey).toBe('xprv9z78fizET65qsCaRr1MSutTSGk1fcKfSt1sBqmuWShtkjRJJ4WCKcSnha6EmgNzFSsyom3MWtydHyPtJtSLZQUtictVQtM2vkPcguh6TQCH')
|
expect(privateExtendedKey).toBe(
|
||||||
expect(publicExtendedKey).toBe('xpub6D6V5EX8HTe95getx2tTH2QApmrA1nPJFEnneAK813RjcDdSc3WaAF7BRNpTF7o7zXjVm3DD3VMX66jhQ7wLaZ9sS6NzyfiwfzqDZbxvpDN')
|
'xprv9z78fizET65qsCaRr1MSutTSGk1fcKfSt1sBqmuWShtkjRJJ4WCKcSnha6EmgNzFSsyom3MWtydHyPtJtSLZQUtictVQtM2vkPcguh6TQCH',
|
||||||
|
)
|
||||||
|
expect(publicExtendedKey).toBe(
|
||||||
|
'xpub6D6V5EX8HTe95getx2tTH2QApmrA1nPJFEnneAK813RjcDdSc3WaAF7BRNpTF7o7zXjVm3DD3VMX66jhQ7wLaZ9sS6NzyfiwfzqDZbxvpDN',
|
||||||
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('generate account from extended private key', () => {
|
test('generate account from extended private key', () => {
|
||||||
const xprv = 'xprv9z78fizET65qsCaRr1MSutTSGk1fcKfSt1sBqmuWShtkjRJJ4WCKcSnha6EmgNzFSsyom3MWtydHyPtJtSLZQUtictVQtM2vkPcguh6TQCH'
|
const xprv =
|
||||||
|
'xprv9z78fizET65qsCaRr1MSutTSGk1fcKfSt1sBqmuWShtkjRJJ4WCKcSnha6EmgNzFSsyom3MWtydHyPtJtSLZQUtictVQtM2vkPcguh6TQCH'
|
||||||
const { privateKey, publicKey } = accountFromExtendedKey(xprv)
|
const { privateKey, publicKey } = accountFromExtendedKey(xprv)
|
||||||
|
|
||||||
expect(privateKey).toBe('5f29af3b9676180290e77a4efad265c4c2ff28a5302461f73597fda26bb25731')
|
expect(privateKey).toEqual(hexToBytes('5f29af3b9676180290e77a4efad265c4c2ff28a5302461f73597fda26bb25731'))
|
||||||
expect(publicKey).toBe('e8bcf3823669444d0b49ad45d65088635d9fd8500a75b5f20b59abefa56a144f')
|
expect(publicKey).toBe('e8bcf3823669444d0b49ad45d65088635d9fd8500a75b5f20b59abefa56a144f')
|
||||||
})
|
})
|
||||||
|
|
||||||
test('generate account from extended public key', () => {
|
test('generate account from extended public key', () => {
|
||||||
const xpub = 'xpub6D6V5EX8HTe95getx2tTH2QApmrA1nPJFEnneAK813RjcDdSc3WaAF7BRNpTF7o7zXjVm3DD3VMX66jhQ7wLaZ9sS6NzyfiwfzqDZbxvpDN'
|
const xpub =
|
||||||
|
'xpub6D6V5EX8HTe95getx2tTH2QApmrA1nPJFEnneAK813RjcDdSc3WaAF7BRNpTF7o7zXjVm3DD3VMX66jhQ7wLaZ9sS6NzyfiwfzqDZbxvpDN'
|
||||||
const { publicKey } = accountFromExtendedKey(xpub)
|
const { publicKey } = accountFromExtendedKey(xpub)
|
||||||
|
|
||||||
expect(publicKey).toBe('e8bcf3823669444d0b49ad45d65088635d9fd8500a75b5f20b59abefa56a144f')
|
expect(publicKey).toBe('e8bcf3823669444d0b49ad45d65088635d9fd8500a75b5f20b59abefa56a144f')
|
||||||
|
|||||||
39
nip06.ts
39
nip06.ts
@@ -5,29 +5,37 @@ import { HDKey } from '@scure/bip32'
|
|||||||
|
|
||||||
const DERIVATION_PATH = `m/44'/1237'`
|
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): Uint8Array {
|
||||||
let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))
|
let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))
|
||||||
let privateKey = root.derive(`${DERIVATION_PATH}/${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 privateKey
|
||||||
}
|
}
|
||||||
|
|
||||||
export function accountFromSeedWords(mnemonic: string, passphrase?: string, accountIndex = 0): {
|
export function accountFromSeedWords(
|
||||||
privateKey: string,
|
mnemonic: string,
|
||||||
publicKey: string,
|
passphrase?: string,
|
||||||
|
accountIndex = 0,
|
||||||
|
): {
|
||||||
|
privateKey: Uint8Array
|
||||||
|
publicKey: string
|
||||||
} {
|
} {
|
||||||
const root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))
|
const root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))
|
||||||
const seed = root.derive(`${DERIVATION_PATH}/${accountIndex}'/0/0`)
|
const seed = root.derive(`${DERIVATION_PATH}/${accountIndex}'/0/0`)
|
||||||
const privateKey = bytesToHex(seed.privateKey!)
|
|
||||||
const publicKey = bytesToHex(seed.publicKey!.slice(1))
|
const publicKey = bytesToHex(seed.publicKey!.slice(1))
|
||||||
if (!privateKey && !publicKey) {
|
const privateKey = seed.privateKey
|
||||||
|
if (!privateKey || !publicKey) {
|
||||||
throw new Error('could not derive key pair')
|
throw new Error('could not derive key pair')
|
||||||
}
|
}
|
||||||
return { privateKey, publicKey }
|
return { privateKey, publicKey }
|
||||||
}
|
}
|
||||||
|
|
||||||
export function extendedKeysFromSeedWords(mnemonic: string, passphrase?: string, extendedAccountIndex = 0): {
|
export function extendedKeysFromSeedWords(
|
||||||
privateExtendedKey: string,
|
mnemonic: string,
|
||||||
|
passphrase?: string,
|
||||||
|
extendedAccountIndex = 0,
|
||||||
|
): {
|
||||||
|
privateExtendedKey: string
|
||||||
publicExtendedKey: string
|
publicExtendedKey: string
|
||||||
} {
|
} {
|
||||||
let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))
|
let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))
|
||||||
@@ -38,8 +46,11 @@ export function extendedKeysFromSeedWords(mnemonic: string, passphrase?: string,
|
|||||||
return { privateExtendedKey, publicExtendedKey }
|
return { privateExtendedKey, publicExtendedKey }
|
||||||
}
|
}
|
||||||
|
|
||||||
export function accountFromExtendedKey(base58key: string, accountIndex = 0): {
|
export function accountFromExtendedKey(
|
||||||
privateKey?: string,
|
base58key: string,
|
||||||
|
accountIndex = 0,
|
||||||
|
): {
|
||||||
|
privateKey?: Uint8Array
|
||||||
publicKey: string
|
publicKey: string
|
||||||
} {
|
} {
|
||||||
let extendedKey = HDKey.fromExtendedKey(base58key)
|
let extendedKey = HDKey.fromExtendedKey(base58key)
|
||||||
@@ -48,11 +59,11 @@ export function accountFromExtendedKey(base58key: string, accountIndex = 0): {
|
|||||||
let publicKey = bytesToHex(child.publicKey!.slice(1))
|
let publicKey = bytesToHex(child.publicKey!.slice(1))
|
||||||
if (!publicKey) throw new Error('could not derive public key')
|
if (!publicKey) throw new Error('could not derive public key')
|
||||||
if (version === 'xprv') {
|
if (version === 'xprv') {
|
||||||
let privateKey = bytesToHex(child.privateKey!)
|
let privateKey = child.privateKey!
|
||||||
if (!privateKey) throw new Error('could not derive private key')
|
if (!privateKey) throw new Error('could not derive private key')
|
||||||
return { privateKey, publicKey }
|
return { privateKey, publicKey }
|
||||||
}
|
}
|
||||||
return { publicKey }
|
return { publicKey }
|
||||||
}
|
}
|
||||||
|
|
||||||
export function generateSeedWords(): string {
|
export function generateSeedWords(): string {
|
||||||
|
|||||||
2
nip07.ts
2
nip07.ts
@@ -7,7 +7,7 @@ export interface WindowNostr {
|
|||||||
getRelays(): Promise<RelayRecord>
|
getRelays(): Promise<RelayRecord>
|
||||||
nip04?: {
|
nip04?: {
|
||||||
encrypt(pubkey: string, plaintext: string): Promise<string>
|
encrypt(pubkey: string, plaintext: string): Promise<string>
|
||||||
ecrypt(pubkey: string, ciphertext: string): Promise<string>
|
decrypt(pubkey: string, ciphertext: string): Promise<string>
|
||||||
}
|
}
|
||||||
nip44?: {
|
nip44?: {
|
||||||
encrypt(pubkey: string, plaintext: string): Promise<string>
|
encrypt(pubkey: string, plaintext: string): Promise<string>
|
||||||
|
|||||||
187
nip10.test.ts
187
nip10.test.ts
@@ -5,20 +5,21 @@ describe('parse NIP10-referenced events', () => {
|
|||||||
test('legacy + a lot of events', () => {
|
test('legacy + a lot of events', () => {
|
||||||
let event = {
|
let event = {
|
||||||
tags: [
|
tags: [
|
||||||
['e', 'b857504288c18a15950dd05b9e8772c62ca6289d5aac373c0a8ee5b132e94e7c'],
|
|
||||||
['e', 'bbd72f0ae14374aa8fb166b483cfcf99b57d7f4cf1600ccbf17c350040834631'],
|
|
||||||
['e', '5e081ebb19153357d7c31e8a10b9ceeef29313f58dc8d701f66727fab02aef64'],
|
|
||||||
['e', '49aff7ae6daeaaa2777931b90f9bb29f6cb01c5a3d7d88c8ba82d890f264afb4'],
|
|
||||||
['e', '567b7c11f0fe582361e3cea6fcc7609a8942dfe196ee1b98d5604c93fbeea976'],
|
|
||||||
['e', '090c037b2e399ee74d9f134758928948dd9154413ca1a1acb37155046e03a051'],
|
|
||||||
['e', '89f220b63465c93542b1a78caa3a952cf4f196e91a50596493c8093c533ebc4d'],
|
|
||||||
['p', '77ce56f89d1228f7ff3743ce1ad1b254857b9008564727ebd5a1f317362f6ca7'],
|
|
||||||
['p', '534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec'],
|
|
||||||
['p', '4ca4f5533e40da5e0508796d409e6bb35a50b26fc304345617ab017183d83ac0'],
|
['p', '4ca4f5533e40da5e0508796d409e6bb35a50b26fc304345617ab017183d83ac0'],
|
||||||
|
['p', '534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec'],
|
||||||
|
['p', '77ce56f89d1228f7ff3743ce1ad1b254857b9008564727ebd5a1f317362f6ca7'],
|
||||||
|
['e', '89f220b63465c93542b1a78caa3a952cf4f196e91a50596493c8093c533ebc4d'],
|
||||||
|
['e', '090c037b2e399ee74d9f134758928948dd9154413ca1a1acb37155046e03a051'],
|
||||||
|
['e', '567b7c11f0fe582361e3cea6fcc7609a8942dfe196ee1b98d5604c93fbeea976'],
|
||||||
|
['e', '49aff7ae6daeaaa2777931b90f9bb29f6cb01c5a3d7d88c8ba82d890f264afb4'],
|
||||||
|
['e', '5e081ebb19153357d7c31e8a10b9ceeef29313f58dc8d701f66727fab02aef64'],
|
||||||
|
['e', 'bbd72f0ae14374aa8fb166b483cfcf99b57d7f4cf1600ccbf17c350040834631'],
|
||||||
|
['e', 'b857504288c18a15950dd05b9e8772c62ca6289d5aac373c0a8ee5b132e94e7c'],
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
expect(parse(event)).toEqual({
|
expect(parse(event)).toEqual({
|
||||||
|
quotes: [],
|
||||||
mentions: [
|
mentions: [
|
||||||
{
|
{
|
||||||
id: 'bbd72f0ae14374aa8fb166b483cfcf99b57d7f4cf1600ccbf17c350040834631',
|
id: 'bbd72f0ae14374aa8fb166b483cfcf99b57d7f4cf1600ccbf17c350040834631',
|
||||||
@@ -55,33 +56,80 @@ describe('parse NIP10-referenced events', () => {
|
|||||||
relays: [],
|
relays: [],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
reply: {
|
root: {
|
||||||
id: '89f220b63465c93542b1a78caa3a952cf4f196e91a50596493c8093c533ebc4d',
|
id: '89f220b63465c93542b1a78caa3a952cf4f196e91a50596493c8093c533ebc4d',
|
||||||
relays: [],
|
relays: [],
|
||||||
},
|
},
|
||||||
root: {
|
reply: {
|
||||||
id: 'b857504288c18a15950dd05b9e8772c62ca6289d5aac373c0a8ee5b132e94e7c',
|
id: 'b857504288c18a15950dd05b9e8772c62ca6289d5aac373c0a8ee5b132e94e7c',
|
||||||
relays: [],
|
relays: [],
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test('legacy + 3 events', () => {
|
test('modern', () => {
|
||||||
let event = {
|
let event = {
|
||||||
tags: [
|
tags: [
|
||||||
['e', 'b857504288c18a15950dd05b9e8772c62ca6289d5aac373c0a8ee5b132e94e7c'],
|
|
||||||
['e', 'bbd72f0ae14374aa8fb166b483cfcf99b57d7f4cf1600ccbf17c350040834631'],
|
|
||||||
['e', '5e081ebb19153357d7c31e8a10b9ceeef29313f58dc8d701f66727fab02aef64'],
|
|
||||||
['p', '77ce56f89d1228f7ff3743ce1ad1b254857b9008564727ebd5a1f317362f6ca7'],
|
|
||||||
['p', '534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec'],
|
|
||||||
['p', '4ca4f5533e40da5e0508796d409e6bb35a50b26fc304345617ab017183d83ac0'],
|
['p', '4ca4f5533e40da5e0508796d409e6bb35a50b26fc304345617ab017183d83ac0'],
|
||||||
|
['p', '534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec'],
|
||||||
|
['e', '77ce56f89d1228f7ff3743ce1ad1b254857b9008564727ebd5a1f317362f6ca7'],
|
||||||
|
['e', 'bbd72f0ae14374aa8fb166b483cfcf99b57d7f4cf1600ccbf17c350040834631', '', 'root'],
|
||||||
|
['e', 'b857504288c18a15950dd05b9e8772c62ca6289d5aac373c0a8ee5b132e94e7c', '', 'reply'],
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
expect(parse(event)).toEqual({
|
expect(parse(event)).toEqual({
|
||||||
|
quotes: [],
|
||||||
mentions: [
|
mentions: [
|
||||||
{
|
{
|
||||||
id: 'bbd72f0ae14374aa8fb166b483cfcf99b57d7f4cf1600ccbf17c350040834631',
|
id: '77ce56f89d1228f7ff3743ce1ad1b254857b9008564727ebd5a1f317362f6ca7',
|
||||||
|
relays: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
profiles: [
|
||||||
|
{
|
||||||
|
pubkey: '534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec',
|
||||||
|
relays: [],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
pubkey: '4ca4f5533e40da5e0508796d409e6bb35a50b26fc304345617ab017183d83ac0',
|
||||||
|
relays: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
root: {
|
||||||
|
id: 'bbd72f0ae14374aa8fb166b483cfcf99b57d7f4cf1600ccbf17c350040834631',
|
||||||
|
relays: [],
|
||||||
|
},
|
||||||
|
reply: {
|
||||||
|
id: 'b857504288c18a15950dd05b9e8772c62ca6289d5aac373c0a8ee5b132e94e7c',
|
||||||
|
relays: [],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('modern, inverted, author hint', () => {
|
||||||
|
let event = {
|
||||||
|
tags: [
|
||||||
|
['p', '4ca4f5533e40da5e0508796d409e6bb35a50b26fc304345617ab017183d83ac0', 'wss://goiaba.com'],
|
||||||
|
['p', '534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec'],
|
||||||
|
['p', '77ce56f89d1228f7ff3743ce1ad1b254857b9008564727ebd5a1f317362f6ca7'],
|
||||||
|
['e', '5e081ebb19153357d7c31e8a10b9ceeef29313f58dc8d701f66727fab02aef64', '', 'reply'],
|
||||||
|
[
|
||||||
|
'e',
|
||||||
|
'bbd72f0ae14374aa8fb166b483cfcf99b57d7f4cf1600ccbf17c350040834631',
|
||||||
|
'wss://banana.com',
|
||||||
|
'root',
|
||||||
|
'4ca4f5533e40da5e0508796d409e6bb35a50b26fc304345617ab017183d83ac0',
|
||||||
|
],
|
||||||
|
['e', 'b857504288c18a15950dd05b9e8772c62ca6289d5aac373c0a8ee5b132e94e7c'],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(parse(event)).toEqual({
|
||||||
|
quotes: [],
|
||||||
|
mentions: [
|
||||||
|
{
|
||||||
|
id: 'b857504288c18a15950dd05b9e8772c62ca6289d5aac373c0a8ee5b132e94e7c',
|
||||||
relays: [],
|
relays: [],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -96,98 +144,80 @@ describe('parse NIP10-referenced events', () => {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
pubkey: '4ca4f5533e40da5e0508796d409e6bb35a50b26fc304345617ab017183d83ac0',
|
pubkey: '4ca4f5533e40da5e0508796d409e6bb35a50b26fc304345617ab017183d83ac0',
|
||||||
relays: [],
|
relays: ['wss://banana.com', 'wss://goiaba.com'],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
root: {
|
||||||
|
id: 'bbd72f0ae14374aa8fb166b483cfcf99b57d7f4cf1600ccbf17c350040834631',
|
||||||
|
relays: ['wss://banana.com', 'wss://goiaba.com'],
|
||||||
|
author: '4ca4f5533e40da5e0508796d409e6bb35a50b26fc304345617ab017183d83ac0',
|
||||||
|
},
|
||||||
reply: {
|
reply: {
|
||||||
id: '5e081ebb19153357d7c31e8a10b9ceeef29313f58dc8d701f66727fab02aef64',
|
id: '5e081ebb19153357d7c31e8a10b9ceeef29313f58dc8d701f66727fab02aef64',
|
||||||
relays: [],
|
relays: [],
|
||||||
},
|
},
|
||||||
root: {
|
|
||||||
id: 'b857504288c18a15950dd05b9e8772c62ca6289d5aac373c0a8ee5b132e94e7c',
|
|
||||||
relays: [],
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test('legacy + 2 events', () => {
|
test('1 event, relay hint from author', () => {
|
||||||
let event = {
|
let event = {
|
||||||
tags: [
|
tags: [
|
||||||
['e', 'b857504288c18a15950dd05b9e8772c62ca6289d5aac373c0a8ee5b132e94e7c'],
|
['p', '534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec', 'wss://banana.com'],
|
||||||
['e', 'bbd72f0ae14374aa8fb166b483cfcf99b57d7f4cf1600ccbf17c350040834631'],
|
[
|
||||||
['p', '77ce56f89d1228f7ff3743ce1ad1b254857b9008564727ebd5a1f317362f6ca7'],
|
'e',
|
||||||
['p', '534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec'],
|
'9abbfd9b9ac5ecdab45d14b8bf8d746139ea039e931a1b376d19a239f1946590',
|
||||||
['p', '4ca4f5533e40da5e0508796d409e6bb35a50b26fc304345617ab017183d83ac0'],
|
'',
|
||||||
|
'root',
|
||||||
|
'534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec',
|
||||||
|
],
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
expect(parse(event)).toEqual({
|
expect(parse(event)).toEqual({
|
||||||
|
quotes: [],
|
||||||
mentions: [],
|
mentions: [],
|
||||||
profiles: [
|
profiles: [
|
||||||
{
|
|
||||||
pubkey: '77ce56f89d1228f7ff3743ce1ad1b254857b9008564727ebd5a1f317362f6ca7',
|
|
||||||
relays: [],
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
pubkey: '534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec',
|
pubkey: '534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec',
|
||||||
relays: [],
|
relays: ['wss://banana.com'],
|
||||||
},
|
|
||||||
{
|
|
||||||
pubkey: '4ca4f5533e40da5e0508796d409e6bb35a50b26fc304345617ab017183d83ac0',
|
|
||||||
relays: [],
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
reply: {
|
reply: {
|
||||||
id: 'bbd72f0ae14374aa8fb166b483cfcf99b57d7f4cf1600ccbf17c350040834631',
|
author: '534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec',
|
||||||
relays: [],
|
|
||||||
},
|
|
||||||
root: {
|
|
||||||
id: 'b857504288c18a15950dd05b9e8772c62ca6289d5aac373c0a8ee5b132e94e7c',
|
|
||||||
relays: [],
|
|
||||||
},
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
test('legacy + 1 event', () => {
|
|
||||||
let event = {
|
|
||||||
tags: [
|
|
||||||
['e', '9abbfd9b9ac5ecdab45d14b8bf8d746139ea039e931a1b376d19a239f1946590'],
|
|
||||||
['p', '534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec'],
|
|
||||||
],
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(parse(event)).toEqual({
|
|
||||||
mentions: [],
|
|
||||||
profiles: [
|
|
||||||
{
|
|
||||||
pubkey: '534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec',
|
|
||||||
relays: [],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
reply: undefined,
|
|
||||||
root: {
|
|
||||||
id: '9abbfd9b9ac5ecdab45d14b8bf8d746139ea039e931a1b376d19a239f1946590',
|
id: '9abbfd9b9ac5ecdab45d14b8bf8d746139ea039e931a1b376d19a239f1946590',
|
||||||
relays: [],
|
relays: ['wss://banana.com'],
|
||||||
|
},
|
||||||
|
root: {
|
||||||
|
author: '534780e44da7b494485e85cd4cca6af4f6caa1627472432b6f2a4ece0e9e54ec',
|
||||||
|
id: '9abbfd9b9ac5ecdab45d14b8bf8d746139ea039e931a1b376d19a239f1946590',
|
||||||
|
relays: ['wss://banana.com'],
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test('recommended + 1 event', () => {
|
test('many p 1 reply', () => {
|
||||||
let event = {
|
let event = {
|
||||||
tags: [
|
tags: [
|
||||||
['p', 'a8c21fcd8aa1f4befba14d72fc7a012397732d30d8b3131af912642f3c726f52', 'wss://relay.mostr.pub'],
|
|
||||||
['p', '003d7fd21fd09ff7f6f63a75daf194dd99feefbe6919cc376b7359d5090aa9a6', 'wss://relay.mostr.pub'],
|
|
||||||
['p', '2f6fbe452edd3987d3c67f3b034c03ec5bcf4d054c521c3a954686f89f03212e', 'wss://relay.mostr.pub'],
|
|
||||||
['p', '44c7c74668ff222b0e0b30579c49fc6e22dafcdeaad091036c947f9856590f1e', 'wss://relay.mostr.pub'],
|
|
||||||
['p', 'c5cf39149caebda4cdd61771c51f6ba91ef5645919004e5c4998a4ea69f00512', 'wss://relay.mostr.pub'],
|
|
||||||
['p', '094d44bb1e812696c57f57ad1c0c707812dedbe72c07e538b80639032c236a9e', 'wss://relay.mostr.pub'],
|
|
||||||
['p', 'a1ba0ac9b6ec098f726a3c11ec654df4a32cbb84b5377e8788395e9c27d9ecda', 'wss://relay.mostr.pub'],
|
['p', 'a1ba0ac9b6ec098f726a3c11ec654df4a32cbb84b5377e8788395e9c27d9ecda', 'wss://relay.mostr.pub'],
|
||||||
['e', 'f9472913904ab7e9da008dcb2d85fd4af2d2993ada483d00c646d0c4481d031d', 'wss://relay.mostr.pub', 'reply'],
|
['p', '094d44bb1e812696c57f57ad1c0c707812dedbe72c07e538b80639032c236a9e', 'wss://relay.mostr.pub'],
|
||||||
|
['p', 'c5cf39149caebda4cdd61771c51f6ba91ef5645919004e5c4998a4ea69f00512', 'wss://relay.mostr.pub'],
|
||||||
|
['p', '44c7c74668ff222b0e0b30579c49fc6e22dafcdeaad091036c947f9856590f1e', 'wss://relay.mostr.pub'],
|
||||||
|
['p', '2f6fbe452edd3987d3c67f3b034c03ec5bcf4d054c521c3a954686f89f03212e', 'wss://relay.mostr.pub'],
|
||||||
|
['p', '003d7fd21fd09ff7f6f63a75daf194dd99feefbe6919cc376b7359d5090aa9a6', 'wss://relay.mostr.pub'],
|
||||||
|
['p', 'a8c21fcd8aa1f4befba14d72fc7a012397732d30d8b3131af912642f3c726f52', 'wss://relay.mostr.pub'],
|
||||||
|
[
|
||||||
|
'e',
|
||||||
|
'f9472913904ab7e9da008dcb2d85fd4af2d2993ada483d00c646d0c4481d031d',
|
||||||
|
'wss://relay.mostr.pub',
|
||||||
|
'reply',
|
||||||
|
'c5cf39149caebda4cdd61771c51f6ba91ef5645919004e5c4998a4ea69f00512',
|
||||||
|
],
|
||||||
['mostr', 'https://poa.st/objects/dc50684b-6364-4264-ab16-49f4622f05ea'],
|
['mostr', 'https://poa.st/objects/dc50684b-6364-4264-ab16-49f4622f05ea'],
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
expect(parse(event)).toEqual({
|
expect(parse(event)).toEqual({
|
||||||
|
quotes: [],
|
||||||
mentions: [],
|
mentions: [],
|
||||||
profiles: [
|
profiles: [
|
||||||
{
|
{
|
||||||
@@ -222,8 +252,13 @@ describe('parse NIP10-referenced events', () => {
|
|||||||
reply: {
|
reply: {
|
||||||
id: 'f9472913904ab7e9da008dcb2d85fd4af2d2993ada483d00c646d0c4481d031d',
|
id: 'f9472913904ab7e9da008dcb2d85fd4af2d2993ada483d00c646d0c4481d031d',
|
||||||
relays: ['wss://relay.mostr.pub'],
|
relays: ['wss://relay.mostr.pub'],
|
||||||
|
author: 'c5cf39149caebda4cdd61771c51f6ba91ef5645919004e5c4998a4ea69f00512',
|
||||||
|
},
|
||||||
|
root: {
|
||||||
|
id: 'f9472913904ab7e9da008dcb2d85fd4af2d2993ada483d00c646d0c4481d031d',
|
||||||
|
relays: ['wss://relay.mostr.pub'],
|
||||||
|
author: 'c5cf39149caebda4cdd61771c51f6ba91ef5645919004e5c4998a4ea69f00512',
|
||||||
},
|
},
|
||||||
root: undefined,
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
152
nip10.ts
152
nip10.ts
@@ -1,7 +1,7 @@
|
|||||||
import type { Event } from './core.ts'
|
import type { Event } from './core.ts'
|
||||||
import type { EventPointer, ProfilePointer } from './nip19.ts'
|
import type { EventPointer, ProfilePointer } from './nip19.ts'
|
||||||
|
|
||||||
export type NIP10Result = {
|
export function parse(event: Pick<Event, 'tags'>): {
|
||||||
/**
|
/**
|
||||||
* Pointer to the root of the thread.
|
* Pointer to the root of the thread.
|
||||||
*/
|
*/
|
||||||
@@ -13,29 +13,80 @@ export type NIP10Result = {
|
|||||||
reply: EventPointer | undefined
|
reply: EventPointer | undefined
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pointers to events which may or may not be in the reply chain.
|
* Pointers to events that may or may not be in the reply chain.
|
||||||
*/
|
*/
|
||||||
mentions: EventPointer[]
|
mentions: EventPointer[]
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pointers to events that were directly quoted.
|
||||||
|
*/
|
||||||
|
quotes: EventPointer[]
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* List of pubkeys that are involved in the thread in no particular order.
|
* List of pubkeys that are involved in the thread in no particular order.
|
||||||
*/
|
*/
|
||||||
profiles: ProfilePointer[]
|
profiles: ProfilePointer[]
|
||||||
}
|
} {
|
||||||
|
const result: ReturnType<typeof parse> = {
|
||||||
export function parse(event: Pick<Event, 'tags'>): NIP10Result {
|
|
||||||
const result: NIP10Result = {
|
|
||||||
reply: undefined,
|
reply: undefined,
|
||||||
root: undefined,
|
root: undefined,
|
||||||
mentions: [],
|
mentions: [],
|
||||||
profiles: [],
|
profiles: [],
|
||||||
|
quotes: [],
|
||||||
}
|
}
|
||||||
|
|
||||||
const eTags: string[][] = []
|
let maybeParent: EventPointer | undefined
|
||||||
|
let maybeRoot: EventPointer | undefined
|
||||||
|
|
||||||
|
for (let i = event.tags.length - 1; i >= 0; i--) {
|
||||||
|
const tag = event.tags[i]
|
||||||
|
|
||||||
for (const tag of event.tags) {
|
|
||||||
if (tag[0] === 'e' && tag[1]) {
|
if (tag[0] === 'e' && tag[1]) {
|
||||||
eTags.push(tag)
|
const [_, eTagEventId, eTagRelayUrl, eTagMarker, eTagAuthor] = tag as [
|
||||||
|
string,
|
||||||
|
string,
|
||||||
|
undefined | string,
|
||||||
|
undefined | string,
|
||||||
|
undefined | string,
|
||||||
|
]
|
||||||
|
|
||||||
|
const eventPointer: EventPointer = {
|
||||||
|
id: eTagEventId,
|
||||||
|
relays: eTagRelayUrl ? [eTagRelayUrl] : [],
|
||||||
|
author: eTagAuthor,
|
||||||
|
}
|
||||||
|
|
||||||
|
if (eTagMarker === 'root') {
|
||||||
|
result.root = eventPointer
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if (eTagMarker === 'reply') {
|
||||||
|
result.reply = eventPointer
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if (eTagMarker === 'mention') {
|
||||||
|
result.mentions.push(eventPointer)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!maybeParent) {
|
||||||
|
maybeParent = eventPointer
|
||||||
|
} else {
|
||||||
|
maybeRoot = eventPointer
|
||||||
|
}
|
||||||
|
|
||||||
|
result.mentions.push(eventPointer)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tag[0] === 'q' && tag[1]) {
|
||||||
|
const [_, eTagEventId, eTagRelayUrl] = tag as [string, string, undefined | string]
|
||||||
|
result.quotes.push({
|
||||||
|
id: eTagEventId,
|
||||||
|
relays: eTagRelayUrl ? [eTagRelayUrl] : [],
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if (tag[0] === 'p' && tag[1]) {
|
if (tag[0] === 'p' && tag[1]) {
|
||||||
@@ -43,49 +94,54 @@ export function parse(event: Pick<Event, 'tags'>): NIP10Result {
|
|||||||
pubkey: tag[1],
|
pubkey: tag[1],
|
||||||
relays: tag[2] ? [tag[2]] : [],
|
relays: tag[2] ? [tag[2]] : [],
|
||||||
})
|
})
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (let eTagIndex = 0; eTagIndex < eTags.length; eTagIndex++) {
|
// get legacy (positional) markers, set reply to root and vice-versa if one of them is missing
|
||||||
const eTag = eTags[eTagIndex]
|
if (!result.root) {
|
||||||
|
result.root = maybeRoot || maybeParent || result.reply
|
||||||
const [_, eTagEventId, eTagRelayUrl, eTagMarker] = eTag as [string, string, undefined | string, undefined | string]
|
|
||||||
|
|
||||||
const eventPointer: EventPointer = {
|
|
||||||
id: eTagEventId,
|
|
||||||
relays: eTagRelayUrl ? [eTagRelayUrl] : [],
|
|
||||||
}
|
|
||||||
|
|
||||||
const isFirstETag = eTagIndex === 0
|
|
||||||
const isLastETag = eTagIndex === eTags.length - 1
|
|
||||||
|
|
||||||
if (eTagMarker === 'root') {
|
|
||||||
result.root = eventPointer
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if (eTagMarker === 'reply') {
|
|
||||||
result.reply = eventPointer
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if (eTagMarker === 'mention') {
|
|
||||||
result.mentions.push(eventPointer)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isFirstETag) {
|
|
||||||
result.root = eventPointer
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isLastETag) {
|
|
||||||
result.reply = eventPointer
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
result.mentions.push(eventPointer)
|
|
||||||
}
|
}
|
||||||
|
if (!result.reply) {
|
||||||
|
result.reply = maybeParent || result.root
|
||||||
|
}
|
||||||
|
|
||||||
|
// remove root and reply from mentions, inherit relay hints from authors if any
|
||||||
|
;[result.reply, result.root].forEach(ref => {
|
||||||
|
if (!ref) return
|
||||||
|
|
||||||
|
let idx = result.mentions.indexOf(ref)
|
||||||
|
if (idx !== -1) {
|
||||||
|
result.mentions.splice(idx, 1)
|
||||||
|
}
|
||||||
|
if (ref.author) {
|
||||||
|
let author = result.profiles.find(p => p.pubkey === ref.author)
|
||||||
|
if (author && author.relays) {
|
||||||
|
if (!ref.relays) {
|
||||||
|
ref.relays = []
|
||||||
|
}
|
||||||
|
author.relays.forEach(url => {
|
||||||
|
if (ref.relays!?.indexOf(url) === -1) ref.relays!.push(url)
|
||||||
|
})
|
||||||
|
author.relays = ref.relays
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
result.mentions.forEach(ref => {
|
||||||
|
if (ref!.author) {
|
||||||
|
let author = result.profiles.find(p => p.pubkey === ref.author)
|
||||||
|
if (author && author.relays) {
|
||||||
|
if (!ref.relays) {
|
||||||
|
ref.relays = []
|
||||||
|
}
|
||||||
|
author.relays.forEach(url => {
|
||||||
|
if (ref.relays!.indexOf(url) === -1) ref.relays!.push(url)
|
||||||
|
})
|
||||||
|
author.relays = ref.relays
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|||||||
12
nip11.ts
12
nip11.ts
@@ -68,7 +68,7 @@ export interface BasicRelayInformation {
|
|||||||
* from `[` to `]` and is after UTF-8 serialization (so some
|
* from `[` to `]` and is after UTF-8 serialization (so some
|
||||||
* unicode characters will cost 2-3 bytes). It is equal to
|
* unicode characters will cost 2-3 bytes). It is equal to
|
||||||
* the maximum size of the WebSocket message frame.
|
* the maximum size of the WebSocket message frame.
|
||||||
* @param max_subscription total number of subscriptions
|
* @param max_subscriptions total number of subscriptions
|
||||||
* that may be active on a single websocket connection to
|
* that may be active on a single websocket connection to
|
||||||
* this relay. It's possible that authenticated clients with
|
* this relay. It's possible that authenticated clients with
|
||||||
* a (paid) relationship to the relay may have higher limits.
|
* a (paid) relationship to the relay may have higher limits.
|
||||||
@@ -101,12 +101,17 @@ export interface BasicRelayInformation {
|
|||||||
* authentication to happen before a new connection may
|
* authentication to happen before a new connection may
|
||||||
* perform any other action. Even if set to False,
|
* perform any other action. Even if set to False,
|
||||||
* authentication may be required for specific actions.
|
* authentication may be required for specific actions.
|
||||||
|
* @param restricted_writes: this relay requires some kind
|
||||||
|
* of condition to be fulfilled in order to accept events
|
||||||
|
* (not necessarily, but including
|
||||||
* @param payment_required this relay requires payment
|
* @param payment_required this relay requires payment
|
||||||
* before a new connection may perform any action.
|
* before a new connection may perform any action.
|
||||||
|
* @param created_at_lower_limit: 'created_at' lower limit
|
||||||
|
* @param created_at_upper_limit: 'created_at' upper limit
|
||||||
*/
|
*/
|
||||||
export interface Limitations {
|
export interface Limitations {
|
||||||
max_message_length: number
|
max_message_length: number
|
||||||
max_subscription: number
|
max_subscriptions: number
|
||||||
max_filters: number
|
max_filters: number
|
||||||
max_limit: number
|
max_limit: number
|
||||||
max_subid_length: number
|
max_subid_length: number
|
||||||
@@ -116,6 +121,9 @@ export interface Limitations {
|
|||||||
min_pow_difficulty: number
|
min_pow_difficulty: number
|
||||||
auth_required: boolean
|
auth_required: boolean
|
||||||
payment_required: boolean
|
payment_required: boolean
|
||||||
|
created_at_lower_limit: number
|
||||||
|
created_at_upper_limit: number
|
||||||
|
restricted_writes: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
interface RetentionDetails {
|
interface RetentionDetails {
|
||||||
|
|||||||
@@ -2,9 +2,14 @@ import { test, expect } from 'bun:test'
|
|||||||
import { getPow, minePow } from './nip13.ts'
|
import { getPow, minePow } from './nip13.ts'
|
||||||
|
|
||||||
test('identifies proof-of-work difficulty', async () => {
|
test('identifies proof-of-work difficulty', async () => {
|
||||||
const id = '000006d8c378af1779d2feebc7603a125d99eca0ccf1085959b307f64e5dd358'
|
;[
|
||||||
const difficulty = getPow(id)
|
['000006d8c378af1779d2feebc7603a125d99eca0ccf1085959b307f64e5dd358', 21],
|
||||||
expect(difficulty).toEqual(21)
|
['6bf5b4f434813c64b523d2b0e6efe18f3bd0cbbd0a5effd8ece9e00fd2531996', 1],
|
||||||
|
['00003479309ecdb46b1c04ce129d2709378518588bed6776e60474ebde3159ae', 18],
|
||||||
|
['01a76167d41add96be4959d9e618b7a35f26551d62c43c11e5e64094c6b53c83', 7],
|
||||||
|
['ac4f44bae06a45ebe88cfbd3c66358750159650a26c0d79e8ccaa92457fca4f6', 0],
|
||||||
|
['0000000000000000006cfbd3c66358750159650a26c0d79e8ccaa92457fca4f6', 73],
|
||||||
|
].forEach(([id, diff]) => expect(getPow(id as string)).toEqual(diff as number))
|
||||||
})
|
})
|
||||||
|
|
||||||
test('mines POW for an event', async () => {
|
test('mines POW for an event', async () => {
|
||||||
|
|||||||
24
nip13.ts
24
nip13.ts
@@ -1,15 +1,19 @@
|
|||||||
import { type UnsignedEvent, type Event, getEventHash } from './pure.ts'
|
import { bytesToHex } from '@noble/hashes/utils'
|
||||||
|
import { type UnsignedEvent, type Event } from './pure.ts'
|
||||||
|
import { sha256 } from '@noble/hashes/sha256'
|
||||||
|
|
||||||
|
import { utf8Encoder } from './utils.ts'
|
||||||
|
|
||||||
/** Get POW difficulty from a Nostr hex ID. */
|
/** Get POW difficulty from a Nostr hex ID. */
|
||||||
export function getPow(hex: string): number {
|
export function getPow(hex: string): number {
|
||||||
let count = 0
|
let count = 0
|
||||||
|
|
||||||
for (let i = 0; i < hex.length; i++) {
|
for (let i = 0; i < 64; i += 8) {
|
||||||
const nibble = parseInt(hex[i], 16)
|
const nibble = parseInt(hex.substring(i, i + 8), 16)
|
||||||
if (nibble === 0) {
|
if (nibble === 0) {
|
||||||
count += 4
|
count += 32
|
||||||
} else {
|
} else {
|
||||||
count += Math.clz32(nibble) - 28
|
count += Math.clz32(nibble)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -20,8 +24,6 @@ export function getPow(hex: string): number {
|
|||||||
/**
|
/**
|
||||||
* Mine an event with the desired POW. This function mutates the event.
|
* Mine an event with the desired POW. This function mutates the event.
|
||||||
* Note that this operation is synchronous and should be run in a worker context to avoid blocking the main thread.
|
* Note that this operation is synchronous and should be run in a worker context to avoid blocking the main thread.
|
||||||
*
|
|
||||||
* Adapted from Snort: https://git.v0l.io/Kieran/snort/src/commit/4df6c19248184218c4c03728d61e94dae5f2d90c/packages/system/src/pow-util.ts#L14-L36
|
|
||||||
*/
|
*/
|
||||||
export function minePow(unsigned: UnsignedEvent, difficulty: number): Omit<Event, 'sig'> {
|
export function minePow(unsigned: UnsignedEvent, difficulty: number): Omit<Event, 'sig'> {
|
||||||
let count = 0
|
let count = 0
|
||||||
@@ -41,7 +43,7 @@ export function minePow(unsigned: UnsignedEvent, difficulty: number): Omit<Event
|
|||||||
|
|
||||||
tag[1] = (++count).toString()
|
tag[1] = (++count).toString()
|
||||||
|
|
||||||
event.id = getEventHash(event)
|
event.id = fastEventHash(event)
|
||||||
|
|
||||||
if (getPow(event.id) >= difficulty) {
|
if (getPow(event.id) >= difficulty) {
|
||||||
break
|
break
|
||||||
@@ -50,3 +52,9 @@ export function minePow(unsigned: UnsignedEvent, difficulty: number): Omit<Event
|
|||||||
|
|
||||||
return event
|
return event
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function fastEventHash(evt: UnsignedEvent): string {
|
||||||
|
return bytesToHex(
|
||||||
|
sha256(utf8Encoder.encode(JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]))),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|||||||
97
nip17.test.ts
Normal file
97
nip17.test.ts
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
import { test, expect } from 'bun:test'
|
||||||
|
import { getPublicKey } from './pure.ts'
|
||||||
|
import { decode } from './nip19.ts'
|
||||||
|
import { wrapEvent, wrapManyEvents, unwrapEvent } from './nip17.ts'
|
||||||
|
import { hexToBytes } from '@noble/hashes/utils'
|
||||||
|
|
||||||
|
const senderPrivateKey = decode(`nsec1p0ht6p3wepe47sjrgesyn4m50m6avk2waqudu9rl324cg2c4ufesyp6rdg`).data
|
||||||
|
|
||||||
|
const sk1 = hexToBytes('f09ac9b695d0a4c6daa418fe95b977eea20f54d9545592bc36a4f9e14f3eb840')
|
||||||
|
const sk2 = hexToBytes('5393a825e5892d8e18d4a5ea61ced105e8bb2a106f42876be3a40522e0b13747')
|
||||||
|
|
||||||
|
const recipients = [
|
||||||
|
{ publicKey: getPublicKey(sk1), relayUrl: 'wss://relay1.com' },
|
||||||
|
{ publicKey: getPublicKey(sk2) }, // No relay URL for this recipient
|
||||||
|
]
|
||||||
|
const message = 'Hello, this is a direct message!'
|
||||||
|
const conversationTitle = 'Private Group Conversation' // Optional
|
||||||
|
const replyTo = { eventId: 'previousEventId123' } // Optional, for replies
|
||||||
|
|
||||||
|
const wrappedEvent = wrapEvent(senderPrivateKey, recipients[0], message, conversationTitle, replyTo)
|
||||||
|
|
||||||
|
test('wrapEvent', () => {
|
||||||
|
const expected = {
|
||||||
|
content: '',
|
||||||
|
id: '',
|
||||||
|
created_at: 1728537932,
|
||||||
|
kind: 1059,
|
||||||
|
pubkey: '',
|
||||||
|
sig: '',
|
||||||
|
tags: [['p', 'b60849e5aae4113b236f9deb34f6f85605b4c53930651309a0d60c7ea721aad0']],
|
||||||
|
[Symbol('verified')]: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(wrappedEvent.kind).toEqual(expected.kind)
|
||||||
|
expect(wrappedEvent.tags).toEqual(expected.tags)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('wrapManyEvents', () => {
|
||||||
|
const expected = [
|
||||||
|
{
|
||||||
|
kind: 1059,
|
||||||
|
content: '',
|
||||||
|
created_at: 1729581521,
|
||||||
|
tags: [['p', '611df01bfcf85c26ae65453b772d8f1dfd25c264621c0277e1fc1518686faef9']],
|
||||||
|
pubkey: '',
|
||||||
|
id: '',
|
||||||
|
sig: '',
|
||||||
|
[Symbol('verified')]: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: 1059,
|
||||||
|
content: '',
|
||||||
|
created_at: 1729594619,
|
||||||
|
tags: [['p', 'b60849e5aae4113b236f9deb34f6f85605b4c53930651309a0d60c7ea721aad0']],
|
||||||
|
pubkey: '',
|
||||||
|
id: '',
|
||||||
|
sig: '',
|
||||||
|
[Symbol('verified')]: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: 1059,
|
||||||
|
content: '',
|
||||||
|
created_at: 1729560014,
|
||||||
|
tags: [['p', '36f7288c84d85ca6aa189dc3581d63ce140b7eeef5ae759421c5b5a3627312db']],
|
||||||
|
pubkey: '',
|
||||||
|
id: '',
|
||||||
|
sig: '',
|
||||||
|
[Symbol('verified')]: true,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
const wrappedEvents = wrapManyEvents(senderPrivateKey, recipients, message, conversationTitle, replyTo)
|
||||||
|
|
||||||
|
wrappedEvents.forEach((event, index) => {
|
||||||
|
expect(event.kind).toEqual(expected[index].kind)
|
||||||
|
expect(event.tags).toEqual(expected[index].tags)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('unwrapEvent', () => {
|
||||||
|
const expected = {
|
||||||
|
kind: 14,
|
||||||
|
content: 'Hello, this is a direct message!',
|
||||||
|
pubkey: '611df01bfcf85c26ae65453b772d8f1dfd25c264621c0277e1fc1518686faef9',
|
||||||
|
tags: [
|
||||||
|
['p', 'b60849e5aae4113b236f9deb34f6f85605b4c53930651309a0d60c7ea721aad0', 'wss://relay1.com'],
|
||||||
|
['e', 'previousEventId123', '', 'reply'],
|
||||||
|
['subject', 'Private Group Conversation'],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const result = unwrapEvent(wrappedEvent, sk1)
|
||||||
|
|
||||||
|
expect(result.kind).toEqual(expected.kind)
|
||||||
|
expect(result.content).toEqual(expected.content)
|
||||||
|
expect(result.pubkey).toEqual(expected.pubkey)
|
||||||
|
expect(result.tags).toEqual(expected.tags)
|
||||||
|
})
|
||||||
77
nip17.ts
Normal file
77
nip17.ts
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
import { PrivateDirectMessage } from './kinds.ts'
|
||||||
|
import { EventTemplate, NostrEvent, getPublicKey } from './pure.ts'
|
||||||
|
import * as nip59 from './nip59.ts'
|
||||||
|
|
||||||
|
type Recipient = {
|
||||||
|
publicKey: string
|
||||||
|
relayUrl?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
type ReplyTo = {
|
||||||
|
eventId: string
|
||||||
|
relayUrl?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function createEvent(
|
||||||
|
recipients: Recipient | Recipient[],
|
||||||
|
message: string,
|
||||||
|
conversationTitle?: string,
|
||||||
|
replyTo?: ReplyTo,
|
||||||
|
): EventTemplate {
|
||||||
|
const baseEvent: EventTemplate = {
|
||||||
|
created_at: Math.ceil(Date.now() / 1000),
|
||||||
|
kind: PrivateDirectMessage,
|
||||||
|
tags: [],
|
||||||
|
content: message,
|
||||||
|
}
|
||||||
|
|
||||||
|
const recipientsArray = Array.isArray(recipients) ? recipients : [recipients]
|
||||||
|
|
||||||
|
recipientsArray.forEach(({ publicKey, relayUrl }) => {
|
||||||
|
baseEvent.tags.push(relayUrl ? ['p', publicKey, relayUrl] : ['p', publicKey])
|
||||||
|
})
|
||||||
|
|
||||||
|
if (replyTo) {
|
||||||
|
baseEvent.tags.push(['e', replyTo.eventId, replyTo.relayUrl || '', 'reply'])
|
||||||
|
}
|
||||||
|
|
||||||
|
if (conversationTitle) {
|
||||||
|
baseEvent.tags.push(['subject', conversationTitle])
|
||||||
|
}
|
||||||
|
|
||||||
|
return baseEvent
|
||||||
|
}
|
||||||
|
|
||||||
|
export function wrapEvent(
|
||||||
|
senderPrivateKey: Uint8Array,
|
||||||
|
recipient: Recipient,
|
||||||
|
message: string,
|
||||||
|
conversationTitle?: string,
|
||||||
|
replyTo?: ReplyTo,
|
||||||
|
): NostrEvent {
|
||||||
|
const event = createEvent(recipient, message, conversationTitle, replyTo)
|
||||||
|
return nip59.wrapEvent(event, senderPrivateKey, recipient.publicKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function wrapManyEvents(
|
||||||
|
senderPrivateKey: Uint8Array,
|
||||||
|
recipients: Recipient[],
|
||||||
|
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)
|
||||||
|
|
||||||
|
// 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
|
||||||
|
|
||||||
|
export const unwrapManyEvents = nip59.unwrapManyEvents
|
||||||
141
nip19.test.ts
141
nip19.test.ts
@@ -1,16 +1,16 @@
|
|||||||
import { test, expect } from 'bun:test'
|
import { test, expect, describe } from 'bun:test'
|
||||||
import { generateSecretKey, getPublicKey } from './pure.ts'
|
import { generateSecretKey, getPublicKey } from './pure.ts'
|
||||||
import {
|
import {
|
||||||
decode,
|
decode,
|
||||||
naddrEncode,
|
naddrEncode,
|
||||||
nprofileEncode,
|
nprofileEncode,
|
||||||
npubEncode,
|
npubEncode,
|
||||||
nrelayEncode,
|
|
||||||
nsecEncode,
|
nsecEncode,
|
||||||
neventEncode,
|
neventEncode,
|
||||||
type AddressPointer,
|
type AddressPointer,
|
||||||
type ProfilePointer,
|
type ProfilePointer,
|
||||||
EventPointer,
|
EventPointer,
|
||||||
|
NostrTypeGuard,
|
||||||
} from './nip19.ts'
|
} from './nip19.ts'
|
||||||
|
|
||||||
test('encode and decode nsec', () => {
|
test('encode and decode nsec', () => {
|
||||||
@@ -153,11 +153,134 @@ test('decode naddr from go-nostr with different TLV ordering', () => {
|
|||||||
expect(pointer.identifier).toEqual('banana')
|
expect(pointer.identifier).toEqual('banana')
|
||||||
})
|
})
|
||||||
|
|
||||||
test('encode and decode nrelay', () => {
|
describe('NostrTypeGuard', () => {
|
||||||
let url = 'wss://relay.nostr.example'
|
test('isNProfile', () => {
|
||||||
let nrelay = nrelayEncode(url)
|
const is = NostrTypeGuard.isNProfile('nprofile1qqsvc6ulagpn7kwrcwdqgp797xl7usumqa6s3kgcelwq6m75x8fe8yc5usxdg')
|
||||||
expect(nrelay).toMatch(/nrelay1\w+/)
|
|
||||||
let { type, data } = decode(nrelay)
|
expect(is).toBeTrue()
|
||||||
expect(type).toEqual('nrelay')
|
})
|
||||||
expect(data).toEqual(url)
|
|
||||||
|
test('isNProfile invalid nprofile', () => {
|
||||||
|
const is = NostrTypeGuard.isNProfile('nprofile1qqsvc6ulagpn7kwrcwdqgp797xl7usumqa6s3kgcelwq6m75x8fe8yc5usxãg')
|
||||||
|
|
||||||
|
expect(is).toBeFalse()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('isNProfile with invalid nprofile', () => {
|
||||||
|
const is = NostrTypeGuard.isNProfile('nsec1lqw6zqyanj9mz8gwhdam6tqge42vptz4zg93qsfej440xm5h5esqya0juv')
|
||||||
|
|
||||||
|
expect(is).toBeFalse()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('isNEvent', () => {
|
||||||
|
const is = NostrTypeGuard.isNEvent(
|
||||||
|
'nevent1qqst8cujky046negxgwwm5ynqwn53t8aqjr6afd8g59nfqwxpdhylpcpzamhxue69uhhyetvv9ujuetcv9khqmr99e3k7mg8arnc9',
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(is).toBeTrue()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('isNEvent with invalid nevent', () => {
|
||||||
|
const is = NostrTypeGuard.isNEvent(
|
||||||
|
'nevent1qqst8cujky046negxgwwm5ynqwn53t8aqjr6afd8g59nfqwxpdhylpcpzamhxue69uhhyetvv9ujuetcv9khqmr99e3k7mg8ãrnc9',
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(is).toBeFalse()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('isNEvent with invalid nevent', () => {
|
||||||
|
const is = NostrTypeGuard.isNEvent('nprofile1qqsvc6ulagpn7kwrcwdqgp797xl7usumqa6s3kgcelwq6m75x8fe8yc5usxdg')
|
||||||
|
|
||||||
|
expect(is).toBeFalse()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('isNAddr', () => {
|
||||||
|
const is = NostrTypeGuard.isNAddr(
|
||||||
|
'naddr1qqxnzdesxqmnxvpexqunzvpcqyt8wumn8ghj7un9d3shjtnwdaehgu3wvfskueqzypve7elhmamff3sr5mgxxms4a0rppkmhmn7504h96pfcdkpplvl2jqcyqqq823cnmhuld',
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(is).toBeTrue()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('isNAddr with invalid nadress', () => {
|
||||||
|
const is = NostrTypeGuard.isNAddr('nsec1lqw6zqyanj9mz8gwhdam6tqge42vptz4zg93qsfej440xm5h5esqya0juv')
|
||||||
|
|
||||||
|
expect(is).toBeFalse()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('isNSec', () => {
|
||||||
|
const is = NostrTypeGuard.isNSec('nsec1lqw6zqyanj9mz8gwhdam6tqge42vptz4zg93qsfej440xm5h5esqya0juv')
|
||||||
|
|
||||||
|
expect(is).toBeTrue()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('isNSec with invalid nsec', () => {
|
||||||
|
const is = NostrTypeGuard.isNSec('nsec1lqw6zqyanj9mz8gwhdam6tqge42vptz4zg93qsfej440xm5h5esqya0juã')
|
||||||
|
|
||||||
|
expect(is).toBeFalse()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('isNSec with invalid nsec', () => {
|
||||||
|
const is = NostrTypeGuard.isNSec('nprofile1qqsvc6ulagpn7kwrcwdqgp797xl7usumqa6s3kgcelwq6m75x8fe8yc5usxdg')
|
||||||
|
|
||||||
|
expect(is).toBeFalse()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('isNPub', () => {
|
||||||
|
const is = NostrTypeGuard.isNPub('npub1jz5mdljkmffmqjshpyjgqgrhdkuxd9ztzasv8xeh5q92fv33sjgqy4pats')
|
||||||
|
|
||||||
|
expect(is).toBeTrue()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('isNPub with invalid npub', () => {
|
||||||
|
const is = NostrTypeGuard.isNPub('npub1jz5mdljkmffmqjshpyjgqgrhdkuxd9ztzãsv8xeh5q92fv33sjgqy4pats')
|
||||||
|
|
||||||
|
expect(is).toBeFalse()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('isNPub with invalid npub', () => {
|
||||||
|
const is = NostrTypeGuard.isNPub('nsec1lqw6zqyanj9mz8gwhdam6tqge42vptz4zg93qsfej440xm5h5esqya0juv')
|
||||||
|
|
||||||
|
expect(is).toBeFalse()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('isNote', () => {
|
||||||
|
const is = NostrTypeGuard.isNote('note1gmtnz6q2m55epmlpe3semjdcq987av3jvx4emmjsa8g3s9x7tg4sclreky')
|
||||||
|
|
||||||
|
expect(is).toBeTrue()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('isNote with invalid note', () => {
|
||||||
|
const is = NostrTypeGuard.isNote('note1gmtnz6q2m55epmlpe3semjdcq987av3jvx4emmjsa8g3s9x7tg4sçlreky')
|
||||||
|
|
||||||
|
expect(is).toBeFalse()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('isNote with invalid note', () => {
|
||||||
|
const is = NostrTypeGuard.isNote('npub1jz5mdljkmffmqjshpyjgqgrhdkuxd9ztzasv8xeh5q92fv33sjgqy4pats')
|
||||||
|
|
||||||
|
expect(is).toBeFalse()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('isNcryptsec', () => {
|
||||||
|
const is = NostrTypeGuard.isNcryptsec(
|
||||||
|
'ncryptsec1qgg9947rlpvqu76pj5ecreduf9jxhselq2nae2kghhvd5g7dgjtcxfqtd67p9m0w57lspw8gsq6yphnm8623nsl8xn9j4jdzz84zm3frztj3z7s35vpzmqf6ksu8r89qk5z2zxfmu5gv8th8wclt0h4p',
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(is).toBeTrue()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('isNcryptsec with invalid ncrytpsec', () => {
|
||||||
|
const is = NostrTypeGuard.isNcryptsec(
|
||||||
|
'ncryptsec1qgg9947rlpvqu76pj5ecreduf9jxhselq2nae2kghhvd5g7dgjtcxfqtd67p9m0w57lspw8gsq6yphnm8623nsã8xn9j4jdzz84zm3frztj3z7s35vpzmqf6ksu8r89qk5z2zxfmu5gv8th8wclt0h4p',
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(is).toBeFalse()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('isNcryptsec with invalid ncrytpsec', () => {
|
||||||
|
const is = NostrTypeGuard.isNcryptsec('note1gmtnz6q2m55epmlpe3semjdcq987av3jvx4emmjsa8g3s9x7tg4sçlreky')
|
||||||
|
|
||||||
|
expect(is).toBeFalse()
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
48
nip19.ts
48
nip19.ts
@@ -3,6 +3,24 @@ import { bech32 } from '@scure/base'
|
|||||||
|
|
||||||
import { utf8Decoder, utf8Encoder } from './utils.ts'
|
import { utf8Decoder, utf8Encoder } from './utils.ts'
|
||||||
|
|
||||||
|
export type NProfile = `nprofile1${string}`
|
||||||
|
export type NEvent = `nevent1${string}`
|
||||||
|
export type NAddr = `naddr1${string}`
|
||||||
|
export type NSec = `nsec1${string}`
|
||||||
|
export type NPub = `npub1${string}`
|
||||||
|
export type Note = `note1${string}`
|
||||||
|
export type Ncryptsec = `ncryptsec1${string}`
|
||||||
|
|
||||||
|
export const NostrTypeGuard = {
|
||||||
|
isNProfile: (value?: string | null): value is NProfile => /^nprofile1[a-z\d]+$/.test(value || ''),
|
||||||
|
isNEvent: (value?: string | null): value is NEvent => /^nevent1[a-z\d]+$/.test(value || ''),
|
||||||
|
isNAddr: (value?: string | null): value is NAddr => /^naddr1[a-z\d]+$/.test(value || ''),
|
||||||
|
isNSec: (value?: string | null): value is NSec => /^nsec1[a-z\d]{58}$/.test(value || ''),
|
||||||
|
isNPub: (value?: string | null): value is NPub => /^npub1[a-z\d]{58}$/.test(value || ''),
|
||||||
|
isNote: (value?: string | null): value is Note => /^note1[a-z\d]+$/.test(value || ''),
|
||||||
|
isNcryptsec: (value?: string | null): value is Ncryptsec => /^ncryptsec1[a-z\d]+$/.test(value || ''),
|
||||||
|
}
|
||||||
|
|
||||||
export const Bech32MaxSize = 5000
|
export const Bech32MaxSize = 5000
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -45,7 +63,6 @@ export type AddressPointer = {
|
|||||||
|
|
||||||
type Prefixes = {
|
type Prefixes = {
|
||||||
nprofile: ProfilePointer
|
nprofile: ProfilePointer
|
||||||
nrelay: string
|
|
||||||
nevent: EventPointer
|
nevent: EventPointer
|
||||||
naddr: AddressPointer
|
naddr: AddressPointer
|
||||||
nsec: Uint8Array
|
nsec: Uint8Array
|
||||||
@@ -119,16 +136,6 @@ export function decode(nip19: string): DecodeResult {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
case 'nrelay': {
|
|
||||||
let tlv = parseTLV(data)
|
|
||||||
if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nrelay')
|
|
||||||
|
|
||||||
return {
|
|
||||||
type: 'nrelay',
|
|
||||||
data: utf8Decoder.decode(tlv[0][0]),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'nsec':
|
case 'nsec':
|
||||||
return { type: prefix, data }
|
return { type: prefix, data }
|
||||||
|
|
||||||
@@ -158,15 +165,15 @@ function parseTLV(data: Uint8Array): TLV {
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
export function nsecEncode(key: Uint8Array): `nsec1${string}` {
|
export function nsecEncode(key: Uint8Array): NSec {
|
||||||
return encodeBytes('nsec', key)
|
return encodeBytes('nsec', key)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function npubEncode(hex: string): `npub1${string}` {
|
export function npubEncode(hex: string): NPub {
|
||||||
return encodeBytes('npub', hexToBytes(hex))
|
return encodeBytes('npub', hexToBytes(hex))
|
||||||
}
|
}
|
||||||
|
|
||||||
export function noteEncode(hex: string): `note1${string}` {
|
export function noteEncode(hex: string): Note {
|
||||||
return encodeBytes('note', hexToBytes(hex))
|
return encodeBytes('note', hexToBytes(hex))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,7 +186,7 @@ export function encodeBytes<Prefix extends string>(prefix: Prefix, bytes: Uint8A
|
|||||||
return encodeBech32(prefix, bytes)
|
return encodeBech32(prefix, bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function nprofileEncode(profile: ProfilePointer): `nprofile1${string}` {
|
export function nprofileEncode(profile: ProfilePointer): NProfile {
|
||||||
let data = encodeTLV({
|
let data = encodeTLV({
|
||||||
0: [hexToBytes(profile.pubkey)],
|
0: [hexToBytes(profile.pubkey)],
|
||||||
1: (profile.relays || []).map(url => utf8Encoder.encode(url)),
|
1: (profile.relays || []).map(url => utf8Encoder.encode(url)),
|
||||||
@@ -187,7 +194,7 @@ export function nprofileEncode(profile: ProfilePointer): `nprofile1${string}` {
|
|||||||
return encodeBech32('nprofile', data)
|
return encodeBech32('nprofile', data)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function neventEncode(event: EventPointer): `nevent1${string}` {
|
export function neventEncode(event: EventPointer): NEvent {
|
||||||
let kindArray
|
let kindArray
|
||||||
if (event.kind !== undefined) {
|
if (event.kind !== undefined) {
|
||||||
kindArray = integerToUint8Array(event.kind)
|
kindArray = integerToUint8Array(event.kind)
|
||||||
@@ -203,7 +210,7 @@ export function neventEncode(event: EventPointer): `nevent1${string}` {
|
|||||||
return encodeBech32('nevent', data)
|
return encodeBech32('nevent', data)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function naddrEncode(addr: AddressPointer): `naddr1${string}` {
|
export function naddrEncode(addr: AddressPointer): NAddr {
|
||||||
let kind = new ArrayBuffer(4)
|
let kind = new ArrayBuffer(4)
|
||||||
new DataView(kind).setUint32(0, addr.kind, false)
|
new DataView(kind).setUint32(0, addr.kind, false)
|
||||||
|
|
||||||
@@ -216,13 +223,6 @@ export function naddrEncode(addr: AddressPointer): `naddr1${string}` {
|
|||||||
return encodeBech32('naddr', data)
|
return encodeBech32('naddr', data)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function nrelayEncode(url: string): `nrelay1${string}` {
|
|
||||||
let data = encodeTLV({
|
|
||||||
0: [utf8Encoder.encode(url)],
|
|
||||||
})
|
|
||||||
return encodeBech32('nrelay', data)
|
|
||||||
}
|
|
||||||
|
|
||||||
function encodeTLV(tlv: TLV): Uint8Array {
|
function encodeTLV(tlv: TLV): Uint8Array {
|
||||||
let entries: Uint8Array[] = []
|
let entries: Uint8Array[] = []
|
||||||
|
|
||||||
|
|||||||
10
nip28.ts
10
nip28.ts
@@ -1,5 +1,11 @@
|
|||||||
import { Event, finalizeEvent } from './pure.ts'
|
import { Event, finalizeEvent } from './pure.ts'
|
||||||
import { ChannelCreation, ChannelHideMessage, ChannelMessage, ChannelMetadata, ChannelMuteUser } from './kinds.ts'
|
import {
|
||||||
|
ChannelCreation,
|
||||||
|
ChannelHideMessage,
|
||||||
|
ChannelMessage,
|
||||||
|
ChannelMetadata as KindChannelMetadata,
|
||||||
|
ChannelMuteUser,
|
||||||
|
} from './kinds.ts'
|
||||||
|
|
||||||
export interface ChannelMetadata {
|
export interface ChannelMetadata {
|
||||||
name: string
|
name: string
|
||||||
@@ -78,7 +84,7 @@ export const channelMetadataEvent = (t: ChannelMetadataEventTemplate, privateKey
|
|||||||
|
|
||||||
return finalizeEvent(
|
return finalizeEvent(
|
||||||
{
|
{
|
||||||
kind: ChannelMetadata,
|
kind: KindChannelMetadata,
|
||||||
tags: [['e', t.channel_create_event_id], ...(t.tags ?? [])],
|
tags: [['e', t.channel_create_event_id], ...(t.tags ?? [])],
|
||||||
content: content,
|
content: content,
|
||||||
created_at: t.created_at,
|
created_at: t.created_at,
|
||||||
|
|||||||
684
nip29.ts
684
nip29.ts
@@ -1,80 +1,514 @@
|
|||||||
import { AbstractSimplePool } from './abstract-pool.ts'
|
import { AbstractSimplePool } from './abstract-pool.ts'
|
||||||
import { Subscription } from './abstract-relay.ts'
|
import { Subscription } from './abstract-relay.ts'
|
||||||
import { decode } from './nip19.ts'
|
import type { Event, EventTemplate } from './core.ts'
|
||||||
import type { Event } from './core.ts'
|
import { fetchRelayInformation, RelayInformation } from './nip11.ts'
|
||||||
import { fetchRelayInformation } from './nip11.ts'
|
import { AddressPointer, decode } from './nip19.ts'
|
||||||
import { normalizeURL } from './utils.ts'
|
import { normalizeURL } from './utils.ts'
|
||||||
import { AddressPointer } from './nip19.ts'
|
|
||||||
|
|
||||||
export function subscribeRelayGroups(
|
/**
|
||||||
pool: AbstractSimplePool,
|
* Represents a NIP29 group.
|
||||||
url: string,
|
*/
|
||||||
params: {
|
export type Group = {
|
||||||
ongroups: (_: Group[]) => void
|
relay: string
|
||||||
onerror: (_: Error) => void
|
metadata: GroupMetadata
|
||||||
onconnect?: () => void
|
admins?: GroupAdmin[]
|
||||||
},
|
members?: GroupMember[]
|
||||||
): () => void {
|
reference: GroupReference
|
||||||
let normalized = normalizeURL(url)
|
|
||||||
let sub: Subscription
|
|
||||||
let groups: Group[] = []
|
|
||||||
|
|
||||||
fetchRelayInformation(normalized)
|
|
||||||
.then(async info => {
|
|
||||||
let rl = await pool.ensureRelay(normalized)
|
|
||||||
params.onconnect?.()
|
|
||||||
sub = rl.prepareSubscription(
|
|
||||||
[
|
|
||||||
{
|
|
||||||
kinds: [39000],
|
|
||||||
limit: 50,
|
|
||||||
authors: [info.pubkey],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
{
|
|
||||||
onevent(event: Event) {
|
|
||||||
groups.push(parseGroup(event, normalized))
|
|
||||||
},
|
|
||||||
oneose() {
|
|
||||||
params.ongroups(groups)
|
|
||||||
sub.onevent = (event: Event) => {
|
|
||||||
groups.push(parseGroup(event, normalized))
|
|
||||||
params.ongroups(groups)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
)
|
|
||||||
sub.fire()
|
|
||||||
})
|
|
||||||
.catch(params.onerror)
|
|
||||||
|
|
||||||
return () => sub.close()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function loadGroup(pool: AbstractSimplePool, gr: GroupReference): Promise<Group> {
|
/**
|
||||||
let normalized = normalizeURL(gr.host)
|
* Represents the metadata for a NIP29 group.
|
||||||
|
*/
|
||||||
let info = await fetchRelayInformation(normalized)
|
export type GroupMetadata = {
|
||||||
let event = await pool.get([normalized], {
|
id: string
|
||||||
kinds: [39000],
|
pubkey: string
|
||||||
authors: [info.pubkey],
|
name?: string
|
||||||
'#d': [gr.id],
|
picture?: string
|
||||||
})
|
about?: string
|
||||||
if (!event) throw new Error(`group '${gr.id}' not found on ${gr.host}`)
|
isPublic?: boolean
|
||||||
return parseGroup(event, normalized)
|
isOpen?: boolean
|
||||||
}
|
|
||||||
|
|
||||||
export async function loadGroupFromCode(pool: AbstractSimplePool, code: string): Promise<Group> {
|
|
||||||
let gr = parseGroupCode(code)
|
|
||||||
if (!gr) throw new Error(`code "${code}" does not identify a group`)
|
|
||||||
return loadGroup(pool, gr)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents a NIP29 group reference.
|
||||||
|
*/
|
||||||
export type GroupReference = {
|
export type GroupReference = {
|
||||||
id: string
|
id: string
|
||||||
host: string
|
host: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents a NIP29 group member.
|
||||||
|
*/
|
||||||
|
export type GroupMember = {
|
||||||
|
pubkey: string
|
||||||
|
label?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents a NIP29 group admin.
|
||||||
|
*/
|
||||||
|
export type GroupAdmin = {
|
||||||
|
pubkey: string
|
||||||
|
label?: string
|
||||||
|
permissions: GroupAdminPermission[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents the permissions that a NIP29 group admin can have.
|
||||||
|
*/
|
||||||
|
export enum GroupAdminPermission {
|
||||||
|
AddUser = 'add-user',
|
||||||
|
EditMetadata = 'edit-metadata',
|
||||||
|
DeleteEvent = 'delete-event',
|
||||||
|
RemoveUser = 'remove-user',
|
||||||
|
AddPermission = 'add-permission',
|
||||||
|
RemovePermission = 'remove-permission',
|
||||||
|
EditGroupStatus = 'edit-group-status',
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates a group metadata event template.
|
||||||
|
*
|
||||||
|
* @param group - The group object.
|
||||||
|
* @returns An event template with the generated group metadata that can be signed later.
|
||||||
|
*/
|
||||||
|
export function generateGroupMetadataEventTemplate(group: Group): EventTemplate {
|
||||||
|
const tags: string[][] = [['d', group.metadata.id]]
|
||||||
|
group.metadata.name && tags.push(['name', group.metadata.name])
|
||||||
|
group.metadata.picture && tags.push(['picture', group.metadata.picture])
|
||||||
|
group.metadata.about && tags.push(['about', group.metadata.about])
|
||||||
|
group.metadata.isPublic && tags.push(['public'])
|
||||||
|
group.metadata.isOpen && tags.push(['open'])
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: '',
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
kind: 39000,
|
||||||
|
tags,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates a group metadata event.
|
||||||
|
*
|
||||||
|
* @param event - The event to validate.
|
||||||
|
* @returns A boolean indicating whether the event is valid.
|
||||||
|
*/
|
||||||
|
export function validateGroupMetadataEvent(event: Event): boolean {
|
||||||
|
if (event.kind !== 39000) return false
|
||||||
|
|
||||||
|
if (!event.pubkey) 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 event template for group admins.
|
||||||
|
*
|
||||||
|
* @param group - The group object.
|
||||||
|
* @param admins - An array of group admins.
|
||||||
|
* @returns The generated event template with the group admins that can be signed later.
|
||||||
|
*/
|
||||||
|
export function generateGroupAdminsEventTemplate(group: Group, admins: GroupAdmin[]): EventTemplate {
|
||||||
|
const tags: string[][] = [['d', group.metadata.id]]
|
||||||
|
for (const admin of admins) {
|
||||||
|
tags.push(['p', admin.pubkey, admin.label || '', ...admin.permissions])
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: '',
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
kind: 39001,
|
||||||
|
tags,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates a group admins event.
|
||||||
|
*
|
||||||
|
* @param event - The event to validate.
|
||||||
|
* @returns True if the event is valid, false otherwise.
|
||||||
|
*/
|
||||||
|
export function validateGroupAdminsEvent(event: Event): boolean {
|
||||||
|
if (event.kind !== 39001) return false
|
||||||
|
|
||||||
|
const requiredTags = ['d'] as const
|
||||||
|
for (const tag of requiredTags) {
|
||||||
|
if (!event.tags.find(([t]) => t == tag)) return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate permissions
|
||||||
|
for (const [tag, _value, _label, ...permissions] of event.tags) {
|
||||||
|
if (tag !== 'p') continue
|
||||||
|
|
||||||
|
for (let i = 0; i < permissions.length; i += 1) {
|
||||||
|
if (typeof permissions[i] !== 'string') return false
|
||||||
|
|
||||||
|
// validate permission name from the GroupAdminPermission enum
|
||||||
|
if (!Object.values(GroupAdminPermission).includes(permissions[i] as GroupAdminPermission)) return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates an event template for a group with its members.
|
||||||
|
*
|
||||||
|
* @param group - The group object.
|
||||||
|
* @param members - An array of group members.
|
||||||
|
* @returns The generated event template with the group members that can be signed later.
|
||||||
|
*/
|
||||||
|
export function generateGroupMembersEventTemplate(group: Group, members: GroupMember[]): EventTemplate {
|
||||||
|
const tags: string[][] = [['d', group.metadata.id]]
|
||||||
|
for (const member of members) {
|
||||||
|
tags.push(['p', member.pubkey, member.label || ''])
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: '',
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
kind: 39002,
|
||||||
|
tags,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates a group members event.
|
||||||
|
*
|
||||||
|
* @param event - The event to validate.
|
||||||
|
* @returns Returns `true` if the event is a valid group members event, `false` otherwise.
|
||||||
|
*/
|
||||||
|
export function validateGroupMembersEvent(event: Event): boolean {
|
||||||
|
if (event.kind !== 39002) return false
|
||||||
|
|
||||||
|
const requiredTags = ['d'] as const
|
||||||
|
for (const tag of requiredTags) {
|
||||||
|
if (!event.tags.find(([t]) => t == tag)) return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the normalized relay URL based on the provided group reference.
|
||||||
|
*
|
||||||
|
* @param groupReference - The group reference object containing the host.
|
||||||
|
* @returns The normalized relay URL.
|
||||||
|
*/
|
||||||
|
export function getNormalizedRelayURLByGroupReference(groupReference: GroupReference): string {
|
||||||
|
return normalizeURL(groupReference.host)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetches relay information by group reference.
|
||||||
|
*
|
||||||
|
* @param groupReference The group reference.
|
||||||
|
* @returns A promise that resolves to the relay information.
|
||||||
|
*/
|
||||||
|
export async function fetchRelayInformationByGroupReference(groupReference: GroupReference): Promise<RelayInformation> {
|
||||||
|
const normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference)
|
||||||
|
|
||||||
|
return fetchRelayInformation(normalizedRelayURL)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetches the group metadata event from the specified pool.
|
||||||
|
* If the normalizedRelayURL is not provided, it will be obtained using the groupReference.
|
||||||
|
* If the relayInformation is not provided, it will be fetched using the normalizedRelayURL.
|
||||||
|
*
|
||||||
|
* @param {Object} options - The options object.
|
||||||
|
* @param {AbstractSimplePool} options.pool - The pool to fetch the group metadata event from.
|
||||||
|
* @param {GroupReference} options.groupReference - The reference to the group.
|
||||||
|
* @param {string} [options.normalizedRelayURL] - The normalized URL of the relay.
|
||||||
|
* @param {RelayInformation} [options.relayInformation] - The relay information object.
|
||||||
|
* @returns {Promise<Event>} The group metadata event that can be parsed later to get the group metadata object.
|
||||||
|
* @throws {Error} If the group is not found on the specified relay.
|
||||||
|
*/
|
||||||
|
export async function fetchGroupMetadataEvent({
|
||||||
|
pool,
|
||||||
|
groupReference,
|
||||||
|
relayInformation,
|
||||||
|
normalizedRelayURL,
|
||||||
|
}: {
|
||||||
|
pool: AbstractSimplePool
|
||||||
|
groupReference: GroupReference
|
||||||
|
normalizedRelayURL?: string
|
||||||
|
relayInformation?: RelayInformation
|
||||||
|
}): Promise<Event> {
|
||||||
|
if (!normalizedRelayURL) {
|
||||||
|
normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!relayInformation) {
|
||||||
|
relayInformation = await fetchRelayInformation(normalizedRelayURL)
|
||||||
|
}
|
||||||
|
|
||||||
|
const groupMetadataEvent = await pool.get([normalizedRelayURL], {
|
||||||
|
kinds: [39000],
|
||||||
|
authors: [relayInformation.pubkey],
|
||||||
|
'#d': [groupReference.id],
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!groupMetadataEvent) throw new Error(`group '${groupReference.id}' not found on ${normalizedRelayURL}`)
|
||||||
|
|
||||||
|
return groupMetadataEvent
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses a group metadata event and returns the corresponding GroupMetadata object.
|
||||||
|
*
|
||||||
|
* @param event - The event to parse.
|
||||||
|
* @returns The parsed GroupMetadata object.
|
||||||
|
* @throws An error if the group metadata event is invalid.
|
||||||
|
*/
|
||||||
|
export function parseGroupMetadataEvent(event: Event): GroupMetadata {
|
||||||
|
if (!validateGroupMetadataEvent(event)) throw new Error('invalid group metadata event')
|
||||||
|
|
||||||
|
const metadata: GroupMetadata = {
|
||||||
|
id: '',
|
||||||
|
pubkey: event.pubkey,
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const [tag, value] of event.tags) {
|
||||||
|
switch (tag) {
|
||||||
|
case 'd':
|
||||||
|
metadata.id = value
|
||||||
|
break
|
||||||
|
case 'name':
|
||||||
|
metadata.name = value
|
||||||
|
break
|
||||||
|
case 'picture':
|
||||||
|
metadata.picture = value
|
||||||
|
break
|
||||||
|
case 'about':
|
||||||
|
metadata.about = value
|
||||||
|
break
|
||||||
|
case 'public':
|
||||||
|
metadata.isPublic = true
|
||||||
|
break
|
||||||
|
case 'open':
|
||||||
|
metadata.isOpen = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return metadata
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetches the group admins event from the specified pool.
|
||||||
|
* If the normalizedRelayURL is not provided, it will be obtained from the groupReference.
|
||||||
|
* If the relayInformation is not provided, it will be fetched using the normalizedRelayURL.
|
||||||
|
*
|
||||||
|
* @param {Object} options - The options object.
|
||||||
|
* @param {AbstractSimplePool} options.pool - The pool to fetch the group admins event from.
|
||||||
|
* @param {GroupReference} options.groupReference - The reference to the group.
|
||||||
|
* @param {string} [options.normalizedRelayURL] - The normalized relay URL.
|
||||||
|
* @param {RelayInformation} [options.relayInformation] - The relay information.
|
||||||
|
* @returns {Promise<Event>} The group admins event that can be parsed later to get the group admins object.
|
||||||
|
* @throws {Error} If the group admins event is not found on the specified relay.
|
||||||
|
*/
|
||||||
|
export async function fetchGroupAdminsEvent({
|
||||||
|
pool,
|
||||||
|
groupReference,
|
||||||
|
relayInformation,
|
||||||
|
normalizedRelayURL,
|
||||||
|
}: {
|
||||||
|
pool: AbstractSimplePool
|
||||||
|
groupReference: GroupReference
|
||||||
|
normalizedRelayURL?: string
|
||||||
|
relayInformation?: RelayInformation
|
||||||
|
}): Promise<Event> {
|
||||||
|
if (!normalizedRelayURL) {
|
||||||
|
normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!relayInformation) {
|
||||||
|
relayInformation = await fetchRelayInformation(normalizedRelayURL)
|
||||||
|
}
|
||||||
|
|
||||||
|
const groupAdminsEvent = await pool.get([normalizedRelayURL], {
|
||||||
|
kinds: [39001],
|
||||||
|
authors: [relayInformation.pubkey],
|
||||||
|
'#d': [groupReference.id],
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!groupAdminsEvent) throw new Error(`admins for group '${groupReference.id}' not found on ${normalizedRelayURL}`)
|
||||||
|
|
||||||
|
return groupAdminsEvent
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses a group admins event and returns an array of GroupAdmin objects.
|
||||||
|
*
|
||||||
|
* @param event - The event to parse.
|
||||||
|
* @returns An array of GroupAdmin objects.
|
||||||
|
* @throws Throws an error if the group admins event is invalid.
|
||||||
|
*/
|
||||||
|
export function parseGroupAdminsEvent(event: Event): GroupAdmin[] {
|
||||||
|
if (!validateGroupAdminsEvent(event)) throw new Error('invalid group admins event')
|
||||||
|
|
||||||
|
const admins: GroupAdmin[] = []
|
||||||
|
|
||||||
|
for (const [tag, value, label, ...permissions] of event.tags) {
|
||||||
|
if (tag !== 'p') continue
|
||||||
|
|
||||||
|
admins.push({
|
||||||
|
pubkey: value,
|
||||||
|
label,
|
||||||
|
permissions: permissions as GroupAdminPermission[],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return admins
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetches the group members event from the specified relay.
|
||||||
|
* If the normalizedRelayURL is not provided, it will be obtained using the groupReference.
|
||||||
|
* If the relayInformation is not provided, it will be fetched using the normalizedRelayURL.
|
||||||
|
*
|
||||||
|
* @param {Object} options - The options object.
|
||||||
|
* @param {AbstractSimplePool} options.pool - The pool object.
|
||||||
|
* @param {GroupReference} options.groupReference - The group reference object.
|
||||||
|
* @param {string} [options.normalizedRelayURL] - The normalized relay URL.
|
||||||
|
* @param {RelayInformation} [options.relayInformation] - The relay information object.
|
||||||
|
* @returns {Promise<Event>} The group members event that can be parsed later to get the group members object.
|
||||||
|
* @throws {Error} If the group members event is not found.
|
||||||
|
*/
|
||||||
|
export async function fetchGroupMembersEvent({
|
||||||
|
pool,
|
||||||
|
groupReference,
|
||||||
|
relayInformation,
|
||||||
|
normalizedRelayURL,
|
||||||
|
}: {
|
||||||
|
pool: AbstractSimplePool
|
||||||
|
groupReference: GroupReference
|
||||||
|
normalizedRelayURL?: string
|
||||||
|
relayInformation?: RelayInformation
|
||||||
|
}): Promise<Event> {
|
||||||
|
if (!normalizedRelayURL) {
|
||||||
|
normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!relayInformation) {
|
||||||
|
relayInformation = await fetchRelayInformation(normalizedRelayURL)
|
||||||
|
}
|
||||||
|
|
||||||
|
const groupMembersEvent = await pool.get([normalizedRelayURL], {
|
||||||
|
kinds: [39002],
|
||||||
|
authors: [relayInformation.pubkey],
|
||||||
|
'#d': [groupReference.id],
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!groupMembersEvent) throw new Error(`members for group '${groupReference.id}' not found on ${normalizedRelayURL}`)
|
||||||
|
|
||||||
|
return groupMembersEvent
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses a group members event and returns an array of GroupMember objects.
|
||||||
|
* @param event - The event to parse.
|
||||||
|
* @returns An array of GroupMember objects.
|
||||||
|
* @throws Throws an error if the group members event is invalid.
|
||||||
|
*/
|
||||||
|
export function parseGroupMembersEvent(event: Event): GroupMember[] {
|
||||||
|
if (!validateGroupMembersEvent(event)) throw new Error('invalid group members event')
|
||||||
|
|
||||||
|
const members: GroupMember[] = []
|
||||||
|
|
||||||
|
for (const [tag, value, label] of event.tags) {
|
||||||
|
if (tag !== 'p') continue
|
||||||
|
|
||||||
|
members.push({
|
||||||
|
pubkey: value,
|
||||||
|
label,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return members
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetches and parses the group metadata event, group admins event, and group members event from the specified pool.
|
||||||
|
* If the normalized relay URL is not provided, it will be obtained using the group reference.
|
||||||
|
* If the relay information is not provided, it will be fetched using the normalized relay URL.
|
||||||
|
*
|
||||||
|
* @param {Object} options - The options for loading the group.
|
||||||
|
* @param {AbstractSimplePool} options.pool - The pool to load the group from.
|
||||||
|
* @param {GroupReference} options.groupReference - The reference of the group to load.
|
||||||
|
* @param {string} [options.normalizedRelayURL] - The normalized URL of the relay to use.
|
||||||
|
* @param {RelayInformation} [options.relayInformation] - The relay information to use.
|
||||||
|
* @returns {Promise<Group>} A promise that resolves to the loaded group.
|
||||||
|
*/
|
||||||
|
export async function loadGroup({
|
||||||
|
pool,
|
||||||
|
groupReference,
|
||||||
|
normalizedRelayURL,
|
||||||
|
relayInformation,
|
||||||
|
}: {
|
||||||
|
pool: AbstractSimplePool
|
||||||
|
groupReference: GroupReference
|
||||||
|
normalizedRelayURL?: string
|
||||||
|
relayInformation?: RelayInformation
|
||||||
|
}): Promise<Group> {
|
||||||
|
if (!normalizedRelayURL) {
|
||||||
|
normalizedRelayURL = getNormalizedRelayURLByGroupReference(groupReference)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!relayInformation) {
|
||||||
|
relayInformation = await fetchRelayInformation(normalizedRelayURL)
|
||||||
|
}
|
||||||
|
|
||||||
|
const metadataEvent = await fetchGroupMetadataEvent({ pool, groupReference, normalizedRelayURL, relayInformation })
|
||||||
|
const metadata = parseGroupMetadataEvent(metadataEvent)
|
||||||
|
|
||||||
|
const adminsEvent = await fetchGroupAdminsEvent({ pool, groupReference, normalizedRelayURL, relayInformation })
|
||||||
|
const admins = parseGroupAdminsEvent(adminsEvent)
|
||||||
|
|
||||||
|
const membersEvent = await fetchGroupMembersEvent({ pool, groupReference, normalizedRelayURL, relayInformation })
|
||||||
|
const members = parseGroupMembersEvent(membersEvent)
|
||||||
|
|
||||||
|
const group: Group = {
|
||||||
|
relay: normalizedRelayURL,
|
||||||
|
metadata,
|
||||||
|
admins,
|
||||||
|
members,
|
||||||
|
reference: groupReference,
|
||||||
|
}
|
||||||
|
|
||||||
|
return group
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loads a group from the specified pool using the provided group code.
|
||||||
|
*
|
||||||
|
* @param {AbstractSimplePool} pool - The pool to load the group from.
|
||||||
|
* @param {string} code - The code representing the group.
|
||||||
|
* @returns {Promise<Group>} - A promise that resolves to the loaded group.
|
||||||
|
* @throws {Error} - If the group code is invalid.
|
||||||
|
*/
|
||||||
|
export async function loadGroupFromCode(pool: AbstractSimplePool, code: string): Promise<Group> {
|
||||||
|
const groupReference = parseGroupCode(code)
|
||||||
|
|
||||||
|
if (!groupReference) throw new Error('invalid group code')
|
||||||
|
|
||||||
|
return loadGroup({ pool, groupReference })
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses a group code and returns a GroupReference object.
|
||||||
|
*
|
||||||
|
* @param code The group code to parse.
|
||||||
|
* @returns A GroupReference object if the code is valid, otherwise null.
|
||||||
|
*/
|
||||||
export function parseGroupCode(code: string): null | GroupReference {
|
export function parseGroupCode(code: string): null | GroupReference {
|
||||||
if (code.startsWith('naddr1')) {
|
if (code.startsWith('naddr1')) {
|
||||||
try {
|
try {
|
||||||
@@ -99,68 +533,74 @@ export function parseGroupCode(code: string): null | GroupReference {
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encodes a group reference into a string.
|
||||||
|
*
|
||||||
|
* @param gr - The group reference to encode.
|
||||||
|
* @returns The encoded group reference as a string.
|
||||||
|
*/
|
||||||
export function encodeGroupReference(gr: GroupReference): string {
|
export function encodeGroupReference(gr: GroupReference): string {
|
||||||
if (gr.host.startsWith('https://')) gr.host = gr.host.slice(8)
|
const { host, id } = gr
|
||||||
if (gr.host.startsWith('wss://')) gr.host = gr.host.slice(6)
|
const normalizedHost = host.replace(/^(https?:\/\/|wss?:\/\/)/, '')
|
||||||
return `${gr.host}'${gr.id}`
|
|
||||||
|
return `${normalizedHost}'${id}`
|
||||||
}
|
}
|
||||||
|
|
||||||
export type Group = {
|
/**
|
||||||
id: string
|
* Subscribes to relay groups metadata events and calls the provided event handler function
|
||||||
relay: string
|
* when an event is received.
|
||||||
pubkey: string
|
*
|
||||||
name?: string
|
* @param {Object} options - The options for subscribing to relay groups metadata events.
|
||||||
picture?: string
|
* @param {AbstractSimplePool} options.pool - The pool to subscribe to.
|
||||||
about?: string
|
* @param {string} options.relayURL - The URL of the relay.
|
||||||
public?: boolean
|
* @param {Function} options.onError - The error handler function.
|
||||||
open?: boolean
|
* @param {Function} options.onEvent - The event handler function.
|
||||||
}
|
* @param {Function} [options.onConnect] - The connect handler function.
|
||||||
|
* @returns {Function} - A function to close the subscription
|
||||||
|
*/
|
||||||
|
export function subscribeRelayGroupsMetadataEvents({
|
||||||
|
pool,
|
||||||
|
relayURL,
|
||||||
|
onError,
|
||||||
|
onEvent,
|
||||||
|
onConnect,
|
||||||
|
}: {
|
||||||
|
pool: AbstractSimplePool
|
||||||
|
relayURL: string
|
||||||
|
onError: (err: Error) => void
|
||||||
|
onEvent: (event: Event) => void
|
||||||
|
onConnect?: () => void
|
||||||
|
}): () => void {
|
||||||
|
let sub: Subscription
|
||||||
|
|
||||||
export function parseGroup(event: Event, relay: string): Group {
|
const normalizedRelayURL = normalizeURL(relayURL)
|
||||||
const group: Partial<Group> = { relay, pubkey: event.pubkey }
|
|
||||||
for (let i = 0; i < event.tags.length; i++) {
|
|
||||||
const tag = event.tags[i]
|
|
||||||
switch (tag[0]) {
|
|
||||||
case 'd':
|
|
||||||
group.id = tag[1] || ''
|
|
||||||
break
|
|
||||||
case 'name':
|
|
||||||
group.name = tag[1] || ''
|
|
||||||
break
|
|
||||||
case 'about':
|
|
||||||
group.about = tag[1] || ''
|
|
||||||
break
|
|
||||||
case 'picture':
|
|
||||||
group.picture = tag[1] || ''
|
|
||||||
break
|
|
||||||
case 'open':
|
|
||||||
group.open = true
|
|
||||||
break
|
|
||||||
case 'public':
|
|
||||||
group.public = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return group as Group
|
|
||||||
}
|
|
||||||
|
|
||||||
export type Member = {
|
fetchRelayInformation(normalizedRelayURL)
|
||||||
pubkey: string
|
.then(async info => {
|
||||||
label?: string
|
const abstractedRelay = await pool.ensureRelay(normalizedRelayURL)
|
||||||
permissions: string[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export function parseMembers(event: Event): Member[] {
|
onConnect?.()
|
||||||
const members = []
|
|
||||||
for (let i = 0; i < event.tags.length; i++) {
|
sub = abstractedRelay.prepareSubscription(
|
||||||
const tag = event.tags[i]
|
[
|
||||||
if (tag.length < 2) continue
|
{
|
||||||
if (tag[0] !== 'p') continue
|
kinds: [39000],
|
||||||
if (!tag[1].match(/^[0-9a-f]{64}$/)) continue
|
limit: 50,
|
||||||
const member: Member = { pubkey: tag[1], permissions: [] }
|
authors: [info.pubkey],
|
||||||
if (tag.length > 2) member.label = tag[2]
|
},
|
||||||
if (tag.length > 3) member.permissions = tag.slice(3)
|
],
|
||||||
members.push(member)
|
{
|
||||||
}
|
onevent(event: Event) {
|
||||||
return members
|
onEvent(event)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
sub.close()
|
||||||
|
|
||||||
|
onError(err)
|
||||||
|
})
|
||||||
|
|
||||||
|
return () => sub.close()
|
||||||
}
|
}
|
||||||
|
|||||||
44
nip46.ts
44
nip46.ts
@@ -1,9 +1,8 @@
|
|||||||
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 as legacyDecrypt } from './nip04.ts'
|
||||||
import { getConversationKey, decrypt as nip44decrypt } from './nip44.ts'
|
import { getConversationKey, decrypt, encrypt } 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 } from './kinds.ts'
|
import { Handlerinformation, NostrConnect } from './kinds.ts'
|
||||||
@@ -49,7 +48,7 @@ export async function parseBunkerInput(input: string): Promise<BunkerPointer | n
|
|||||||
return queryBunkerProfile(input)
|
return queryBunkerProfile(input)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function queryBunkerProfile(nip05: string): Promise<BunkerPointer | null> {
|
export async function queryBunkerProfile(nip05: string): Promise<BunkerPointer | null> {
|
||||||
const match = nip05.match(NIP05_REGEX)
|
const match = nip05.match(NIP05_REGEX)
|
||||||
if (!match) return null
|
if (!match) return null
|
||||||
|
|
||||||
@@ -87,8 +86,11 @@ export class BunkerSigner {
|
|||||||
}
|
}
|
||||||
private waitingForAuth: { [id: string]: boolean }
|
private waitingForAuth: { [id: string]: boolean }
|
||||||
private secretKey: Uint8Array
|
private secretKey: Uint8Array
|
||||||
|
private conversationKey: Uint8Array
|
||||||
public bp: BunkerPointer
|
public bp: BunkerPointer
|
||||||
|
|
||||||
|
private cachedPubKey: string | undefined
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new instance of the Nip46 class.
|
* Creates a new instance of the Nip46 class.
|
||||||
* @param relays - An array of relay addresses.
|
* @param relays - An array of relay addresses.
|
||||||
@@ -102,6 +104,7 @@ export class BunkerSigner {
|
|||||||
|
|
||||||
this.pool = params.pool || new SimplePool()
|
this.pool = params.pool || new SimplePool()
|
||||||
this.secretKey = clientSecretKey
|
this.secretKey = clientSecretKey
|
||||||
|
this.conversationKey = getConversationKey(clientSecretKey, bp.pubkey)
|
||||||
this.bp = bp
|
this.bp = bp
|
||||||
this.isOpen = false
|
this.isOpen = false
|
||||||
this.idPrefix = Math.random().toString(36).substring(7)
|
this.idPrefix = Math.random().toString(36).substring(7)
|
||||||
@@ -111,18 +114,18 @@ export class BunkerSigner {
|
|||||||
|
|
||||||
const listeners = this.listeners
|
const listeners = this.listeners
|
||||||
const waitingForAuth = this.waitingForAuth
|
const waitingForAuth = this.waitingForAuth
|
||||||
const skBytes = this.secretKey
|
const convKey = this.conversationKey
|
||||||
|
|
||||||
this.subCloser = this.pool.subscribeMany(
|
this.subCloser = this.pool.subscribeMany(
|
||||||
this.bp.relays,
|
this.bp.relays,
|
||||||
[{ kinds: [NostrConnect], '#p': [getPublicKey(this.secretKey)] }],
|
[{ kinds: [NostrConnect], authors: [bp.pubkey], '#p': [getPublicKey(this.secretKey)] }],
|
||||||
{
|
{
|
||||||
async onevent(event: NostrEvent) {
|
async onevent(event: NostrEvent) {
|
||||||
let o
|
let o
|
||||||
try {
|
try {
|
||||||
o = JSON.parse(await decrypt(clientSecretKey, event.pubkey, event.content))
|
o = JSON.parse(decrypt(event.content, convKey))
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
o = JSON.parse(nip44decrypt(event.content, getConversationKey(skBytes, event.pubkey)))
|
o = JSON.parse(await legacyDecrypt(clientSecretKey, event.pubkey, event.content))
|
||||||
}
|
}
|
||||||
|
|
||||||
const { id, result, error } = o
|
const { id, result, error } = o
|
||||||
@@ -165,7 +168,7 @@ export class BunkerSigner {
|
|||||||
this.serial++
|
this.serial++
|
||||||
const id = `${this.idPrefix}-${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
|
// the request event
|
||||||
const verifiedEvent: VerifiedEvent = finalizeEvent(
|
const verifiedEvent: VerifiedEvent = finalizeEvent(
|
||||||
@@ -207,11 +210,16 @@ export class BunkerSigner {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This was supposed to call the "get_public_key" method on the bunker,
|
* Calls the "get_public_key" method on the bunker.
|
||||||
* but instead we just returns the public key we already know.
|
* (before we would return the public key hardcoded in the bunker parameters, but
|
||||||
|
* that is not correct as that may be the bunker pubkey and the actual signer
|
||||||
|
* pubkey may be different.)
|
||||||
*/
|
*/
|
||||||
async getPublicKey(): Promise<string> {
|
async getPublicKey(): Promise<string> {
|
||||||
return this.bp.pubkey
|
if (!this.cachedPubKey) {
|
||||||
|
this.cachedPubKey = await this.sendRequest('get_public_key', [])
|
||||||
|
}
|
||||||
|
return this.cachedPubKey
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -229,7 +237,7 @@ 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.bp.pubkey && verifyEvent(signed)) {
|
if (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)}`)
|
||||||
@@ -244,17 +252,12 @@ export class BunkerSigner {
|
|||||||
return await this.sendRequest('nip04_decrypt', [thirdPartyPubkey, ciphertext])
|
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> {
|
async nip44Encrypt(thirdPartyPubkey: string, plaintext: string): Promise<string> {
|
||||||
return await this.sendRequest('nip44_encrypt', [thirdPartyPubkey, plaintext])
|
return await this.sendRequest('nip44_encrypt', [thirdPartyPubkey, plaintext])
|
||||||
}
|
}
|
||||||
|
|
||||||
async nip44Decrypt(thirdPartyPubkey: string, ciphertext: string): Promise<string> {
|
async nip44Decrypt(thirdPartyPubkey: string, ciphertext: string): Promise<string> {
|
||||||
return await this.sendRequest('nip44_encrypt', [thirdPartyPubkey, ciphertext])
|
return await this.sendRequest('nip44_decrypt', [thirdPartyPubkey, ciphertext])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -291,9 +294,6 @@ export async function createAccount(
|
|||||||
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.
|
||||||
|
|||||||
9
nip49.ts
9
nip49.ts
@@ -1,10 +1,15 @@
|
|||||||
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.ts'
|
import { Bech32MaxSize, Ncryptsec, 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,
|
||||||
|
): Ncryptsec {
|
||||||
let salt = randomBytes(16)
|
let salt = randomBytes(16)
|
||||||
let n = 2 ** logn
|
let n = 2 ** logn
|
||||||
let key = scrypt(password.normalize('NFKC'), salt, { N: n, r: 8, p: 1, dkLen: 32 })
|
let key = scrypt(password.normalize('NFKC'), salt, { N: n, r: 8, p: 1, dkLen: 32 })
|
||||||
|
|||||||
113
nip59.test.ts
Normal file
113
nip59.test.ts
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
import { test, expect } from 'bun:test'
|
||||||
|
import { wrapEvent, wrapManyEvents, unwrapEvent, unwrapManyEvents } from './nip59.ts'
|
||||||
|
import { decode } from './nip19.ts'
|
||||||
|
import { NostrEvent, getPublicKey } from './pure.ts'
|
||||||
|
import { SimplePool } from './pool.ts'
|
||||||
|
import { GiftWrap } from './kinds.ts'
|
||||||
|
import { hexToBytes } from '@noble/hashes/utils'
|
||||||
|
|
||||||
|
const senderPrivateKey = decode(`nsec1p0ht6p3wepe47sjrgesyn4m50m6avk2waqudu9rl324cg2c4ufesyp6rdg`).data
|
||||||
|
const recipientPrivateKey = decode(`nsec1uyyrnx7cgfp40fcskcr2urqnzekc20fj0er6de0q8qvhx34ahazsvs9p36`).data
|
||||||
|
const recipientPublicKey = getPublicKey(recipientPrivateKey)
|
||||||
|
const event = {
|
||||||
|
kind: 1,
|
||||||
|
content: 'Are you going to the party tonight?',
|
||||||
|
}
|
||||||
|
|
||||||
|
const wrappedEvent = wrapEvent(event, senderPrivateKey, recipientPublicKey)
|
||||||
|
|
||||||
|
test('wrapEvent', () => {
|
||||||
|
const expected = {
|
||||||
|
content: '',
|
||||||
|
id: '',
|
||||||
|
created_at: 1728537932,
|
||||||
|
kind: 1059,
|
||||||
|
pubkey: '',
|
||||||
|
sig: '',
|
||||||
|
tags: [['p', '166bf3765ebd1fc55decfe395beff2ea3b2a4e0a8946e7eb578512b555737c99']],
|
||||||
|
[Symbol('verified')]: true,
|
||||||
|
}
|
||||||
|
const result = wrapEvent(event, senderPrivateKey, recipientPublicKey)
|
||||||
|
|
||||||
|
expect(result.kind).toEqual(expected.kind)
|
||||||
|
expect(result.tags).toEqual(expected.tags)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('wrapManyEvent', () => {
|
||||||
|
const expected = [
|
||||||
|
{
|
||||||
|
kind: 1059,
|
||||||
|
content: '',
|
||||||
|
created_at: 1729581521,
|
||||||
|
tags: [['p', '611df01bfcf85c26ae65453b772d8f1dfd25c264621c0277e1fc1518686faef9']],
|
||||||
|
pubkey: '',
|
||||||
|
id: '',
|
||||||
|
sig: '',
|
||||||
|
[Symbol('verified')]: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: 1059,
|
||||||
|
content: '',
|
||||||
|
created_at: 1729594619,
|
||||||
|
tags: [['p', '166bf3765ebd1fc55decfe395beff2ea3b2a4e0a8946e7eb578512b555737c99']],
|
||||||
|
pubkey: '',
|
||||||
|
id: '',
|
||||||
|
sig: '',
|
||||||
|
[Symbol('verified')]: true,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
const wrappedEvents = wrapManyEvents(event, senderPrivateKey, [recipientPublicKey])
|
||||||
|
|
||||||
|
wrappedEvents.forEach((event, index) => {
|
||||||
|
expect(event.kind).toEqual(expected[index].kind)
|
||||||
|
expect(event.tags).toEqual(expected[index].tags)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('unwrapEvent', () => {
|
||||||
|
const expected = {
|
||||||
|
kind: 1,
|
||||||
|
content: 'Are you going to the party tonight?',
|
||||||
|
pubkey: '611df01bfcf85c26ae65453b772d8f1dfd25c264621c0277e1fc1518686faef9',
|
||||||
|
tags: [],
|
||||||
|
}
|
||||||
|
const result = unwrapEvent(wrappedEvent, recipientPrivateKey)
|
||||||
|
|
||||||
|
expect(result.kind).toEqual(expected.kind)
|
||||||
|
expect(result.content).toEqual(expected.content)
|
||||||
|
expect(result.pubkey).toEqual(expected.pubkey)
|
||||||
|
expect(result.tags).toEqual(expected.tags)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('getWrappedEvents and unwrapManyEvents', async () => {
|
||||||
|
const expected = [
|
||||||
|
{
|
||||||
|
created_at: 1729721879,
|
||||||
|
content: 'Hello!',
|
||||||
|
tags: [['p', '33d6bb037bf2e8c4571708e480e42d141bedc5a562b4884ec233b22d6fdea6aa']],
|
||||||
|
kind: 14,
|
||||||
|
pubkey: 'c0f56665e73eedc90b9565ecb34d961a2eb7ac1e2747899e4f73a813f940bc22',
|
||||||
|
id: 'aee0a3e6487b2ac8c1851cc84f3ae0fca9af8a9bdad85c4ba5fdf45d3ee817c3',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
created_at: 1729722025,
|
||||||
|
content: 'How are you?',
|
||||||
|
tags: [['p', '33d6bb037bf2e8c4571708e480e42d141bedc5a562b4884ec233b22d6fdea6aa']],
|
||||||
|
kind: 14,
|
||||||
|
pubkey: 'c0f56665e73eedc90b9565ecb34d961a2eb7ac1e2747899e4f73a813f940bc22',
|
||||||
|
id: '212387ec5efee7d6eb20b747121e9fc1adb798de6c3185e932335bb1bcc61a77',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
const relays = ['wss://relay.damus.io', 'wss://nos.lol']
|
||||||
|
const privateKey = hexToBytes('582c3e7902c10c84d1cfe899a102e56bde628972d58d63011163ce0cdf4279b6')
|
||||||
|
const publicKey = '33d6bb037bf2e8c4571708e480e42d141bedc5a562b4884ec233b22d6fdea6aa'
|
||||||
|
|
||||||
|
const pool = new SimplePool()
|
||||||
|
const wrappedEvents: NostrEvent[] = await pool.querySync(relays, { kinds: [GiftWrap], '#p': [publicKey] })
|
||||||
|
const unwrappedEvents = unwrapManyEvents(wrappedEvents, privateKey)
|
||||||
|
|
||||||
|
unwrappedEvents.forEach((event, index) => {
|
||||||
|
expect(event).toEqual(expected[index])
|
||||||
|
})
|
||||||
|
})
|
||||||
107
nip59.ts
Normal file
107
nip59.ts
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
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'
|
||||||
|
|
||||||
|
type Rumor = UnsignedEvent & { id: string }
|
||||||
|
|
||||||
|
const TWO_DAYS = 2 * 24 * 60 * 60
|
||||||
|
|
||||||
|
const now = () => Math.round(Date.now() / 1000)
|
||||||
|
const randomNow = () => Math.round(now() - Math.random() * TWO_DAYS)
|
||||||
|
|
||||||
|
const nip44ConversationKey = (privateKey: Uint8Array, publicKey: string) => getConversationKey(privateKey, publicKey)
|
||||||
|
|
||||||
|
const nip44Encrypt = (data: EventTemplate, privateKey: Uint8Array, publicKey: string) =>
|
||||||
|
encrypt(JSON.stringify(data), nip44ConversationKey(privateKey, publicKey))
|
||||||
|
|
||||||
|
const nip44Decrypt = (data: NostrEvent, privateKey: Uint8Array) =>
|
||||||
|
JSON.parse(decrypt(data.content, nip44ConversationKey(privateKey, data.pubkey)))
|
||||||
|
|
||||||
|
export function createRumor(event: Partial<UnsignedEvent>, privateKey: Uint8Array): Rumor {
|
||||||
|
const rumor = {
|
||||||
|
created_at: now(),
|
||||||
|
content: '',
|
||||||
|
tags: [],
|
||||||
|
...event,
|
||||||
|
pubkey: getPublicKey(privateKey),
|
||||||
|
} as any
|
||||||
|
|
||||||
|
rumor.id = getEventHash(rumor)
|
||||||
|
|
||||||
|
return rumor as Rumor
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createSeal(rumor: Rumor, privateKey: Uint8Array, recipientPublicKey: string): NostrEvent {
|
||||||
|
return finalizeEvent(
|
||||||
|
{
|
||||||
|
kind: Seal,
|
||||||
|
content: nip44Encrypt(rumor, privateKey, recipientPublicKey),
|
||||||
|
created_at: randomNow(),
|
||||||
|
tags: [],
|
||||||
|
},
|
||||||
|
privateKey,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createWrap(seal: NostrEvent, recipientPublicKey: string): NostrEvent {
|
||||||
|
const randomKey = generateSecretKey()
|
||||||
|
|
||||||
|
return finalizeEvent(
|
||||||
|
{
|
||||||
|
kind: GiftWrap,
|
||||||
|
content: nip44Encrypt(seal, randomKey, recipientPublicKey),
|
||||||
|
created_at: randomNow(),
|
||||||
|
tags: [['p', recipientPublicKey]],
|
||||||
|
},
|
||||||
|
randomKey,
|
||||||
|
) as NostrEvent
|
||||||
|
}
|
||||||
|
|
||||||
|
export function wrapEvent(
|
||||||
|
event: Partial<UnsignedEvent>,
|
||||||
|
senderPrivateKey: Uint8Array,
|
||||||
|
recipientPublicKey: string,
|
||||||
|
): NostrEvent {
|
||||||
|
const rumor = createRumor(event, senderPrivateKey)
|
||||||
|
|
||||||
|
const seal = createSeal(rumor, senderPrivateKey, recipientPublicKey)
|
||||||
|
return createWrap(seal, recipientPublicKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
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.')
|
||||||
|
}
|
||||||
|
|
||||||
|
const senderPublicKey = getPublicKey(senderPrivateKey)
|
||||||
|
|
||||||
|
const wrappeds = [wrapEvent(event, senderPrivateKey, senderPublicKey)]
|
||||||
|
|
||||||
|
recipientsPublicKeys.forEach(recipientPublicKey => {
|
||||||
|
wrappeds.push(wrapEvent(event, senderPrivateKey, recipientPublicKey))
|
||||||
|
})
|
||||||
|
|
||||||
|
return wrappeds
|
||||||
|
}
|
||||||
|
|
||||||
|
export function unwrapEvent(wrap: NostrEvent, recipientPrivateKey: Uint8Array): Rumor {
|
||||||
|
const unwrappedSeal = nip44Decrypt(wrap, recipientPrivateKey)
|
||||||
|
return nip44Decrypt(unwrappedSeal, recipientPrivateKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function unwrapManyEvents(wrappedEvents: NostrEvent[], recipientPrivateKey: Uint8Array): Rumor[] {
|
||||||
|
let unwrappedEvents: Rumor[] = []
|
||||||
|
|
||||||
|
wrappedEvents.forEach(e => {
|
||||||
|
unwrappedEvents.push(unwrapEvent(e, recipientPrivateKey))
|
||||||
|
})
|
||||||
|
|
||||||
|
unwrappedEvents.sort((a, b) => a.created_at - b.created_at)
|
||||||
|
|
||||||
|
return unwrappedEvents
|
||||||
|
}
|
||||||
@@ -21,6 +21,7 @@ describe('generateEventTemplate', () => {
|
|||||||
image: 'https://example.com/image.jpg',
|
image: 'https://example.com/image.jpg',
|
||||||
summary: 'Lorem ipsum',
|
summary: 'Lorem ipsum',
|
||||||
alt: 'Image alt text',
|
alt: 'Image alt text',
|
||||||
|
fallback: ['https://fallback1.example.com/image.jpg', 'https://fallback2.example.com/image.jpg'],
|
||||||
}
|
}
|
||||||
|
|
||||||
const expectedEventTemplate: EventTemplate = {
|
const expectedEventTemplate: EventTemplate = {
|
||||||
@@ -40,6 +41,8 @@ describe('generateEventTemplate', () => {
|
|||||||
['image', 'https://example.com/image.jpg'],
|
['image', 'https://example.com/image.jpg'],
|
||||||
['summary', 'Lorem ipsum'],
|
['summary', 'Lorem ipsum'],
|
||||||
['alt', 'Image alt text'],
|
['alt', 'Image alt text'],
|
||||||
|
['fallback', 'https://fallback1.example.com/image.jpg'],
|
||||||
|
['fallback', 'https://fallback2.example.com/image.jpg'],
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,6 +74,7 @@ describe('validateEvent', () => {
|
|||||||
['image', 'https://example.com/image.jpg'],
|
['image', 'https://example.com/image.jpg'],
|
||||||
['summary', 'Lorem ipsum'],
|
['summary', 'Lorem ipsum'],
|
||||||
['alt', 'Image alt text'],
|
['alt', 'Image alt text'],
|
||||||
|
['fallback', 'https://fallback.example.com/image.jpg'],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
sk,
|
sk,
|
||||||
@@ -100,6 +104,7 @@ describe('validateEvent', () => {
|
|||||||
['image', 'https://example.com/image.jpg'],
|
['image', 'https://example.com/image.jpg'],
|
||||||
['summary', 'Lorem ipsum'],
|
['summary', 'Lorem ipsum'],
|
||||||
['alt', 'Image alt text'],
|
['alt', 'Image alt text'],
|
||||||
|
['fallback', 'https://fallback.example.com/image.jpg'],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
sk,
|
sk,
|
||||||
@@ -129,6 +134,7 @@ describe('validateEvent', () => {
|
|||||||
['image', 'https://example.com/image.jpg'],
|
['image', 'https://example.com/image.jpg'],
|
||||||
['summary', 'Lorem ipsum'],
|
['summary', 'Lorem ipsum'],
|
||||||
['alt', 'Image alt text'],
|
['alt', 'Image alt text'],
|
||||||
|
['fallback', 'https://fallback.example.com/image.jpg'],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
sk,
|
sk,
|
||||||
@@ -158,6 +164,7 @@ describe('validateEvent', () => {
|
|||||||
['image', 'https://example.com/image.jpg'],
|
['image', 'https://example.com/image.jpg'],
|
||||||
['summary', 'Lorem ipsum'],
|
['summary', 'Lorem ipsum'],
|
||||||
['alt', 'Image alt text'],
|
['alt', 'Image alt text'],
|
||||||
|
['fallback', 'https://fallback.example.com/image.jpg'],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
sk,
|
sk,
|
||||||
@@ -181,6 +188,7 @@ describe('validateEvent', () => {
|
|||||||
['image', 'https://example.com/image.jpg'],
|
['image', 'https://example.com/image.jpg'],
|
||||||
['summary', 'Lorem ipsum'],
|
['summary', 'Lorem ipsum'],
|
||||||
['alt', 'Image alt text'],
|
['alt', 'Image alt text'],
|
||||||
|
['fallback', 'https://fallback.example.com/image.jpg'],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
sk,
|
sk,
|
||||||
@@ -204,6 +212,7 @@ describe('validateEvent', () => {
|
|||||||
['image', 'https://example.com/image.jpg'],
|
['image', 'https://example.com/image.jpg'],
|
||||||
['summary', 'Lorem ipsum'],
|
['summary', 'Lorem ipsum'],
|
||||||
['alt', 'Image alt text'],
|
['alt', 'Image alt text'],
|
||||||
|
['fallback', 'https://fallback.example.com/image.jpg'],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
sk,
|
sk,
|
||||||
@@ -227,6 +236,7 @@ describe('validateEvent', () => {
|
|||||||
['image', 'https://example.com/image.jpg'],
|
['image', 'https://example.com/image.jpg'],
|
||||||
['summary', 'Lorem ipsum'],
|
['summary', 'Lorem ipsum'],
|
||||||
['alt', 'Image alt text'],
|
['alt', 'Image alt text'],
|
||||||
|
['fallback', 'https://fallback.example.com/image.jpg'],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
sk,
|
sk,
|
||||||
@@ -259,6 +269,7 @@ describe('validateEvent', () => {
|
|||||||
['image', 'https://example.com/image.jpg'],
|
['image', 'https://example.com/image.jpg'],
|
||||||
['summary', 'Lorem ipsum'],
|
['summary', 'Lorem ipsum'],
|
||||||
['alt', 'Image alt text'],
|
['alt', 'Image alt text'],
|
||||||
|
['fallback', 'https://fallback.example.com/image.jpg'],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
sk,
|
sk,
|
||||||
@@ -288,6 +299,7 @@ describe('validateEvent', () => {
|
|||||||
['image', 'https://example.com/image.jpg'],
|
['image', 'https://example.com/image.jpg'],
|
||||||
['summary', 'Lorem ipsum'],
|
['summary', 'Lorem ipsum'],
|
||||||
['alt', 'Image alt text'],
|
['alt', 'Image alt text'],
|
||||||
|
['fallback', 'https://fallback.example.com/image.jpg'],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
sk,
|
sk,
|
||||||
@@ -319,6 +331,8 @@ describe('parseEvent', () => {
|
|||||||
['image', 'https://example.com/image.jpg'],
|
['image', 'https://example.com/image.jpg'],
|
||||||
['summary', 'Lorem ipsum'],
|
['summary', 'Lorem ipsum'],
|
||||||
['alt', 'Image alt text'],
|
['alt', 'Image alt text'],
|
||||||
|
['fallback', 'https://fallback1.example.com/image.jpg'],
|
||||||
|
['fallback', 'https://fallback2.example.com/image.jpg'],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
sk,
|
sk,
|
||||||
@@ -340,6 +354,7 @@ describe('parseEvent', () => {
|
|||||||
image: 'https://example.com/image.jpg',
|
image: 'https://example.com/image.jpg',
|
||||||
summary: 'Lorem ipsum',
|
summary: 'Lorem ipsum',
|
||||||
alt: 'Image alt text',
|
alt: 'Image alt text',
|
||||||
|
fallback: ['https://fallback1.example.com/image.jpg', 'https://fallback2.example.com/image.jpg'],
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -364,6 +379,7 @@ describe('parseEvent', () => {
|
|||||||
['image', 'https://example.com/image.jpg'],
|
['image', 'https://example.com/image.jpg'],
|
||||||
['summary', 'Lorem ipsum'],
|
['summary', 'Lorem ipsum'],
|
||||||
['alt', 'Image alt text'],
|
['alt', 'Image alt text'],
|
||||||
|
['fallback', 'https://fallback.example.com/image.jpg'],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
sk,
|
sk,
|
||||||
|
|||||||
10
nip94.ts
10
nip94.ts
@@ -75,6 +75,11 @@ export type FileMetadataObject = {
|
|||||||
* Optional: A description for accessibility, providing context or a brief description of the file.
|
* Optional: A description for accessibility, providing context or a brief description of the file.
|
||||||
*/
|
*/
|
||||||
alt?: string
|
alt?: string
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Optional: fallback URLs in case url fails.
|
||||||
|
*/
|
||||||
|
fallback?: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -104,6 +109,7 @@ export function generateEventTemplate(fileMetadata: FileMetadataObject): EventTe
|
|||||||
if (fileMetadata.image) eventTemplate.tags.push(['image', fileMetadata.image])
|
if (fileMetadata.image) eventTemplate.tags.push(['image', fileMetadata.image])
|
||||||
if (fileMetadata.summary) eventTemplate.tags.push(['summary', fileMetadata.summary])
|
if (fileMetadata.summary) eventTemplate.tags.push(['summary', fileMetadata.summary])
|
||||||
if (fileMetadata.alt) eventTemplate.tags.push(['alt', fileMetadata.alt])
|
if (fileMetadata.alt) eventTemplate.tags.push(['alt', fileMetadata.alt])
|
||||||
|
if (fileMetadata.fallback) fileMetadata.fallback.forEach(url => eventTemplate.tags.push(['fallback', url]))
|
||||||
|
|
||||||
return eventTemplate
|
return eventTemplate
|
||||||
}
|
}
|
||||||
@@ -194,6 +200,10 @@ export function parseEvent(event: Event): FileMetadataObject {
|
|||||||
case 'alt':
|
case 'alt':
|
||||||
fileMetadata.alt = value
|
fileMetadata.alt = value
|
||||||
break
|
break
|
||||||
|
case 'fallback':
|
||||||
|
fileMetadata.fallback ??= []
|
||||||
|
fileMetadata.fallback.push(value)
|
||||||
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
4
nip96.ts
4
nip96.ts
@@ -340,9 +340,6 @@ export async function uploadFile(
|
|||||||
// Create FormData object
|
// Create FormData object
|
||||||
const formData = new FormData()
|
const formData = new FormData()
|
||||||
|
|
||||||
// Append the authorization header to HTML Form Data
|
|
||||||
formData.append('Authorization', nip98AuthorizationHeader)
|
|
||||||
|
|
||||||
// Append optional fields to FormData
|
// Append optional fields to FormData
|
||||||
optionalFormDataFields &&
|
optionalFormDataFields &&
|
||||||
Object.entries(optionalFormDataFields).forEach(([key, value]) => {
|
Object.entries(optionalFormDataFields).forEach(([key, value]) => {
|
||||||
@@ -359,7 +356,6 @@ export async function uploadFile(
|
|||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: nip98AuthorizationHeader,
|
Authorization: nip98AuthorizationHeader,
|
||||||
'Content-Type': 'multipart/form-data',
|
|
||||||
},
|
},
|
||||||
body: formData,
|
body: formData,
|
||||||
})
|
})
|
||||||
|
|||||||
12
package.json
12
package.json
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"name": "nostr-tools",
|
"name": "nostr-tools",
|
||||||
"version": "2.6.0",
|
"version": "2.10.3",
|
||||||
"description": "Tools for making a Nostr client.",
|
"description": "Tools for making a Nostr client.",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -103,6 +103,11 @@
|
|||||||
"require": "./lib/cjs/nip13.js",
|
"require": "./lib/cjs/nip13.js",
|
||||||
"types": "./lib/types/nip13.d.ts"
|
"types": "./lib/types/nip13.d.ts"
|
||||||
},
|
},
|
||||||
|
"./nip17": {
|
||||||
|
"import": "./lib/esm/nip17.js",
|
||||||
|
"require": "./lib/cjs/nip17.js",
|
||||||
|
"types": "./lib/types/nip17.d.ts"
|
||||||
|
},
|
||||||
"./nip18": {
|
"./nip18": {
|
||||||
"import": "./lib/esm/nip18.js",
|
"import": "./lib/esm/nip18.js",
|
||||||
"require": "./lib/cjs/nip18.js",
|
"require": "./lib/cjs/nip18.js",
|
||||||
@@ -173,6 +178,11 @@
|
|||||||
"require": "./lib/cjs/nip57.js",
|
"require": "./lib/cjs/nip57.js",
|
||||||
"types": "./lib/types/nip57.d.ts"
|
"types": "./lib/types/nip57.d.ts"
|
||||||
},
|
},
|
||||||
|
"./nip59": {
|
||||||
|
"import": "./lib/esm/nip59.js",
|
||||||
|
"require": "./lib/cjs/nip59.js",
|
||||||
|
"types": "./lib/types/nip59.d.ts"
|
||||||
|
},
|
||||||
"./nip58": {
|
"./nip58": {
|
||||||
"import": "./lib/esm/nip58.js",
|
"import": "./lib/esm/nip58.js",
|
||||||
"require": "./lib/cjs/nip58.js",
|
"require": "./lib/cjs/nip58.js",
|
||||||
|
|||||||
33
pool.test.ts
33
pool.test.ts
@@ -1,8 +1,7 @@
|
|||||||
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 { useWebSocketImplementation } from './relay.ts'
|
|
||||||
import { MockRelay, MockWebSocketClient } from './test-helpers.ts'
|
import { MockRelay, MockWebSocketClient } from './test-helpers.ts'
|
||||||
import { hexToBytes } from '@noble/hashes/utils'
|
import { hexToBytes } from '@noble/hashes/utils'
|
||||||
|
|
||||||
@@ -206,3 +205,33 @@ test('get()', async () => {
|
|||||||
expect(event).not.toBeNull()
|
expect(event).not.toBeNull()
|
||||||
expect(event).toHaveProperty('id', ids[0])
|
expect(event).toHaveProperty('id', ids[0])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('track relays when publishing', async () => {
|
||||||
|
let event1 = finalizeEvent(
|
||||||
|
{
|
||||||
|
kind: 1,
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
tags: [],
|
||||||
|
content: 'hello',
|
||||||
|
},
|
||||||
|
generateSecretKey(),
|
||||||
|
)
|
||||||
|
let event2 = finalizeEvent(
|
||||||
|
{
|
||||||
|
kind: 1,
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
tags: [],
|
||||||
|
content: 'hello',
|
||||||
|
},
|
||||||
|
generateSecretKey(),
|
||||||
|
)
|
||||||
|
|
||||||
|
pool.trackRelays = true
|
||||||
|
await Promise.all(pool.publish(relayURLs, event1))
|
||||||
|
expect(pool.seenOn.get(event1.id)).toBeDefined()
|
||||||
|
expect(Array.from(pool.seenOn.get(event1.id)!).map(r => r.url)).toEqual(expect.arrayContaining(relayURLs))
|
||||||
|
|
||||||
|
pool.trackRelays = false
|
||||||
|
await Promise.all(pool.publish(relayURLs, event2))
|
||||||
|
expect(pool.seenOn.get(event2.id)).toBeUndefined()
|
||||||
|
})
|
||||||
|
|||||||
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 })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { expect, test } from 'bun:test'
|
import { expect, test } from 'bun:test'
|
||||||
|
import { Server } from 'mock-socket'
|
||||||
import { finalizeEvent, generateSecretKey, getPublicKey } from './pure.ts'
|
import { finalizeEvent, generateSecretKey, getPublicKey } from './pure.ts'
|
||||||
import { Relay, useWebSocketImplementation } from './relay.ts'
|
import { Relay, useWebSocketImplementation } from './relay.ts'
|
||||||
import { MockRelay, MockWebSocketClient } from './test-helpers.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')
|
||||||
|
})
|
||||||
|
|||||||
16
relay.ts
16
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,9 +10,19 @@ 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): Promise<Relay> {
|
static async connect(url: string): Promise<Relay> {
|
||||||
@@ -20,6 +32,6 @@ export class Relay extends AbstractRelay {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export type RelayRecord = Record<string, { read: boolean; write: boolean }>;
|
export type RelayRecord = Record<string, { read: boolean; write: boolean }>
|
||||||
|
|
||||||
export * from './abstract-relay.ts'
|
export * from './abstract-relay.ts'
|
||||||
|
|||||||
Reference in New Issue
Block a user