@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.
@@ -1,4 +1,7 @@
1
- const isPrivateIpv4 = (a, b) => {
1
+ const isPrivateIpv4 = (value) => {
2
+ const a = value >>> 24 & 255;
3
+ const b = value >>> 16 & 255;
4
+ const c = value >>> 8 & 255;
2
5
  if (a === 10 || a === 127 || a === 0)
3
6
  return true;
4
7
  if (a === 169 && b === 254)
@@ -9,6 +12,10 @@ const isPrivateIpv4 = (a, b) => {
9
12
  return true;
10
13
  if (a === 100 && b >= 64 && b <= 127)
11
14
  return true;
15
+ if (a === 198 && (b === 18 || b === 19))
16
+ return true;
17
+ if (a === 192 && b === 0 && c === 0)
18
+ return true;
12
19
  return false;
13
20
  };
14
21
  const parseIpv4Part = (s) => {
@@ -20,7 +27,7 @@ const parseIpv4Part = (s) => {
20
27
  return Number.parseInt(s, 10);
21
28
  return null;
22
29
  };
23
- const ipv4Octets = (host) => {
30
+ const ipv4Value = (host) => {
24
31
  if (!/^[0-9a-fx.]+$/i.test(host))
25
32
  return null;
26
33
  const parts = host.split(".");
@@ -47,7 +54,7 @@ const ipv4Octets = (host) => {
47
54
  value = value * 256 ** remaining + last;
48
55
  if (value > 4294967295)
49
56
  return null;
50
- return [value >>> 24 & 255, value >>> 16 & 255];
57
+ return value >>> 0;
51
58
  };
52
59
  const expandHexIpv6 = (host) => {
53
60
  const halves = host.split("::");
@@ -91,34 +98,41 @@ const ipv4EmbeddedInIpv6 = (g) => {
91
98
  return embedded;
92
99
  return null;
93
100
  };
101
+ const DENIED_HOST_NAMES = /* @__PURE__ */ new Set(["metadata", "metadata.google.internal", "metadata.goog", "instance-data"]);
94
102
  const isPrivateHost = (hostname) => {
95
103
  const host = hostname.replace(/^\[|\]$/g, "").replace(/\.+$/, "").toLowerCase();
96
104
  if (host === "localhost" || host.endsWith(".localhost"))
97
105
  return true;
106
+ if (DENIED_HOST_NAMES.has(host))
107
+ return true;
108
+ if (host.endsWith(".internal") || host.endsWith(".metadata.goog"))
109
+ return true;
98
110
  if (host.includes(":")) {
99
111
  if (host === "::1" || host === "::")
100
112
  return true;
101
113
  if (/^fe[89ab][0-9a-f]:/.test(host))
102
114
  return true;
115
+ if (/^fe[c-f][0-9a-f]:/.test(host))
116
+ return true;
103
117
  if (host.startsWith("fc") || host.startsWith("fd"))
104
118
  return true;
105
119
  const dotted = /:((?:\d{1,3}\.){3}\d{1,3})$/.exec(host);
106
120
  if (dotted?.[1]) {
107
- const oct2 = ipv4Octets(dotted[1]);
108
- if (oct2)
109
- return isPrivateIpv4(oct2[0], oct2[1]);
121
+ const value2 = ipv4Value(dotted[1]);
122
+ if (value2 !== null)
123
+ return isPrivateIpv4(value2);
110
124
  }
111
125
  const groups = expandHexIpv6(host);
112
126
  if (groups) {
113
127
  const embedded = ipv4EmbeddedInIpv6(groups);
114
128
  if (embedded !== null)
115
- return isPrivateIpv4(embedded >>> 24 & 255, embedded >>> 16 & 255);
129
+ return isPrivateIpv4(embedded);
116
130
  }
117
131
  return false;
118
132
  }
119
- const oct = ipv4Octets(host);
120
- if (oct)
121
- return isPrivateIpv4(oct[0], oct[1]);
133
+ const value = ipv4Value(host);
134
+ if (value !== null)
135
+ return isPrivateIpv4(value);
122
136
  return false;
123
137
  };
124
138
  export {
@@ -0,0 +1,24 @@
1
+ import type { ResolveError } from './types.js';
2
+ /**
3
+ * How deep either resolver walks before it gives up on a branch.
4
+ *
5
+ * Both walkers are recursive, so a pathologically nested document (`{"a":{"a":…`
6
+ * repeated thousands of times — trivial to produce, and JSON.parse happily
7
+ * accepts it) used to unwind the whole call stack with a `RangeError`. That
8
+ * broke the package's headline contract: errors are *collected* on the result,
9
+ * never thrown. Capping the walk turns that crash into an ordinary
10
+ * {@link ResolveError} on the result.
11
+ *
12
+ * 512 is far past anything a hand-written or generated schema reaches (deeply
13
+ * bundled OpenAPI documents live around 20–40 levels) while staying comfortably
14
+ * inside the default stack on every runtime we target.
15
+ */
16
+ export declare const DEFAULT_MAX_DEPTH = 512;
17
+ /**
18
+ * The error recorded when a walk hits {@link DEFAULT_MAX_DEPTH} (or the
19
+ * caller's `maxDepth`). Reported once per resolve — a wide *and* deep document
20
+ * would otherwise push one error per branch and turn the error array into its
21
+ * own memory problem. The offending subtree is left unresolved rather than
22
+ * dropped, so no data disappears silently.
23
+ */
24
+ export declare const depthLimitError: (maxDepth: number) => ResolveError;
@@ -0,0 +1,9 @@
1
+ const DEFAULT_MAX_DEPTH = 512;
2
+ const depthLimitError = (maxDepth) => ({
3
+ message: `Document nesting exceeds the maximum depth of ${maxDepth}; the deeper subtrees were left unresolved (raise maxDepth to allow more)`,
4
+ path: []
5
+ });
6
+ export {
7
+ DEFAULT_MAX_DEPTH,
8
+ depthLimitError
9
+ };
package/dist/reference.js CHANGED
@@ -1,4 +1,6 @@
1
+ import { childRole } from "./child-role.js";
1
2
  import { getByPointer, pointerToPath } from "./get-by-pointer.js";
3
+ import { DEFAULT_MAX_DEPTH } from "./max-depth.js";
2
4
  const REF_KEYWORDS = ["$ref", "$dynamicRef", "$recursiveRef"];
3
5
  const readReference = (obj) => {
4
6
  for (const keyword of REF_KEYWORDS) {
@@ -11,28 +13,31 @@ const readReference = (obj) => {
11
13
  const isPointerFragment = (fragment) => fragment === "" || fragment.startsWith("/");
12
14
  const search = (root, predicate) => {
13
15
  const seen = /* @__PURE__ */ new Set();
14
- const walk = (node, pointer) => {
15
- if (node === null || typeof node !== "object" || seen.has(node))
16
+ const walk = (node, pointer, depth, role) => {
17
+ if (node === null || typeof node !== "object" || seen.has(node) || depth > DEFAULT_MAX_DEPTH)
18
+ return void 0;
19
+ if (role === "value")
16
20
  return void 0;
17
21
  seen.add(node);
18
- if (!Array.isArray(node) && predicate(node))
22
+ if (!Array.isArray(node) && role !== "schemaMap" && predicate(node)) {
19
23
  return { value: node, pointer };
24
+ }
20
25
  if (Array.isArray(node)) {
21
26
  for (let i = 0; i < node.length; i++) {
22
- const found = walk(node[i], [...pointer, i]);
27
+ const found = walk(node[i], [...pointer, i], depth + 1, childRole(role, i));
23
28
  if (found)
24
29
  return found;
25
30
  }
26
31
  } else {
27
32
  for (const key of Object.keys(node)) {
28
- const found = walk(node[key], [...pointer, key]);
33
+ const found = walk(node[key], [...pointer, key], depth + 1, childRole(role, key));
29
34
  if (found)
30
35
  return found;
31
36
  }
32
37
  }
33
38
  return void 0;
34
39
  };
35
- return walk(root, []);
40
+ return walk(root, [], 0, "schema");
36
41
  };
37
42
  const resolveFragment = (root, keyword, fragment) => {
38
43
  if (keyword === "$recursiveRef") {
@@ -1,11 +1,30 @@
1
1
  import type { ResolveOptions, ResolveResult } from './types.js';
2
- /** Drops every cached remote document. Mainly useful for tests/long sessions. */
3
- export declare const clearRemoteCache: () => void;
2
+ /**
3
+ * Drops cached remote documents. Pass a URL to drop just that document (across
4
+ * every credential scope it was fetched under); pass nothing to drop them all.
5
+ * Mainly useful in tests, or when a remote schema is known to have changed.
6
+ */
7
+ export declare const clearRemoteCache: (location?: string) => void;
4
8
  /**
5
9
  * Resolves `$ref`s in a document on disk (or at a URL), including cross-file
6
10
  * and remote refs. Remote documents are fetched on the fly and cached in memory
7
11
  * for the session; `options` governs whether/which remote hosts are allowed,
8
12
  * how they are fetched (`headers`, `fetch`, `timeoutMs`, `maxRedirects`,
9
- * `maxBytes`), and whether the session cache is used (`cache`).
13
+ * `maxBytes`), which local directories may be read (`localRefs`,
14
+ * `allowedRoots`), the limits on the resolve as a whole (`maxDocuments`,
15
+ * `totalTimeoutMs`, `maxDepth`), and whether the session cache is used
16
+ * (`cache`).
17
+ *
18
+ * Only references in *schema* positions are followed: a `$ref`-shaped object
19
+ * inside `enum`, `const`, `default` or `examples` is instance data, so it is
20
+ * kept verbatim and the document it names is never loaded (see `child-role.ts`).
21
+ *
22
+ * As in {@link resolveRefs}, a reference the resolver cannot answer without
23
+ * changing what the document accepts is *kept* rather than guessed at, and
24
+ * resolves within the output: a cycle (rewritten to a root-relative `$ref`, its
25
+ * target hoisted into `$defs` when it came from another file), and — for a
26
+ * resolve that stayed inside a single document — a `$dynamicRef` whose anchor
27
+ * name is declared more than once. Neither is reported on `errors`; nothing
28
+ * failed.
10
29
  */
11
30
  export declare const resolveRefsFromFile: (filename: string, options?: ResolveOptions) => Promise<ResolveResult>;