@amritk/resolve-refs 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AI.md CHANGED
@@ -39,7 +39,9 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
39
39
  `169.254.169.254` / metadata hosts by name (`metadata.google.internal`,
40
40
  `*.internal`) are refused unless `allowPrivateHosts: true` or an explicit
41
41
  `allowedHosts` entry. Hostnames are also resolved and refused when they point
42
- at a private address (`verifyDns: false` opts out).
42
+ at a private address, and the connection dials only the addresses that were
43
+ checked, so a DNS-rebinding record cannot slip past (`verifyDns: false` opts
44
+ out; a custom `fetch` gets the check as a pre-flight only).
43
45
  4. **Local `$ref`s are confined to the root document's directory.** A
44
46
  `{"$ref": "../common/schemas.json"}` is refused by default — pass
45
47
  `allowedRoots: ['./specs']` (or whatever contains both files) to allow it.
package/README.md CHANGED
@@ -109,14 +109,16 @@ The remote path has always been default-deny; the local path now matches it.
109
109
  uses the same key.
110
110
  - **The SSRF guard runs in two passes.** `isPrivateHost` is synchronous and reads
111
111
  only the URL (every IPv4 encoding, IPv4-in-IPv6 embeddings, ULA/link-local/
112
- site-local IPv6, plus a name denylist for cloud-metadata endpoints).
113
- `assertPublicHost` then resolves the name and refuses it when any address is
114
- non-public. Both run on every redirect hop.
115
- - **Known residual gap: DNS rebinding.** A record that changes between the check
116
- and the connection still wins; closing that requires pinning the socket to the
117
- verified address, which Node's `fetch` does not let us do. What the DNS pass
118
- buys is that a name *statically* pointing at a private address is refused —
119
- which is the case that actually shows up.
112
+ site-local IPv6, plus a name denylist for cloud-metadata endpoints). The name
113
+ is then resolved and refused when any address is non-public. Both run on every
114
+ redirect hop.
115
+ - **The connection dials the addresses that were checked.** The DNS pass runs
116
+ inside the socket's own lookup, so the name is resolved once per connection and
117
+ a rebinding record (public for the check, `127.0.0.1` for the connect) has no
118
+ second answer to give. `Host`, SNI, and certificate checks still use the name.
119
+ A custom `fetch` makes its own connections and cannot be pinned: it gets the
120
+ check as a pre-flight only, which stops a name that statically points at a
121
+ private address but not one that rebinds.
120
122
  - **A resolve is bounded** by `maxDocuments`, `totalTimeoutMs`, and `maxDepth`, so
121
123
  a hostile document cannot use the resolver as an egress amplifier, hold the
122
124
  process for hours, or crash it with nesting.
@@ -1,18 +1,10 @@
1
- /**
2
- * Resolves a hostname to the addresses it points at. Only the `address` is used
3
- * — the shape matches `dns.lookup(host, { all: true })` so the real resolver
4
- * drops straight in. Exposed as a parameter so the guard can be exercised
5
- * against known records without a live resolver, and so a caller that resolves
6
- * names some other way (a custom DoH client) can supply it.
7
- */
8
- export type HostLookup = (hostname: string) => Promise<{
9
- address: string;
10
- }[]>;
1
+ import { type HostLookup } from './resolve-public-host.js';
2
+ export type { HostLookup } from './resolve-public-host.js';
11
3
  /**
12
4
  * The name-resolving half of the SSRF guard: resolves `hostname` and rejects if
13
5
  * **any** address it resolves to is non-public. {@link isPrivateHost} only reads
14
6
  * the URL, so `127.0.0.1.nip.io` — a public-looking name whose A record is
15
- * `127.0.0.1` — sails past it. This closes that hole for the fetch path.
7
+ * `127.0.0.1` — sails past it.
16
8
  *
17
9
  * It is deliberately a separate async function rather than a change to
18
10
  * `isPrivateHost`: that predicate is synchronous, pure, and exported (the CLI
@@ -25,13 +17,11 @@ export type HostLookup = (hostname: string) => Promise<{
25
17
  * the resolving (so names do not resolve locally) should allow-list the host or
26
18
  * pass `verifyDns: false`.
27
19
  *
28
- * **Residual gap — DNS rebinding is narrowed, not closed.** Between this check
29
- * and the connection, the record can change to a private address (the classic
30
- * TOCTOU rebind). Truly closing it means pinning the socket to the address we
31
- * just verified, and Node's `fetch` offers no seam for that. What this does buy:
32
- * a name that *statically* points at a private address — the overwhelmingly
33
- * common case, every `nip.io`-style trick included — is refused, and an attacker
34
- * is pushed to a short-TTL rebinding record instead of a plain A record.
20
+ * **A check on its own does not stop DNS rebinding.** Anything that resolves the
21
+ * name again before connecting can be handed a different, private answer.
22
+ * `resolveRefsFromFile` does not rely on this function for its own fetches: it
23
+ * dials the very addresses it verified. Use this as a pre-check only where the
24
+ * connection is made by code you cannot pin, and treat it as advisory there.
35
25
  *
36
26
  * Rejects with an `Error` explaining the refusal; resolves when the host looks
37
27
  * public.
@@ -1,27 +1,6 @@
1
- import { lookup } from "node:dns/promises";
2
- import { isPrivateHost } from "./is-private-host.js";
3
- const defaultLookup = (hostname) => lookup(hostname, { all: true, verbatim: true });
4
- const assertPublicHost = async (hostname, lookupHost = defaultLookup) => {
5
- const host = hostname.replace(/^\[|\]$/g, "").replace(/\.+$/, "").toLowerCase();
6
- if (host === "")
7
- throw new Error("host is empty");
8
- if (isPrivateHost(host)) {
9
- throw new Error(`host "${hostname}" is a private or loopback address (set allowPrivateHosts to permit)`);
10
- }
11
- let addresses;
12
- try {
13
- addresses = await lookupHost(host);
14
- } catch (err) {
15
- throw new Error(`cannot verify that host "${hostname}" is public: DNS lookup failed (${String(err)}) (allow-list the host or set verifyDns: false to skip this check)`);
16
- }
17
- if (addresses.length === 0) {
18
- throw new Error(`cannot verify that host "${hostname}" is public: DNS returned no addresses (allow-list the host or set verifyDns: false to skip this check)`);
19
- }
20
- for (const { address } of addresses) {
21
- if (isPrivateHost(address)) {
22
- throw new Error(`host "${hostname}" resolves to the non-public address ${address} (set allowPrivateHosts to permit)`);
23
- }
24
- }
1
+ import { resolvePublicHost } from "./resolve-public-host.js";
2
+ const assertPublicHost = async (hostname, lookupHost) => {
3
+ await resolvePublicHost(hostname, lookupHost);
25
4
  };
26
5
  export {
27
6
  assertPublicHost
@@ -0,0 +1,30 @@
1
+ import type { PublicAddress } from './resolve-public-host.js';
2
+ /** The subset of `fetch`'s `init` that remote `$ref` resolution sends. */
3
+ export type PinnedFetchInit = {
4
+ redirect: 'manual';
5
+ signal: AbortSignal;
6
+ headers?: Record<string, string>;
7
+ };
8
+ /** Resolves a hostname to the only addresses the connection may dial. */
9
+ export type ResolveHost = (hostname: string) => Promise<PublicAddress[]>;
10
+ /**
11
+ * A `fetch` for remote `$ref`s that dials only the addresses `resolveHost`
12
+ * returns, closing the DNS-rebinding hole a check-then-`fetch` guard leaves.
13
+ *
14
+ * Checking a name and then calling `fetch` resolves it twice: once for the
15
+ * check and again inside the socket. A record with a short TTL can answer the
16
+ * first with a public address and the second with `127.0.0.1` or
17
+ * `169.254.169.254`. Node's `fetch` offers no seam to pin the address, but
18
+ * `http.request` does: its `lookup` option *is* the socket's resolver, so
19
+ * running the guard there makes the verified addresses the dialed ones. The
20
+ * host name itself is still what goes on the wire, so `Host`, SNI, and
21
+ * certificate verification are unchanged.
22
+ *
23
+ * `agent: false` gives every request its own socket. A shared agent could hand
24
+ * back a keep-alive socket some other code opened to the same `host:port`
25
+ * without this guard — connected to wherever the name pointed then.
26
+ *
27
+ * Bodies are requested uncompressed (`accept-encoding: identity`) because,
28
+ * unlike `fetch`, `http.request` does not decode them.
29
+ */
30
+ export declare const createPinnedFetch: (resolveHost: ResolveHost) => (url: string, init: PinnedFetchInit) => Promise<Response>;
@@ -0,0 +1,76 @@
1
+ import { request as httpRequest } from "node:http";
2
+ import { request as httpsRequest } from "node:https";
3
+ import { Readable } from "node:stream";
4
+ const NULL_BODY_STATUSES = /* @__PURE__ */ new Set([101, 204, 205, 304]);
5
+ const wantedFamily = (family) => {
6
+ if (family === 4 || family === "IPv4")
7
+ return 4;
8
+ if (family === 6 || family === "IPv6")
9
+ return 6;
10
+ return void 0;
11
+ };
12
+ const toResponse = (message) => {
13
+ const headers = new Headers();
14
+ for (let i = 0; i + 1 < message.rawHeaders.length; i += 2) {
15
+ headers.append(message.rawHeaders[i], message.rawHeaders[i + 1]);
16
+ }
17
+ const status = message.statusCode ?? 0;
18
+ if (NULL_BODY_STATUSES.has(status)) {
19
+ message.resume();
20
+ return new Response(null, { status, statusText: message.statusMessage ?? "", headers });
21
+ }
22
+ return new Response(Readable.toWeb(message), {
23
+ status,
24
+ statusText: message.statusMessage ?? "",
25
+ headers
26
+ });
27
+ };
28
+ const createPinnedFetch = (resolveHost) => (url, init) => {
29
+ const target = new URL(url);
30
+ if (target.username !== "" || target.password !== "") {
31
+ return Promise.reject(new TypeError(`refusing a URL that includes credentials: ${target.host}`));
32
+ }
33
+ const send = target.protocol === "https:" ? httpsRequest : httpRequest;
34
+ const lookup = (hostname, options, callback) => {
35
+ resolveHost(hostname).then((addresses) => {
36
+ const family = wantedFamily(options.family);
37
+ const usable = family === void 0 ? addresses : addresses.filter((entry) => entry.family === family);
38
+ const first = usable[0];
39
+ if (first === void 0) {
40
+ callback(new Error(`host "${hostname}" has no IPv${family} address`), "", 0);
41
+ return;
42
+ }
43
+ if (options.all)
44
+ callback(null, usable);
45
+ else
46
+ callback(null, first.address, first.family);
47
+ }, (err) => callback(err instanceof Error ? err : new Error(String(err)), "", 0));
48
+ };
49
+ return new Promise((resolve, reject) => {
50
+ const request = send({
51
+ protocol: target.protocol,
52
+ // IP literals never reach `lookup` (the socket dials them directly);
53
+ // `denialReason` has already vetted those by syntax.
54
+ host: target.hostname.replace(/^\[|\]$/g, ""),
55
+ port: target.port === "" ? void 0 : target.port,
56
+ path: `${target.pathname}${target.search}`,
57
+ method: "GET",
58
+ headers: { accept: "*/*", ...init.headers, "accept-encoding": "identity" },
59
+ lookup,
60
+ agent: false,
61
+ signal: init.signal
62
+ }, (message) => {
63
+ try {
64
+ resolve(toResponse(message));
65
+ } catch (err) {
66
+ message.destroy();
67
+ reject(err);
68
+ }
69
+ });
70
+ request.on("error", reject);
71
+ request.end();
72
+ });
73
+ };
74
+ export {
75
+ createPinnedFetch
76
+ };
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Resolves a hostname to the addresses it points at. Only the `address` is used
3
+ * — the shape matches `dns.lookup(host, { all: true })` so the real resolver
4
+ * drops straight in. Exposed as a parameter so the guard can be exercised
5
+ * against known records without a live resolver, and so a caller that resolves
6
+ * names some other way (a custom DoH client) can supply it.
7
+ */
8
+ export type HostLookup = (hostname: string) => Promise<{
9
+ address: string;
10
+ }[]>;
11
+ /** An address that passed the guard, with the family a socket needs to dial it. */
12
+ export type PublicAddress = {
13
+ address: string;
14
+ family: 4 | 6;
15
+ };
16
+ /**
17
+ * Resolves `hostname` once and returns its addresses, rejecting if **any** of
18
+ * them is non-public. Returning the addresses (rather than a yes/no) is the
19
+ * point: a caller that dials exactly these — see `pinned-fetch` — closes the
20
+ * DNS-rebinding window, because there is no second lookup for the record to
21
+ * change under.
22
+ *
23
+ * {@link isPrivateHost} runs first so an IP literal or a denied name never
24
+ * costs a resolver round-trip, and so the refusal reads the same either way.
25
+ *
26
+ * **Fails closed.** A lookup that errors, returns nothing, or returns something
27
+ * that is not an IP address is rejected: we cannot show the host is public.
28
+ */
29
+ export declare const resolvePublicHost: (hostname: string, lookupHost?: HostLookup) => Promise<PublicAddress[]>;
@@ -0,0 +1,34 @@
1
+ import { lookup } from "node:dns/promises";
2
+ import { isIP } from "node:net";
3
+ import { isPrivateHost } from "./is-private-host.js";
4
+ const defaultLookup = (hostname) => lookup(hostname, { all: true, verbatim: true });
5
+ const resolvePublicHost = async (hostname, lookupHost = defaultLookup) => {
6
+ const host = hostname.replace(/^\[|\]$/g, "").replace(/\.+$/, "").toLowerCase();
7
+ if (host === "")
8
+ throw new Error("host is empty");
9
+ if (isPrivateHost(host)) {
10
+ throw new Error(`host "${hostname}" is a private or loopback address (set allowPrivateHosts to permit)`);
11
+ }
12
+ let answers;
13
+ try {
14
+ answers = await lookupHost(host);
15
+ } catch (err) {
16
+ throw new Error(`cannot verify that host "${hostname}" is public: DNS lookup failed (${String(err)}) (allow-list the host or set verifyDns: false to skip this check)`);
17
+ }
18
+ if (answers.length === 0) {
19
+ throw new Error(`cannot verify that host "${hostname}" is public: DNS returned no addresses (allow-list the host or set verifyDns: false to skip this check)`);
20
+ }
21
+ return answers.map(({ address }) => {
22
+ const family = isIP(address);
23
+ if (family !== 4 && family !== 6) {
24
+ throw new Error(`cannot verify that host "${hostname}" is public: DNS returned "${address}", not an IP address`);
25
+ }
26
+ if (isPrivateHost(address)) {
27
+ throw new Error(`host "${hostname}" resolves to the non-public address ${address} (set allowPrivateHosts to permit)`);
28
+ }
29
+ return { address, family };
30
+ });
31
+ };
32
+ export {
33
+ resolvePublicHost
34
+ };
@@ -8,8 +8,10 @@ import { getByPointer } from "./get-by-pointer.js";
8
8
  import { isContainedPath } from "./is-contained-path.js";
9
9
  import { isPrivateHost } from "./is-private-host.js";
10
10
  import { DEFAULT_MAX_DEPTH, depthLimitError } from "./max-depth.js";
11
+ import { createPinnedFetch } from "./pinned-fetch.js";
11
12
  import { refPathIndex } from "./ref-path-index.js";
12
13
  import { ANNOTATION_ONLY_SIBLINGS, readReference, resolveFragment } from "./reference.js";
14
+ import { resolvePublicHost } from "./resolve-public-host.js";
13
15
  import { baseOfNode, buildResourceRegistry, resolveRefInScope, SYNTHETIC_BASE } from "./resource-registry.js";
14
16
  import { roleAtPath } from "./role-at-path.js";
15
17
  import { assignKey } from "./safe-assign.js";
@@ -132,18 +134,20 @@ const fetchScope = (location, options) => [
132
134
  [...options.allowedHosts ?? []].sort().join(",")
133
135
  ].join("|");
134
136
  const cacheKeyFor = (location, options) => `${fetchScope(location, options)}${SCOPE_SEPARATOR}${location}`;
137
+ const pinnedPublicFetch = createPinnedFetch((hostname) => resolvePublicHost(hostname));
135
138
  const fetchRemote = async (location, options, deadline) => {
136
139
  const maxRedirects = options.maxRedirects ?? MAX_REDIRECTS;
137
140
  const timeoutMs = options.timeoutMs ?? FETCH_TIMEOUT_MS;
138
141
  const maxBytes = options.maxBytes ?? MAX_REMOTE_BYTES;
139
- const doFetch = options.fetch ?? fetch;
142
+ const verifyDns = needsDnsVerification(options);
143
+ const doFetch = options.fetch ?? (verifyDns ? pinnedPublicFetch : fetch);
140
144
  const origin = new URL(location).origin;
141
145
  let current = location;
142
146
  for (let hop = 0; hop <= maxRedirects; hop++) {
143
147
  const reason = denialReason(current, options);
144
148
  if (reason !== null)
145
149
  throw new Error(`refusing to follow redirect (${reason}): ${current}`);
146
- if (needsDnsVerification(options))
150
+ if (verifyDns && options.fetch !== void 0)
147
151
  await assertPublicHost(new URL(current).hostname);
148
152
  const headers = new URL(current).origin === origin ? headersFor(location, options) : void 0;
149
153
  const response = await doFetch(current, {
@@ -156,13 +160,16 @@ const fetchRemote = async (location, options, deadline) => {
156
160
  });
157
161
  if (response.status >= 300 && response.status < 400) {
158
162
  const next = response.headers.get("location");
163
+ await response.body?.cancel();
159
164
  if (!next)
160
165
  throw new Error(`HTTP ${response.status} redirect with no Location header`);
161
166
  current = new URL(next, current).href;
162
167
  continue;
163
168
  }
164
- if (!response.ok)
169
+ if (!response.ok) {
170
+ await response.body?.cancel();
165
171
  throw new Error(`HTTP ${response.status} ${response.statusText}`);
172
+ }
166
173
  return parseDocument(await readCapped(response, maxBytes), location, options);
167
174
  }
168
175
  throw new Error(`too many redirects (>${maxRedirects}): ${location}`);
package/dist/types.d.ts CHANGED
@@ -106,9 +106,10 @@ export type ResolveOptions = {
106
106
  * (behind an egress proxy) and a local lookup would fail; allow-listed hosts
107
107
  * skip the check either way.
108
108
  *
109
- * This narrows DNS rebinding rather than closing it: the record can still
110
- * change between the check and the connection, which would take pinning the
111
- * socket to the verified address to prevent.
109
+ * The default client verifies inside the connection's own lookup and dials
110
+ * only the addresses it verified, so a rebinding record cannot answer the
111
+ * check and the connection differently. A custom `fetch` cannot be pinned
112
+ * that way and gets the check as a pre-flight only.
112
113
  */
113
114
  verifyDns?: boolean;
114
115
  /**
@@ -196,7 +197,13 @@ export type ResolveOptions = {
196
197
  * proxy-aware one, a test stub). Called once per redirect hop with
197
198
  * `redirect: 'manual'` and a timeout signal. The SSRF guard still evaluates
198
199
  * every hop before this is called — a custom fetch widens *how* documents are
199
- * fetched, never *which* hosts may be. Defaults to the global `fetch`.
200
+ * fetched, never *which* hosts may be.
201
+ *
202
+ * Defaults to a built-in client that pins each connection to the addresses
203
+ * the DNS check verified (see `verifyDns`), or to the global `fetch` when that
204
+ * check is off. A custom fetch resolves names itself, so for it the DNS check
205
+ * is a pre-flight that a rebinding record can still answer differently from
206
+ * the connection: pin the address yourself if that matters.
200
207
  */
201
208
  fetch?: (url: string, init: {
202
209
  redirect: 'manual';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/resolve-refs",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Resolve and inline JSON Schema / OpenAPI $refs — internal, cross-file, and remote — with session caching and a default-deny SSRF guard.",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",