@amritk/resolve-refs 0.4.4 → 0.6.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
@@ -31,15 +31,25 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
31
31
  2. **Errors are collected, never thrown.** A missing file, refused host, or bad
32
32
  URL lands on `result.errors` while the rest still resolves. Always check it.
33
33
  3. **Default-deny SSRF guard.** Remote refs to loopback / private / link-local /
34
- `169.254.169.254` are refused unless `allowPrivateHosts: true` or an explicit
35
- `allowedHosts` entry.
36
- 4. **JSON-only by default** (`JSON.parse`). For YAML pass a custom
34
+ `169.254.169.254` / metadata hosts by name (`metadata.google.internal`,
35
+ `*.internal`) are refused unless `allowPrivateHosts: true` or an explicit
36
+ `allowedHosts` entry. Hostnames are also resolved and refused when they point
37
+ at a private address (`verifyDns: false` opts out).
38
+ 4. **Local `$ref`s are confined to the root document's directory.** A
39
+ `{"$ref": "../common/schemas.json"}` is refused by default — pass
40
+ `allowedRoots: ['./specs']` (or whatever contains both files) to allow it.
41
+ `localRefs: false` refuses cross-file reads entirely.
42
+ 5. **JSON-only by default** (`JSON.parse`). For YAML pass a custom
37
43
  `parse: (content, location) => …` (e.g. wrapping `@amritk/yaml`).
38
- 5. **`origins` exists only with `trackOrigins: true`.** Cycles are preserved (the
44
+ 6. **`origins` exists only with `trackOrigins: true`.** Cycles are preserved (the
39
45
  cycle point stays a `$ref`), so output is not always fully flat. The remote
40
- cache is process-wide — `clearRemoteCache()` or `cache: false` when a schema
41
- may have changed.
46
+ cache is process-wide but credential-scoped and bounded (10 min TTL, 256
47
+ entries) — `clearRemoteCache()` / `clearRemoteCache(url)` or `cache: false`
48
+ when a schema may have changed.
49
+ 7. **A resolve is bounded** by `maxDocuments` (500), `totalTimeoutMs` (60s), and
50
+ `maxDepth` (512). Hitting one is an entry on `errors`, never a throw.
42
51
 
43
52
  Exports: `resolveRefs`, `resolveRefsFromFile`, `clearRemoteCache`,
44
- `getByPointer`, `pointerToPath`, `isPrivateHost` + types. Only the `.` entry.
53
+ `getByPointer`, `pointerToPath`, `isPrivateHost`, `assertPublicHost` + types.
54
+ Only the `.` entry.
45
55
  Install: `bun add @amritk/resolve-refs`.
package/README.md CHANGED
@@ -18,9 +18,16 @@ refs, and remote (http/https) documents — into a single dereferenced document.
18
18
  subset.
19
19
  - **Cross-file + remote.** Relative refs resolve against the document they appear
20
20
  in (a ref inside a remote doc stays remote, one inside a local file stays
21
- local). Fetched remote documents are cached for the lifetime of the process.
21
+ local). Fetched remote documents are cached for the session, keyed by URL *and*
22
+ by the credentials they were fetched with.
22
23
  - **Default-deny SSRF guard.** Remote refs to loopback, private, link-local, and
23
- cloud-metadata (`169.254.169.254`) hosts are refused unless you opt in.
24
+ cloud-metadata hosts — by IP (`169.254.169.254`) *and* by name
25
+ (`metadata.google.internal`, anything under `.internal`) — are refused unless
26
+ you opt in. Hostnames are additionally resolved and refused when any address
27
+ they point at is non-public, so `127.0.0.1.nip.io` does not slip through.
28
+ - **Default-deny local reads.** A local `$ref` may only resolve **under the root
29
+ document's directory**. `{"$ref": "../../../secrets.env"}` is refused; widen it
30
+ with `allowedRoots` when your spec legitimately spans folders.
24
31
  - **OpenAPI Reference Objects.** A `$ref` whose only siblings are `summary` /
25
32
  `description` inlines the target with those annotations overriding — matching
26
33
  OpenAPI 3.1 Reference Object semantics, where an `allOf` wrapper would be
@@ -48,23 +55,62 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
48
55
  | Option | Default | Description |
49
56
  |:---|:---|:---|
50
57
  | `remote` | `true` | Whether http(s) refs may be fetched at all. |
51
- | `allowedHosts` | `[]` | If non-empty, only these hosts may be fetched. An explicit entry bypasses the private-host guard. |
58
+ | `localRefs` | `true` | Whether `$ref`s to other files on disk may be read. `false` still reads the root document you named — it refuses everything a ref reaches out to. |
59
+ | `allowedRoots` | `[dirname(root)]` | Directories a local `$ref` must resolve inside. The default confines a ref to the folder holding the root document. |
60
+ | `allowedHosts` | `[]` | If non-empty, only these hosts may be fetched. Matched case-insensitively; an entry without a port matches any port, one with a port must match it (a URL that omits the port counts as its protocol default). An explicit entry bypasses the private-host and DNS guards. |
52
61
  | `allowPrivateHosts` | `false` | Allow loopback/private/link-local targets. Left off, these are refused as an SSRF guard. |
62
+ | `verifyDns` | `true` | Resolve each remote host and refuse it when any address it resolves to is non-public. Pass `false` where names resolve at an egress proxy rather than locally. |
53
63
  | `headers` | — | Extra headers for remote requests (record, or `(url) => headers` for per-host credentials). Never sent across a cross-origin redirect. |
54
64
  | `fetch` | global `fetch` | Custom fetch implementation. The SSRF guard still evaluates every hop before it is called. |
55
65
  | `timeoutMs` | `30_000` | Abort an unresponsive remote fetch after this many milliseconds. |
66
+ | `totalTimeoutMs` | `60_000` | Wall-clock budget for the whole resolve, across every document. |
67
+ | `maxDocuments` | `500` | Documents (root included) a single resolve may load. |
56
68
  | `maxRedirects` | `5` | Redirect hops to follow per remote document (each hop re-runs the SSRF guard). |
57
69
  | `maxBytes` | `16` MiB | Refuse to buffer a remote document larger than this. |
70
+ | `maxDepth` | `512` | How deep to walk before leaving a subtree unresolved and recording an error. |
58
71
  | `cache` | `true` | Pass `false` to bypass the process-wide session cache for this call — everything is re-fetched, nothing is stored. |
59
72
  | `parse` | `JSON.parse` | Custom content parser (e.g. YAML-aware). |
60
73
  | `trackOrigins` | `false` | Record a per-node origin map on the result. |
61
74
 
62
- Errors (a missing file, a refused host, a bad URL) are collected on
63
- `result.errors` rather than thrown; the corresponding ref resolves to `{}` so the
64
- rest of the document still resolves.
75
+ Errors (a missing file, a refused host, a refused path, a bad URL, a document too
76
+ deeply nested) are collected on `result.errors` rather than thrown; the
77
+ corresponding ref resolves to `{}` so the rest of the document still resolves.
65
78
 
66
79
  `clearRemoteCache()` drops every cached remote document — useful in tests or
67
- long-lived sessions where remote schemas may change.
80
+ long-lived sessions where remote schemas may change. Pass a URL
81
+ (`clearRemoteCache(url)`) to drop just that one. The cache expires entries after
82
+ 10 minutes and evicts the least recently used past 256 documents, so a long-lived
83
+ process does not accumulate every schema it has ever seen.
84
+
85
+ ### Security posture
86
+
87
+ The remote path has always been default-deny; the local path now matches it.
88
+
89
+ - **Local reads are confined** to `dirname(rootLocation)` unless you pass
90
+ `allowedRoots`. This is deliberately strict: a ref like `../common/schemas.json`
91
+ — an ordinary split-spec layout — is refused until you opt in, because the same
92
+ shape is what reads `/etc/passwd` out of a document you did not write. Both the
93
+ lexical and the symlink-resolved path must land inside a root, so a symlink
94
+ planted in the tree cannot be used to escape it. The root document itself is
95
+ exempt: it is the file you explicitly named.
96
+ - **The session cache is credential-scoped.** Its key covers the request headers,
97
+ the `fetch`/`parse` callbacks, and the transfer limits, so a document fetched
98
+ with one tenant's token is invisible to a call carrying different (or no)
99
+ credentials — and no caller inherits another's `fetch`. In-flight coalescing
100
+ uses the same key.
101
+ - **The SSRF guard runs in two passes.** `isPrivateHost` is synchronous and reads
102
+ only the URL (every IPv4 encoding, IPv4-in-IPv6 embeddings, ULA/link-local/
103
+ site-local IPv6, plus a name denylist for cloud-metadata endpoints).
104
+ `assertPublicHost` then resolves the name and refuses it when any address is
105
+ non-public. Both run on every redirect hop.
106
+ - **Known residual gap: DNS rebinding.** A record that changes between the check
107
+ and the connection still wins; closing that requires pinning the socket to the
108
+ verified address, which Node's `fetch` does not let us do. What the DNS pass
109
+ buys is that a name *statically* pointing at a private address is refused —
110
+ which is the case that actually shows up.
111
+ - **A resolve is bounded** by `maxDocuments`, `totalTimeoutMs`, and `maxDepth`, so
112
+ a hostile document cannot use the resolver as an egress amplifier, hold the
113
+ process for hours, or crash it with nesting.
68
114
 
69
115
  ## `$id` scoping
70
116
 
@@ -79,21 +125,54 @@ full spec:
79
125
  - **Anchors** bind within the resource that declares them first; an anchor not
80
126
  found in scope falls back to a document-global search (compatibility with
81
127
  documents that reference across sibling resources).
82
- - A plain `#/pointer` fragment stays **document-root-relative** — the behavior
83
- bundled real-world documents rely on — even inside an embedded resource.
128
+ - A plain `#/pointer` fragment resolves **within the resource in scope** first,
129
+ and falls back to the document root when it matches nothing there — which is
130
+ the behavior bundled real-world documents rely on (a bundled OpenAPI file points
131
+ at `#/components/schemas/…` from inside an `$id` scope). When both could match,
132
+ the resource wins, which is the order the spec asks for.
84
133
  - `$dynamicRef` prefers a `$dynamicAnchor` in scope, then degrades to `$ref`
85
- semantics. The full dynamic-scope algorithm (outermost anchor along the
86
- runtime reference chain) is not modelled.
134
+ semantics; a pointer-form `$dynamicRef` (`#/$defs/items`) resolves exactly like
135
+ a `$ref`, which is what the spec says it is. The full dynamic-scope algorithm
136
+ (outermost anchor along the runtime reference chain) is not modelled, and
137
+ cannot be by a resolver that inlines — see [Conformance, measured](#conformance-measured).
87
138
  - Document **retrieval is unaffected**: which file/URL an external ref loads
88
139
  from is derived from the referencing document's *location*, never its `$id` —
89
140
  a root `$id` naming a remote URL cannot turn a local sibling-file ref into a
90
141
  network fetch.
91
142
 
143
+ ## Conformance, measured
144
+
145
+ Inlining a document must not change what it accepts, and that is checked against
146
+ the corpus of `$ref` shapes the spec authors wrote for exactly this purpose.
147
+ `src/conformance.test.ts` takes every reference-carrying case in the official
148
+ [JSON Schema Test Suite](https://github.com/json-schema-org/JSON-Schema-Test-Suite)
149
+ (required Draft 2020-12 tests), validates the instance twice with
150
+ [`@amritk/runtime-validators`](../runtime-validators) — once through the original
151
+ schema, once through the resolved one — and requires both to agree with the spec:
152
+
153
+ **170 / 170 cases pass (100%).**
154
+
155
+ The corpus is the reference-carrying cases the interpreter already answers
156
+ correctly *before* resolution, so a disagreement afterwards is the resolver's and
157
+ nobody else's.
158
+
159
+ Getting the last ten meant *not* answering them: a `$dynamicRef` whose
160
+ `$dynamicAnchor` name is declared more than once binds at evaluation time, and
161
+ inlining collapses that to one target by construction. Those are now kept in the
162
+ output with the scaffolding they need, exactly as a reference cycle is — see
163
+ [`$id` scoping](#id-scoping) above. The expected-failure list is empty and kept in
164
+ place, so the build names the first case that regresses rather than letting a
165
+ percentage tick down. The corpus is vendored under
166
+ [`fixtures/json-schema-test-suite`](../../fixtures/json-schema-test-suite); none
167
+ of it is published.
168
+
92
169
  ## Documents
93
170
 
94
- Every document — local file or remote — is parsed as **JSON**. mjst works with
95
- JSON Schema documents only, so this resolver stays JSON-only and dependency-free.
96
- (The Loupe linter's sibling resolver additionally accepts YAML.)
171
+ Every document — local file or remote — is parsed as **JSON** by default, so the
172
+ resolver stays dependency-free. Other formats plug in through the `parse` option:
173
+ `mjst lint` passes a YAML-aware parser there, which is how a `.lint.yaml`
174
+ document's cross-file `$ref`s resolve without this package depending on a YAML
175
+ parser.
97
176
 
98
177
  ## Benchmarks
99
178
 
@@ -111,10 +190,10 @@ produce byte-identical output before either is timed. Representative numbers
111
190
 
112
191
  | schema | cached | naive | speedup |
113
192
  |:---|---:|---:|---:|
114
- | chain (40 `$ref` → `$ref` links) | ~2.6k ops/s | ~0.8k ops/s | **~3.2×** |
115
- | reuse-heavy (50 refs → 1 def) | ~4.5k ops/s | ~8k ops/s | ~0.5× |
116
- | cyclic tree | ~27k ops/s | ~74k ops/s | ~0.37× |
117
- | wide-distinct (60 defs, each used once) | ~2.3k ops/s | ~7.3k ops/s | ~0.32× |
193
+ | chain (40 `$ref` → `$ref` links) | ~2.7k ops/s | ~0.77k ops/s | **~3.6×** |
194
+ | reuse-heavy (50 refs → 1 def) | ~4.2k ops/s | ~8.9k ops/s | ~0.47× |
195
+ | cyclic tree | ~32k ops/s | ~99k ops/s | ~0.32× |
196
+ | wide-distinct (60 defs, each used once) | ~2.3k ops/s | ~7.7k ops/s | ~0.29× |
118
197
 
119
198
  Memoization overtakes the naive walk only on the **chain** shape, where a long
120
199
  indirection path is expensive to re-resolve and the cache collapses it to one
@@ -128,4 +207,4 @@ rows are kept in the table precisely to show that trade honestly rather than
128
207
  cherry-picking the one shape the cache wins.
129
208
 
130
209
  Opting into `trackOrigins` (which records where each inlined value came from) adds
131
- roughly **0–20%** on top, within run-to-run noise on these small schemas.
210
+ roughly **0–15%** on top, within run-to-run noise on these small schemas.
@@ -0,0 +1,39 @@
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
+ /**
12
+ * The name-resolving half of the SSRF guard: resolves `hostname` and rejects if
13
+ * **any** address it resolves to is non-public. {@link isPrivateHost} only reads
14
+ * 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.
16
+ *
17
+ * It is deliberately a separate async function rather than a change to
18
+ * `isPrivateHost`: that predicate is synchronous, pure, and exported (the CLI
19
+ * and `@amritk/lint` pass it URL hostnames), and making it async would break
20
+ * every caller for no gain outside the fetch path.
21
+ *
22
+ * **Fails closed.** A lookup that errors, or returns nothing, is rejected: we
23
+ * cannot show the host is public, and a name we cannot resolve was almost
24
+ * certainly not going to be fetched anyway. Environments where the *proxy* does
25
+ * the resolving (so names do not resolve locally) should allow-list the host or
26
+ * pass `verifyDns: false`.
27
+ *
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.
35
+ *
36
+ * Rejects with an `Error` explaining the refusal; resolves when the host looks
37
+ * public.
38
+ */
39
+ export declare const assertPublicHost: (hostname: string, lookupHost?: HostLookup) => Promise<void>;
@@ -0,0 +1,28 @@
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
+ }
25
+ };
26
+ export {
27
+ assertPublicHost
28
+ };
@@ -0,0 +1,43 @@
1
+ /**
2
+ * What a node *is* in the JSON Schema vocabulary, which is what decides whether
3
+ * a `$ref` key inside it means anything.
4
+ *
5
+ * The resolvers used to walk documents purely structurally, so any object with a
6
+ * string `$ref` was a reference wherever it sat. That is wrong in a value
7
+ * position: `{ "enum": [ { "$ref": "#/$defs/a_string" } ] }` references nothing —
8
+ * `enum` holds *instances*, and one of them happens to be an object with a
9
+ * `$ref` key. Inlining it changes what the schema accepts, which is why the
10
+ * official suite carries that case under "naive replacement of `$ref` with its
11
+ * destination is not correct".
12
+ */
13
+ export type NodeRole =
14
+ /** A schema: its keys are keywords, and a `$ref` here is a reference. */
15
+ 'schema'
16
+ /**
17
+ * A map of arbitrary names to schemas (`properties`, `$defs`, …). Its keys are
18
+ * names chosen by the author, so a definition named `enum` is a definition,
19
+ * not the keyword — and a property named `$ref` is a property, not a reference.
20
+ */
21
+ | 'schemaMap'
22
+ /** Instance data (`enum`, `const`, `default`, `examples`). Nothing in here is a keyword. */
23
+ | 'value'
24
+ /**
25
+ * Outside any vocabulary we model — an extension keyword, or anything under
26
+ * one. Walked structurally, exactly as the resolvers always have: we cannot
27
+ * know what an unrecognized keyword holds, so we keep finding references in it.
28
+ */
29
+ | 'unknown';
30
+ /**
31
+ * The role of the child at `key` (an object key, or an array index) inside a
32
+ * node whose role is `role`.
33
+ *
34
+ * An array element inherits its array's role: the members of `allOf` are schemas
35
+ * because `allOf` sits in a schema position, and the members of `enum` are data
36
+ * because `enum` does not.
37
+ *
38
+ * Unrecognized keywords hand back `'unknown'`, and `'unknown'` is absorbing —
39
+ * once the walk leaves the vocabulary it never claims to be back inside it. That
40
+ * keeps extension keywords (OpenAPI's `components`, an `x-` vendor block)
41
+ * behaving exactly as they did before roles existed.
42
+ */
43
+ export declare const childRole: (role: NodeRole, key: string | number) => NodeRole;
@@ -0,0 +1,45 @@
1
+ const VALUE_KEYWORDS = /* @__PURE__ */ new Set(["enum", "const", "default", "examples"]);
2
+ const SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([
3
+ "properties",
4
+ "patternProperties",
5
+ "$defs",
6
+ "definitions",
7
+ "dependentSchemas",
8
+ "dependencies"
9
+ ]);
10
+ const SCHEMA_KEYWORDS = /* @__PURE__ */ new Set([
11
+ "additionalItems",
12
+ "additionalProperties",
13
+ "allOf",
14
+ "anyOf",
15
+ "contains",
16
+ "contentSchema",
17
+ "else",
18
+ "if",
19
+ "items",
20
+ "not",
21
+ "oneOf",
22
+ "prefixItems",
23
+ "propertyNames",
24
+ "then",
25
+ "unevaluatedItems",
26
+ "unevaluatedProperties"
27
+ ]);
28
+ const childRole = (role, key) => {
29
+ if (role === "schemaMap")
30
+ return "schema";
31
+ if (role !== "schema")
32
+ return role;
33
+ if (typeof key === "number")
34
+ return "schema";
35
+ if (VALUE_KEYWORDS.has(key))
36
+ return "value";
37
+ if (SCHEMA_MAP_KEYWORDS.has(key))
38
+ return "schemaMap";
39
+ if (SCHEMA_KEYWORDS.has(key))
40
+ return "schema";
41
+ return "unknown";
42
+ };
43
+ export {
44
+ childRole
45
+ };
@@ -0,0 +1,70 @@
1
+ import type { RefKeyword } from './reference.js';
2
+ /**
3
+ * The part of resolution that cannot be answered statically.
4
+ *
5
+ * A `$dynamicRef` does not name one target. It binds at *evaluation* time to the
6
+ * outermost `$dynamicAnchor` of that name along the dynamic scope — the chain of
7
+ * schema resources actually being applied — so the same keyword can resolve to a
8
+ * different schema depending on where evaluation entered from. Inlining happens
9
+ * once, so a resolver that inlines every `$dynamicRef` has to guess, and a wrong
10
+ * guess changes what the document accepts.
11
+ *
12
+ * So we do not guess. Where the binding is decidable we inline as before; where
13
+ * it is not, the `$dynamicRef` stays in the output and the scaffolding it needs
14
+ * to resolve at validation time — the `$dynamicAnchor`s it may bind to, and the
15
+ * `$id`s that delimit the resources those anchors live in — stays with it. That
16
+ * is the same move the resolver already makes for a reference cycle: keep the
17
+ * reference rather than collapse it to one wrong answer.
18
+ */
19
+ /**
20
+ * Whether a reference's target is only decided when the document is evaluated,
21
+ * which is what makes it unsafe to inline.
22
+ *
23
+ * Two `$dynamicRef` shapes are decidable and keep being inlined:
24
+ *
25
+ * - a **pointer fragment** (`#`, `#/$defs/items`, or no fragment at all) is a
26
+ * plain `$ref` per the spec — there is no anchor to late-bind to;
27
+ * - an **anchor name declared at most once** in the document. With a single
28
+ * `$dynamicAnchor` of that name there is only one schema the dynamic lookup
29
+ * could ever land on, and with none the keyword degrades to `$ref` semantics
30
+ * against whatever `$anchor` the name resolves to. Either way the static
31
+ * answer is the only answer.
32
+ *
33
+ * Everything else — an anchor name declared twice or more — is kept, because
34
+ * "which one" is exactly the question the dynamic scope answers and we are not
35
+ * the ones evaluating.
36
+ */
37
+ export declare const bindsAtEvaluationTime: (keyword: RefKeyword, ref: string, ambiguousAnchors: ReadonlySet<string>) => boolean;
38
+ /**
39
+ * Nodes of the resolved document whose meaning depends on the `$id` scope they
40
+ * sit in: a kept reference (it is resolved later, against the base it stands
41
+ * in), a `$dynamicAnchor` a kept `$dynamicRef` might bind to, and anything
42
+ * containing either. Tracked by identity, because the resolver shares one
43
+ * resolved object per unique ref.
44
+ */
45
+ export type ScopeSensitiveNodes = WeakSet<object>;
46
+ /** Whether `value` is a node the resolver marked scope-sensitive. */
47
+ export declare const isScopeSensitive: (nodes: ScopeSensitiveNodes, value: unknown) => boolean;
48
+ /**
49
+ * Whether a node declares a `$dynamicAnchor` some kept `$dynamicRef` could bind
50
+ * to. Such a declaration registers its name against the resource it sits in, so
51
+ * moving it into a different resource would add a binding target where the
52
+ * original document had none.
53
+ */
54
+ export declare const declaresAmbiguousAnchor: (node: Record<string, unknown>, ambiguousAnchors: ReadonlySet<string>) => boolean;
55
+ /**
56
+ * Whether inlining `target` into a node whose base URI is `nodeBase` leaves the
57
+ * target in the very resource it was defined in.
58
+ *
59
+ * This is what decides whether a scope-sensitive target may be inlined at all.
60
+ * Inlining copies the target into the referencing node's `$id` scope, and the
61
+ * dynamic scope is a chain of *resources* — so the copy keeps its place in that
62
+ * chain only when it re-establishes the same base: either the target already
63
+ * belongs to the referencing node's resource, or it carries the `$id` that
64
+ * defines its own, and that `$id` still resolves to the same URI from where it
65
+ * lands. A ref pointing *into* another resource (`other#/$defs/thing`) does
66
+ * neither — the copy leaves that resource behind, which is the case the suite
67
+ * calls "`$dynamicRef` avoids the root of each schema, but scopes are still
68
+ * registered".
69
+ */
70
+ export declare const inliningKeepsScope: (target: unknown, nodeBase: string, targetBase: string) => boolean;
@@ -0,0 +1,25 @@
1
+ import { baseAfterId, splitFragment } from "./resource-registry.js";
2
+ const bindsAtEvaluationTime = (keyword, ref, ambiguousAnchors) => {
3
+ if (keyword !== "$dynamicRef")
4
+ return false;
5
+ const { fragment } = splitFragment(ref);
6
+ if (fragment === "" || fragment.startsWith("/"))
7
+ return false;
8
+ return ambiguousAnchors.has(fragment);
9
+ };
10
+ const isScopeSensitive = (nodes, value) => value !== null && typeof value === "object" && nodes.has(value);
11
+ const declaresAmbiguousAnchor = (node, ambiguousAnchors) => {
12
+ const anchor = node["$dynamicAnchor"];
13
+ return typeof anchor === "string" && ambiguousAnchors.has(anchor);
14
+ };
15
+ const inliningKeepsScope = (target, nodeBase, targetBase) => {
16
+ if (target === null || typeof target !== "object" || Array.isArray(target))
17
+ return nodeBase === targetBase;
18
+ return baseAfterId(target, nodeBase) === targetBase;
19
+ };
20
+ export {
21
+ bindsAtEvaluationTime,
22
+ declaresAmbiguousAnchor,
23
+ inliningKeepsScope,
24
+ isScopeSensitive
25
+ };
@@ -14,5 +14,11 @@ export declare const pointerToPath: (pointer: string) => JsonPath;
14
14
  * `root`. A bare `''` or `'/'` returns the root document. Segment escapes are
15
15
  * decoded (`~1` → `/`, `~0` → `~`). Returns `undefined` when any segment along
16
16
  * the path is missing or traverses a non-object.
17
+ *
18
+ * Only *own* properties are addressable. A plain `[key]` read let `#/constructor`
19
+ * resolve to `Object`'s constructor and inline a JS function into the
20
+ * "dereferenced" document — and, on a process where anything had polluted
21
+ * `Object.prototype`, let an arbitrary `#/<name>` resolve to the injected value
22
+ * instead of being reported as unresolvable.
17
23
  */
18
24
  export declare const getByPointer: (root: unknown, pointer: string) => unknown;
@@ -23,6 +23,8 @@ const getByPointer = (root, pointer) => {
23
23
  if (current === null || typeof current !== "object")
24
24
  return void 0;
25
25
  const key = Array.isArray(current) ? Number(segment) : segment;
26
+ if (!Object.hasOwn(current, key))
27
+ return void 0;
26
28
  current = current[key];
27
29
  }
28
30
  return current;
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export { assertPublicHost, type HostLookup } from './assert-public-host.js';
1
2
  export { getByPointer, pointerToPath } from './get-by-pointer.js';
2
3
  export { isPrivateHost } from './is-private-host.js';
3
4
  export { type ResolveRefsOptions, resolveRefs } from './resolve-refs.js';
package/dist/index.js CHANGED
@@ -1,8 +1,10 @@
1
+ import { assertPublicHost } from "./assert-public-host.js";
1
2
  import { getByPointer, pointerToPath } from "./get-by-pointer.js";
2
3
  import { isPrivateHost } from "./is-private-host.js";
3
4
  import { resolveRefs } from "./resolve-refs.js";
4
5
  import { clearRemoteCache, resolveRefsFromFile } from "./resolve-refs-from-file.js";
5
6
  export {
7
+ assertPublicHost,
6
8
  clearRemoteCache,
7
9
  getByPointer,
8
10
  isPrivateHost,
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Whether the file at `target` is confined to the directory `root`, used to keep
3
+ * a local `$ref` from reaching outside the document tree it belongs to
4
+ * (`{"$ref": "../../../etc/passwd"}`).
5
+ *
6
+ * Both the lexical path *and* the symlink-resolved path must be contained: the
7
+ * lexical check alone misses a symlink planted inside the root that points out
8
+ * of it, and the real-path check alone would reject a root that is itself
9
+ * reached through a symlink (`/tmp` → `/private/tmp` on macOS) unless both sides
10
+ * were normalized the same way — which is exactly what this does.
11
+ */
12
+ export declare const isContainedPath: (root: string, target: string) => boolean;
@@ -0,0 +1,32 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
3
+ const isUnder = (root, target) => {
4
+ const rel = relative(root, target);
5
+ return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
6
+ };
7
+ const realPathOf = (path) => {
8
+ const tail = [];
9
+ let current = path;
10
+ for (; ; ) {
11
+ try {
12
+ const real = realpathSync(current);
13
+ return tail.length === 0 ? real : join(real, ...tail);
14
+ } catch {
15
+ const parent = dirname(current);
16
+ if (parent === current)
17
+ return path;
18
+ tail.unshift(basename(current));
19
+ current = parent;
20
+ }
21
+ }
22
+ };
23
+ const isContainedPath = (root, target) => {
24
+ const absoluteRoot = resolve(root);
25
+ const absoluteTarget = resolve(target);
26
+ if (!isUnder(absoluteRoot, absoluteTarget))
27
+ return false;
28
+ return isUnder(realPathOf(absoluteRoot), realPathOf(absoluteTarget));
29
+ };
30
+ export {
31
+ isContainedPath
32
+ };
@@ -1,9 +1,16 @@
1
1
  /**
2
2
  * Best-effort check for a hostname that resolves to a non-public address —
3
3
  * loopback, private (RFC 1918 / ULA), link-local (incl. the `169.254.169.254`
4
- * cloud-metadata endpoint), or otherwise host-local. This is a syntactic guard
5
- * on the URL only; it does not perform DNS, so a public name that resolves to a
6
- * private IP is not caught here. It exists to stop the obvious SSRF footguns
7
- * when resolving remote `$ref`s.
4
+ * cloud-metadata endpoint), or otherwise host-local — plus a small denylist of
5
+ * names that always mean "infrastructure endpoint" (`metadata.google.internal`,
6
+ * anything under `.internal`, …).
7
+ *
8
+ * This is a **syntactic** guard on the URL only: it does not perform DNS, so a
9
+ * public name that resolves to a private IP (`127.0.0.1.nip.io` and friends, or
10
+ * a rebinding record) is not caught here. Use `assertPublicHost` for that — it
11
+ * resolves the name and runs every returned address back through this check.
12
+ * This one stays synchronous and pure because it is the cheap first pass, and
13
+ * because callers outside the fetch path (the CLI, `@amritk/lint`) use it as a
14
+ * plain predicate.
8
15
  */
9
16
  export declare const isPrivateHost: (hostname: string) => boolean;