@amritk/resolve-refs 0.1.2 → 0.2.1
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/dist/get-by-pointer.d.ts +11 -1
- package/dist/get-by-pointer.js +35 -13
- package/dist/index.d.ts +3 -4
- package/dist/index.js +1 -1
- package/dist/is-private-host.d.ts +0 -1
- package/dist/is-private-host.js +84 -21
- package/dist/resolve-refs-from-file.d.ts +0 -1
- package/dist/resolve-refs-from-file.js +67 -12
- package/dist/resolve-refs.d.ts +11 -2
- package/dist/resolve-refs.js +15 -8
- package/dist/types.d.ts +30 -1
- package/package.json +4 -5
- package/dist/get-by-pointer.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/is-private-host.d.ts.map +0 -1
- package/dist/resolve-refs-from-file.d.ts.map +0 -1
- package/dist/resolve-refs.d.ts.map +0 -1
- package/dist/types.d.ts.map +0 -1
- package/src/get-by-pointer.test.ts +0 -42
- package/src/get-by-pointer.ts +0 -30
- package/src/index.ts +0 -5
- package/src/is-private-host.test.ts +0 -36
- package/src/is-private-host.ts +0 -34
- package/src/resolve-refs-from-file.test.ts +0 -125
- package/src/resolve-refs-from-file.ts +0 -232
- package/src/resolve-refs.test.ts +0 -50
- package/src/resolve-refs.ts +0 -49
- package/src/types.ts +0 -56
package/dist/get-by-pointer.d.ts
CHANGED
|
@@ -1,3 +1,14 @@
|
|
|
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, and coerces canonical array-index
|
|
5
|
+
* tokens to numbers so indices and object keys read back the way a path consumer
|
|
6
|
+
* expects. Only RFC 6901 array indices (`0` or a non-zero-leading run of digits)
|
|
7
|
+
* are coerced; a numeric *object* key with a leading zero such as `"01"` is kept
|
|
8
|
+
* as a string, since coercing it would alias to a different key (`obj["01"]` is
|
|
9
|
+
* not `obj[1]`). A bare `''` or `'/'` is the empty path.
|
|
10
|
+
*/
|
|
11
|
+
export declare const pointerToPath: (pointer: string) => JsonPath;
|
|
1
12
|
/**
|
|
2
13
|
* Walks a JSON Pointer string (RFC 6901) to the value it points to within
|
|
3
14
|
* `root`. A bare `''` or `'/'` returns the root document. Segment escapes are
|
|
@@ -5,4 +16,3 @@
|
|
|
5
16
|
* the path is missing or traverses a non-object.
|
|
6
17
|
*/
|
|
7
18
|
export declare const getByPointer: (root: unknown, pointer: string) => unknown;
|
|
8
|
-
//# sourceMappingURL=get-by-pointer.d.ts.map
|
package/dist/get-by-pointer.js
CHANGED
|
@@ -1,3 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Decodes a single JSON Pointer segment (RFC 6901): percent-decodes it, then
|
|
3
|
+
* unescapes `~1` → `/` and `~0` → `~`. Invalid percent-escapes are left as-is.
|
|
4
|
+
*/
|
|
5
|
+
const decodeSegment = (segment) => {
|
|
6
|
+
let decoded = segment;
|
|
7
|
+
try {
|
|
8
|
+
decoded = decodeURIComponent(segment);
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
// leave invalid percent-escapes as-is
|
|
12
|
+
}
|
|
13
|
+
return decoded.replace(/~1/g, '/').replace(/~0/g, '~');
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Parses a JSON Pointer string (RFC 6901) into a path of keys: strips the leading
|
|
17
|
+
* `/`, splits on `/`, decodes each segment, and coerces canonical array-index
|
|
18
|
+
* tokens to numbers so indices and object keys read back the way a path consumer
|
|
19
|
+
* expects. Only RFC 6901 array indices (`0` or a non-zero-leading run of digits)
|
|
20
|
+
* are coerced; a numeric *object* key with a leading zero such as `"01"` is kept
|
|
21
|
+
* as a string, since coercing it would alias to a different key (`obj["01"]` is
|
|
22
|
+
* not `obj[1]`). A bare `''` or `'/'` is the empty path.
|
|
23
|
+
*/
|
|
24
|
+
export const pointerToPath = (pointer) => {
|
|
25
|
+
if (pointer === '' || pointer === '/')
|
|
26
|
+
return [];
|
|
27
|
+
return pointer
|
|
28
|
+
.replace(/^\//, '')
|
|
29
|
+
.split('/')
|
|
30
|
+
.map((segment) => {
|
|
31
|
+
const decoded = decodeSegment(segment);
|
|
32
|
+
return /^(0|[1-9]\d*)$/.test(decoded) ? Number(decoded) : decoded;
|
|
33
|
+
});
|
|
34
|
+
};
|
|
1
35
|
/**
|
|
2
36
|
* Walks a JSON Pointer string (RFC 6901) to the value it points to within
|
|
3
37
|
* `root`. A bare `''` or `'/'` returns the root document. Segment escapes are
|
|
@@ -7,19 +41,7 @@
|
|
|
7
41
|
export const getByPointer = (root, pointer) => {
|
|
8
42
|
if (pointer === '' || pointer === '/')
|
|
9
43
|
return root;
|
|
10
|
-
const segments = 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
|
-
return decoded.replace(/~1/g, '/').replace(/~0/g, '~');
|
|
22
|
-
});
|
|
44
|
+
const segments = pointer.replace(/^\//, '').split('/').map(decodeSegment);
|
|
23
45
|
let current = root;
|
|
24
46
|
for (const segment of segments) {
|
|
25
47
|
if (current === null || typeof current !== 'object')
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
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';
|
|
6
|
-
//# sourceMappingURL=index.d.ts.map
|
|
5
|
+
export type { JsonPath, Origin, OriginMap, ResolveError, ResolveOptions, ResolveResult } from './types.js';
|
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';
|
package/dist/is-private-host.js
CHANGED
|
@@ -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
|
-
|
|
35
|
-
|
|
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
|
};
|
|
@@ -7,4 +7,3 @@ export declare const clearRemoteCache: () => void;
|
|
|
7
7
|
* for the session; `options` governs whether/which remote hosts are allowed.
|
|
8
8
|
*/
|
|
9
9
|
export declare const resolveRefsFromFile: (filename: string, options?: ResolveOptions) => Promise<ResolveResult>;
|
|
10
|
-
//# sourceMappingURL=resolve-refs-from-file.d.ts.map
|
|
@@ -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
|
|
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
|
|
207
|
-
|
|
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
|
};
|
package/dist/resolve-refs.d.ts
CHANGED
|
@@ -1,8 +1,17 @@
|
|
|
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;
|
|
8
|
-
//# sourceMappingURL=resolve-refs.d.ts.map
|
|
17
|
+
export declare const resolveRefs: (data: unknown, options?: ResolveRefsOptions) => ResolveResult;
|
package/dist/resolve-refs.js
CHANGED
|
@@ -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
|
|
44
|
-
|
|
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,11 @@ 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
|
-
//# sourceMappingURL=types.d.ts.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amritk/resolve-refs",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
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",
|
|
@@ -26,8 +26,7 @@
|
|
|
26
26
|
"url": "https://github.com/amritk/mjst/issues"
|
|
27
27
|
},
|
|
28
28
|
"files": [
|
|
29
|
-
"dist"
|
|
30
|
-
"src"
|
|
29
|
+
"dist"
|
|
31
30
|
],
|
|
32
31
|
"publishConfig": {
|
|
33
32
|
"access": "public"
|
|
@@ -35,11 +34,11 @@
|
|
|
35
34
|
"scripts": {
|
|
36
35
|
"build": "tsgo -p tsconfig.build.json && tsc-alias -p tsconfig.build.json -f",
|
|
37
36
|
"types:check": "tsgo -p . --noEmit",
|
|
38
|
-
"test": "NODE_ENV=production vitest run --root ../.. resolve-refs"
|
|
37
|
+
"test": "NODE_ENV=production vitest run --root ../.. resolve-refs",
|
|
38
|
+
"bench": "bun run ./bench/run.ts"
|
|
39
39
|
},
|
|
40
40
|
"exports": {
|
|
41
41
|
".": {
|
|
42
|
-
"development": "./src/index.ts",
|
|
43
42
|
"default": "./dist/index.js",
|
|
44
43
|
"types": "./dist/index.d.ts"
|
|
45
44
|
}
|
|
@@ -1 +0,0 @@
|
|
|
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,OAuB7D,CAAA"}
|
package/dist/index.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
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 +0,0 @@
|
|
|
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 +0,0 @@
|
|
|
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 +0,0 @@
|
|
|
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"}
|
package/dist/types.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
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,42 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'vitest'
|
|
2
|
-
|
|
3
|
-
import { getByPointer } from './get-by-pointer'
|
|
4
|
-
|
|
5
|
-
describe('get-by-pointer', () => {
|
|
6
|
-
const root = {
|
|
7
|
-
info: { title: 'API' },
|
|
8
|
-
paths: [{ get: { id: 1 } }, { post: { id: 2 } }],
|
|
9
|
-
'weird/key': true,
|
|
10
|
-
'tilde~key': false,
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
it('returns the root for an empty or bare-slash pointer', () => {
|
|
14
|
-
expect(getByPointer(root, '')).toBe(root)
|
|
15
|
-
expect(getByPointer(root, '/')).toBe(root)
|
|
16
|
-
})
|
|
17
|
-
|
|
18
|
-
it('navigates object keys', () => {
|
|
19
|
-
expect(getByPointer(root, '/info/title')).toBe('API')
|
|
20
|
-
})
|
|
21
|
-
|
|
22
|
-
it('navigates array indices', () => {
|
|
23
|
-
expect(getByPointer(root, '/paths/1/post/id')).toBe(2)
|
|
24
|
-
})
|
|
25
|
-
|
|
26
|
-
it('decodes ~1 and ~0 escapes', () => {
|
|
27
|
-
expect(getByPointer(root, '/weird~1key')).toBe(true)
|
|
28
|
-
expect(getByPointer(root, '/tilde~0key')).toBe(false)
|
|
29
|
-
})
|
|
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
|
-
|
|
38
|
-
it('returns undefined when a segment is missing', () => {
|
|
39
|
-
expect(getByPointer(root, '/info/nope')).toBeUndefined()
|
|
40
|
-
expect(getByPointer(root, '/info/title/tooDeep')).toBeUndefined()
|
|
41
|
-
})
|
|
42
|
-
})
|
package/src/get-by-pointer.ts
DELETED
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Walks a JSON Pointer string (RFC 6901) to the value it points to within
|
|
3
|
-
* `root`. A bare `''` or `'/'` returns the root document. Segment escapes are
|
|
4
|
-
* decoded (`~1` → `/`, `~0` → `~`). Returns `undefined` when any segment along
|
|
5
|
-
* the path is missing or traverses a non-object.
|
|
6
|
-
*/
|
|
7
|
-
export const getByPointer = (root: unknown, pointer: string): unknown => {
|
|
8
|
-
if (pointer === '' || pointer === '/') return root
|
|
9
|
-
|
|
10
|
-
const segments = pointer
|
|
11
|
-
.replace(/^\//, '')
|
|
12
|
-
.split('/')
|
|
13
|
-
.map((segment) => {
|
|
14
|
-
let decoded = segment
|
|
15
|
-
try {
|
|
16
|
-
decoded = decodeURIComponent(segment)
|
|
17
|
-
} catch {
|
|
18
|
-
// leave invalid percent-escapes as-is
|
|
19
|
-
}
|
|
20
|
-
return decoded.replace(/~1/g, '/').replace(/~0/g, '~')
|
|
21
|
-
})
|
|
22
|
-
|
|
23
|
-
let current: unknown = root
|
|
24
|
-
for (const segment of segments) {
|
|
25
|
-
if (current === null || typeof current !== 'object') return undefined
|
|
26
|
-
const key = Array.isArray(current) ? Number(segment) : segment
|
|
27
|
-
current = (current as Record<string, unknown>)[key]
|
|
28
|
-
}
|
|
29
|
-
return current
|
|
30
|
-
}
|
package/src/index.ts
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
export { getByPointer } from './get-by-pointer'
|
|
2
|
-
export { isPrivateHost } from './is-private-host'
|
|
3
|
-
export { resolveRefs } from './resolve-refs'
|
|
4
|
-
export { clearRemoteCache, resolveRefsFromFile } from './resolve-refs-from-file'
|
|
5
|
-
export type { JsonPath, ResolveError, ResolveOptions, ResolveResult } from './types'
|
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'vitest'
|
|
2
|
-
|
|
3
|
-
import { isPrivateHost } from './is-private-host'
|
|
4
|
-
|
|
5
|
-
describe('is-private-host', () => {
|
|
6
|
-
it('treats localhost and its subdomains as private', () => {
|
|
7
|
-
expect(isPrivateHost('localhost')).toBe(true)
|
|
8
|
-
expect(isPrivateHost('api.localhost')).toBe(true)
|
|
9
|
-
})
|
|
10
|
-
|
|
11
|
-
it('flags loopback and RFC 1918 / CGNAT IPv4 ranges', () => {
|
|
12
|
-
expect(isPrivateHost('127.0.0.1')).toBe(true)
|
|
13
|
-
expect(isPrivateHost('10.1.2.3')).toBe(true)
|
|
14
|
-
expect(isPrivateHost('172.16.0.1')).toBe(true)
|
|
15
|
-
expect(isPrivateHost('172.31.255.255')).toBe(true)
|
|
16
|
-
expect(isPrivateHost('192.168.0.1')).toBe(true)
|
|
17
|
-
expect(isPrivateHost('100.64.0.1')).toBe(true)
|
|
18
|
-
})
|
|
19
|
-
|
|
20
|
-
it('flags the cloud-metadata link-local endpoint', () => {
|
|
21
|
-
expect(isPrivateHost('169.254.169.254')).toBe(true)
|
|
22
|
-
})
|
|
23
|
-
|
|
24
|
-
it('flags private IPv6 (loopback, link-local, unique-local)', () => {
|
|
25
|
-
expect(isPrivateHost('::1')).toBe(true)
|
|
26
|
-
expect(isPrivateHost('[::1]')).toBe(true)
|
|
27
|
-
expect(isPrivateHost('fe80::1')).toBe(true)
|
|
28
|
-
expect(isPrivateHost('fd00::1')).toBe(true)
|
|
29
|
-
})
|
|
30
|
-
|
|
31
|
-
it('allows public hosts', () => {
|
|
32
|
-
expect(isPrivateHost('example.com')).toBe(false)
|
|
33
|
-
expect(isPrivateHost('8.8.8.8')).toBe(false)
|
|
34
|
-
expect(isPrivateHost('172.32.0.1')).toBe(false)
|
|
35
|
-
})
|
|
36
|
-
})
|
package/src/is-private-host.ts
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Best-effort check for a hostname that resolves to a non-public address —
|
|
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.
|
|
8
|
-
*/
|
|
9
|
-
export const isPrivateHost = (hostname: string): boolean => {
|
|
10
|
-
const host = hostname.replace(/^\[|\]$/g, '').toLowerCase()
|
|
11
|
-
if (host === 'localhost' || host.endsWith('.localhost')) return true
|
|
12
|
-
|
|
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
|
-
if (host.includes(':')) {
|
|
28
|
-
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
|
|
31
|
-
return false
|
|
32
|
-
}
|
|
33
|
-
return false
|
|
34
|
-
}
|
|
@@ -1,125 +0,0 @@
|
|
|
1
|
-
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
|
2
|
-
import { tmpdir } from 'node:os'
|
|
3
|
-
import { join } from 'node:path'
|
|
4
|
-
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
5
|
-
|
|
6
|
-
import { clearRemoteCache, resolveRefsFromFile } from './resolve-refs-from-file'
|
|
7
|
-
|
|
8
|
-
describe('resolve-refs-from-file', () => {
|
|
9
|
-
let dir: string
|
|
10
|
-
|
|
11
|
-
beforeEach(() => {
|
|
12
|
-
dir = mkdtempSync(join(tmpdir(), 'resolve-refs-'))
|
|
13
|
-
clearRemoteCache()
|
|
14
|
-
})
|
|
15
|
-
|
|
16
|
-
afterEach(() => {
|
|
17
|
-
rmSync(dir, { recursive: true, force: true })
|
|
18
|
-
vi.restoreAllMocks()
|
|
19
|
-
})
|
|
20
|
-
|
|
21
|
-
it('inlines a cross-file $ref between local documents', async () => {
|
|
22
|
-
writeFileSync(
|
|
23
|
-
join(dir, 'pet.json'),
|
|
24
|
-
JSON.stringify({ Pet: { type: 'object', properties: { name: { type: 'string' } } } }),
|
|
25
|
-
)
|
|
26
|
-
writeFileSync(
|
|
27
|
-
join(dir, 'api.json'),
|
|
28
|
-
JSON.stringify({ components: { schemas: { Pet: { $ref: './pet.json#/Pet' } } } }),
|
|
29
|
-
)
|
|
30
|
-
|
|
31
|
-
const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'))
|
|
32
|
-
|
|
33
|
-
expect(errors).toEqual([])
|
|
34
|
-
expect(resolved).toMatchObject({
|
|
35
|
-
components: { schemas: { Pet: { type: 'object', properties: { name: { type: 'string' } } } } },
|
|
36
|
-
})
|
|
37
|
-
})
|
|
38
|
-
|
|
39
|
-
it('inlines an internal $ref within a single document', async () => {
|
|
40
|
-
writeFileSync(join(dir, 'root.json'), JSON.stringify({ a: { $ref: '#/b' }, b: { value: 1 } }))
|
|
41
|
-
|
|
42
|
-
const { resolved } = await resolveRefsFromFile(join(dir, 'root.json'))
|
|
43
|
-
|
|
44
|
-
expect(resolved).toMatchObject({ a: { value: 1 }, b: { value: 1 } })
|
|
45
|
-
})
|
|
46
|
-
|
|
47
|
-
it('records an error and degrades to {} when a referenced file is missing', async () => {
|
|
48
|
-
writeFileSync(join(dir, 'api.json'), JSON.stringify({ x: { $ref: './missing.json#/Nope' } }))
|
|
49
|
-
|
|
50
|
-
const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'))
|
|
51
|
-
|
|
52
|
-
// The missing document degrades to {}, so the pointer into it misses and the
|
|
53
|
-
// ref resolves to undefined — the important part is that we recorded the
|
|
54
|
-
// failure instead of throwing.
|
|
55
|
-
expect((resolved as { x: unknown }).x).toBeUndefined()
|
|
56
|
-
expect(errors.length).toBeGreaterThan(0)
|
|
57
|
-
})
|
|
58
|
-
|
|
59
|
-
it('refuses a remote $ref to a private host by default (SSRF guard)', async () => {
|
|
60
|
-
const fetchSpy = vi.spyOn(globalThis, 'fetch')
|
|
61
|
-
writeFileSync(
|
|
62
|
-
join(dir, 'api.json'),
|
|
63
|
-
JSON.stringify({ x: { $ref: 'http://169.254.169.254/latest/meta-data#/foo' } }),
|
|
64
|
-
)
|
|
65
|
-
|
|
66
|
-
const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'))
|
|
67
|
-
|
|
68
|
-
// The refused document degrades to {}, so the pointer into it misses.
|
|
69
|
-
expect((resolved as { x: unknown }).x).toBeUndefined()
|
|
70
|
-
expect(errors[0]?.message).toMatch(/Refusing to resolve remote \$ref/)
|
|
71
|
-
// The guard is syntactic — we never even attempt the request.
|
|
72
|
-
expect(fetchSpy).not.toHaveBeenCalled()
|
|
73
|
-
})
|
|
74
|
-
|
|
75
|
-
it('refuses any remote $ref when remote resolution is disabled', async () => {
|
|
76
|
-
const fetchSpy = vi.spyOn(globalThis, 'fetch')
|
|
77
|
-
writeFileSync(join(dir, 'api.json'), JSON.stringify({ x: { $ref: 'https://example.com/s.json#/Foo' } }))
|
|
78
|
-
|
|
79
|
-
const { errors } = await resolveRefsFromFile(join(dir, 'api.json'), { remote: false })
|
|
80
|
-
|
|
81
|
-
expect(errors[0]?.message).toMatch(/remote \$ref resolution is disabled/)
|
|
82
|
-
expect(fetchSpy).not.toHaveBeenCalled()
|
|
83
|
-
})
|
|
84
|
-
|
|
85
|
-
it('uses a custom parse callback to load non-JSON (e.g. YAML) documents', async () => {
|
|
86
|
-
// Real YAML that JSON.parse would reject — a custom callback handles it.
|
|
87
|
-
writeFileSync(join(dir, 'contact.yaml'), 'type: object\nproperties:\n name:\n type: string\n')
|
|
88
|
-
writeFileSync(join(dir, 'api.json'), JSON.stringify({ contact: { $ref: './contact.yaml' } }))
|
|
89
|
-
|
|
90
|
-
const parse = (content: string, location: string): unknown => {
|
|
91
|
-
if (/\.ya?ml$/i.test(location)) return { type: 'object', properties: { name: { type: 'string' } } }
|
|
92
|
-
return JSON.parse(content) as unknown
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'), { parse })
|
|
96
|
-
|
|
97
|
-
expect(errors).toEqual([])
|
|
98
|
-
expect(resolved).toMatchObject({ contact: { type: 'object', properties: { name: { type: 'string' } } } })
|
|
99
|
-
})
|
|
100
|
-
|
|
101
|
-
it('fetches an allow-listed remote $ref and caches it for the session', async () => {
|
|
102
|
-
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
|
103
|
-
new Response(JSON.stringify({ Foo: { type: 'string' } }), {
|
|
104
|
-
status: 200,
|
|
105
|
-
headers: { 'content-type': 'application/json' },
|
|
106
|
-
}),
|
|
107
|
-
)
|
|
108
|
-
writeFileSync(
|
|
109
|
-
join(dir, 'api.json'),
|
|
110
|
-
JSON.stringify({
|
|
111
|
-
a: { $ref: 'https://api.example.com/s.json#/Foo' },
|
|
112
|
-
b: { $ref: 'https://api.example.com/s.json#/Foo' },
|
|
113
|
-
}),
|
|
114
|
-
)
|
|
115
|
-
|
|
116
|
-
const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'), {
|
|
117
|
-
allowedHosts: ['api.example.com'],
|
|
118
|
-
})
|
|
119
|
-
|
|
120
|
-
expect(errors).toEqual([])
|
|
121
|
-
expect(resolved).toMatchObject({ a: { type: 'string' }, b: { type: 'string' } })
|
|
122
|
-
// Both refs hit the same document, which is fetched and cached exactly once.
|
|
123
|
-
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
|
124
|
-
})
|
|
125
|
-
})
|
|
@@ -1,232 +0,0 @@
|
|
|
1
|
-
import { readFileSync } from 'node:fs'
|
|
2
|
-
import { dirname, resolve as resolvePath } from 'node:path'
|
|
3
|
-
|
|
4
|
-
import { getByPointer } from './get-by-pointer'
|
|
5
|
-
import { isPrivateHost } from './is-private-host'
|
|
6
|
-
import type { ResolveError, ResolveOptions, ResolveResult } from './types'
|
|
7
|
-
|
|
8
|
-
// A ref currently mid-resolution is marked with this sentinel; revisiting it
|
|
9
|
-
// means a cycle, so we return `{}` instead of recursing forever.
|
|
10
|
-
const CYCLE = Symbol('cycle')
|
|
11
|
-
type CacheValue = unknown | typeof CYCLE
|
|
12
|
-
|
|
13
|
-
// --- Document location helpers ---------------------------------------------
|
|
14
|
-
//
|
|
15
|
-
// A "location" is the absolute identity of a document: either an absolute file
|
|
16
|
-
// path or an absolute http(s) URL. Refs are resolved relative to the location
|
|
17
|
-
// of the document they appear in, so a relative ref inside a remote document
|
|
18
|
-
// resolves to another remote URL, and one inside a local file to another path.
|
|
19
|
-
|
|
20
|
-
const isRemote = (location: string): boolean => /^https?:\/\//i.test(location)
|
|
21
|
-
|
|
22
|
-
/** Resolves the location of `ref` (its file/URL part) relative to `base`. */
|
|
23
|
-
const joinLocation = (base: string, ref: string): string => {
|
|
24
|
-
if (isRemote(ref)) return ref
|
|
25
|
-
if (isRemote(base)) return new URL(ref, base).href
|
|
26
|
-
return resolvePath(dirname(base), ref)
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
/** Splits a `$ref` into its document part and JSON-pointer part. */
|
|
30
|
-
const splitRef = (ref: string): { filePart: string; pointer: string } => {
|
|
31
|
-
const hashIdx = ref.indexOf('#')
|
|
32
|
-
return {
|
|
33
|
-
filePart: hashIdx === -1 ? ref : ref.slice(0, hashIdx),
|
|
34
|
-
pointer: hashIdx === -1 ? '' : ref.slice(hashIdx + 1),
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
// --- Remote document cache -------------------------------------------------
|
|
39
|
-
//
|
|
40
|
-
// Fetched remote documents are cached in memory for the lifetime of the
|
|
41
|
-
// process ("the session"). Local files are intentionally NOT cached across
|
|
42
|
-
// resolve passes — they can change on disk during a long-lived session (e.g.
|
|
43
|
-
// an editor/LSP), so each pass re-reads them. Remote documents are assumed
|
|
44
|
-
// stable for the session; call `clearRemoteCache()` to drop them.
|
|
45
|
-
|
|
46
|
-
const remoteCache = new Map<string, unknown>()
|
|
47
|
-
|
|
48
|
-
/** Drops every cached remote document. Mainly useful for tests/long sessions. */
|
|
49
|
-
export const clearRemoteCache = (): void => {
|
|
50
|
-
remoteCache.clear()
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
/** Returns why a remote location may not be fetched, or `null` if it is allowed. */
|
|
54
|
-
const denialReason = (location: string, options: ResolveOptions): string | null => {
|
|
55
|
-
if (options.remote === false) return 'remote $ref resolution is disabled'
|
|
56
|
-
|
|
57
|
-
let url: URL
|
|
58
|
-
try {
|
|
59
|
-
url = new URL(location)
|
|
60
|
-
} catch {
|
|
61
|
-
return 'the URL is invalid'
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
const allow = options.allowedHosts
|
|
65
|
-
// An explicit allow-list entry is an intentional opt-in and bypasses the
|
|
66
|
-
// private-host guard; otherwise refuse non-public targets by default.
|
|
67
|
-
if (allow && allow.length > 0) {
|
|
68
|
-
return allow.includes(url.host) ? null : 'host is not in the allow-list'
|
|
69
|
-
}
|
|
70
|
-
if (!options.allowPrivateHosts && isPrivateHost(url.hostname)) {
|
|
71
|
-
return 'host resolves to a private or loopback address (set allowPrivateHosts to permit)'
|
|
72
|
-
}
|
|
73
|
-
return null
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
/**
|
|
77
|
-
* Loads a document into `docCache`, fetching/reading it if needed. Remote
|
|
78
|
-
* documents are additionally cached for the session in `remoteCache`. On
|
|
79
|
-
* failure an error is recorded and the location is cached as `{}` so that
|
|
80
|
-
* pointer lookups degrade gracefully instead of throwing. Returns whether the
|
|
81
|
-
* document loaded successfully.
|
|
82
|
-
*/
|
|
83
|
-
const loadDoc = async (
|
|
84
|
-
location: string,
|
|
85
|
-
docCache: Map<string, unknown>,
|
|
86
|
-
options: ResolveOptions,
|
|
87
|
-
errors: ResolveError[],
|
|
88
|
-
): Promise<boolean> => {
|
|
89
|
-
if (docCache.has(location)) return true
|
|
90
|
-
|
|
91
|
-
if (isRemote(location)) {
|
|
92
|
-
if (remoteCache.has(location)) {
|
|
93
|
-
docCache.set(location, remoteCache.get(location))
|
|
94
|
-
return true
|
|
95
|
-
}
|
|
96
|
-
const reason = denialReason(location, options)
|
|
97
|
-
if (reason !== null) {
|
|
98
|
-
errors.push({ message: `Refusing to resolve remote $ref (${reason}): ${location}`, path: [] })
|
|
99
|
-
docCache.set(location, {})
|
|
100
|
-
return false
|
|
101
|
-
}
|
|
102
|
-
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)
|
|
107
|
-
remoteCache.set(location, doc)
|
|
108
|
-
docCache.set(location, doc)
|
|
109
|
-
return true
|
|
110
|
-
} catch (err) {
|
|
111
|
-
errors.push({ message: `Failed to fetch ${location}: ${String(err)}`, path: [] })
|
|
112
|
-
docCache.set(location, {})
|
|
113
|
-
return false
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
try {
|
|
118
|
-
const parse = options.parse ?? ((c: string) => JSON.parse(c) as unknown)
|
|
119
|
-
docCache.set(location, parse(readFileSync(location, 'utf8'), location))
|
|
120
|
-
return true
|
|
121
|
-
} catch (err) {
|
|
122
|
-
errors.push({ message: String(err), path: [] })
|
|
123
|
-
docCache.set(location, {})
|
|
124
|
-
return false
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
/** Collects the distinct document parts of every `$ref` directly under `node`. */
|
|
129
|
-
const collectRefTargets = (node: unknown, out: Set<string>): Set<string> => {
|
|
130
|
-
if (node === null || typeof node !== 'object') return out
|
|
131
|
-
if (Array.isArray(node)) {
|
|
132
|
-
for (const item of node) collectRefTargets(item, out)
|
|
133
|
-
return out
|
|
134
|
-
}
|
|
135
|
-
const obj = node as Record<string, unknown>
|
|
136
|
-
if (typeof obj['$ref'] === 'string') {
|
|
137
|
-
// A `$ref` object's siblings are ignored on resolution, so we do not recurse
|
|
138
|
-
// into them — mirroring resolveAt's behaviour.
|
|
139
|
-
const { filePart } = splitRef(obj['$ref'])
|
|
140
|
-
if (filePart !== '') out.add(filePart)
|
|
141
|
-
return out
|
|
142
|
-
}
|
|
143
|
-
for (const key of Object.keys(obj)) collectRefTargets(obj[key], out)
|
|
144
|
-
return out
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
/**
|
|
148
|
-
* Walks every reachable document starting from `rootLocation`, loading each one
|
|
149
|
-
* so the synchronous resolve pass can look them up. This is the only async part
|
|
150
|
-
* of resolution: remote documents are fetched here (in dependency order) and
|
|
151
|
-
* cached for the session.
|
|
152
|
-
*/
|
|
153
|
-
const prefetch = async (
|
|
154
|
-
rootLocation: string,
|
|
155
|
-
docCache: Map<string, unknown>,
|
|
156
|
-
options: ResolveOptions,
|
|
157
|
-
errors: ResolveError[],
|
|
158
|
-
): Promise<void> => {
|
|
159
|
-
const seen = new Set<string>([rootLocation])
|
|
160
|
-
const queue: string[] = [rootLocation]
|
|
161
|
-
while (queue.length > 0) {
|
|
162
|
-
const location = queue.shift() as string
|
|
163
|
-
for (const filePart of collectRefTargets(docCache.get(location), new Set())) {
|
|
164
|
-
const target = joinLocation(location, filePart)
|
|
165
|
-
if (seen.has(target)) continue
|
|
166
|
-
seen.add(target)
|
|
167
|
-
await loadDoc(target, docCache, options, errors)
|
|
168
|
-
queue.push(target)
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
/**
|
|
174
|
-
* Single-pass resolver that inlines internal and external (`$ref` to other
|
|
175
|
-
* file/URL) references. Every reachable document has already been loaded into
|
|
176
|
-
* `docCache` by `prefetch`, so this stays synchronous. Refs are resolved once
|
|
177
|
-
* (`refCache`); the CYCLE sentinel short-circuits re-entrant resolution.
|
|
178
|
-
*
|
|
179
|
-
* `baseLocation` is the location of the document `node` belongs to, used to
|
|
180
|
-
* resolve relative refs and `#/...` pointers within it.
|
|
181
|
-
*/
|
|
182
|
-
const resolveAt = (
|
|
183
|
-
node: unknown,
|
|
184
|
-
baseLocation: string,
|
|
185
|
-
docCache: Map<string, unknown>,
|
|
186
|
-
refCache: Map<string, CacheValue>,
|
|
187
|
-
): unknown => {
|
|
188
|
-
if (node === null || typeof node !== 'object') return node
|
|
189
|
-
if (Array.isArray(node)) {
|
|
190
|
-
return node.map((item) => resolveAt(item, baseLocation, docCache, refCache))
|
|
191
|
-
}
|
|
192
|
-
const obj = node as Record<string, unknown>
|
|
193
|
-
if (typeof obj['$ref'] === 'string') {
|
|
194
|
-
const { filePart, pointer } = splitRef(obj['$ref'])
|
|
195
|
-
const targetLocation = filePart === '' ? baseLocation : joinLocation(baseLocation, filePart)
|
|
196
|
-
const targetRoot = docCache.get(targetLocation) ?? {}
|
|
197
|
-
|
|
198
|
-
const cacheKey = `${targetLocation}#${pointer}`
|
|
199
|
-
if (refCache.has(cacheKey)) {
|
|
200
|
-
const cached = refCache.get(cacheKey)
|
|
201
|
-
return cached === CYCLE ? {} : cached
|
|
202
|
-
}
|
|
203
|
-
refCache.set(cacheKey, CYCLE)
|
|
204
|
-
const target = pointer ? getByPointer(targetRoot, pointer) : targetRoot
|
|
205
|
-
const resolved = resolveAt(target, targetLocation, docCache, refCache)
|
|
206
|
-
refCache.set(cacheKey, resolved)
|
|
207
|
-
return resolved
|
|
208
|
-
}
|
|
209
|
-
const result: Record<string, unknown> = {}
|
|
210
|
-
for (const key of Object.keys(obj)) {
|
|
211
|
-
result[key] = resolveAt(obj[key], baseLocation, docCache, refCache)
|
|
212
|
-
}
|
|
213
|
-
return result
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
/**
|
|
217
|
-
* Resolves `$ref`s in a document on disk (or at a URL), including cross-file
|
|
218
|
-
* and remote refs. Remote documents are fetched on the fly and cached in memory
|
|
219
|
-
* for the session; `options` governs whether/which remote hosts are allowed.
|
|
220
|
-
*/
|
|
221
|
-
export const resolveRefsFromFile = async (filename: string, options: ResolveOptions = {}): Promise<ResolveResult> => {
|
|
222
|
-
const rootLocation = isRemote(filename) ? filename : resolvePath(filename)
|
|
223
|
-
const errors: ResolveError[] = []
|
|
224
|
-
const docCache = new Map<string, unknown>()
|
|
225
|
-
|
|
226
|
-
if (!(await loadDoc(rootLocation, docCache, options, errors))) {
|
|
227
|
-
return { resolved: {}, errors }
|
|
228
|
-
}
|
|
229
|
-
await prefetch(rootLocation, docCache, options, errors)
|
|
230
|
-
const resolved = resolveAt(docCache.get(rootLocation), rootLocation, docCache, new Map())
|
|
231
|
-
return { resolved, errors }
|
|
232
|
-
}
|
package/src/resolve-refs.test.ts
DELETED
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'vitest'
|
|
2
|
-
|
|
3
|
-
import { resolveRefs } from './resolve-refs'
|
|
4
|
-
|
|
5
|
-
describe('resolve-refs', () => {
|
|
6
|
-
it('inlines an internal $ref', () => {
|
|
7
|
-
const { resolved, errors } = resolveRefs({
|
|
8
|
-
type: 'object',
|
|
9
|
-
properties: { contact: { $ref: '#/$defs/contact' } },
|
|
10
|
-
$defs: { contact: { type: 'string' } },
|
|
11
|
-
})
|
|
12
|
-
|
|
13
|
-
expect(errors).toEqual([])
|
|
14
|
-
expect(resolved).toMatchObject({ properties: { contact: { type: 'string' } } })
|
|
15
|
-
})
|
|
16
|
-
|
|
17
|
-
it('breaks a self-referential cycle with an empty object', () => {
|
|
18
|
-
const { resolved } = resolveRefs({
|
|
19
|
-
$defs: { node: { type: 'object', properties: { next: { $ref: '#/$defs/node' } } } },
|
|
20
|
-
properties: { head: { $ref: '#/$defs/node' } },
|
|
21
|
-
})
|
|
22
|
-
|
|
23
|
-
const head = (resolved as { properties: { head: { properties: { next: unknown } } } }).properties.head
|
|
24
|
-
// The first level resolves; the recursive self-reference terminates at `{}`.
|
|
25
|
-
expect(head.properties.next).toEqual({})
|
|
26
|
-
})
|
|
27
|
-
|
|
28
|
-
it('breaks a mutual cycle (A → B → A) without infinite recursion', () => {
|
|
29
|
-
const { resolved } = resolveRefs({
|
|
30
|
-
$defs: {
|
|
31
|
-
a: { type: 'object', properties: { b: { $ref: '#/$defs/b' } } },
|
|
32
|
-
b: { type: 'object', properties: { a: { $ref: '#/$defs/a' } } },
|
|
33
|
-
},
|
|
34
|
-
properties: { root: { $ref: '#/$defs/a' } },
|
|
35
|
-
})
|
|
36
|
-
|
|
37
|
-
// Resolution terminates; `a` is in the cache by the time `properties.root` is
|
|
38
|
-
// processed, so we get the partially-resolved shape where the back-reference
|
|
39
|
-
// leg terminated at `{}` rather than looping forever.
|
|
40
|
-
const root = (resolved as { properties: { root: { type: string; properties: { b: unknown } } } }).properties.root
|
|
41
|
-
expect(root.type).toBe('object')
|
|
42
|
-
expect(root.properties.b).toEqual({})
|
|
43
|
-
})
|
|
44
|
-
|
|
45
|
-
it('leaves external (non-#) refs untouched', () => {
|
|
46
|
-
const { resolved } = resolveRefs({ properties: { pet: { $ref: 'pet.json#/Pet' } } })
|
|
47
|
-
|
|
48
|
-
expect(resolved).toEqual({ properties: { pet: { $ref: 'pet.json#/Pet' } } })
|
|
49
|
-
})
|
|
50
|
-
})
|
package/src/resolve-refs.ts
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import { getByPointer } from './get-by-pointer'
|
|
2
|
-
import type { ResolveResult } from './types'
|
|
3
|
-
|
|
4
|
-
// A ref currently mid-resolution is marked with this sentinel; revisiting it
|
|
5
|
-
// means we have looped, so we return `{}` instead of recursing forever.
|
|
6
|
-
const CYCLE = Symbol('cycle')
|
|
7
|
-
type CacheValue = unknown | typeof CYCLE
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* Single-pass internal-only `$ref` resolver. Each unique ref string is resolved
|
|
11
|
-
* exactly once (the `cache`); revisiting a ref that is still mid-resolution
|
|
12
|
-
* means a cycle, so we return `{}` (the CYCLE sentinel). Non-`#` refs (external
|
|
13
|
-
* files, HTTP) are left untouched — callers that need those should use
|
|
14
|
-
* `resolveRefsFromFile`.
|
|
15
|
-
*/
|
|
16
|
-
const resolveInternal = (node: unknown, root: unknown, cache: Map<string, CacheValue>): unknown => {
|
|
17
|
-
if (node === null || typeof node !== 'object') return node
|
|
18
|
-
if (Array.isArray(node)) return node.map((item) => resolveInternal(item, root, cache))
|
|
19
|
-
|
|
20
|
-
const obj = node as Record<string, unknown>
|
|
21
|
-
if (typeof obj['$ref'] === 'string') {
|
|
22
|
-
const ref = obj['$ref']
|
|
23
|
-
if (!ref.startsWith('#')) return obj // external ref — leave as-is
|
|
24
|
-
if (cache.has(ref)) {
|
|
25
|
-
const cached = cache.get(ref)
|
|
26
|
-
return cached === CYCLE ? {} : cached
|
|
27
|
-
}
|
|
28
|
-
cache.set(ref, CYCLE)
|
|
29
|
-
const resolved = resolveInternal(getByPointer(root, ref.slice(1)), root, cache)
|
|
30
|
-
cache.set(ref, resolved)
|
|
31
|
-
return resolved
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
const result: Record<string, unknown> = {}
|
|
35
|
-
for (const key of Object.keys(obj)) {
|
|
36
|
-
result[key] = resolveInternal(obj[key], root, cache)
|
|
37
|
-
}
|
|
38
|
-
return result
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
/**
|
|
42
|
-
* Resolves all internal (`#/...`) `$ref`s in an in-memory document, inlining
|
|
43
|
-
* each target. External and remote refs are left as-is. Cycles are broken with
|
|
44
|
-
* an empty object so the result is always finite.
|
|
45
|
-
*/
|
|
46
|
-
export const resolveRefs = (data: unknown): ResolveResult => {
|
|
47
|
-
const resolved = resolveInternal(data, data, new Map())
|
|
48
|
-
return { resolved, errors: [] }
|
|
49
|
-
}
|
package/src/types.ts
DELETED
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* A path into a JSON document: object keys and array indices, in order. Errors
|
|
3
|
-
* report the location of the offending `$ref` with one of these.
|
|
4
|
-
*/
|
|
5
|
-
export type JsonPath = (string | number)[]
|
|
6
|
-
|
|
7
|
-
/** A single `$ref` resolution failure (a missing file, a bad URL, a refusal). */
|
|
8
|
-
export type ResolveError = {
|
|
9
|
-
message: string
|
|
10
|
-
path: JsonPath
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
/** The outcome of a resolve pass: the dereferenced document plus any errors. */
|
|
14
|
-
export type ResolveResult = {
|
|
15
|
-
/** The dereferenced document (all resolvable `$ref`s inlined). */
|
|
16
|
-
resolved: unknown
|
|
17
|
-
errors: ResolveError[]
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
/** Controls how external `$ref`s to other documents are loaded. */
|
|
21
|
-
export type ResolveOptions = {
|
|
22
|
-
/**
|
|
23
|
-
* Whether http(s) `$ref`s may be fetched. Defaults to `true`.
|
|
24
|
-
*/
|
|
25
|
-
remote?: boolean
|
|
26
|
-
/**
|
|
27
|
-
* If non-empty, only these hosts (e.g. `api.example.com`) may be fetched for
|
|
28
|
-
* remote `$ref`s. An empty/undefined list allows any host (subject to
|
|
29
|
-
* `remote`). An explicit entry here always bypasses the private-host guard.
|
|
30
|
-
*/
|
|
31
|
-
allowedHosts?: string[]
|
|
32
|
-
/**
|
|
33
|
-
* Allow remote `$ref`s to loopback, private, link-local, and other
|
|
34
|
-
* non-public addresses. Defaults to `false`: such hosts are refused as a
|
|
35
|
-
* best-effort SSRF guard (notably the `169.254.169.254` cloud-metadata
|
|
36
|
-
* endpoint). An explicit `allowedHosts` entry always bypasses this guard.
|
|
37
|
-
*/
|
|
38
|
-
allowPrivateHosts?: boolean
|
|
39
|
-
/**
|
|
40
|
-
* Custom content parser. Receives the raw text of every loaded document and
|
|
41
|
-
* its absolute location (file path or URL). Defaults to `JSON.parse`.
|
|
42
|
-
*
|
|
43
|
-
* Pass a YAML-aware function to support `.yaml`/`.yml` documents without
|
|
44
|
-
* adding a dependency to this package:
|
|
45
|
-
*
|
|
46
|
-
* ```ts
|
|
47
|
-
* import { parse as parseYaml } from 'yaml'
|
|
48
|
-
*
|
|
49
|
-
* resolveRefsFromFile(path, {
|
|
50
|
-
* parse: (content, location) =>
|
|
51
|
-
* /\.ya?ml$/i.test(location) ? parseYaml(content) : JSON.parse(content),
|
|
52
|
-
* })
|
|
53
|
-
* ```
|
|
54
|
-
*/
|
|
55
|
-
parse?: (content: string, location: string) => unknown
|
|
56
|
-
}
|