@amritk/resolve-refs 0.1.1 → 0.2.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,3 +1,11 @@
1
+ import type { JsonPath } from './types.js';
2
+ /**
3
+ * Parses a JSON Pointer string (RFC 6901) into a path of keys: strips the leading
4
+ * `/`, splits on `/`, decodes each segment (`%XX`, then `~1` → `/`, `~0` → `~`),
5
+ * and coerces all-digit segments to numbers so array indices and object keys read
6
+ * back the same way a path consumer expects. A bare `''` or `'/'` is the empty path.
7
+ */
8
+ export declare const pointerToPath: (pointer: string) => JsonPath;
1
9
  /**
2
10
  * Walks a JSON Pointer string (RFC 6901) to the value it points to within
3
11
  * `root`. A bare `''` or `'/'` returns the root document. Segment escapes are
@@ -1 +1 @@
1
- {"version":3,"file":"get-by-pointer.d.ts","sourceRoot":"","sources":["../src/get-by-pointer.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,eAAO,MAAM,YAAY,SAAU,OAAO,WAAW,MAAM,KAAG,OAe7D,CAAA"}
1
+ {"version":3,"file":"get-by-pointer.d.ts","sourceRoot":"","sources":["../src/get-by-pointer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAEvC;;;;;GAKG;AACH,eAAO,MAAM,aAAa,YAAa,MAAM,KAAG,QAe/C,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,YAAY,SAAU,OAAO,WAAW,MAAM,KAAG,OAuB7D,CAAA"}
@@ -1,3 +1,27 @@
1
+ /**
2
+ * Parses a JSON Pointer string (RFC 6901) into a path of keys: strips the leading
3
+ * `/`, splits on `/`, decodes each segment (`%XX`, then `~1` → `/`, `~0` → `~`),
4
+ * and coerces all-digit segments to numbers so array indices and object keys read
5
+ * back the same way a path consumer expects. A bare `''` or `'/'` is the empty path.
6
+ */
7
+ export const pointerToPath = (pointer) => {
8
+ if (pointer === '' || pointer === '/')
9
+ return [];
10
+ return pointer
11
+ .replace(/^\//, '')
12
+ .split('/')
13
+ .map((segment) => {
14
+ let decoded = segment;
15
+ try {
16
+ decoded = decodeURIComponent(segment);
17
+ }
18
+ catch {
19
+ // leave invalid percent-escapes as-is
20
+ }
21
+ decoded = decoded.replace(/~1/g, '/').replace(/~0/g, '~');
22
+ return /^\d+$/.test(decoded) ? Number(decoded) : decoded;
23
+ });
24
+ };
1
25
  /**
2
26
  * Walks a JSON Pointer string (RFC 6901) to the value it points to within
3
27
  * `root`. A bare `''` or `'/'` returns the root document. Segment escapes are
@@ -10,7 +34,16 @@ export const getByPointer = (root, pointer) => {
10
34
  const segments = pointer
11
35
  .replace(/^\//, '')
12
36
  .split('/')
13
- .map((segment) => segment.replace(/~1/g, '/').replace(/~0/g, '~'));
37
+ .map((segment) => {
38
+ let decoded = segment;
39
+ try {
40
+ decoded = decodeURIComponent(segment);
41
+ }
42
+ catch {
43
+ // leave invalid percent-escapes as-is
44
+ }
45
+ return decoded.replace(/~1/g, '/').replace(/~0/g, '~');
46
+ });
14
47
  let current = root;
15
48
  for (const segment of segments) {
16
49
  if (current === null || typeof current !== 'object')
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- export { getByPointer } from './get-by-pointer.js';
1
+ export { getByPointer, pointerToPath } from './get-by-pointer.js';
2
2
  export { isPrivateHost } from './is-private-host.js';
3
- export { resolveRefs } from './resolve-refs.js';
3
+ export { type ResolveRefsOptions, resolveRefs } from './resolve-refs.js';
4
4
  export { clearRemoteCache, resolveRefsFromFile } from './resolve-refs-from-file.js';
5
- export type { JsonPath, ResolveError, ResolveOptions, ResolveResult } from './types.js';
5
+ export type { JsonPath, Origin, OriginMap, ResolveError, ResolveOptions, ResolveResult } from './types.js';
6
6
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAA;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AACjD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAC5C,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAA;AAChF,YAAY,EAAE,QAAQ,EAAE,YAAY,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAA;AAC9D,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AACjD,OAAO,EAAE,KAAK,kBAAkB,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AACrE,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAA;AAChF,YAAY,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA"}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { getByPointer } from './get-by-pointer.js';
1
+ export { getByPointer, pointerToPath } from './get-by-pointer.js';
2
2
  export { isPrivateHost } from './is-private-host.js';
3
3
  export { resolveRefs } from './resolve-refs.js';
4
4
  export { clearRemoteCache, resolveRefsFromFile } from './resolve-refs-from-file.js';
@@ -1 +1 @@
1
- {"version":3,"file":"is-private-host.d.ts","sourceRoot":"","sources":["../src/is-private-host.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,eAAO,MAAM,aAAa,aAAc,MAAM,KAAG,OAyBhD,CAAA"}
1
+ {"version":3,"file":"is-private-host.d.ts","sourceRoot":"","sources":["../src/is-private-host.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAoDH,eAAO,MAAM,aAAa,aAAc,MAAM,KAAG,OA+BhD,CAAA"}
@@ -6,36 +6,99 @@
6
6
  * private IP is not caught here. It exists to stop the obvious SSRF footguns
7
7
  * when resolving remote `$ref`s.
8
8
  */
9
+ /** True for an IPv4 address (given its first two octets) in a non-public range. */
10
+ const isPrivateIpv4 = (a, b) => {
11
+ if (a === 10 || a === 127 || a === 0)
12
+ return true;
13
+ if (a === 169 && b === 254)
14
+ return true; // link-local + cloud metadata
15
+ if (a === 172 && b >= 16 && b <= 31)
16
+ return true;
17
+ if (a === 192 && b === 168)
18
+ return true;
19
+ if (a === 100 && b >= 64 && b <= 127)
20
+ return true; // CGNAT
21
+ return false;
22
+ };
23
+ /** Parses a single IPv4 part in decimal, octal (`0…`), or hex (`0x…`) form. */
24
+ const parseIpv4Part = (s) => {
25
+ if (/^0x[0-9a-f]+$/i.test(s))
26
+ return Number.parseInt(s, 16);
27
+ if (/^0[0-7]*$/.test(s))
28
+ return Number.parseInt(s, 8);
29
+ if (/^[1-9][0-9]*$/.test(s))
30
+ return Number.parseInt(s, 10);
31
+ return null;
32
+ };
33
+ /**
34
+ * Resolves the first two octets of an IPv4 host written in any inet_aton form
35
+ * (dotted/decimal/octal/hex, 1–4 parts), or `null` if it is not an IPv4 literal.
36
+ * The WHATWG URL parser normalizes these to dotted-decimal before they reach us,
37
+ * but a direct caller (this is an exported guard) can pass the raw form.
38
+ */
39
+ const ipv4Octets = (host) => {
40
+ if (!/^[0-9a-fx.]+$/i.test(host))
41
+ return null;
42
+ const parts = host.split('.');
43
+ if (parts.length === 0 || parts.length > 4)
44
+ return null;
45
+ const nums = [];
46
+ for (const part of parts) {
47
+ const n = parseIpv4Part(part);
48
+ if (n === null)
49
+ return null;
50
+ nums.push(n);
51
+ }
52
+ // inet_aton packing: every part but the last is one byte; the last fills the
53
+ // remaining low bytes (so `127.1` is 127.0.0.1 and `2130706433` is too).
54
+ let value = 0;
55
+ for (let i = 0; i < nums.length - 1; i++) {
56
+ const byte = nums[i];
57
+ if (byte > 0xff)
58
+ return null;
59
+ value = value * 256 + byte;
60
+ }
61
+ const remaining = 4 - (nums.length - 1);
62
+ const last = nums[nums.length - 1];
63
+ if (last > 256 ** remaining - 1)
64
+ return null;
65
+ value = value * 256 ** remaining + last;
66
+ if (value > 0xffffffff)
67
+ return null;
68
+ return [(value >>> 24) & 0xff, (value >>> 16) & 0xff];
69
+ };
9
70
  export const isPrivateHost = (hostname) => {
10
71
  const host = hostname.replace(/^\[|\]$/g, '').toLowerCase();
11
72
  if (host === 'localhost' || host.endsWith('.localhost'))
12
73
  return true;
13
- // IPv4 (incl. IPv4-mapped IPv6 like ::ffff:127.0.0.1)
14
- const v4 = host.match(/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
15
- if (v4) {
16
- const a = Number(v4[1]);
17
- const b = Number(v4[2]);
18
- if (a === 10 || a === 127 || a === 0)
19
- return true;
20
- if (a === 169 && b === 254)
21
- return true; // link-local + metadata
22
- if (a === 172 && b >= 16 && b <= 31)
23
- return true;
24
- if (a === 192 && b === 168)
25
- return true;
26
- if (a === 100 && b >= 64 && b <= 127)
27
- return true; // CGNAT
28
- return false;
29
- }
30
- // IPv6
31
74
  if (host.includes(':')) {
75
+ // --- IPv6 (and IPv4-mapped IPv6) ---
32
76
  if (host === '::1' || host === '::')
33
77
  return true;
34
- if (host.startsWith('fe80:') || host.startsWith('fe80::'))
35
- return true; // link-local
78
+ // fe80::/10 link-local spans fe80–febf (third nibble 8–b).
79
+ if (/^fe[89ab][0-9a-f]:/.test(host))
80
+ return true;
36
81
  if (host.startsWith('fc') || host.startsWith('fd'))
37
- return true; // unique-local
82
+ return true; // fc00::/7 unique-local
83
+ // IPv4-mapped/compatible, dotted (`::ffff:127.0.0.1`) — the URL parser
84
+ // rewrites this to hex, but a direct caller may pass the dotted form.
85
+ const dotted = /:((?:\d{1,3}\.){3}\d{1,3})$/.exec(host);
86
+ if (dotted?.[1]) {
87
+ const oct = ipv4Octets(dotted[1]);
88
+ if (oct)
89
+ return isPrivateIpv4(oct[0], oct[1]);
90
+ }
91
+ // IPv4-mapped, hex (`::ffff:7f00:1`) — what `new URL()` produces.
92
+ const hex = /:ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(host);
93
+ if (hex?.[1] && hex[2]) {
94
+ const hi = Number.parseInt(hex[1], 16);
95
+ return isPrivateIpv4((hi >> 8) & 0xff, hi & 0xff);
96
+ }
38
97
  return false;
39
98
  }
99
+ // --- IPv4 (any inet_aton encoding) ---
100
+ const oct = ipv4Octets(host);
101
+ if (oct)
102
+ return isPrivateIpv4(oct[0], oct[1]);
40
103
  return false;
41
104
  };
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-refs-from-file.d.ts","sourceRoot":"","sources":["../src/resolve-refs-from-file.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAgB,cAAc,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AA0C1E,iFAAiF;AACjF,eAAO,MAAM,gBAAgB,QAAO,IAEnC,CAAA;AAqKD;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,aAAoB,MAAM,YAAW,cAAc,KAAQ,OAAO,CAAC,aAAa,CAW/G,CAAA"}
1
+ {"version":3,"file":"resolve-refs-from-file.d.ts","sourceRoot":"","sources":["../src/resolve-refs-from-file.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAA2B,cAAc,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AA+CrF,iFAAiF;AACjF,eAAO,MAAM,gBAAgB,QAAO,IAEnC,CAAA;AAwND;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,aAAoB,MAAM,YAAW,cAAc,KAAQ,OAAO,CAAC,aAAa,CAY/G,CAAA"}
@@ -1,6 +1,6 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { dirname, resolve as resolvePath } from 'node:path';
3
- import { getByPointer } from './get-by-pointer.js';
3
+ import { getByPointer, pointerToPath } from './get-by-pointer.js';
4
4
  import { isPrivateHost } from './is-private-host.js';
5
5
  // A ref currently mid-resolution is marked with this sentinel; revisiting it
6
6
  // means a cycle, so we return `{}` instead of recursing forever.
@@ -36,10 +36,47 @@ const splitRef = (ref) => {
36
36
  // an editor/LSP), so each pass re-reads them. Remote documents are assumed
37
37
  // stable for the session; call `clearRemoteCache()` to drop them.
38
38
  const remoteCache = new Map();
39
+ // In-flight remote loads, keyed by location. Two resolve passes that start at
40
+ // the same time and reach the same URL share a single fetch instead of racing
41
+ // two requests; whichever arrives first installs the promise, the rest await it.
42
+ const inFlight = new Map();
39
43
  /** Drops every cached remote document. Mainly useful for tests/long sessions. */
40
44
  export const clearRemoteCache = () => {
41
45
  remoteCache.clear();
42
46
  };
47
+ // Cap on redirect hops before we give up — generous enough for real services,
48
+ // low enough to stop a redirect loop from spinning forever.
49
+ const MAX_REDIRECTS = 5;
50
+ /**
51
+ * Fetches and parses a remote document, following redirects manually so the
52
+ * SSRF guard is re-applied to every hop. `fetch` follows redirects by default,
53
+ * which would let an allow-listed public URL bounce to a private/loopback
54
+ * address (e.g. the `169.254.169.254` metadata endpoint) — so we set
55
+ * `redirect: 'manual'` and re-run {@link denialReason} on each `Location`.
56
+ */
57
+ const fetchRemote = async (location, options) => {
58
+ let current = location;
59
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
60
+ const reason = denialReason(current, options);
61
+ if (reason !== null)
62
+ throw new Error(`refusing to follow redirect (${reason}): ${current}`);
63
+ const response = await fetch(current, { redirect: 'manual' });
64
+ if (response.status >= 300 && response.status < 400) {
65
+ const next = response.headers.get('location');
66
+ if (!next)
67
+ throw new Error(`HTTP ${response.status} redirect with no Location header`);
68
+ current = new URL(next, current).href;
69
+ continue;
70
+ }
71
+ if (!response.ok)
72
+ throw new Error(`HTTP ${response.status} ${response.statusText}`);
73
+ const parse = options.parse ?? ((c) => JSON.parse(c));
74
+ // Parse against the original request location so the caller's format sniffing
75
+ // (e.g. `.yaml` vs `.json`) and any relative refs key off a stable identity.
76
+ return parse(await response.text(), location);
77
+ }
78
+ throw new Error(`too many redirects (>${MAX_REDIRECTS}): ${location}`);
79
+ };
43
80
  /** Returns why a remote location may not be fetched, or `null` if it is allowed. */
44
81
  const denialReason = (location, options) => {
45
82
  if (options.remote === false)
@@ -83,12 +120,16 @@ const loadDoc = async (location, docCache, options, errors) => {
83
120
  docCache.set(location, {});
84
121
  return false;
85
122
  }
123
+ // Coalesce concurrent loads of the same URL onto one in-flight request; the
124
+ // owner (first caller) clears the slot once it settles.
125
+ let pending = inFlight.get(location);
126
+ const owner = pending === undefined;
127
+ if (pending === undefined) {
128
+ pending = fetchRemote(location, options);
129
+ inFlight.set(location, pending);
130
+ }
86
131
  try {
87
- const response = await fetch(location);
88
- if (!response.ok)
89
- throw new Error(`HTTP ${response.status} ${response.statusText}`);
90
- const parse = options.parse ?? ((c) => JSON.parse(c));
91
- const doc = parse(await response.text(), location);
132
+ const doc = await pending;
92
133
  remoteCache.set(location, doc);
93
134
  docCache.set(location, doc);
94
135
  return true;
@@ -98,6 +139,10 @@ const loadDoc = async (location, docCache, options, errors) => {
98
139
  docCache.set(location, {});
99
140
  return false;
100
141
  }
142
+ finally {
143
+ if (owner)
144
+ inFlight.delete(location);
145
+ }
101
146
  }
102
147
  try {
103
148
  const parse = options.parse ?? ((c) => JSON.parse(c));
@@ -162,11 +207,11 @@ const prefetch = async (rootLocation, docCache, options, errors) => {
162
207
  * `baseLocation` is the location of the document `node` belongs to, used to
163
208
  * resolve relative refs and `#/...` pointers within it.
164
209
  */
165
- const resolveAt = (node, baseLocation, docCache, refCache) => {
210
+ const resolveAt = (node, baseLocation, docCache, refCache, origins) => {
166
211
  if (node === null || typeof node !== 'object')
167
212
  return node;
168
213
  if (Array.isArray(node)) {
169
- return node.map((item) => resolveAt(item, baseLocation, docCache, refCache));
214
+ return node.map((item) => resolveAt(item, baseLocation, docCache, refCache, origins));
170
215
  }
171
216
  const obj = node;
172
217
  if (typeof obj['$ref'] === 'string') {
@@ -180,13 +225,22 @@ const resolveAt = (node, baseLocation, docCache, refCache) => {
180
225
  }
181
226
  refCache.set(cacheKey, CYCLE);
182
227
  const target = pointer ? getByPointer(targetRoot, pointer) : targetRoot;
183
- const resolved = resolveAt(target, targetLocation, docCache, refCache);
228
+ const resolved = resolveAt(target, targetLocation, docCache, refCache, origins);
184
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) });
238
+ }
185
239
  return resolved;
186
240
  }
187
241
  const result = {};
188
242
  for (const key of Object.keys(obj)) {
189
- result[key] = resolveAt(obj[key], baseLocation, docCache, refCache);
243
+ result[key] = resolveAt(obj[key], baseLocation, docCache, refCache, origins);
190
244
  }
191
245
  return result;
192
246
  };
@@ -203,6 +257,7 @@ export const resolveRefsFromFile = async (filename, options = {}) => {
203
257
  return { resolved: {}, errors };
204
258
  }
205
259
  await prefetch(rootLocation, docCache, options, errors);
206
- const resolved = resolveAt(docCache.get(rootLocation), rootLocation, docCache, new Map());
207
- return { resolved, errors };
260
+ const origins = options.trackOrigins ? new Map() : undefined;
261
+ const resolved = resolveAt(docCache.get(rootLocation), rootLocation, docCache, new Map(), origins);
262
+ return origins ? { resolved, errors, origins } : { resolved, errors };
208
263
  };
@@ -1,8 +1,18 @@
1
1
  import type { ResolveResult } from './types.js';
2
+ /** Options for the in-memory resolver. */
3
+ export type ResolveRefsOptions = {
4
+ /**
5
+ * Record a per-node origin map on the result (`origins`). For every object or
6
+ * array inlined in place of a `$ref`, the map records the in-document path it
7
+ * was defined at (the `location` is `''`, the single in-memory document).
8
+ * Defaults to `false`.
9
+ */
10
+ trackOrigins?: boolean;
11
+ };
2
12
  /**
3
13
  * Resolves all internal (`#/...`) `$ref`s in an in-memory document, inlining
4
14
  * each target. External and remote refs are left as-is. Cycles are broken with
5
15
  * an empty object so the result is always finite.
6
16
  */
7
- export declare const resolveRefs: (data: unknown) => ResolveResult;
17
+ export declare const resolveRefs: (data: unknown, options?: ResolveRefsOptions) => ResolveResult;
8
18
  //# sourceMappingURL=resolve-refs.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-refs.d.ts","sourceRoot":"","sources":["../src/resolve-refs.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAuC5C;;;;GAIG;AACH,eAAO,MAAM,WAAW,SAAU,OAAO,KAAG,aAG3C,CAAA"}
1
+ {"version":3,"file":"resolve-refs.d.ts","sourceRoot":"","sources":["../src/resolve-refs.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAa,aAAa,EAAE,MAAM,SAAS,CAAA;AAOvD,0CAA0C;AAC1C,MAAM,MAAM,kBAAkB,GAAG;IAC/B;;;;;OAKG;IACH,YAAY,CAAC,EAAE,OAAO,CAAA;CACvB,CAAA;AA6CD;;;;GAIG;AACH,eAAO,MAAM,WAAW,SAAU,OAAO,YAAW,kBAAkB,KAAQ,aAI7E,CAAA"}
@@ -1,4 +1,4 @@
1
- import { getByPointer } from './get-by-pointer.js';
1
+ import { getByPointer, pointerToPath } from './get-by-pointer.js';
2
2
  // A ref currently mid-resolution is marked with this sentinel; revisiting it
3
3
  // means we have looped, so we return `{}` instead of recursing forever.
4
4
  const CYCLE = Symbol('cycle');
@@ -9,11 +9,11 @@ const CYCLE = Symbol('cycle');
9
9
  * files, HTTP) are left untouched — callers that need those should use
10
10
  * `resolveRefsFromFile`.
11
11
  */
12
- const resolveInternal = (node, root, cache) => {
12
+ const resolveInternal = (node, root, cache, origins) => {
13
13
  if (node === null || typeof node !== 'object')
14
14
  return node;
15
15
  if (Array.isArray(node))
16
- return node.map((item) => resolveInternal(item, root, cache));
16
+ return node.map((item) => resolveInternal(item, root, cache, origins));
17
17
  const obj = node;
18
18
  if (typeof obj['$ref'] === 'string') {
19
19
  const ref = obj['$ref'];
@@ -24,13 +24,19 @@ const resolveInternal = (node, root, cache) => {
24
24
  return cached === CYCLE ? {} : cached;
25
25
  }
26
26
  cache.set(ref, CYCLE);
27
- const resolved = resolveInternal(getByPointer(root, ref.slice(1)), root, cache);
27
+ const resolved = resolveInternal(getByPointer(root, ref.slice(1)), root, cache, origins);
28
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)) });
34
+ }
29
35
  return resolved;
30
36
  }
31
37
  const result = {};
32
38
  for (const key of Object.keys(obj)) {
33
- result[key] = resolveInternal(obj[key], root, cache);
39
+ result[key] = resolveInternal(obj[key], root, cache, origins);
34
40
  }
35
41
  return result;
36
42
  };
@@ -39,7 +45,8 @@ const resolveInternal = (node, root, cache) => {
39
45
  * each target. External and remote refs are left as-is. Cycles are broken with
40
46
  * an empty object so the result is always finite.
41
47
  */
42
- export const resolveRefs = (data) => {
43
- const resolved = resolveInternal(data, data, new Map());
44
- return { resolved, errors: [] };
48
+ export const resolveRefs = (data, options = {}) => {
49
+ const origins = options.trackOrigins ? new Map() : undefined;
50
+ const resolved = resolveInternal(data, data, new Map(), origins);
51
+ return origins ? { resolved, errors: [], origins } : { resolved, errors: [] };
45
52
  };
package/dist/types.d.ts CHANGED
@@ -8,11 +8,34 @@ export type ResolveError = {
8
8
  message: string;
9
9
  path: JsonPath;
10
10
  };
11
+ /**
12
+ * Where an inlined node came from: the absolute location (file path or URL, or
13
+ * `''` for the single in-memory document) of the document it was defined in, and
14
+ * the path to it within that document.
15
+ */
16
+ export type Origin = {
17
+ location: string;
18
+ pointer: JsonPath;
19
+ };
20
+ /**
21
+ * Per-node origin map produced when `trackOrigins` is set: maps each object/array
22
+ * that was inlined in place of a `$ref` to where it was defined. A consumer can
23
+ * then attribute a node in the resolved tree back to its source document and path
24
+ * with a single lookup instead of re-deriving the `$ref` traversal. Keyed by node
25
+ * identity, so it relies on the resolver sharing one object per repeated `$ref`
26
+ * target (which it does).
27
+ */
28
+ export type OriginMap = Map<object, Origin>;
11
29
  /** The outcome of a resolve pass: the dereferenced document plus any errors. */
12
30
  export type ResolveResult = {
13
31
  /** The dereferenced document (all resolvable `$ref`s inlined). */
14
32
  resolved: unknown;
15
33
  errors: ResolveError[];
34
+ /**
35
+ * Per-node origin map. Present only when `trackOrigins` was requested; each
36
+ * entry maps an inlined object/array to the document and path it came from.
37
+ */
38
+ origins?: OriginMap;
16
39
  };
17
40
  /** Controls how external `$ref`s to other documents are loaded. */
18
41
  export type ResolveOptions = {
@@ -50,5 +73,12 @@ export type ResolveOptions = {
50
73
  * ```
51
74
  */
52
75
  parse?: (content: string, location: string) => unknown;
76
+ /**
77
+ * Record a per-node origin map on the result (`origins`). For every object or
78
+ * array inlined in place of a `$ref`, the map records the document and in-file
79
+ * path it was defined at, so a consumer can attribute resolved-tree nodes back
80
+ * to their source without re-walking the `$ref` chain. Defaults to `false`.
81
+ */
82
+ trackOrigins?: boolean;
53
83
  };
54
84
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,MAAM,QAAQ,GAAG,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAA;AAE1C,iFAAiF;AACjF,MAAM,MAAM,YAAY,GAAG;IACzB,OAAO,EAAE,MAAM,CAAA;IACf,IAAI,EAAE,QAAQ,CAAA;CACf,CAAA;AAED,gFAAgF;AAChF,MAAM,MAAM,aAAa,GAAG;IAC1B,kEAAkE;IAClE,QAAQ,EAAE,OAAO,CAAA;IACjB,MAAM,EAAE,YAAY,EAAE,CAAA;CACvB,CAAA;AAED,mEAAmE;AACnE,MAAM,MAAM,cAAc,GAAG;IAC3B;;OAEG;IACH,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,EAAE,CAAA;IACvB;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B;;;;;;;;;;;;;;;OAeG;IACH,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAA;CACvD,CAAA"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,MAAM,QAAQ,GAAG,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAA;AAE1C,iFAAiF;AACjF,MAAM,MAAM,YAAY,GAAG;IACzB,OAAO,EAAE,MAAM,CAAA;IACf,IAAI,EAAE,QAAQ,CAAA;CACf,CAAA;AAED;;;;GAIG;AACH,MAAM,MAAM,MAAM,GAAG;IACnB,QAAQ,EAAE,MAAM,CAAA;IAChB,OAAO,EAAE,QAAQ,CAAA;CAClB,CAAA;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,SAAS,GAAG,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAE3C,gFAAgF;AAChF,MAAM,MAAM,aAAa,GAAG;IAC1B,kEAAkE;IAClE,QAAQ,EAAE,OAAO,CAAA;IACjB,MAAM,EAAE,YAAY,EAAE,CAAA;IACtB;;;OAGG;IACH,OAAO,CAAC,EAAE,SAAS,CAAA;CACpB,CAAA;AAED,mEAAmE;AACnE,MAAM,MAAM,cAAc,GAAG;IAC3B;;OAEG;IACH,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,EAAE,CAAA;IACvB;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B;;;;;;;;;;;;;;;OAeG;IACH,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAA;IACtD;;;;;OAKG;IACH,YAAY,CAAC,EAAE,OAAO,CAAA;CACvB,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/resolve-refs",
3
- "version": "0.1.1",
3
+ "version": "0.2.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
  "module": "./dist/index.js",
6
6
  "type": "module",
@@ -28,6 +28,13 @@ describe('get-by-pointer', () => {
28
28
  expect(getByPointer(root, '/tilde~0key')).toBe(false)
29
29
  })
30
30
 
31
+ it('percent-decodes URI-encoded segments', () => {
32
+ const doc = { '{volume_id}': 'found', 'weird/key': true }
33
+ expect(getByPointer(doc, '/%7Bvolume_id%7D')).toBe('found')
34
+ // %2F in a segment must not be treated as a path separator
35
+ expect(getByPointer(doc, '/weird%2Fkey')).toBe(true)
36
+ })
37
+
31
38
  it('returns undefined when a segment is missing', () => {
32
39
  expect(getByPointer(root, '/info/nope')).toBeUndefined()
33
40
  expect(getByPointer(root, '/info/title/tooDeep')).toBeUndefined()
@@ -1,3 +1,28 @@
1
+ import type { JsonPath } from './types'
2
+
3
+ /**
4
+ * Parses a JSON Pointer string (RFC 6901) into a path of keys: strips the leading
5
+ * `/`, splits on `/`, decodes each segment (`%XX`, then `~1` → `/`, `~0` → `~`),
6
+ * and coerces all-digit segments to numbers so array indices and object keys read
7
+ * back the same way a path consumer expects. A bare `''` or `'/'` is the empty path.
8
+ */
9
+ export const pointerToPath = (pointer: string): JsonPath => {
10
+ if (pointer === '' || pointer === '/') return []
11
+ return pointer
12
+ .replace(/^\//, '')
13
+ .split('/')
14
+ .map((segment) => {
15
+ let decoded = segment
16
+ try {
17
+ decoded = decodeURIComponent(segment)
18
+ } catch {
19
+ // leave invalid percent-escapes as-is
20
+ }
21
+ decoded = decoded.replace(/~1/g, '/').replace(/~0/g, '~')
22
+ return /^\d+$/.test(decoded) ? Number(decoded) : decoded
23
+ })
24
+ }
25
+
1
26
  /**
2
27
  * Walks a JSON Pointer string (RFC 6901) to the value it points to within
3
28
  * `root`. A bare `''` or `'/'` returns the root document. Segment escapes are
@@ -10,7 +35,15 @@ export const getByPointer = (root: unknown, pointer: string): unknown => {
10
35
  const segments = pointer
11
36
  .replace(/^\//, '')
12
37
  .split('/')
13
- .map((segment) => segment.replace(/~1/g, '/').replace(/~0/g, '~'))
38
+ .map((segment) => {
39
+ let decoded = segment
40
+ try {
41
+ decoded = decodeURIComponent(segment)
42
+ } catch {
43
+ // leave invalid percent-escapes as-is
44
+ }
45
+ return decoded.replace(/~1/g, '/').replace(/~0/g, '~')
46
+ })
14
47
 
15
48
  let current: unknown = root
16
49
  for (const segment of segments) {
package/src/index.ts CHANGED
@@ -1,5 +1,5 @@
1
- export { getByPointer } from './get-by-pointer'
1
+ export { getByPointer, pointerToPath } from './get-by-pointer'
2
2
  export { isPrivateHost } from './is-private-host'
3
- export { resolveRefs } from './resolve-refs'
3
+ export { type ResolveRefsOptions, resolveRefs } from './resolve-refs'
4
4
  export { clearRemoteCache, resolveRefsFromFile } from './resolve-refs-from-file'
5
- export type { JsonPath, ResolveError, ResolveOptions, ResolveResult } from './types'
5
+ export type { JsonPath, Origin, OriginMap, ResolveError, ResolveOptions, ResolveResult } from './types'
@@ -28,9 +28,37 @@ describe('is-private-host', () => {
28
28
  expect(isPrivateHost('fd00::1')).toBe(true)
29
29
  })
30
30
 
31
+ it('flags the full fe80::/10 link-local range, not just fe80', () => {
32
+ expect(isPrivateHost('fe9a::1')).toBe(true)
33
+ expect(isPrivateHost('feba::1')).toBe(true)
34
+ expect(isPrivateHost('febf::1')).toBe(true)
35
+ // fec0:: is outside fe80::/10 (third nibble c), so it is not link-local.
36
+ expect(isPrivateHost('fec0::1')).toBe(false)
37
+ })
38
+
39
+ it('flags IPv4-mapped IPv6 loopback in both dotted and hex form', () => {
40
+ expect(isPrivateHost('::ffff:127.0.0.1')).toBe(true)
41
+ // The form `new URL()` produces for ::ffff:127.0.0.1.
42
+ expect(isPrivateHost('::ffff:7f00:1')).toBe(true)
43
+ // ::ffff:169.254.169.254 (cloud metadata) → hex a9fe:a9fe.
44
+ expect(isPrivateHost('::ffff:a9fe:a9fe')).toBe(true)
45
+ // A mapped public address stays public.
46
+ expect(isPrivateHost('::ffff:8.8.8.8')).toBe(false)
47
+ })
48
+
49
+ it('flags decimal/octal/hex IPv4 encodings (defense-in-depth)', () => {
50
+ expect(isPrivateHost('2130706433')).toBe(true) // 127.0.0.1
51
+ expect(isPrivateHost('0177.0.0.1')).toBe(true)
52
+ expect(isPrivateHost('0x7f000001')).toBe(true)
53
+ expect(isPrivateHost('127.1')).toBe(true)
54
+ })
55
+
31
56
  it('allows public hosts', () => {
32
57
  expect(isPrivateHost('example.com')).toBe(false)
33
58
  expect(isPrivateHost('8.8.8.8')).toBe(false)
34
59
  expect(isPrivateHost('172.32.0.1')).toBe(false)
60
+ // Hostnames made only of hex letters must not be mistaken for IPs.
61
+ expect(isPrivateHost('cafe')).toBe(false)
62
+ expect(isPrivateHost('dead.beef')).toBe(false)
35
63
  })
36
64
  })
@@ -6,29 +6,86 @@
6
6
  * private IP is not caught here. It exists to stop the obvious SSRF footguns
7
7
  * when resolving remote `$ref`s.
8
8
  */
9
+
10
+ /** True for an IPv4 address (given its first two octets) in a non-public range. */
11
+ const isPrivateIpv4 = (a: number, b: number): boolean => {
12
+ if (a === 10 || a === 127 || a === 0) return true
13
+ if (a === 169 && b === 254) return true // link-local + cloud metadata
14
+ if (a === 172 && b >= 16 && b <= 31) return true
15
+ if (a === 192 && b === 168) return true
16
+ if (a === 100 && b >= 64 && b <= 127) return true // CGNAT
17
+ return false
18
+ }
19
+
20
+ /** Parses a single IPv4 part in decimal, octal (`0…`), or hex (`0x…`) form. */
21
+ const parseIpv4Part = (s: string): number | null => {
22
+ if (/^0x[0-9a-f]+$/i.test(s)) return Number.parseInt(s, 16)
23
+ if (/^0[0-7]*$/.test(s)) return Number.parseInt(s, 8)
24
+ if (/^[1-9][0-9]*$/.test(s)) return Number.parseInt(s, 10)
25
+ return null
26
+ }
27
+
28
+ /**
29
+ * Resolves the first two octets of an IPv4 host written in any inet_aton form
30
+ * (dotted/decimal/octal/hex, 1–4 parts), or `null` if it is not an IPv4 literal.
31
+ * The WHATWG URL parser normalizes these to dotted-decimal before they reach us,
32
+ * but a direct caller (this is an exported guard) can pass the raw form.
33
+ */
34
+ const ipv4Octets = (host: string): [number, number] | null => {
35
+ if (!/^[0-9a-fx.]+$/i.test(host)) return null
36
+ const parts = host.split('.')
37
+ if (parts.length === 0 || parts.length > 4) return null
38
+ const nums: number[] = []
39
+ for (const part of parts) {
40
+ const n = parseIpv4Part(part)
41
+ if (n === null) return null
42
+ nums.push(n)
43
+ }
44
+ // inet_aton packing: every part but the last is one byte; the last fills the
45
+ // remaining low bytes (so `127.1` is 127.0.0.1 and `2130706433` is too).
46
+ let value = 0
47
+ for (let i = 0; i < nums.length - 1; i++) {
48
+ const byte = nums[i] as number
49
+ if (byte > 0xff) return null
50
+ value = value * 256 + byte
51
+ }
52
+ const remaining = 4 - (nums.length - 1)
53
+ const last = nums[nums.length - 1] as number
54
+ if (last > 256 ** remaining - 1) return null
55
+ value = value * 256 ** remaining + last
56
+ if (value > 0xffffffff) return null
57
+ return [(value >>> 24) & 0xff, (value >>> 16) & 0xff]
58
+ }
59
+
9
60
  export const isPrivateHost = (hostname: string): boolean => {
10
61
  const host = hostname.replace(/^\[|\]$/g, '').toLowerCase()
11
62
  if (host === 'localhost' || host.endsWith('.localhost')) return true
12
63
 
13
- // IPv4 (incl. IPv4-mapped IPv6 like ::ffff:127.0.0.1)
14
- const v4 = host.match(/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/)
15
- if (v4) {
16
- const a = Number(v4[1])
17
- const b = Number(v4[2])
18
- if (a === 10 || a === 127 || a === 0) return true
19
- if (a === 169 && b === 254) return true // link-local + metadata
20
- if (a === 172 && b >= 16 && b <= 31) return true
21
- if (a === 192 && b === 168) return true
22
- if (a === 100 && b >= 64 && b <= 127) return true // CGNAT
23
- return false
24
- }
25
-
26
- // IPv6
27
64
  if (host.includes(':')) {
65
+ // --- IPv6 (and IPv4-mapped IPv6) ---
28
66
  if (host === '::1' || host === '::') return true
29
- if (host.startsWith('fe80:') || host.startsWith('fe80::')) return true // link-local
30
- if (host.startsWith('fc') || host.startsWith('fd')) return true // unique-local
67
+ // fe80::/10 link-local spans fe80–febf (third nibble 8–b).
68
+ if (/^fe[89ab][0-9a-f]:/.test(host)) return true
69
+ if (host.startsWith('fc') || host.startsWith('fd')) return true // fc00::/7 unique-local
70
+
71
+ // IPv4-mapped/compatible, dotted (`::ffff:127.0.0.1`) — the URL parser
72
+ // rewrites this to hex, but a direct caller may pass the dotted form.
73
+ const dotted = /:((?:\d{1,3}\.){3}\d{1,3})$/.exec(host)
74
+ if (dotted?.[1]) {
75
+ const oct = ipv4Octets(dotted[1])
76
+ if (oct) return isPrivateIpv4(oct[0], oct[1])
77
+ }
78
+ // IPv4-mapped, hex (`::ffff:7f00:1`) — what `new URL()` produces.
79
+ const hex = /:ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(host)
80
+ if (hex?.[1] && hex[2]) {
81
+ const hi = Number.parseInt(hex[1], 16)
82
+ return isPrivateIpv4((hi >> 8) & 0xff, hi & 0xff)
83
+ }
31
84
  return false
32
85
  }
86
+
87
+ // --- IPv4 (any inet_aton encoding) ---
88
+ const oct = ipv4Octets(host)
89
+ if (oct) return isPrivateIpv4(oct[0], oct[1])
33
90
  return false
34
91
  }
@@ -44,6 +44,65 @@ describe('resolve-refs-from-file', () => {
44
44
  expect(resolved).toMatchObject({ a: { value: 1 }, b: { value: 1 } })
45
45
  })
46
46
 
47
+ it('omits the origin map unless trackOrigins is set', async () => {
48
+ writeFileSync(join(dir, 'root.json'), JSON.stringify({ a: { $ref: '#/b' }, b: { value: 1 } }))
49
+
50
+ const result = await resolveRefsFromFile(join(dir, 'root.json'))
51
+
52
+ expect(result.origins).toBeUndefined()
53
+ })
54
+
55
+ it('stamps inlined nodes with their origin document and in-file path', async () => {
56
+ const petPath = join(dir, 'pet.json')
57
+ const apiPath = join(dir, 'api.json')
58
+ writeFileSync(petPath, JSON.stringify({ Pet: { type: 'object', properties: { name: { type: 'string' } } } }))
59
+ writeFileSync(
60
+ apiPath,
61
+ JSON.stringify({
62
+ components: { schemas: { Pet: { $ref: './pet.json#/Pet' }, Pet2: { $ref: './pet.json#/Pet' } } },
63
+ widget: { type: 'object' },
64
+ useWidget: { $ref: '#/widget' },
65
+ }),
66
+ )
67
+
68
+ const { resolved, origins } = await resolveRefsFromFile(apiPath, { trackOrigins: true })
69
+ expect(origins).toBeDefined()
70
+ const tree = resolved as {
71
+ components: { schemas: { Pet: object; Pet2: object } }
72
+ useWidget: object
73
+ }
74
+
75
+ // The cross-file node is stamped with pet.json and its in-file path; both call
76
+ // sites share the one inlined object, so the stamp identifies the definition.
77
+ expect(tree.components.schemas.Pet).toBe(tree.components.schemas.Pet2)
78
+ expect(origins?.get(tree.components.schemas.Pet)).toEqual({ location: petPath, pointer: ['Pet'] })
79
+
80
+ // An internal ref is stamped against the root document at the target path.
81
+ expect(origins?.get(tree.useWidget)).toEqual({ location: apiPath, pointer: ['widget'] })
82
+ })
83
+
84
+ it('keeps the definition origin when a node is reached through a chained ref (first-write-wins)', async () => {
85
+ const petPath = join(dir, 'pet.json')
86
+ const apiPath = join(dir, 'api.json')
87
+ writeFileSync(petPath, JSON.stringify({ Pet: { type: 'object' } }))
88
+ writeFileSync(
89
+ apiPath,
90
+ JSON.stringify({
91
+ components: { schemas: { Pet: { $ref: './pet.json#/Pet' } } },
92
+ // Resolves through the internal ref to the same pet.json object.
93
+ alias: { $ref: '#/components/schemas/Pet' },
94
+ }),
95
+ )
96
+
97
+ const { resolved, origins } = await resolveRefsFromFile(apiPath, { trackOrigins: true })
98
+ const tree = resolved as { components: { schemas: { Pet: object } }; alias: object }
99
+
100
+ // `alias` resolves through to the same object; its origin stays the pet.json
101
+ // definition rather than the intermediate root-document pointer.
102
+ expect(tree.alias).toBe(tree.components.schemas.Pet)
103
+ expect(origins?.get(tree.alias)).toEqual({ location: petPath, pointer: ['Pet'] })
104
+ })
105
+
47
106
  it('records an error and degrades to {} when a referenced file is missing', async () => {
48
107
  writeFileSync(join(dir, 'api.json'), JSON.stringify({ x: { $ref: './missing.json#/Nope' } }))
49
108
 
@@ -122,4 +181,66 @@ describe('resolve-refs-from-file', () => {
122
181
  // Both refs hit the same document, which is fetched and cached exactly once.
123
182
  expect(fetchSpy).toHaveBeenCalledTimes(1)
124
183
  })
184
+
185
+ it('refuses a redirect that lands on a private host (SSRF via redirect)', async () => {
186
+ const fetchSpy = vi
187
+ .spyOn(globalThis, 'fetch')
188
+ .mockResolvedValue(
189
+ new Response(null, { status: 302, headers: { location: 'http://169.254.169.254/latest/meta-data' } }),
190
+ )
191
+ writeFileSync(join(dir, 'api.json'), JSON.stringify({ x: { $ref: 'https://api.example.com/s.json#/Foo' } }))
192
+
193
+ const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'), {
194
+ allowedHosts: ['api.example.com'],
195
+ })
196
+
197
+ expect((resolved as { x: unknown }).x).toBeUndefined()
198
+ expect(errors[0]?.message).toMatch(/refusing to follow redirect/i)
199
+ // The initial host was allowed, so the first request happened — but the
200
+ // redirect target was re-checked and refused before any second request.
201
+ expect(fetchSpy).toHaveBeenCalledTimes(1)
202
+ expect(fetchSpy).toHaveBeenCalledWith('https://api.example.com/s.json', { redirect: 'manual' })
203
+ })
204
+
205
+ it('follows a redirect to another allowed host', async () => {
206
+ const fetchSpy = vi
207
+ .spyOn(globalThis, 'fetch')
208
+ .mockResolvedValueOnce(
209
+ new Response(null, { status: 301, headers: { location: 'https://cdn.example.com/s.json' } }),
210
+ )
211
+ .mockResolvedValueOnce(new Response(JSON.stringify({ Foo: { type: 'string' } }), { status: 200 }))
212
+ writeFileSync(join(dir, 'api.json'), JSON.stringify({ x: { $ref: 'https://api.example.com/s.json#/Foo' } }))
213
+
214
+ const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'), {
215
+ allowedHosts: ['api.example.com', 'cdn.example.com'],
216
+ })
217
+
218
+ expect(errors).toEqual([])
219
+ expect(resolved).toMatchObject({ x: { type: 'string' } })
220
+ expect(fetchSpy).toHaveBeenCalledTimes(2)
221
+ })
222
+
223
+ it('coalesces two concurrent resolves of the same remote URL into one fetch', async () => {
224
+ let resolveFetch: ((r: Response) => void) | undefined
225
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(
226
+ () =>
227
+ new Promise<Response>((res) => {
228
+ resolveFetch = res
229
+ }),
230
+ )
231
+ writeFileSync(join(dir, 'api.json'), JSON.stringify({ x: { $ref: 'https://api.example.com/s.json#/Foo' } }))
232
+
233
+ // Two passes start before either fetch settles — they must share one request.
234
+ const pass1 = resolveRefsFromFile(join(dir, 'api.json'), { allowedHosts: ['api.example.com'] })
235
+ const pass2 = resolveRefsFromFile(join(dir, 'api.json'), { allowedHosts: ['api.example.com'] })
236
+ await Promise.resolve()
237
+ resolveFetch?.(new Response(JSON.stringify({ Foo: { type: 'string' } }), { status: 200 }))
238
+
239
+ const [r1, r2] = await Promise.all([pass1, pass2])
240
+ expect(r1.errors).toEqual([])
241
+ expect(r2.errors).toEqual([])
242
+ expect(r1.resolved).toMatchObject({ x: { type: 'string' } })
243
+ expect(r2.resolved).toMatchObject({ x: { type: 'string' } })
244
+ expect(fetchSpy).toHaveBeenCalledTimes(1)
245
+ })
125
246
  })
@@ -1,9 +1,9 @@
1
1
  import { readFileSync } from 'node:fs'
2
2
  import { dirname, resolve as resolvePath } from 'node:path'
3
3
 
4
- import { getByPointer } from './get-by-pointer'
4
+ import { getByPointer, pointerToPath } from './get-by-pointer'
5
5
  import { isPrivateHost } from './is-private-host'
6
- import type { ResolveError, ResolveOptions, ResolveResult } from './types'
6
+ import type { OriginMap, ResolveError, ResolveOptions, ResolveResult } from './types'
7
7
 
8
8
  // A ref currently mid-resolution is marked with this sentinel; revisiting it
9
9
  // means a cycle, so we return `{}` instead of recursing forever.
@@ -45,11 +45,50 @@ const splitRef = (ref: string): { filePart: string; pointer: string } => {
45
45
 
46
46
  const remoteCache = new Map<string, unknown>()
47
47
 
48
+ // In-flight remote loads, keyed by location. Two resolve passes that start at
49
+ // the same time and reach the same URL share a single fetch instead of racing
50
+ // two requests; whichever arrives first installs the promise, the rest await it.
51
+ const inFlight = new Map<string, Promise<unknown>>()
52
+
48
53
  /** Drops every cached remote document. Mainly useful for tests/long sessions. */
49
54
  export const clearRemoteCache = (): void => {
50
55
  remoteCache.clear()
51
56
  }
52
57
 
58
+ // Cap on redirect hops before we give up — generous enough for real services,
59
+ // low enough to stop a redirect loop from spinning forever.
60
+ const MAX_REDIRECTS = 5
61
+
62
+ /**
63
+ * Fetches and parses a remote document, following redirects manually so the
64
+ * SSRF guard is re-applied to every hop. `fetch` follows redirects by default,
65
+ * which would let an allow-listed public URL bounce to a private/loopback
66
+ * address (e.g. the `169.254.169.254` metadata endpoint) — so we set
67
+ * `redirect: 'manual'` and re-run {@link denialReason} on each `Location`.
68
+ */
69
+ const fetchRemote = async (location: string, options: ResolveOptions): Promise<unknown> => {
70
+ let current = location
71
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
72
+ const reason = denialReason(current, options)
73
+ if (reason !== null) throw new Error(`refusing to follow redirect (${reason}): ${current}`)
74
+
75
+ const response = await fetch(current, { redirect: 'manual' })
76
+ if (response.status >= 300 && response.status < 400) {
77
+ const next = response.headers.get('location')
78
+ if (!next) throw new Error(`HTTP ${response.status} redirect with no Location header`)
79
+ current = new URL(next, current).href
80
+ continue
81
+ }
82
+ if (!response.ok) throw new Error(`HTTP ${response.status} ${response.statusText}`)
83
+
84
+ const parse = options.parse ?? ((c: string) => JSON.parse(c) as unknown)
85
+ // Parse against the original request location so the caller's format sniffing
86
+ // (e.g. `.yaml` vs `.json`) and any relative refs key off a stable identity.
87
+ return parse(await response.text(), location)
88
+ }
89
+ throw new Error(`too many redirects (>${MAX_REDIRECTS}): ${location}`)
90
+ }
91
+
53
92
  /** Returns why a remote location may not be fetched, or `null` if it is allowed. */
54
93
  const denialReason = (location: string, options: ResolveOptions): string | null => {
55
94
  if (options.remote === false) return 'remote $ref resolution is disabled'
@@ -99,11 +138,16 @@ const loadDoc = async (
99
138
  docCache.set(location, {})
100
139
  return false
101
140
  }
141
+ // Coalesce concurrent loads of the same URL onto one in-flight request; the
142
+ // owner (first caller) clears the slot once it settles.
143
+ let pending = inFlight.get(location)
144
+ const owner = pending === undefined
145
+ if (pending === undefined) {
146
+ pending = fetchRemote(location, options)
147
+ inFlight.set(location, pending)
148
+ }
102
149
  try {
103
- const response = await fetch(location)
104
- if (!response.ok) throw new Error(`HTTP ${response.status} ${response.statusText}`)
105
- const parse = options.parse ?? ((c: string) => JSON.parse(c) as unknown)
106
- const doc = parse(await response.text(), location)
150
+ const doc = await pending
107
151
  remoteCache.set(location, doc)
108
152
  docCache.set(location, doc)
109
153
  return true
@@ -111,6 +155,8 @@ const loadDoc = async (
111
155
  errors.push({ message: `Failed to fetch ${location}: ${String(err)}`, path: [] })
112
156
  docCache.set(location, {})
113
157
  return false
158
+ } finally {
159
+ if (owner) inFlight.delete(location)
114
160
  }
115
161
  }
116
162
 
@@ -184,10 +230,11 @@ const resolveAt = (
184
230
  baseLocation: string,
185
231
  docCache: Map<string, unknown>,
186
232
  refCache: Map<string, CacheValue>,
233
+ origins: OriginMap | undefined,
187
234
  ): unknown => {
188
235
  if (node === null || typeof node !== 'object') return node
189
236
  if (Array.isArray(node)) {
190
- return node.map((item) => resolveAt(item, baseLocation, docCache, refCache))
237
+ return node.map((item) => resolveAt(item, baseLocation, docCache, refCache, origins))
191
238
  }
192
239
  const obj = node as Record<string, unknown>
193
240
  if (typeof obj['$ref'] === 'string') {
@@ -202,13 +249,22 @@ const resolveAt = (
202
249
  }
203
250
  refCache.set(cacheKey, CYCLE)
204
251
  const target = pointer ? getByPointer(targetRoot, pointer) : targetRoot
205
- const resolved = resolveAt(target, targetLocation, docCache, refCache)
252
+ const resolved = resolveAt(target, targetLocation, docCache, refCache, origins)
206
253
  refCache.set(cacheKey, resolved)
254
+ // Stamp the inlined node with where it was defined so a consumer can map a
255
+ // resolved-tree node back to its source document/path. Only objects/arrays are
256
+ // stamped (primitives can't key the map). First-write-wins: resolution recurses
257
+ // to the deepest `$ref` before returning, so the *definition* site stamps first;
258
+ // an outer ref that merely points (transitively) at the same object must not
259
+ // overwrite it with an intermediate location.
260
+ if (origins && resolved !== null && typeof resolved === 'object' && !origins.has(resolved)) {
261
+ origins.set(resolved, { location: targetLocation, pointer: pointerToPath(pointer) })
262
+ }
207
263
  return resolved
208
264
  }
209
265
  const result: Record<string, unknown> = {}
210
266
  for (const key of Object.keys(obj)) {
211
- result[key] = resolveAt(obj[key], baseLocation, docCache, refCache)
267
+ result[key] = resolveAt(obj[key], baseLocation, docCache, refCache, origins)
212
268
  }
213
269
  return result
214
270
  }
@@ -227,6 +283,7 @@ export const resolveRefsFromFile = async (filename: string, options: ResolveOpti
227
283
  return { resolved: {}, errors }
228
284
  }
229
285
  await prefetch(rootLocation, docCache, options, errors)
230
- const resolved = resolveAt(docCache.get(rootLocation), rootLocation, docCache, new Map())
231
- return { resolved, errors }
286
+ const origins: OriginMap | undefined = options.trackOrigins ? new Map() : undefined
287
+ const resolved = resolveAt(docCache.get(rootLocation), rootLocation, docCache, new Map(), origins)
288
+ return origins ? { resolved, errors, origins } : { resolved, errors }
232
289
  }
@@ -47,4 +47,32 @@ describe('resolve-refs', () => {
47
47
 
48
48
  expect(resolved).toEqual({ properties: { pet: { $ref: 'pet.json#/Pet' } } })
49
49
  })
50
+
51
+ it('omits the origin map unless trackOrigins is set', () => {
52
+ const result = resolveRefs({ a: { $ref: '#/$defs/x' }, $defs: { x: { type: 'string' } } })
53
+ expect(result.origins).toBeUndefined()
54
+ })
55
+
56
+ it('stamps each inlined node with its in-document origin path', () => {
57
+ const { resolved, origins } = resolveRefs(
58
+ {
59
+ properties: { a: { $ref: '#/$defs/x' }, b: { $ref: '#/$defs/x' } },
60
+ $defs: { x: { type: 'object', properties: { id: { type: 'string' } } } },
61
+ },
62
+ { trackOrigins: true },
63
+ )
64
+ const tree = resolved as { properties: { a: object; b: object } }
65
+ // Repeated refs share one object, stamped once with the definition path.
66
+ expect(tree.properties.a).toBe(tree.properties.b)
67
+ expect(origins?.get(tree.properties.a)).toEqual({ location: '', pointer: ['$defs', 'x'] })
68
+ })
69
+
70
+ it('decodes pointer escapes and array indices in origin paths', () => {
71
+ const { resolved, origins } = resolveRefs(
72
+ { ref: { $ref: '#/a~1b/c~0d/0' }, 'a/b': { 'c~d': [{ type: 'number' }] } },
73
+ { trackOrigins: true },
74
+ )
75
+ const node = (resolved as { ref: object }).ref
76
+ expect(origins?.get(node)).toEqual({ location: '', pointer: ['a/b', 'c~d', 0] })
77
+ })
50
78
  })
@@ -1,11 +1,22 @@
1
- import { getByPointer } from './get-by-pointer'
2
- import type { ResolveResult } from './types'
1
+ import { getByPointer, pointerToPath } from './get-by-pointer'
2
+ import type { OriginMap, ResolveResult } from './types'
3
3
 
4
4
  // A ref currently mid-resolution is marked with this sentinel; revisiting it
5
5
  // means we have looped, so we return `{}` instead of recursing forever.
6
6
  const CYCLE = Symbol('cycle')
7
7
  type CacheValue = unknown | typeof CYCLE
8
8
 
9
+ /** Options for the in-memory resolver. */
10
+ export type ResolveRefsOptions = {
11
+ /**
12
+ * Record a per-node origin map on the result (`origins`). For every object or
13
+ * array inlined in place of a `$ref`, the map records the in-document path it
14
+ * was defined at (the `location` is `''`, the single in-memory document).
15
+ * Defaults to `false`.
16
+ */
17
+ trackOrigins?: boolean
18
+ }
19
+
9
20
  /**
10
21
  * Single-pass internal-only `$ref` resolver. Each unique ref string is resolved
11
22
  * exactly once (the `cache`); revisiting a ref that is still mid-resolution
@@ -13,9 +24,14 @@ type CacheValue = unknown | typeof CYCLE
13
24
  * files, HTTP) are left untouched — callers that need those should use
14
25
  * `resolveRefsFromFile`.
15
26
  */
16
- const resolveInternal = (node: unknown, root: unknown, cache: Map<string, CacheValue>): unknown => {
27
+ const resolveInternal = (
28
+ node: unknown,
29
+ root: unknown,
30
+ cache: Map<string, CacheValue>,
31
+ origins: OriginMap | undefined,
32
+ ): unknown => {
17
33
  if (node === null || typeof node !== 'object') return node
18
- if (Array.isArray(node)) return node.map((item) => resolveInternal(item, root, cache))
34
+ if (Array.isArray(node)) return node.map((item) => resolveInternal(item, root, cache, origins))
19
35
 
20
36
  const obj = node as Record<string, unknown>
21
37
  if (typeof obj['$ref'] === 'string') {
@@ -26,14 +42,20 @@ const resolveInternal = (node: unknown, root: unknown, cache: Map<string, CacheV
26
42
  return cached === CYCLE ? {} : cached
27
43
  }
28
44
  cache.set(ref, CYCLE)
29
- const resolved = resolveInternal(getByPointer(root, ref.slice(1)), root, cache)
45
+ const resolved = resolveInternal(getByPointer(root, ref.slice(1)), root, cache, origins)
30
46
  cache.set(ref, resolved)
47
+ // Stamp the inlined node with the path it was defined at (see resolveAt).
48
+ // First-write-wins so the deepest definition stamps before any outer ref that
49
+ // transitively points at the same object. Primitives can't key the map.
50
+ if (origins && resolved !== null && typeof resolved === 'object' && !origins.has(resolved)) {
51
+ origins.set(resolved, { location: '', pointer: pointerToPath(ref.slice(1)) })
52
+ }
31
53
  return resolved
32
54
  }
33
55
 
34
56
  const result: Record<string, unknown> = {}
35
57
  for (const key of Object.keys(obj)) {
36
- result[key] = resolveInternal(obj[key], root, cache)
58
+ result[key] = resolveInternal(obj[key], root, cache, origins)
37
59
  }
38
60
  return result
39
61
  }
@@ -43,7 +65,8 @@ const resolveInternal = (node: unknown, root: unknown, cache: Map<string, CacheV
43
65
  * each target. External and remote refs are left as-is. Cycles are broken with
44
66
  * an empty object so the result is always finite.
45
67
  */
46
- export const resolveRefs = (data: unknown): ResolveResult => {
47
- const resolved = resolveInternal(data, data, new Map())
48
- return { resolved, errors: [] }
68
+ export const resolveRefs = (data: unknown, options: ResolveRefsOptions = {}): ResolveResult => {
69
+ const origins: OriginMap | undefined = options.trackOrigins ? new Map() : undefined
70
+ const resolved = resolveInternal(data, data, new Map(), origins)
71
+ return origins ? { resolved, errors: [], origins } : { resolved, errors: [] }
49
72
  }
package/src/types.ts CHANGED
@@ -10,11 +10,36 @@ export type ResolveError = {
10
10
  path: JsonPath
11
11
  }
12
12
 
13
+ /**
14
+ * Where an inlined node came from: the absolute location (file path or URL, or
15
+ * `''` for the single in-memory document) of the document it was defined in, and
16
+ * the path to it within that document.
17
+ */
18
+ export type Origin = {
19
+ location: string
20
+ pointer: JsonPath
21
+ }
22
+
23
+ /**
24
+ * Per-node origin map produced when `trackOrigins` is set: maps each object/array
25
+ * that was inlined in place of a `$ref` to where it was defined. A consumer can
26
+ * then attribute a node in the resolved tree back to its source document and path
27
+ * with a single lookup instead of re-deriving the `$ref` traversal. Keyed by node
28
+ * identity, so it relies on the resolver sharing one object per repeated `$ref`
29
+ * target (which it does).
30
+ */
31
+ export type OriginMap = Map<object, Origin>
32
+
13
33
  /** The outcome of a resolve pass: the dereferenced document plus any errors. */
14
34
  export type ResolveResult = {
15
35
  /** The dereferenced document (all resolvable `$ref`s inlined). */
16
36
  resolved: unknown
17
37
  errors: ResolveError[]
38
+ /**
39
+ * Per-node origin map. Present only when `trackOrigins` was requested; each
40
+ * entry maps an inlined object/array to the document and path it came from.
41
+ */
42
+ origins?: OriginMap
18
43
  }
19
44
 
20
45
  /** Controls how external `$ref`s to other documents are loaded. */
@@ -53,4 +78,11 @@ export type ResolveOptions = {
53
78
  * ```
54
79
  */
55
80
  parse?: (content: string, location: string) => unknown
81
+ /**
82
+ * Record a per-node origin map on the result (`origins`). For every object or
83
+ * array inlined in place of a `$ref`, the map records the document and in-file
84
+ * path it was defined at, so a consumer can attribute resolved-tree nodes back
85
+ * to their source without re-walking the `$ref` chain. Defaults to `false`.
86
+ */
87
+ trackOrigins?: boolean
56
88
  }