Docs Packages
@procedures/http
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#
| Procedure | What it does | Effects |
|---|---|---|
http.request | It sends a request with each method and gives the status, the headers and the body. | reads and writes network |
http.json | It sends a GET or a POST of JSON and gives the parsed body. | reads and writes network |
http.ndjson | It sends a GET or a POST and gives a stream of the JSON values of the lines. | reads and writes network |
http.sse | It 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.requestalso sends a PUT or a DELETE. http.ndjsonandhttp.ssedeclarestream: { 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:
| Field | Meaning |
|---|---|
method | GET or POST. The default is POST with body or json, and GET without them. |
json | A body of JSON. The procedure sets content-type: application/json. |
body | A body of text. The procedure sets content-type: text/plain; charset=utf-8. |
headers | The 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
GETwith 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/8and::1 - Private:
10.0.0.0/8,172.16.0.0/12,192.168.0.0/16andfc00::/7 - Link-local:
169.254.0.0/16andfe80::/10, with the cloud metadata address169.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"] }));
| Option | Meaning |
|---|---|
allow | More hosts: a host name, a wildcard (*.example.com), an IP address or a CIDR range. Each entry can end with a port. |
publicHosts | false: only the hosts of allow. The default is true. |
maxRequestBytes | The largest body of a request. The default is 10 MiB. |
maxResponseBytes | The largest body of a response, and the maximum of each input. The default is 10 MiB. |
resolve | The resolver of host names. The default is dns.lookup. A test gives its own resolver. |
Rules#
- A host name in
allowlets 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
allowlets 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
allowmakescreateHttpModule()throw. - A host gives
createHttpModule()tocreateRegistry()before its bundles. Then it replaces thehttpModulein 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.forecastuses it by default.createGeoModule({ fetch })andcreateIcsModule({ fetch })take it. Their default stays the globalfetch, because their roots run in a browser.mcpHostModulesof@procedures/bundle-assistantgives it to the modules ofgeoandics. 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
localhostor a name in the domainlocalhost,local,internalorhome.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
internalby 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.urlis its address, for examplehttp://127.0.0.1:41234. - A
CONNECTrequest opens a tunnel tohost:port. A browser sendshttps:,wss:andws:requests in a tunnel. - A plain request has an absolute
http:URL, for exampleGET 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.refusalsgives the first 1000 refusals (MAX_PROXY_REFUSALS).onRefusalgets each refusal at its time. An error ofonRefusaldoes 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-authorizationandconnection. proxy.requestsgives the number of requests that the proxy got, also each refused request. The value stays afterclose().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
allowentry 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.requestandhttp.jsonhastimeoutMs. The default is 30 seconds. - The streams have no default time.
timeoutMsstops the whole stream, andidleTimeoutMsstops 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, orABORTEDfor an abort of the caller. maxResponseByteslimits the body of the response after its content encoding. The limit of the input can only be smaller than the limit of the module.maxLineByteslimits one NDJSON line, andmaxEventByteslimits one event. The default of each is 1 MiB.- The procedures decode
gzip,deflateandbr. The size limit counts the decoded bytes, so a small compressed body cannot fill the memory.
Redirects#
redirect: "follow"is the default.maxRedirectsis 5 by default.redirect: "manual"gives the redirect response.redirect: "error"fails withREDIRECT.- 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,cookieandproxy-authorization.
Errors#
| Error | Code | Cause |
|---|---|---|
InvocationError | FORBIDDEN | The module refuses the host (reason host-not-allowed). |
InvocationError | TIMEOUT | timeoutMs, idleTimeoutMs or the deadline passed. |
InvocationError | ABORTED | The caller aborted the call. |
HttpError | RESPONSE_TOO_LARGE, REQUEST_TOO_LARGE, LINE_TOO_LARGE, EVENT_TOO_LARGE | A body, a line or an event is larger than its limit. |
HttpError | HTTP_STATUS | http.json, http.ndjson or http.sse got a status outside 200 to 299. |
HttpError | BAD_JSON, BAD_CONTENT_TYPE, BAD_URL | The response or the URL is not correct. |
HttpError | REDIRECT, TOO_MANY_REDIRECTS | A redirect that the input does not permit. |
HttpError | CONNECTION | The connection failed. |
http.requestgives each status. A status of 400 or more is not an error.http.jsonwithfailOnStatus: falsegives 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(messageby default),data, the last event IDidandretry. - 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-ancestorsdecides. Then the function ignoresX-Frame-Options. Each such policy must accept the ancestor. - Else
X-Frame-Optionsdecides, by the rules of the HTML standard.DENYrefuses, andSAMEORIGINrefuses an ancestor of another origin. - Values of
X-Frame-Optionsthat do not agree refuse each frame.ALLOW-FROMand unknown values do not refuse, as in a browser. Content-Security-Policy-Report-Onlydoes not refuse.parseCsp,sourceAllowsandsourceListAllowsgive 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.
Related packages#
@procedures/client: the core, with the capabilities and the deadline.@procedures/json: the transforms of JSON values.