publicUrl

tcmts.atproto.publicUrl · #qfnvhexr · term · runs on the server

uses node:net

A URL tcm may fetch on someone else's say-so (a record's, a DID document's, a registry visitor's): https, with no credentials in it, at a host whose addresses are all public. On a local network (localNetwork) http, and any address, are allowed. Throws a Refused saying why otherwise.

import { localNetwork, privateAddress, Refused } from "#codebase/tcmts/atproto";
import { lookup } from "node:dns/promises";
import { isIP } from "node:net";

export async function publicUrl(url: string, what: string): Promise<URL> {
  let u: URL;
  try {
    u = new URL(url);
  } catch {
    throw new Refused(`${what} isn't a URL: ${url}`);
  }
  const local = localNetwork();
  if (u.protocol !== "https:" && !(local && u.protocol === "http:"))
    throw new Refused(`${what} must be https: ${url}`);
  if (u.username || u.password) throw new Refused(`${what} mustn't hold credentials: ${u.host}`);
  if (local) return u;
  const host = u.hostname.replace(/^\[|\]$/g, "");
  const addresses = isIP(host)
    ? [host]
    : await lookup(host, { all: true, verbatim: true }).then(
        (r) => r.map((a) => a.address),
        () => {
          throw new Refused(`${what}'s host ${host} doesn't resolve`);
        },
      );
  if (!addresses.length || addresses.some(privateAddress))
    throw new Refused(
      `${what} is on a private or local address (${host}): only public servers are asked`,
    );
  return u;
}

uses

used by