From 943cc4fb48b4308f87877396b6e39055fa17e3ee Mon Sep 17 00:00:00 2001 From: fiatjaf Date: Sun, 11 Feb 2024 08:32:08 -0300 Subject: [PATCH] nip46 beginnings. --- nip46.ts | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 nip46.ts diff --git a/nip46.ts b/nip46.ts new file mode 100644 index 0000000..02c7139 --- /dev/null +++ b/nip46.ts @@ -0,0 +1,54 @@ +import { NIP05_REGEX } from './nip05.ts' + +var _fetch: any + +try { + _fetch = fetch +} catch {} + +export function useFetchImplementation(fetchImplementation: any) { + _fetch = fetchImplementation +} + +export const BUNKER_REGEX = /^bunker:\/\/[0-9a-f]{64}\??[?\/\w:.=&%]*$/ + +type BunkerPointer = { + relays: string[] + pubkey: string + secret: null | string +} + +/** This takes either a bunker:// URL or a name@domain.com NIP-05 identifier + and returns a BunkerPointer -- or null in case of error */ +export async function parseBunkerInput(input: string): Promise { + let match = input.match(BUNKER_REGEX) + if (match) { + try { + const bunkerURL = new URL(input) + return { + pubkey: bunkerURL.host, + relays: bunkerURL.searchParams.getAll('relay'), + secret: bunkerURL.searchParams.get('secret'), + } + } catch (_err) { + /* just move to the next case */ + } + } + + match = input.match(NIP05_REGEX) + if (!match) return null + + const [_, name = '_', domain] = match + + try { + const url = `https://${domain}/.well-known/nostr.json?name=${name}` + const res = await (await _fetch(url, { redirect: 'error' })).json() + + let pubkey = res.names[name] + let relays = res.nip46[pubkey] || [] + + return { pubkey, relays, secret: null } + } catch (_err) { + return null + } +}