iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / scripts / zone-enrollment / fake-cloudflare.tsmain at aacbc74

// fake-cloudflare.ts — A CLOUDFLARE OF ONE ACCOUNT'S ZONES, on 127.0.0.1, for the offline proof of
// a zone's enrollment (zone-enrollment.test.ts). It serves the routes of Cloudflare's API that
// Alchemy asks for a zone's resources, from a `World` in memory, and keeps every call. A route
// that it does not serve is a 501, kept in `unserved`: the proof fails on one, so that no call
// goes unseen.
//
// WHAT IT TAKES FROM CLOUDFLARE'S DOCS AND NOT FROM A LIVE ACCOUNT: enabling Email Routing adds
// the zone's receiving records itself (three MX, one SPF TXT, one DKIM TXT), and a zone has one
// catch-all rule from the start, disabled, with the action `drop`.
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";

export type DnsRecord = {
  id: string;
  name: string;
  type: string;
  content: string;
  priority?: number;
  proxied?: boolean;
  ttl?: number;
  comment?: string;
};
export type FakeZone = {
  id: string;
  name: string;
  records: DnsRecord[];
  routes: { id: string; pattern: string; script?: string }[];
  routing: { id: string; enabled: boolean; status: string };
  catchAll: { id: string; name: string; enabled: boolean; actions: unknown[] };
  sending: {
    tag: string;
    name: string;
    enabled: boolean;
    dkim_selector: string;
    return_path_domain: string;
    preview_enabled?: boolean;
  }[];
};
export type World = {
  accountId: string;
  zones: FakeZone[];
  subscriptions: Record<string, unknown>[];
};
export type Call = { method: string; path: string; query: string; body?: unknown; status: number };

/** THE RECORDS THAT CLOUDFLARE ADDS WHEN EMAIL ROUTING IS ENABLED on a zone, by its docs
 *  (developers.cloudflare.com/email-service/configuration/domains): Cloudflare's own act, in
 *  no call of the client. */
export const receivingRecordsOf = (zone: string): Omit<DnsRecord, "id">[] => [
  { name: zone, type: "MX", content: "route1.mx.cloudflare.net", priority: 77 },
  { name: zone, type: "MX", content: "route2.mx.cloudflare.net", priority: 8 },
  { name: zone, type: "MX", content: "route3.mx.cloudflare.net", priority: 70 },
  { name: zone, type: "TXT", content: '"v=spf1 include:_spf.mx.cloudflare.net ~all"' },
  { name: `cf2024-1._domainkey.${zone}`, type: "TXT", content: '"v=DKIM1; a fake public key"' },
];

const ok = (result: unknown, more: object = {}) => ({
  status: 200,
  body: { success: true, errors: [], messages: [], result, ...more },
});
const paged = (result: unknown[]) =>
  ok(result, {
    result_info: { page: 1, per_page: 100, count: result.length, total_count: result.length },
  });
const refused = (status: number, code: number, message: string) => ({
  status,
  body: { success: false, errors: [{ code, message }], messages: [], result: null },
});

/** One answer of the fake, or undefined for a route that it does not serve. `made`: a new id. */
function answerOf(
  world: World,
  call: { method: string; path: string; query: URLSearchParams; body: any },
  made: () => string,
) {
  const { method, path, query, body } = call;
  const at = (pattern: RegExp) => pattern.exec(path);
  if (method === "GET" && path === "/zones")
    return paged(
      world.zones
        .filter((zone) => !query.get("name") || zone.name === query.get("name"))
        .map((zone) => ({
          id: zone.id,
          name: zone.name,
          status: "active",
          account: { id: world.accountId },
        })),
    );
  if (method === "GET" && path === "/user/tokens/verify") return ok({ status: "active" });
  const subscriptions = at(/^\/accounts\/([^/]+)\/event_subscriptions\/subscriptions$/);
  if (subscriptions && method === "GET") return paged(world.subscriptions);
  if (subscriptions && method === "POST") {
    const now = "2026-11-25T00:00:00Z";
    const row = { id: made(), created_at: now, modified_at: now, ...body };
    world.subscriptions.push(row);
    return ok(row);
  }
  const subscription = at(/^\/accounts\/[^/]+\/event_subscriptions\/subscriptions\/([^/]+)$/);
  if (subscription) {
    const found = world.subscriptions.find((each) => each.id === subscription[1]);
    if (!found) return refused(404, 10007, "Subscription not found.");
    if (method === "GET") return ok(found);
    if (method === "DELETE") {
      world.subscriptions.splice(world.subscriptions.indexOf(found), 1);
      return ok(found);
    }
  }
  const inZone = at(/^\/zones\/([^/]+)(\/.*)?$/);
  const zone = world.zones.find((each) => each.id === inZone?.[1]);
  if (!inZone || !zone) return undefined;
  const rest = inZone[2] ?? "";
  if (method === "GET" && rest === "")
    return ok({ id: zone.id, name: zone.name, account: { id: world.accountId } });

  // ── DNS records ──
  if (rest === "/dns_records" && method === "GET") {
    const name = query.get("name") ?? query.get("name.exact");
    const type = query.get("type");
    return paged(
      zone.records.filter(
        (record) => (!name || record.name === name) && (!type || record.type === type),
      ),
    );
  }
  if (rest === "/dns_records" && method === "POST") {
    const record = { id: made(), ...body };
    zone.records.push(record);
    return ok(record);
  }
  const record = /^\/dns_records\/([^/]+)$/.exec(rest);
  if (record) {
    const found = zone.records.find((each) => each.id === record[1]);
    if (!found) return refused(404, 81044, "Record does not exist.");
    if (method === "GET") return ok(found);
    if (method === "PATCH" || method === "PUT") return ok(Object.assign(found, body));
    if (method === "DELETE") {
      zone.records.splice(zone.records.indexOf(found), 1);
      return ok({ id: found.id });
    }
  }

  // ── Worker routes ──
  if (rest === "/workers/routes" && method === "GET") return paged(zone.routes);
  if (rest === "/workers/routes" && method === "POST") {
    const route = { id: made(), ...body };
    zone.routes.push(route);
    return ok(route);
  }
  const route = /^\/workers\/routes\/([^/]+)$/.exec(rest);
  if (route) {
    const found = zone.routes.find((each) => each.id === route[1]);
    if (!found) return refused(404, 10020, "Route not found.");
    if (method === "GET") return ok(found);
    if (method === "PUT") return ok(Object.assign(found, body));
    if (method === "DELETE") {
      zone.routes.splice(zone.routes.indexOf(found), 1);
      return ok({ id: found.id });
    }
  }

  // ── Email Routing: the zone's setting and its one catch-all rule ──
  const routing = () => ({ ...zone.routing, name: zone.name, tag: zone.routing.id });
  if (rest === "/email/routing" && method === "GET") return ok(routing());
  if (rest === "/email/routing/enable" && method === "POST") {
    if (!zone.routing.enabled)
      for (const each of receivingRecordsOf(zone.name)) zone.records.push({ id: made(), ...each });
    zone.routing = { ...zone.routing, enabled: true, status: "ready" };
    return ok(routing());
  }
  if (rest === "/email/routing/disable" && method === "POST") {
    zone.routing = { ...zone.routing, enabled: false, status: "unconfigured" };
    return ok(routing());
  }
  const catchAll = () => ({ ...zone.catchAll, matchers: [{ type: "all" }], tag: zone.catchAll.id });
  if (rest === "/email/routing/rules/catch_all" && method === "GET") return ok(catchAll());
  if (rest === "/email/routing/rules/catch_all" && method === "PUT") {
    zone.catchAll = {
      id: zone.catchAll.id,
      name: body.name ?? zone.catchAll.name,
      enabled: body.enabled ?? zone.catchAll.enabled,
      actions: body.actions,
    };
    return ok(catchAll());
  }

  // ── Email Sending: the zone's sending domains ──
  if (rest === "/email/sending/subdomains" && method === "GET") return paged(zone.sending);
  if (rest === "/email/sending/subdomains" && method === "POST") {
    if (zone.sending.some((each) => each.name === body.name))
      return refused(409, 2040, "Sending subdomain already exists.");
    const domain = {
      tag: made(),
      name: body.name,
      enabled: true,
      dkim_selector: "cf-bounce",
      return_path_domain: `cf-bounce.${body.name}`,
    };
    zone.sending.push(domain);
    return ok(domain);
  }
  const sending = /^\/email\/sending\/subdomains\/([^/]+)$/.exec(rest);
  if (sending) {
    const found = zone.sending.find((each) => each.tag === sending[1]);
    if (!found) return refused(404, 2033, "Sending subdomain not found.");
    if (method === "GET") return ok(found);
    if (method === "DELETE") {
      zone.sending.splice(zone.sending.indexOf(found), 1);
      return ok({ tag: found.tag });
    }
  }
  return undefined;
}

/** The fake on a port of 127.0.0.1: its address for CLOUDFLARE_API_BASE_URL, every call in the
 *  order it came, and the calls that it did not serve. */
export async function startFake(world: World) {
  const calls: Call[] = [];
  const unserved: Call[] = [];
  /** THE CALLS THAT CLOUDFLARE REFUSES, for a deploy that fails midway: a call whose
   *  `METHOD path` one of these matches gets a 400, which the client does not send again, and
   *  changes nothing. A test fills and empties the list. */
  const refuses: RegExp[] = [];
  let made = 0;
  const server = createServer((request, response) => {
    const chunks: Buffer[] = [];
    request.on("data", (chunk: Buffer) => chunks.push(chunk));
    request.on("end", () => {
      const url = new URL(request.url || "/", "http://fake");
      const text = Buffer.concat(chunks).toString("utf8");
      const body = text ? JSON.parse(text) : undefined;
      const method = request.method || "GET";
      const path = url.pathname.replace(/^\/client\/v4/, "");
      const answer = refuses.some((each) => each.test(`${method} ${path}`))
        ? refused(400, 1004, "the fake refuses this call")
        : (answerOf(
            world,
            { method, path, query: url.searchParams, body },
            () => `made-${String(++made).padStart(2, "0")}`,
          ) ?? { status: 501, body: refused(501, 0, "the fake serves no such route").body });
      const call = {
        method,
        path,
        query: url.searchParams.toString(),
        body,
        status: answer.status,
      };
      calls.push(call);
      if (answer.status === 501) unserved.push(call);
      response.writeHead(answer.status, { "content-type": "application/json" });
      response.end(JSON.stringify(answer.body));
    });
  });
  await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  // a server that listens on a port answers its address as an object
  const { port } = server.address() as AddressInfo;
  return {
    url: `http://127.0.0.1:${port}/client/v4`,
    calls,
    unserved,
    refuses,
    close: () => new Promise<void>((resolve) => server.close(() => resolve())),
  };
}