@amritk/resolve-refs 0.2.1 → 0.2.3

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.
@@ -2,6 +2,7 @@ import { readFileSync } from 'node:fs';
2
2
  import { dirname, resolve as resolvePath } from 'node:path';
3
3
  import { getByPointer, pointerToPath } from './get-by-pointer.js';
4
4
  import { isPrivateHost } from './is-private-host.js';
5
+ import { assignKey } from './safe-assign.js';
5
6
  // A ref currently mid-resolution is marked with this sentinel; revisiting it
6
7
  // means a cycle, so we return `{}` instead of recursing forever.
7
8
  const CYCLE = Symbol('cycle');
@@ -47,6 +48,34 @@ export const clearRemoteCache = () => {
47
48
  // Cap on redirect hops before we give up — generous enough for real services,
48
49
  // low enough to stop a redirect loop from spinning forever.
49
50
  const MAX_REDIRECTS = 5;
51
+ /** Abort a remote fetch that has not responded within this many milliseconds. */
52
+ const FETCH_TIMEOUT_MS = 30_000;
53
+ /** Refuse to buffer a remote document larger than this (bytes) to bound memory. */
54
+ const MAX_REMOTE_BYTES = 16 * 1024 * 1024;
55
+ /**
56
+ * Reads a response body, refusing to buffer more than {@link MAX_REMOTE_BYTES}.
57
+ * A `Content-Length` over the limit is rejected up front; a missing/lying header
58
+ * is caught while streaming so a chunked response can't exhaust memory either.
59
+ */
60
+ const readCapped = async (response) => {
61
+ const declared = Number(response.headers.get('content-length'));
62
+ if (Number.isFinite(declared) && declared > MAX_REMOTE_BYTES) {
63
+ throw new Error(`remote document exceeds ${MAX_REMOTE_BYTES} bytes`);
64
+ }
65
+ const body = response.body;
66
+ if (!body)
67
+ return response.text();
68
+ const decoder = new TextDecoder();
69
+ let text = '';
70
+ let total = 0;
71
+ for await (const chunk of body) {
72
+ total += chunk.byteLength;
73
+ if (total > MAX_REMOTE_BYTES)
74
+ throw new Error(`remote document exceeds ${MAX_REMOTE_BYTES} bytes`);
75
+ text += decoder.decode(chunk, { stream: true });
76
+ }
77
+ return text + decoder.decode();
78
+ };
50
79
  /**
51
80
  * Fetches and parses a remote document, following redirects manually so the
52
81
  * SSRF guard is re-applied to every hop. `fetch` follows redirects by default,
@@ -60,7 +89,11 @@ const fetchRemote = async (location, options) => {
60
89
  const reason = denialReason(current, options);
61
90
  if (reason !== null)
62
91
  throw new Error(`refusing to follow redirect (${reason}): ${current}`);
63
- const response = await fetch(current, { redirect: 'manual' });
92
+ const response = await fetch(current, {
93
+ redirect: 'manual',
94
+ // Cap the wait for a response so a stalling host can't hang resolution forever.
95
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
96
+ });
64
97
  if (response.status >= 300 && response.status < 400) {
65
98
  const next = response.headers.get('location');
66
99
  if (!next)
@@ -73,7 +106,7 @@ const fetchRemote = async (location, options) => {
73
106
  const parse = options.parse ?? ((c) => JSON.parse(c));
74
107
  // Parse against the original request location so the caller's format sniffing
75
108
  // (e.g. `.yaml` vs `.json`) and any relative refs key off a stable identity.
76
- return parse(await response.text(), location);
109
+ return parse(await readCapped(response), location);
77
110
  }
78
111
  throw new Error(`too many redirects (>${MAX_REDIRECTS}): ${location}`);
79
112
  };
@@ -88,6 +121,12 @@ const denialReason = (location, options) => {
88
121
  catch {
89
122
  return 'the URL is invalid';
90
123
  }
124
+ // Only http(s) may be fetched. Without this, a redirect to `file:///etc/passwd`
125
+ // or a `data:` URL passes every host check below (their `hostname` is empty, so
126
+ // `isPrivateHost('')` is false) and Bun's `fetch` would happily read the file.
127
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
128
+ return `unsupported URL protocol "${url.protocol}" (only http and https are allowed)`;
129
+ }
91
130
  const allow = options.allowedHosts;
92
131
  // An explicit allow-list entry is an intentional opt-in and bypasses the
93
132
  // private-host guard; otherwise refuse non-public targets by default.
@@ -166,15 +205,17 @@ const collectRefTargets = (node, out) => {
166
205
  }
167
206
  const obj = node;
168
207
  if (typeof obj['$ref'] === 'string') {
169
- // A `$ref` object's siblings are ignored on resolution, so we do not recurse
170
- // into them — mirroring resolveAt's behaviour.
171
208
  const { filePart } = splitRef(obj['$ref']);
172
209
  if (filePart !== '')
173
210
  out.add(filePart);
174
- return out;
175
211
  }
176
- for (const key of Object.keys(obj))
212
+ // Recurse into every key — including a `$ref` node's siblings, which apply
213
+ // alongside the referenced schema (2020-12) and may carry their own refs.
214
+ for (const key of Object.keys(obj)) {
215
+ if (key === '$ref')
216
+ continue;
177
217
  collectRefTargets(obj[key], out);
218
+ }
178
219
  return out;
179
220
  };
180
221
  /**
@@ -219,28 +260,44 @@ const resolveAt = (node, baseLocation, docCache, refCache, origins) => {
219
260
  const targetLocation = filePart === '' ? baseLocation : joinLocation(baseLocation, filePart);
220
261
  const targetRoot = docCache.get(targetLocation) ?? {};
221
262
  const cacheKey = `${targetLocation}#${pointer}`;
263
+ let resolved;
222
264
  if (refCache.has(cacheKey)) {
223
265
  const cached = refCache.get(cacheKey);
224
- return cached === CYCLE ? {} : cached;
266
+ resolved = cached === CYCLE ? {} : cached;
225
267
  }
226
- refCache.set(cacheKey, CYCLE);
227
- const target = pointer ? getByPointer(targetRoot, pointer) : targetRoot;
228
- const resolved = resolveAt(target, targetLocation, docCache, refCache, origins);
229
- refCache.set(cacheKey, resolved);
230
- // Stamp the inlined node with where it was defined so a consumer can map a
231
- // resolved-tree node back to its source document/path. Only objects/arrays are
232
- // stamped (primitives can't key the map). First-write-wins: resolution recurses
233
- // to the deepest `$ref` before returning, so the *definition* site stamps first;
234
- // an outer ref that merely points (transitively) at the same object must not
235
- // overwrite it with an intermediate location.
236
- if (origins && resolved !== null && typeof resolved === 'object' && !origins.has(resolved)) {
237
- origins.set(resolved, { location: targetLocation, pointer: pointerToPath(pointer) });
268
+ else {
269
+ refCache.set(cacheKey, CYCLE);
270
+ const target = pointer ? getByPointer(targetRoot, pointer) : targetRoot;
271
+ resolved = resolveAt(target, targetLocation, docCache, refCache, origins);
272
+ refCache.set(cacheKey, resolved);
273
+ // Stamp the inlined node with where it was defined so a consumer can map a
274
+ // resolved-tree node back to its source document/path. Only objects/arrays are
275
+ // stamped (primitives can't key the map). First-write-wins: resolution recurses
276
+ // to the deepest `$ref` before returning, so the *definition* site stamps first;
277
+ // an outer ref that merely points (transitively) at the same object must not
278
+ // overwrite it with an intermediate location.
279
+ if (origins && resolved !== null && typeof resolved === 'object' && !origins.has(resolved)) {
280
+ origins.set(resolved, { location: targetLocation, pointer: pointerToPath(pointer) });
281
+ }
238
282
  }
239
- return resolved;
283
+ // Keywords sibling to `$ref` apply alongside the referenced schema (2020-12),
284
+ // so preserve them by combining both in an `allOf` rather than dropping them.
285
+ const siblingKeys = Object.keys(obj).filter((key) => key !== '$ref');
286
+ if (siblingKeys.length === 0)
287
+ return resolved;
288
+ const siblings = {};
289
+ for (const key of siblingKeys)
290
+ assignKey(siblings, key, resolveAt(obj[key], baseLocation, docCache, refCache, origins));
291
+ const existingAllOf = Array.isArray(siblings['allOf']) ? siblings['allOf'] : [];
292
+ const merged = { ...siblings, allOf: [...existingAllOf, resolved] };
293
+ // Stamp the wrapper too, so origin lookups resolve for a `$ref`-with-siblings node.
294
+ if (origins && !origins.has(merged))
295
+ origins.set(merged, { location: targetLocation, pointer: pointerToPath(pointer) });
296
+ return merged;
240
297
  }
241
298
  const result = {};
242
299
  for (const key of Object.keys(obj)) {
243
- result[key] = resolveAt(obj[key], baseLocation, docCache, refCache, origins);
300
+ assignKey(result, key, resolveAt(obj[key], baseLocation, docCache, refCache, origins));
244
301
  }
245
302
  return result;
246
303
  };
@@ -1,4 +1,5 @@
1
1
  import { getByPointer, pointerToPath } from './get-by-pointer.js';
2
+ import { assignKey } from './safe-assign.js';
2
3
  // A ref currently mid-resolution is marked with this sentinel; revisiting it
3
4
  // means we have looped, so we return `{}` instead of recursing forever.
4
5
  const CYCLE = Symbol('cycle');
@@ -9,34 +10,63 @@ const CYCLE = Symbol('cycle');
9
10
  * files, HTTP) are left untouched — callers that need those should use
10
11
  * `resolveRefsFromFile`.
11
12
  */
12
- const resolveInternal = (node, root, cache, origins) => {
13
+ const resolveInternal = (node, root, cache, origins, errors) => {
13
14
  if (node === null || typeof node !== 'object')
14
15
  return node;
15
16
  if (Array.isArray(node))
16
- return node.map((item) => resolveInternal(item, root, cache, origins));
17
+ return node.map((item) => resolveInternal(item, root, cache, origins, errors));
17
18
  const obj = node;
18
19
  if (typeof obj['$ref'] === 'string') {
19
20
  const ref = obj['$ref'];
20
21
  if (!ref.startsWith('#'))
21
22
  return obj; // external ref — leave as-is
23
+ let target;
22
24
  if (cache.has(ref)) {
23
25
  const cached = cache.get(ref);
24
- return cached === CYCLE ? {} : cached;
26
+ target = cached === CYCLE ? {} : cached;
25
27
  }
26
- cache.set(ref, CYCLE);
27
- const resolved = resolveInternal(getByPointer(root, ref.slice(1)), root, cache, origins);
28
- cache.set(ref, resolved);
29
- // Stamp the inlined node with the path it was defined at (see resolveAt).
30
- // First-write-wins so the deepest definition stamps before any outer ref that
31
- // transitively points at the same object. Primitives can't key the map.
32
- if (origins && resolved !== null && typeof resolved === 'object' && !origins.has(resolved)) {
33
- origins.set(resolved, { location: '', pointer: pointerToPath(ref.slice(1)) });
28
+ else {
29
+ cache.set(ref, CYCLE);
30
+ const pointed = getByPointer(root, ref.slice(1));
31
+ if (pointed === undefined) {
32
+ // An internal pointer that resolves to nothing (a typo'd or missing
33
+ // definition) was previously inlined as literal `undefined` with no trace.
34
+ // Record it and keep the original `$ref` node so the failure is visible.
35
+ errors.push({ message: `Cannot resolve internal $ref "${ref}"`, path: pointerToPath(ref.slice(1)) });
36
+ cache.set(ref, obj);
37
+ return obj;
38
+ }
39
+ target = resolveInternal(pointed, root, cache, origins, errors);
40
+ cache.set(ref, target);
41
+ // Stamp the inlined node with the path it was defined at (see resolveAt).
42
+ // First-write-wins so the deepest definition stamps before any outer ref that
43
+ // transitively points at the same object. Primitives can't key the map.
44
+ if (origins && target !== null && typeof target === 'object' && !origins.has(target)) {
45
+ origins.set(target, { location: '', pointer: pointerToPath(ref.slice(1)) });
46
+ }
34
47
  }
35
- return resolved;
48
+ // Per JSON Schema 2020-12, keywords sibling to `$ref` are *not* ignored: they
49
+ // apply alongside the referenced schema. Preserve them by combining both in an
50
+ // `allOf` (so a constraint present on both sides is never silently dropped)
51
+ // rather than returning the bare target. The cache always stores the
52
+ // sibling-free target so each occurrence applies its own siblings.
53
+ const siblingKeys = Object.keys(obj).filter((key) => key !== '$ref');
54
+ if (siblingKeys.length === 0)
55
+ return target;
56
+ const siblings = {};
57
+ for (const key of siblingKeys)
58
+ assignKey(siblings, key, resolveInternal(obj[key], root, cache, origins, errors));
59
+ const existingAllOf = Array.isArray(siblings['allOf']) ? siblings['allOf'] : [];
60
+ const merged = { ...siblings, allOf: [...existingAllOf, target] };
61
+ // Stamp the wrapper too, so a consumer mapping the resolved node back to its
62
+ // origin finds one for a `$ref`-with-siblings node (not only the inner target).
63
+ if (origins && !origins.has(merged))
64
+ origins.set(merged, { location: '', pointer: pointerToPath(ref.slice(1)) });
65
+ return merged;
36
66
  }
37
67
  const result = {};
38
68
  for (const key of Object.keys(obj)) {
39
- result[key] = resolveInternal(obj[key], root, cache, origins);
69
+ assignKey(result, key, resolveInternal(obj[key], root, cache, origins, errors));
40
70
  }
41
71
  return result;
42
72
  };
@@ -47,6 +77,7 @@ const resolveInternal = (node, root, cache, origins) => {
47
77
  */
48
78
  export const resolveRefs = (data, options = {}) => {
49
79
  const origins = options.trackOrigins ? new Map() : undefined;
50
- const resolved = resolveInternal(data, data, new Map(), origins);
51
- return origins ? { resolved, errors: [], origins } : { resolved, errors: [] };
80
+ const errors = [];
81
+ const resolved = resolveInternal(data, data, new Map(), origins, errors);
82
+ return origins ? { resolved, errors, origins } : { resolved, errors };
52
83
  };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Assigns `value` under `key` on a rebuilt object without letting a `__proto__`
3
+ * key hit the prototype setter. Ref resolution rebuilds every object node of a
4
+ * document — including remote/external content — so a plain `target[key] = value`
5
+ * would let a `{ "__proto__": … }` node corrupt the rebuilt object's prototype.
6
+ * Defining it as an own data property preserves the key verbatim instead.
7
+ */
8
+ export declare const assignKey: (target: Record<string, unknown>, key: string, value: unknown) => void;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Assigns `value` under `key` on a rebuilt object without letting a `__proto__`
3
+ * key hit the prototype setter. Ref resolution rebuilds every object node of a
4
+ * document — including remote/external content — so a plain `target[key] = value`
5
+ * would let a `{ "__proto__": … }` node corrupt the rebuilt object's prototype.
6
+ * Defining it as an own data property preserves the key verbatim instead.
7
+ */
8
+ export const assignKey = (target, key, value) => {
9
+ if (key === '__proto__') {
10
+ Object.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true });
11
+ }
12
+ else {
13
+ target[key] = value;
14
+ }
15
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/resolve-refs",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
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
  "module": "./dist/index.js",
6
6
  "type": "module",