Docs Packages

@procedures/http

packages/http/README.md on GitHub · Package map · Procedures

npm install @procedures/http

HTTP requests as procedures. A host allowlist refuses loopback, private and link-local addresses by default. Each call obeys its deadline and a size limit.

The procedures#

ProcedureWhat it doesEffects
http.requestIt sends a request with each method and gives the status, the headers and the body.reads and writes network
http.jsonIt sends a GET or a POST of JSON and gives the parsed body.reads and writes network
http.ndjsonIt sends a GET or a POST and gives a stream of the JSON values of the lines.reads and writes network
http.sseIt sends a GET or a POST and gives a stream of server-sent events.reads and writes network
  • Each procedure can change remote data with a POST, so each procedure declares a write. http.request also sends a PUT or a DELETE.
  • http.ndjson and http.sse declare stream: { unbounded: true }, because a server can send a stream without an end. A face that collects a stream refuses them or stops them at its limits.
import "@procedures/http/register";

await client.call(["http", "json"], { url: "https://api.github.com/repos/nodejs/node" });
await client.call(["http", "request"], { url: "https://example.com/upload", method: "PUT", body: "text" });

The streams of a POST#

An LLM API sends its answer to a POST as server-sent events. http.sse and http.ndjson take the same request fields as http.request:

FieldMeaning
methodGET or POST. The default is POST with body or json, and GET without them.
jsonA body of JSON. The procedure sets content-type: application/json.
bodyA body of text. The procedure sets content-type: text/plain; charset=utf-8.
headersThe headers of the request. A header of the input replaces a header that the procedure sets.
const events = client.stream(["http", "sse"], {
  url: "https://api.example.com/v1/chat",
  headers: { authorization: `Bearer ${key}` },
  json: { prompt: "Hello", stream: true },
});
for await (const event of events) console.log(event.data);
  • A POST of a stream gets the same host check, size limit of the request, time limits and deadline as the other requests.
  • Two bodies, or a GET with a body, fail before the request.

The hosts#

The default module (httpModule) reaches each public host. It refuses these addresses:

  • Loopback: 127.0.0.0/8 and ::1
  • Private: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 and fc00::/7
  • Link-local: 169.254.0.0/16 and fe80::/10, with the cloud metadata address 169.254.169.254
  • Shared, multicast, documentation, benchmarking and reserved addresses
  • An IPv6 address that holds one of these IPv4 addresses: IPv4-mapped, NAT64 and 6to4

A refusal is the error FORBIDDEN with the reason host-not-allowed. A server sends the reason in the metadata key reason.

createHttpModule() gives the same procedures with other hosts:

import { createRegistry } from "@procedures/client";
import { createHttpModule } from "@procedures/http/module";

const registry = createRegistry(createHttpModule({ allow: ["localhost:11434", "10.0.0.0/8", "*.corp.example"] }));
OptionMeaning
allowMore hosts: a host name, a wildcard (*.example.com), an IP address or a CIDR range. Each entry can end with a port.
publicHostsfalse: only the hosts of allow. The default is true.
maxRequestBytesThe largest body of a request. The default is 10 MiB.
maxResponseBytesThe largest body of a response, and the maximum of each input. The default is 10 MiB.
resolveThe resolver of host names. The default is dns.lookup. A test gives its own resolver.

Rules#

  • A host name in allow lets the procedures reach each address of that name. A wildcard lets them reach the names under it, not the name itself.
  • An IP address or a range in allow lets the procedures reach that address, also when a host name resolves to it.
  • An entry without a port applies to each port. An entry with a port applies only to that port.
  • The check resolves the host name and examines each address. The connection uses only the addresses that pass the check, so a second DNS answer cannot change the address.
  • A name with a public address and a private address connects only to the public address.
  • Each redirect goes through the same check before its connection.
  • A bad entry of allow makes createHttpModule() throw.
  • A host gives createHttpModule() to createRegistry() before its bundles. Then it replaces the httpModule in the modules of a bundle.

The host policy in other packages#

createHostFetch(options) gives a fetch for GET and HEAD requests through the same checks. Its options are the options of createHttpModule(). A procedure of another package uses it for a URL of its caller:

  • weather.forecast uses it by default.
  • createGeoModule({ fetch }) and createIcsModule({ fetch }) take it. Their default stays the global fetch, because their roots run in a browser.
  • mcpHostModules of @procedures/bundle-assistant gives it to the modules of geo and ics. The dev-tools server puts them before its bundles.
import { createHostFetch } from "@procedures/http";
import { createGeoModule } from "@procedures/geo/module";

const registry = createRegistry(createGeoModule({ fetch: createHostFetch({ allow: ["osrm.lan:5000"] }) }));

A refusal is FORBIDDEN with the reason host-not-allowed. When the signal of the caller aborts, the function throws the reason of the signal, as fetch does.

The response has headers, with names in lowercase. The option method: "HEAD" reads only the headers of a page, for example for frameRefusal:

const response = await hostFetch(url, { method: "HEAD", signal: AbortSignal.timeout(5_000) });
const decision = frameRefusal(response.headers, { ancestor: "http://127.0.0.1:3000", page: response.url });

The addresses and the local names#

  • isPublicAddress(address) tells if an IP address is public. specialClass(bytes) gives the class of an address that is not public.
  • isLocalName(hostname) tells if a host name is a name of this computer or of the local network. The function reads no DNS.
  • A local name is localhost or a name in the domain localhost, local, internal or home.arpa. The letter case and a final dot change nothing.
  • The sources of the domains are RFC 6761, RFC 6762 (mDNS), RFC 8375 and the reservation of internal by ICANN in 2024.
import { isLocalName } from "@procedures/http";

isLocalName("printer.local"); // true
isLocalName("Router.Home.Arpa."); // true
isLocalName("myinternal.example"); // false

The policy proxy for other programs#

startPolicyProxy(options) starts a local forward proxy. The proxy applies the host policy to each request of another program, for example a headless browser.

import { createHostPolicy, startPolicyProxy } from "@procedures/http";

const proxy = await startPolicyProxy({
  policy: createHostPolicy({ allow: ["intranet.example"] }),
  onRefusal: (refusal) => console.warn(refusal.method, refusal.target, refusal.reason),
});
try {
  // Start the program with the flag `--proxy-server=${proxy.url}`
} finally {
  await proxy.close();
}
  • The proxy listens on 127.0.0.1, on a free port. proxy.url is its address, for example http://127.0.0.1:41234.
  • A CONNECT request opens a tunnel to host:port. A browser sends https:, wss: and ws: requests in a tunnel.
  • A plain request has an absolute http: URL, for example GET http://a.example/page. The proxy sends it to the host, and gives back the response.
  • The proxy examines the host of each request with checkHost. The connection uses only the checked addresses, so a second DNS answer cannot change the address.
  • The proxy gives the status 403 to a host that the policy refuses. The page of the 403 does not tell the reason.
  • proxy.refusals gives the first 1000 refusals (MAX_PROXY_REFUSALS). onRefusal gets each refusal at its time. An error of onRefusal does not stop the proxy.
  • A host with no address, a connection that fails and a response with a bad status (for example 99) get the status 502. Each other request gets the status 400.
  • The proxy does not send the headers of one connection, for example proxy-authorization and connection.
  • proxy.requests gives the number of requests that the proxy got, also each refused request. The value stays after close().
  • close() closes each open connection and the listener. Then the port is free. A second call does nothing.
  • The default policy is DEFAULT_HOST_POLICY: each public host, and no other host.

@procedures/browser uses the proxy for its option hostPolicy.

Use the proxy only for one run, and close it at the end of the run:

  • The listener has no token. While the proxy runs, each program on this computer can send requests through it.
  • Such a program can reach each host that the policy permits. With an allow entry for an intranet host, it can reach that intranet host.
  • The connections to the hosts have no idle time-out. close() closes them.

Limits and time#

  • Each input of http.request and http.json has timeoutMs. The default is 30 seconds.
  • The streams have no default time. timeoutMs stops the whole stream, and idleTimeoutMs stops a stream that gets no data.
  • The deadline of the call (ctx.capability.deadline) and the abort of the caller (ctx.signal) also stop the call. The earliest event wins.
  • A stop gives TIMEOUT, or ABORTED for an abort of the caller.
  • maxResponseBytes limits the body of the response after its content encoding. The limit of the input can only be smaller than the limit of the module.
  • maxLineBytes limits one NDJSON line, and maxEventBytes limits one event. The default of each is 1 MiB.
  • The procedures decode gzip, deflate and br. The size limit counts the decoded bytes, so a small compressed body cannot fill the memory.

Redirects#

  • redirect: "follow" is the default. maxRedirects is 5 by default.
  • redirect: "manual" gives the redirect response. redirect: "error" fails with REDIRECT.
  • A 303 continues with a GET without the body. A 301 or a 302 after a POST also continues with a GET. A 307 and a 308 keep the method and the body.
  • A redirect to another origin removes the headers authorization, cookie and proxy-authorization.

Errors#

ErrorCodeCause
InvocationErrorFORBIDDENThe module refuses the host (reason host-not-allowed).
InvocationErrorTIMEOUTtimeoutMs, idleTimeoutMs or the deadline passed.
InvocationErrorABORTEDThe caller aborted the call.
HttpErrorRESPONSE_TOO_LARGE, REQUEST_TOO_LARGE, LINE_TOO_LARGE, EVENT_TOO_LARGEA body, a line or an event is larger than its limit.
HttpErrorHTTP_STATUShttp.json, http.ndjson or http.sse got a status outside 200 to 299.
HttpErrorBAD_JSON, BAD_CONTENT_TYPE, BAD_URLThe response or the URL is not correct.
HttpErrorREDIRECT, TOO_MANY_REDIRECTSA redirect that the input does not permit.
HttpErrorCONNECTIONThe connection failed.
  • http.request gives each status. A status of 400 or more is not an error.
  • http.json with failOnStatus: false gives the status. A body that is not JSON then gives its text.
  • A stream procedure waits for the status. A refused host or a bad status fails the call before the first item.

Server-sent events#

  • The parse obeys the rules of the HTML standard. A line ends at CR, LF or CRLF. A blank line sends an event. A line that starts with a colon is a comment.
  • An event has event (message by default), data, the last event ID id and retry.
  • The procedure does not connect again after the end of the stream. To continue, a caller sends the last ID in lastEventId.
  • A redirect of a POST obeys the rules of the redirects. A 303, or a 301 or 302, continues with a GET without the body.

The frame rules of a response#

A page can refuse to show in a frame of another page. frameRefusal(headers, { ancestor, page }) gives the decision of a browser. It uses no network.

import { frameRefusal } from "@procedures/http";

const decision = frameRefusal(response.headers, { ancestor: "https://a.example", page: response.url });
// { refused: true, by: "x-frame-options", detail: "X-Frame-Options is SAMEORIGIN, and https://a.example is another origin." }
  • An enforced policy with frame-ancestors decides. Then the function ignores X-Frame-Options. Each such policy must accept the ancestor.
  • Else X-Frame-Options decides, by the rules of the HTML standard. DENY refuses, and SAMEORIGIN refuses an ancestor of another origin.
  • Values of X-Frame-Options that do not agree refuse each frame. ALLOW-FROM and unknown values do not refuse, as in a browser.
  • Content-Security-Policy-Report-Only does not refuse.
  • parseCsp, sourceAllows and sourceListAllows give the parts of the CSP3 rules: the policies of the headers, and the match of a source expression.

Limits of this package#

  • The procedures do not use a proxy.
  • The policy proxy does not decrypt a tunnel. It examines the host and the port of a tunnel, not the requests in it.
  • Each request gets its own connection. The procedures do not keep connections open.
  • The check and the connection use the same addresses. A server can still send a redirect, and the check examines it before its connection.