nip05.queryProfile() and test.

This commit is contained in:
fiatjaf 2022-12-20 18:36:49 -03:00
parent 482c5affd4
commit 3f1025f551
No known key found for this signature in database
GPG Key ID: BAD43C4BE5C1A3A1
4 changed files with 43 additions and 5 deletions

20
nip05.test.js Normal file
View File

@ -0,0 +1,20 @@
/* eslint-env jest */
const fetch = require('node-fetch')
const {nip05} = require('./lib/nostr.cjs')
test('fetch nip05 profiles', async () => {
nip05.useFetchImplementation(fetch)
let p1 = await nip05.queryProfile('jb55.com')
expect(p1.pubkey).toEqual(
'32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245'
)
expect(p1.relays).toEqual(['wss://relay.damus.io'])
let p2 = await nip05.queryProfile('jb55@jb55.com')
expect(p2.pubkey).toEqual(
'32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245'
)
expect(p2.relays).toEqual(['wss://relay.damus.io'])
})

View File

@ -1,3 +1,5 @@
import {ProfilePointer} from './nip19'
var _fetch = fetch var _fetch = fetch
export function useFetchImplementation(fetchImplementation: any) { export function useFetchImplementation(fetchImplementation: any) {
@ -19,13 +21,28 @@ export async function searchDomain(
} }
} }
export async function queryName(fullname: string): Promise<string> { export async function queryProfile(
fullname: string
): Promise<ProfilePointer | null> {
let [name, domain] = fullname.split('@') let [name, domain] = fullname.split('@')
if (!domain) throw new Error('invalid identifier, must contain an @')
if (!domain) {
// if there is no @, it is because it is just a domain, so assume the name is "_"
domain = name
name = '_'
}
let res = await ( let res = await (
await _fetch(`https://${domain}/.well-known/nostr.json?name=${name}`) await _fetch(`https://${domain}/.well-known/nostr.json?name=${name}`)
).json() ).json()
return res.names && res.names[name] if (!res?.names?.[name]) return null
let pubkey = res.names[name] as string
let relays = (res.relays?.[pubkey] || []) as string[] // nip35
return {
pubkey,
relays
}
} }

View File

@ -1,12 +1,12 @@
import * as secp256k1 from '@noble/secp256k1' import * as secp256k1 from '@noble/secp256k1'
import {bech32} from 'bech32' import {bech32} from 'bech32'
type ProfilePointer = { export type ProfilePointer = {
pubkey: string // hex pubkey: string // hex
relays?: string[] relays?: string[]
} }
type EventPointer = { export type EventPointer = {
id: string // hex id: string // hex
relays?: string[] relays?: string[]
} }

View File

@ -36,6 +36,7 @@
"esm-loader-typescript": "^1.0.1", "esm-loader-typescript": "^1.0.1",
"events": "^3.3.0", "events": "^3.3.0",
"jest": "^29.3.1", "jest": "^29.3.1",
"node-fetch": "2",
"ts-jest": "^29.0.3", "ts-jest": "^29.0.3",
"tsd": "^0.22.0", "tsd": "^0.22.0",
"typescript": "^4.9.4" "typescript": "^4.9.4"