diff --git a/nip05.test.js b/nip05.test.js new file mode 100644 index 0000000..8a10f1c --- /dev/null +++ b/nip05.test.js @@ -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']) +}) diff --git a/nip05.ts b/nip05.ts index b3c6c27..3c4e6fe 100644 --- a/nip05.ts +++ b/nip05.ts @@ -1,3 +1,5 @@ +import {ProfilePointer} from './nip19' + var _fetch = fetch export function useFetchImplementation(fetchImplementation: any) { @@ -19,13 +21,28 @@ export async function searchDomain( } } -export async function queryName(fullname: string): Promise { +export async function queryProfile( + fullname: string +): Promise { 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 ( await _fetch(`https://${domain}/.well-known/nostr.json?name=${name}`) ).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 + } } diff --git a/nip19.ts b/nip19.ts index be44135..c4cbad2 100644 --- a/nip19.ts +++ b/nip19.ts @@ -1,12 +1,12 @@ import * as secp256k1 from '@noble/secp256k1' import {bech32} from 'bech32' -type ProfilePointer = { +export type ProfilePointer = { pubkey: string // hex relays?: string[] } -type EventPointer = { +export type EventPointer = { id: string // hex relays?: string[] } diff --git a/package.json b/package.json index a53b741..f74eddc 100644 --- a/package.json +++ b/package.json @@ -36,6 +36,7 @@ "esm-loader-typescript": "^1.0.1", "events": "^3.3.0", "jest": "^29.3.1", + "node-fetch": "2", "ts-jest": "^29.0.3", "tsd": "^0.22.0", "typescript": "^4.9.4"