Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript
28.9 KB
Raw Blame
/**
 * Streamable HTTP transport for the MCP server.
 *
 * This stays transport-only: every accepted JSON-RPC request is dispatched
 * through MCPServer.handleRequest, the same core used by stdio.
 *
 * ## Shutdown
 *
 * `close` used to be a bare `server.close()`. That stops the listener and
 * returns; it does not wait for anything, and the promise this module's
 * own request callback returns is floated, so a shutdown landing during a
 * tool call answered it with a dead socket. {@link HttpServerHandle.close}
 * now drains: it stops accepting NEW MCP work, keeps answering `/health`
 * so a supervisor can watch it happen, waits for the in-flight requests to
 * a bounded deadline, and only then shuts the listener down. The listener
 * outliving the refusal is deliberate - "stopped accepting" is about
 * requests, and a `/health` that answers `connection refused` tells a
 * supervisor nothing about which state it is in.
 */

import { createHash, timingSafeEqual } from "node:crypto";
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
import { once } from "node:events";
import type { Socket } from "node:net";
import type { Writable } from "node:stream";

import { MCPServer, type MCPServerOptions, type MCPServerRuntimeOptions } from "./server.ts";
import { errorResponse, internalErrorResponse, type JsonRpcResponse } from "./server.ts";
import type { RequestIdentity } from "./server.ts";
import { INVALID_REQUEST, PARSE_ERROR } from "./protocol.ts";
import { DRAIN_STATE, RequestDrain, resolveDrainDeadlineMs, type DrainOutcome } from "./drain.ts";
import { ORIGIN_CHANNEL, setOriginChannel } from "../core/origin-channel.ts";
import { TRANSPORT_REACH, type TransportReach } from "../core/graph/transport-reach.ts";
import { discoverConfig, resolveAgentName } from "../core/config.ts";
import { hasAnyMcpToken, resolveMcpToken } from "./token-source.ts";

export type { RequestIdentity };

/**
 * Device-config switch behind which the endpoint refuses credential-less
 * requests once a token map exists (write-side-trust, Task 7). Default
 * off, so every posture that predates tokens is byte-identical; with an
 * empty map the key only warns at startup (`o2b mcp`).
 */
export const MCP_TOKENS_REQUIRED_CONFIG_KEY = "mcp_tokens_required";
export const MCP_TOKENS_REQUIRED_ENV_KEY = "OPEN_SECOND_BRAIN_MCP_TOKENS_REQUIRED";

/** Flat device key with an env twin, resolved exactly like `write_approval.enabled`. */
export function resolveMcpTokensRequired(configPath?: string): boolean {
  const env = process.env[MCP_TOKENS_REQUIRED_ENV_KEY];
  const raw =
    env !== undefined && env !== ""
      ? env
      : discoverConfig(configPath).data[MCP_TOKENS_REQUIRED_CONFIG_KEY];
  return typeof raw === "string" && raw.trim().toLowerCase() === "true";
}

/**
 * The process-level fault counts a served transport reports on `/health`.
 *
 * Typed here and filled by a getter the CLI injects
 * ({@link ServeHttpOptions.faultCounts}): the guard that counts them is
 * process-global and lives in `src/cli/mcp-fault-guard.ts`, and this
 * module imports nothing from the CLI.
 */
export interface McpFaultCounts {
  readonly unhandled_rejection: number;
  readonly uncaught_exception: number;
  /** ISO time of the latest fault of either kind, `null` before any. */
  readonly last_fault_at: string | null;
}

export interface ServeHttpOptions {
  readonly host?: string;
  readonly port?: number;
  readonly apiKey?: string | null;
  /**
   * The `mcp_tokens_required` decision for this bind. Absent resolves the
   * device config key (env twin included) against the server's own
   * config path; injected by `o2b mcp` and by tests so the flag is
   * explicit at the surface that warns about it.
   */
  readonly tokensRequired?: boolean;
  /**
   * Where the transport writes its named warnings (a token store that
   * cannot be read, for one). Defaults to the process stderr; injected
   * so tests can pin what a degraded bind says.
   */
  readonly stderr?: Writable;
  /**
   * How long {@link HttpServerHandle.close} waits for in-flight requests.
   * Defaults to `O2B_MCP_DRAIN_MS`, and to ten seconds without it.
   */
  readonly drainDeadlineMs?: number;
  /**
   * The process-level fault counts, read on every `/health` request.
   * Injected by `o2b mcp` from its fault guard; without it `/health`
   * carries no `faults` field, exactly as before.
   */
  readonly faultCounts?: () => McpFaultCounts;
}

export interface HttpServerHandle {
  readonly server: Server;
  readonly host: string;
  readonly port: number;
  readonly url: string;
  /** The reach this bind minted for every request it will carry. */
  readonly reach: TransportReach;
  /** The in-flight register, so a caller can report what is running. */
  readonly drain: RequestDrain;
  /**
   * Stop accepting, await the in-flight requests to the deadline, close.
   * Returns what happened, including any request the deadline abandoned.
   */
  close(): Promise<DrainOutcome>;
}

const MAX_BODY_BYTES = 1024 * 1024;

export async function startHttp(
  ctx: MCPServerOptions,
  opts: ServeHttpOptions = {},
  runtimeOpts: MCPServerRuntimeOptions = {},
): Promise<HttpServerHandle> {
  // See the same claim in `serveStdio`: the transport is what knows this
  // process serves MCP tool calls (Unit C).
  setOriginChannel(ORIGIN_CHANNEL.mcpTool);
  const apiKey = opts.apiKey ?? null;
  const host = opts.host ?? "127.0.0.1";
  // Safe by default: on the loopback default a bearer is optional (the
  // loopback bind + Host/Origin rebinding guard are the baseline defence).
  // Binding to a NON-loopback interface exposes the Brain on the network, so
  // a credential source is mandatory there - the shared key, or a non-empty
  // per-agent token map (write-side-trust, Task 7). No permissive fallback.
  if (!isLoopbackHost(host) && !hasCredentialSource(apiKey, ctx.vault, ctx.configPath ?? null)) {
    throw new Error(
      "HTTP MCP transport bound to a non-loopback host requires --api-key or at least one " +
        `minted agent token (host=${host}); refusing to expose an unauthenticated endpoint on the network`,
    );
  }
  // Enforcement is an explicit operator key (default off), resolved once
  // per bind like the shared key; the non-empty-map half of the condition
  // is re-read per request behind the store's mtime cache, so minting the
  // first token tightens a running server without a restart.
  const tokensRequired =
    opts.tokensRequired ?? resolveMcpTokensRequired(ctx.configPath ?? undefined);
  const port = opts.port ?? 0;
  // A transport fact, set after the caller's runtime options for the same
  // reason `sendNotification` is on stdio: a runtime option must not be
  // able to claim a reach this bind did not establish.
  const reach = httpBindReach(host);
  const mcp = new MCPServer(ctx, { ...runtimeOpts, reach });
  const drain = new RequestDrain();
  const deadlineMs = opts.drainDeadlineMs ?? resolveDrainDeadlineMs(process.env);
  const server = createServer(async (req, res) => {
    // Registered here rather than inside the handler so the whole
    // request - header parsing, body read, dispatch, response write - is
    // inside the window a drain waits for. `finish` runs on `close`
    // rather than on the handler returning: a client that walks away
    // mid-body leaves the handler parked forever, and a drain waiting on
    // it would sit out its whole deadline for a request nobody wants.
    // The health probe is an OBSERVATION of the drain, not work it waits
    // for: counting it would make the number a supervisor reads include
    // the act of reading it, and a probe arriving as the last request
    // finishes would restart the wait it was checking on.
    // A request that arrives once the drain has started is not work
    // either - it is refused with a 503 below and never dispatched - and
    // counting it let a client retrying in a tight loop keep the register
    // non-empty, holding the shutdown open to its whole deadline over
    // requests the server had already declined to do.
    const untracked = isHealthProbe(req) || drain.draining;
    const finish = untracked ? NOTHING_TO_FINISH : drain.begin(requestLabel(req));
    // On `close` rather than on the handler returning, because that is
    // when the response has actually left: a request counted as finished
    // while its bytes are still queued lets the drain proceed to
    // `closeIdleConnections` over a socket that is not idle yet, and the
    // shutdown then waits for a client that is waiting for it.
    res.on("close", finish);
    try {
      await handleHttpRequest(
        mcp,
        apiKey,
        tokensRequired,
        host,
        drain,
        opts.faultCounts,
        opts.stderr ?? process.stderr,
        req,
        res,
      );
    } catch (exc) {
      // This promise used to be floated. A throw from the dispatch left
      // the socket open with no response on it and no record anywhere;
      // the client waited until its own timeout for a request the server
      // had already given up on.
      // The dispatcher's own INTERNAL_ERROR builder, so the same handling:
      // the prose goes through the redactor for this bind's reach, and
      // the code comes from the classifier, which names the class on
      // stderr when it does not know it.
      if (!res.headersSent) {
        writeJson(res, internalErrorResponse(null, exc, mcp.vault, mcp.reach));
      } else {
        res.end();
      }
    }
  });
  // Every accepted socket, tracked so an expired drain can actually drop
  // what it gave up on. `server.closeAllConnections()` is the documented
  // way to do that and, measured on this runtime, does NOT reach a socket
  // parked mid-body: the request stays open, `server.close` never calls
  // back, and a shutdown that promised a bounded deadline waits forever.
  // The set is the fallback that makes the deadline real.
  const sockets = new Set<Socket>();
  server.on("connection", (socket: Socket) => {
    sockets.add(socket);
    socket.on("close", () => sockets.delete(socket));
  });
  server.listen(port, host);
  await once(server, "listening");
  const addr = server.address();
  const actualPort = typeof addr === "object" && addr !== null ? addr.port : port;
  return {
    server,
    host,
    port: actualPort,
    url: `http://${host}:${actualPort}`,
    reach,
    drain,
    close: () => closeHttp(server, drain, deadlineMs, sockets),
  };
}

/** How one in-flight request is named in a drain report. */
function requestLabel(req: IncomingMessage): string {
  return `${req.method ?? "?"} ${requestPath(req)}`;
}

function requestPath(req: IncomingMessage): string {
  return (req.url ?? "/").split("?")[0] ?? "/";
}

/** The unauthenticated liveness probe, recognised before anything is counted. */
const HEALTH_PATH = "/health";

function isHealthProbe(req: IncomingMessage): boolean {
  return req.method === "GET" && requestPath(req) === HEALTH_PATH;
}

/** The finish for a request the drain does not track. */
const NOTHING_TO_FINISH = (): void => {};

/**
 * Drain, then shut the listener.
 *
 * The order matters and the connection handling is the part that is easy
 * to get wrong. `server.close()` refuses new CONNECTIONS but resolves
 * only once every existing socket is gone, and HTTP keep-alive means an
 * answered request leaves its socket open - so closing without touching
 * the idle ones hangs until the client happens to disconnect.
 * `closeIdleConnections` releases exactly those. Sockets still carrying
 * an abandoned request are dropped only after the deadline has expired,
 * and the outcome returned here still names those requests so the caller
 * can report them rather than dropping them silently.
 */
async function closeHttp(
  server: Server,
  drain: RequestDrain,
  deadlineMs: number,
  sockets: ReadonlySet<Socket>,
): Promise<DrainOutcome> {
  const outcome = await drain.drain(deadlineMs);
  const closed = new Promise<void>((resolve, reject) => {
    server.close((err) => (err ? reject(err) : resolve()));
  });
  server.closeIdleConnections();
  if (outcome.state === DRAIN_STATE.deadlineExpired) {
    for (const socket of sockets) socket.destroy();
  }
  await closed;
  return outcome;
}

export async function serveHttp(
  ctx: MCPServerOptions,
  opts: ServeHttpOptions = {},
  runtimeOpts: MCPServerRuntimeOptions = {},
): Promise<number> {
  const handle = await startHttp(ctx, opts, runtimeOpts);
  await once(handle.server, "close");
  return 0;
}

async function handleHttpRequest(
  mcp: MCPServer,
  apiKey: string | null,
  configTokensRequired: boolean,
  boundHost: string,
  drain: RequestDrain,
  faultCounts: (() => McpFaultCounts) | undefined,
  stderr: Writable,
  req: IncomingMessage,
  res: ServerResponse,
): Promise<void> {
  // DNS-rebinding guard (always enforced, never bypassable): a malicious web
  // page that resolves its own domain to 127.0.0.1 still sends its Host /
  // Origin, so rejecting any non-loopback Host/Origin blocks the rebind even
  // when the socket is loopback-bound.
  if (!hostAllowed(req, boundHost)) {
    res.writeHead(403, { "content-type": "text/plain; charset=utf-8" });
    res.end("Forbidden: Host not allowed\n");
    return;
  }
  if (!originAllowed(req, boundHost)) {
    res.writeHead(403, { "content-type": "text/plain; charset=utf-8" });
    res.end("Forbidden: Origin not allowed\n");
    return;
  }

  // Health endpoint: an unauthenticated liveness probe (still behind the Host
  // guard), so a supervisor can check the transport without a bearer.
  if (isHealthProbe(req)) {
    // Three fields rather than one, because a supervisor's next action
    // differs per state: `ok` keep going, `draining` stop sending work
    // and wait, and the count says how long that wait has left in it.
    // The health probe itself is never refused during a drain - a
    // shutdown a supervisor cannot observe is a shutdown it will report
    // as a crash. The drain does not count this request (see the
    // `untracked` note in `startHttp`), so `in_flight` never includes
    // the act of reading it.
    // `faults` only when the CLI injected a getter: a supervisor that
    // parses this body today sees exactly the three fields it knows.
    res.writeHead(200, { "content-type": "application/json" });
    res.end(
      JSON.stringify({
        status: drain.draining ? DRAIN_STATE.draining : "ok",
        transport: "http",
        in_flight: drain.inFlight,
        ...(faultCounts !== undefined ? { faults: faultCounts() } : {}),
      }) + "\n",
    );
    return;
  }

  // Stopped accepting. The listener is deliberately still up (see the
  // module docblock), so this is where "no more work" is actually said,
  // and it is said with a code a client retries rather than one it reads
  // as a protocol error.
  if (drain.draining) {
    res.writeHead(503, {
      "content-type": "text/plain; charset=utf-8",
      connection: "close",
      "retry-after": "1",
    });
    res.end("Service Unavailable: the MCP transport is shutting down\n");
    return;
  }

  // Credential resolution (write-side-trust, Task 7): the vault's token
  // map first - a match mints the token's agent as the REQUEST identity -
  // then the shared key, which keeps the process config identity. The
  // generic 401 body is unchanged, and no answer distinguishes a revoked
  // token from an unknown one.
  const auth = authenticateHttpRequest(mcp, apiKey, configTokensRequired, boundHost, stderr, req);
  if (auth.refused) {
    res.writeHead(401, { "content-type": "text/plain; charset=utf-8" });
    res.end("Unauthorized\n");
    return;
  }
  if (req.method !== "POST") {
    res.writeHead(405, { allow: "POST", "content-type": "text/plain; charset=utf-8" });
    res.end("Method Not Allowed\n");
    return;
  }

  let raw: string;
  try {
    raw = await readBody(req);
  } catch (exc) {
    writeJson(res, errorResponse(null, INVALID_REQUEST, (exc as Error).message));
    return;
  }

  let request: unknown;
  try {
    request = JSON.parse(raw);
  } catch (exc) {
    writeJson(res, errorResponse(null, PARSE_ERROR, `invalid JSON: ${(exc as Error).message}`));
    return;
  }
  if (Array.isArray(request)) {
    writeJson(
      res,
      errorResponse(
        null,
        INVALID_REQUEST,
        "batch requests are not supported by the 2025-06-18 spec",
      ),
    );
    return;
  }
  if (typeof request !== "object" || request === null) {
    writeJson(res, errorResponse(null, INVALID_REQUEST, "request must be an object"));
    return;
  }

  const jsonReq = request as Record<string, unknown>;
  // `HttpAuth.identity` is null for an anonymous request; the server's
  // parameter is optional, and the two nulls are the same fact spelled
  // in each module's own grammar.
  const response = await mcp.handleRequest(jsonReq, auth.identity ?? undefined);
  if (response === null) {
    res.writeHead(204);
    res.end();
    return;
  }
  // No `mcp-session-id`. The header is a promise of per-session state, and
  // this transport has none: one MCPServer instance serves every request
  // (see `startHttp`) and nothing is keyed by a session. What a request
  // carries instead is the credential-minted identity, threaded through
  // dispatch as a parameter - so the id that used to be minted here would
  // still be advertising state nothing behind it reads. A client that
  // received it would be entitled to expect the server to recognise it -
  // and to be told 404 once it expired - so advertising one was a claim
  // nothing behind it could honour.
  const accept = String(req.headers.accept ?? "");
  if (accept.includes("text/event-stream")) writeSse(res, response);
  else writeJson(res, response);
}

/**
 * Whether a credential was presented at all, from either header a client
 * uses. The shared-key gate's original reader, now also the fast-path
 * probe the token wiring uses to keep credential-less anonymous traffic
 * off the config and store reads it would never need.
 */
function presentedCredential(req: IncomingMessage): string | undefined {
  return bearerToken(req.headers.authorization) ?? firstHeader(req.headers["x-api-key"]);
}

/** The per-request answer of one HTTP request's credential check. */
interface HttpAuth {
  /** The credential-minted identity, or `null` for an anonymous request. */
  readonly identity: RequestIdentity | null;
  /** True when the request must be refused with the generic 401. */
  readonly refused: boolean;
}

/**
 * Resolve one request's credential against the token map and the shared
 * key, and decide whether the request may proceed.
 *
 * The rules, in the order the transport has always applied them:
 *
 * - a presented credential matching the token map mints the token's
 *   agent, `via: "token"`; the map is consulted first, so a credential
 *   that also spells the shared key is a token;
 * - a presented credential matching the shared key proceeds with the
 *   process config identity, `via: "shared-key"` - the operator master
 *   credential, byte-identical to the pre-token gate except that the
 *   identity now rides the request;
 * - a presented credential matching neither is refused outright: a wrong
 *   credential never degrades to anonymous, whatever the bind. The
 *   pre-token gate refused it whenever a key was configured; this gate
 *   refuses it everywhere, because treating a presented credential as
 *   absence would let a stale or forged bearer ride the loopback's
 *   anonymous posture;
 * - a credential-less request proceeds anonymous unless tokens are
 *   required - which is the config key AND a non-empty map, or a key-less
 *   non-loopback bind, where the requirement is the bind itself and
 *   holds whatever the map holds: revoking the last token must not
 *   re-open anonymous access an exposed bind never promised.
 *
 * A token store that cannot be READ never widens this gate for a
 * PRESENTED credential: the match falls through to the shared key with
 * the failure named on stderr - a corrupt store must not lock the
 * operator's master credential out of its own server. The enforcement
 * probe fails the other way: when enforcement was requested (the config
 * key or a key-less exposed bind), an unreadable map is treated as
 * non-empty, so a credential-less request is refused rather than waved
 * through - the requirement must not depend on the store's readability.
 *
 * The store probes sit behind the flags that need them: a loopback bind
 * with no requirement and no presented credential reads nothing.
 */
function authenticateHttpRequest(
  mcp: MCPServer,
  apiKey: string | null,
  configTokensRequired: boolean,
  boundHost: string,
  stderr: Writable,
  req: IncomingMessage,
): HttpAuth {
  const hasKey = apiKey !== null && apiKey !== "";
  const networkBare = !isLoopbackHost(boundHost) && !hasKey;
  let mapNonEmpty = false;
  if (configTokensRequired || networkBare) {
    try {
      mapNonEmpty = hasAnyMcpToken({ vault: mcp.vault, configPath: mcp.configPath });
    } catch (err) {
      warnTokenStoreUnreadable(stderr, err);
      // Enforcement was REQUESTED (the config key, or the exposed bind),
      // so an unreadable map must not read as an empty one: fail closed
      // and refuse what the requirement would have refused. The shared
      // key still answers - see the presented-credential catch below.
      mapNonEmpty = true;
    }
  }
  const enforced = networkBare || (configTokensRequired && mapNonEmpty);
  const presented = presentedCredential(req);
  const identity = authenticateRequest(req, {
    apiKey,
    resolveToken: (candidate) => {
      try {
        return resolveMcpToken({ vault: mcp.vault, configPath: mcp.configPath }, candidate);
      } catch (err) {
        warnTokenStoreUnreadable(stderr, err);
        // Null, not a throw: the presented credential then fails the way
        // any unmatched one does (the generic 401, no oracle), and a
        // matching shared key still authenticates.
        return null;
      }
    },
    sharedKeyAgent: resolveAgentName(mcp.configPath ?? undefined),
  });
  return {
    identity,
    refused: identity === null && (presented !== undefined || enforced || hasKey),
  };
}

/** The one named stderr line a failed token-store read produces. */
function warnTokenStoreUnreadable(stderr: Writable, err: unknown): void {
  stderr.write(
    `warning: the MCP token store could not be read; token matching is off for this ` +
      `request and the shared key still answers: ${(err as Error).message}\n`,
  );
}

export interface AuthenticateRequestOptions {
  /**
   * The shared operator key, launch-captured. `null` or `""` means none
   * is configured, and no key match is possible.
   */
  apiKey: string | null;
  /**
   * The vault's token map, mtime-cached by the store, so a rotation or
   * revocation lands on the next request without a restart.
   */
  resolveToken: (presented: string) => { agent: string } | null;
  /**
   * The process config identity a shared-key match carries. Optional;
   * without it the ambient `resolveAgentName()` answers, which is the
   * same resolution the process context makes.
   */
  sharedKeyAgent?: string;
}

/**
 * Token map first, then the shared key (identity = the process config
 * name), else `null`. A presented-but-unmatched credential and an absent
 * one both answer `null` - the refusal is the caller's decision, so no
 * answer here ever distinguishes a revoked token from an unknown one.
 */
export function authenticateRequest(
  req: IncomingMessage,
  opts: AuthenticateRequestOptions,
): RequestIdentity | null {
  const presented = presentedCredential(req);
  if (presented === undefined) return null;
  const tokenAgent = opts.resolveToken(presented);
  if (tokenAgent !== null) return { agent: tokenAgent.agent, via: "token" };
  if (opts.apiKey !== null && opts.apiKey !== "" && constantTimeEqual(presented, opts.apiKey)) {
    return { agent: opts.sharedKeyAgent ?? resolveAgentName(), via: "shared-key" };
  }
  return null;
}

/** Whether the bind would have any credential source to demand. */
function hasCredentialSource(
  apiKey: string | null,
  vault: string | null,
  configPath: string | null,
): boolean {
  if (apiKey !== null && apiKey !== "") return true;
  return hasAnyMcpToken({ vault, configPath });
}

/** Canonical loopback host names a rebinding guard trusts. */
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);

/**
 * What an HTTP bind on `host` establishes about the callers it will
 * accept: nothing beyond "a request arrived", unless the bind is
 * loopback - in which case the request originated on this host.
 *
 * Keyed on the BIND rather than on a per-request peer address, because
 * that is what this transport actually controls: a non-loopback bind is
 * an explicit decision to expose the Brain on the network, and it already
 * carries a mandatory bearer (see {@link startHttp}). A `Host` header is
 * a caller-supplied string and could not be used here for the reason
 * `./reach-refusal.ts` states.
 */
export function httpBindReach(host: string): TransportReach {
  return isLoopbackHost(host) ? TRANSPORT_REACH.local : TRANSPORT_REACH.remote;
}

export function isLoopbackHost(host: string): boolean {
  return LOOPBACK_HOSTS.has(normaliseHostname(host));
}

/** Strip a port and IPv6 brackets, lowercase - `[::1]:8080` -> `::1`. */
function normaliseHostname(value: string): string {
  let host = value.trim().toLowerCase();
  if (host.startsWith("[")) {
    // Bracketed IPv6, optionally with :port after the bracket.
    const end = host.indexOf("]");
    return end === -1 ? host.slice(1) : host.slice(1, end);
  }
  // IPv4/hostname: drop a trailing :port (a bare IPv6 has multiple colons).
  const colon = host.indexOf(":");
  if (colon !== -1 && host.indexOf(":", colon + 1) === -1) host = host.slice(0, colon);
  return host;
}

/**
 * DNS rebinding exploits a LOOPBACK-bound server reached from a victim's
 * browser (a malicious site rebinds its own domain to 127.0.0.1). The guard is
 * therefore meaningful only for a loopback bind, where the trusted Host set is
 * the enumerable loopback names. A non-loopback bind is an explicit network
 * exposure that always carries a mandatory bearer (see startHttp), so the
 * bearer - not a Host allowlist we cannot enumerate for a wildcard bind - is
 * the auth boundary there; blocking the machine's real IP / DNS Host would
 * make `0.0.0.0` unusable. Skip the guard for non-loopback binds.
 */
function hostGuardApplies(boundHost: string): boolean {
  return isLoopbackHost(boundHost);
}

/**
 * The `Host` header must name a loopback address or the exact bound host.
 * A present-but-foreign Host is the DNS-rebinding signal and is rejected; an
 * absent Host (uncommon; not a browser rebind) is allowed.
 */
function hostAllowed(req: IncomingMessage, boundHost: string): boolean {
  if (!hostGuardApplies(boundHost)) return true;
  const host = req.headers.host;
  if (host === undefined) return true;
  const hostname = normaliseHostname(host);
  return isLoopbackHost(hostname) || hostname === normaliseHostname(boundHost);
}

/**
 * When an `Origin` is present (a browser request), its host must be loopback
 * or the bound host; a cross-origin browser request is rejected. A missing
 * Origin (non-browser client) is allowed.
 */
function originAllowed(req: IncomingMessage, boundHost: string): boolean {
  if (!hostGuardApplies(boundHost)) return true;
  const origin = firstHeader(req.headers.origin);
  if (origin === undefined || origin === "" || origin === "null") return origin !== "null";
  let hostname: string;
  try {
    hostname = new URL(origin).hostname.toLowerCase();
  } catch {
    return false;
  }
  return isLoopbackHost(hostname) || hostname === normaliseHostname(boundHost);
}

function bearerToken(value: string | undefined): string | undefined {
  if (value === undefined) return undefined;
  // One whitespace and then the rest, trimmed after the match: the old
  // `\s+(.+)` let both groups claim the same spaces, which backtracks
  // polynomially on a long run of them.
  const m = /^Bearer\s([\s\S]*)$/i.exec(value.trim());
  const token = m?.[1]?.trimStart();
  return token ? token : undefined;
}

function firstHeader(value: string | string[] | undefined): string | undefined {
  if (Array.isArray(value)) return value[0];
  return value;
}

function constantTimeEqual(a: string, b: string): boolean {
  const da = createHash("sha256").update(a).digest();
  const db = createHash("sha256").update(b).digest();
  return timingSafeEqual(da, db);
}

async function readBody(req: IncomingMessage): Promise<string> {
  const chunks: Buffer[] = [];
  let total = 0;
  for await (const chunk of req) {
    const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
    total += buf.length;
    if (total > MAX_BODY_BYTES) throw new Error("request body too large");
    chunks.push(buf);
  }
  return Buffer.concat(chunks).toString("utf8");
}

function writeJson(res: ServerResponse, response: JsonRpcResponse): void {
  res.writeHead(200, { "content-type": "application/json" });
  res.end(JSON.stringify(response));
}

function writeSse(res: ServerResponse, response: JsonRpcResponse): void {
  res.writeHead(200, {
    "content-type": "text/event-stream",
    "cache-control": "no-cache",
  });
  res.end(`event: message\ndata: ${JSON.stringify(response)}\n\n`);
}