~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
121 lines · 5.0 KB Raw History
// Handles outside the sides' domains, served to both (spec/IDENTITY.md,
// "How it is checked"): a DNS server answering `_atproto.<handle>` TXT
// records, and a web answering `/.well-known/atproto-did` for a handle at
// `<base>/<handle>/.well-known/atproto-did`. The server is told of both
// (PDS_HANDLE_DNS_SERVER, PDS_HANDLE_FETCH); the reference, which runs in
// this process, has its handle resolver ask them. Each answers only the
// handles a check gave it.

import dgram from 'node:dgram'
import { promises as dns } from 'node:dns'
import http from 'node:http'

/// TXT records by the name asked, lowercased: each record its strings.
const txt = new Map()
/// The body of each handle's `/.well-known/atproto-did`, by handle.
const wellKnown = new Map()

/// Serve `handle` (lowercased): `dns`, if given, its `_atproto` TXT records,
/// each a string; `https`, if given, the body of its
/// `/.well-known/atproto-did`. Whatever was served for it before goes.
export function serveHandle(handle, { dns: records, https } = {}) {
  const h = handle.toLowerCase()
  txt.delete(`_atproto.${h}`)
  wellKnown.delete(h)
  if (records) txt.set(`_atproto.${h}`, records.map((r) => r.match(/[\s\S]{1,255}/g) ?? ['']))
  if (https !== undefined) wellKnown.set(h, https)
}

/// The name a DNS query at `off` asks, and where its question ends.
function readName(buf, off) {
  const labels = []
  for (;;) {
    const len = buf[off]
    if (len === undefined) throw new Error('short')
    off++
    if (len === 0) break
    labels.push(buf.subarray(off, off + len).toString('latin1'))
    off += len
  }
  return { name: labels.join('.').toLowerCase(), end: off }
}

/// The answer to a query: the TXT records of a name served, none for a
/// name served asked of another type, and NXDOMAIN for any other name.
function answer(query) {
  const { name, end } = readName(query, 12)
  const qtype = query.readUInt16BE(end)
  const question = query.subarray(12, end + 4)
  const records = txt.get(name)
  const answers = records && qtype === 16 ? records : []
  const header = Buffer.alloc(12)
  header.writeUInt16BE(query.readUInt16BE(0), 0)
  // QR, the query's opcode and RD, AA and RA; NXDOMAIN for a name not served.
  header.writeUInt16BE(0x8000 | (query.readUInt16BE(2) & 0x7900) | 0x0480 | (records ? 0 : 3), 2)
  header.writeUInt16BE(1, 4)
  header.writeUInt16BE(answers.length, 6)
  const rrs = answers.map((strings) => {
    const rdata = Buffer.concat(strings.map((s) => Buffer.concat([Buffer.from([Buffer.byteLength(s, 'latin1')]), Buffer.from(s, 'latin1')])))
    const rr = Buffer.alloc(12)
    rr.writeUInt16BE(0xc00c, 0)
    rr.writeUInt16BE(16, 2)
    rr.writeUInt16BE(1, 4)
    rr.writeUInt32BE(0, 6)
    rr.writeUInt16BE(rdata.length, 10)
    return Buffer.concat([rr, rdata])
  })
  return Buffer.concat([header, question, ...rrs])
}

/// Start the DNS server and the web, and have the reference's handle
/// resolver ask them. Answers `{dns, fetch}`: the server's
/// PDS_HANDLE_DNS_SERVER and PDS_HANDLE_FETCH.
export async function startHandles() {
  const sock = dgram.createSocket('udp4')
  sock.on('message', (msg, from) => {
    try {
      sock.send(answer(msg), from.port, from.address)
    } catch {}
  })
  await new Promise((ok) => sock.bind(0, '127.0.0.1', ok))
  sock.unref()
  const web = http.createServer((req, res) => {
    const m = /^\/([^/]+)\/\.well-known\/atproto-did$/.exec(req.url ?? '')
    const body = m ? wellKnown.get(decodeURIComponent(m[1]).toLowerCase()) : undefined
    if (body === undefined) {
      res.writeHead(404, { 'content-type': 'text/plain' }).end('not found')
      return
    }
    res.writeHead(200, { 'content-type': 'text/plain' }).end(body)
  })
  await new Promise((ok) => web.listen(0, '127.0.0.1', ok))
  web.unref()
  return { dns: `127.0.0.1:${sock.address().port}`, fetch: `http://127.0.0.1:${web.address().port}` }
}

/// Have a reference PDS's handle resolver (`ctx.idResolver.handle`) ask the
/// harness's DNS server and web, and nothing else, for every handle outside
/// `domains`, the PDS's own handle domains. The test network replaces the
/// resolver's `resolve` with one that asks the PDS for a handle of its
/// domains and DNS alone, never HTTPS, for any other: that one is kept for
/// the PDS's domains, and the resolver's own, DNS and HTTPS, used for the
/// rest.
export function resolveHere(resolver, { dns: server, fetch: base }, domains) {
  const r = new dns.Resolver({ timeout: 1000, tries: 1 })
  r.setServers([server])
  resolver.resolveDns = async (handle) => {
    try {
      return resolver.parseDnsResult(await r.resolveTxt(`_atproto.${handle}`))
    } catch {
      return undefined
    }
  }
  resolver.resolveDnsBackup = async () => undefined
  resolver.fetch = (url, init) => {
    const u = new URL(url)
    return fetch(`${base}/${u.host}${u.pathname}${u.search}`, init)
  }
  const own = resolver.resolve
  const real = Object.getPrototypeOf(resolver).resolve
  resolver.resolve = (handle) => (domains.some((d) => handle.endsWith(d)) ? own.call(resolver, handle) : real.call(resolver, handle))
}