nip05 refactoring

This commit is contained in:
Alex Gleason
2023-05-06 21:40:28 -05:00
committed by fiatjaf_
parent 5d92be05bb
commit d2a9af2586

View File

@@ -1,5 +1,14 @@
import {ProfilePointer} from './nip19' import {ProfilePointer} from './nip19'
/**
* NIP-05 regex. The localpart is optional, and should be assumed to be `_` otherwise.
*
* - 0: full match
* - 1: name (optional)
* - 2: domain
*/
export const NIP05_REGEX = /^(?:([\w.+-]+)@)?([\w.-]+)$/
var _fetch: any var _fetch: any
try { try {
@@ -25,36 +34,53 @@ export async function searchDomain(
} }
} }
export async function queryProfile( /** nostr.json result. */
fullname: string export interface NIP05Result {
): Promise<ProfilePointer | null> { names: {
let [name, domain] = fullname.split('@') [name: string]: string
}
if (!domain) { relays?: {
// if there is no @, it is because it is just a domain, so assume the name is "_" [pubkey: string]: string[]
domain = name }
name = '_'
} }
if (!name.match(/^[A-Za-z0-9-_.]+$/)) return null export async function queryProfile(fullname: string): Promise<ProfilePointer | null> {
if (!domain.includes('.')) return null const match = fullname.match(NIP05_REGEX)
if (!match) return null
const [_, name = '_', domain] = match
let res
try { try {
res = await ( const res = await fetch(`https://${domain}/.well-known/nostr.json?name=${name}`)
await _fetch(`https://${domain}/.well-known/nostr.json?name=${name}`) const { names, relays } = parseNIP05Result(await res.json())
).json()
} catch (err) { const pubkey = names[name]
return pubkey ? { pubkey, relays: relays?.[pubkey] } : null
} catch (_e) {
return null return null
} }
}
if (!res?.names?.[name]) return null /** Parse the nostr.json and throw if it's not valid. */
function parseNIP05Result(json: any): NIP05Result {
const result: NIP05Result = {
names: {},
}
let pubkey = res.names[name] as string for (const [name, pubkey] of Object.entries(json.names)) {
let relays = (res.relays?.[pubkey] || []) as string[] // nip35 if (typeof name === 'string' && typeof pubkey === 'string') {
result.names[name] = pubkey
return {
pubkey,
relays
} }
} }
if (json.relays) {
result.relays = {}
for (const [pubkey, relays] of Object.entries(json.relays)) {
if (typeof pubkey === 'string' && Array.isArray(relays)) {
result.relays[pubkey] = relays.filter((relay: unknown) => typeof relay === 'string')
}
}
}
return result
}