@amritk/resolve-refs 0.2.2 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/resolve-refs-from-file.js +43 -4
- package/dist/resolve-refs.js +18 -7
- package/dist/safe-assign.d.ts +8 -0
- package/dist/safe-assign.js +15 -0
- package/package.json +1 -1
|
@@ -2,6 +2,7 @@ import { readFileSync } from 'node:fs';
|
|
|
2
2
|
import { dirname, resolve as resolvePath } from 'node:path';
|
|
3
3
|
import { getByPointer, pointerToPath } from './get-by-pointer.js';
|
|
4
4
|
import { isPrivateHost } from './is-private-host.js';
|
|
5
|
+
import { assignKey } from './safe-assign.js';
|
|
5
6
|
// A ref currently mid-resolution is marked with this sentinel; revisiting it
|
|
6
7
|
// means a cycle, so we return `{}` instead of recursing forever.
|
|
7
8
|
const CYCLE = Symbol('cycle');
|
|
@@ -47,6 +48,34 @@ export const clearRemoteCache = () => {
|
|
|
47
48
|
// Cap on redirect hops before we give up — generous enough for real services,
|
|
48
49
|
// low enough to stop a redirect loop from spinning forever.
|
|
49
50
|
const MAX_REDIRECTS = 5;
|
|
51
|
+
/** Abort a remote fetch that has not responded within this many milliseconds. */
|
|
52
|
+
const FETCH_TIMEOUT_MS = 30_000;
|
|
53
|
+
/** Refuse to buffer a remote document larger than this (bytes) to bound memory. */
|
|
54
|
+
const MAX_REMOTE_BYTES = 16 * 1024 * 1024;
|
|
55
|
+
/**
|
|
56
|
+
* Reads a response body, refusing to buffer more than {@link MAX_REMOTE_BYTES}.
|
|
57
|
+
* A `Content-Length` over the limit is rejected up front; a missing/lying header
|
|
58
|
+
* is caught while streaming so a chunked response can't exhaust memory either.
|
|
59
|
+
*/
|
|
60
|
+
const readCapped = async (response) => {
|
|
61
|
+
const declared = Number(response.headers.get('content-length'));
|
|
62
|
+
if (Number.isFinite(declared) && declared > MAX_REMOTE_BYTES) {
|
|
63
|
+
throw new Error(`remote document exceeds ${MAX_REMOTE_BYTES} bytes`);
|
|
64
|
+
}
|
|
65
|
+
const body = response.body;
|
|
66
|
+
if (!body)
|
|
67
|
+
return response.text();
|
|
68
|
+
const decoder = new TextDecoder();
|
|
69
|
+
let text = '';
|
|
70
|
+
let total = 0;
|
|
71
|
+
for await (const chunk of body) {
|
|
72
|
+
total += chunk.byteLength;
|
|
73
|
+
if (total > MAX_REMOTE_BYTES)
|
|
74
|
+
throw new Error(`remote document exceeds ${MAX_REMOTE_BYTES} bytes`);
|
|
75
|
+
text += decoder.decode(chunk, { stream: true });
|
|
76
|
+
}
|
|
77
|
+
return text + decoder.decode();
|
|
78
|
+
};
|
|
50
79
|
/**
|
|
51
80
|
* Fetches and parses a remote document, following redirects manually so the
|
|
52
81
|
* SSRF guard is re-applied to every hop. `fetch` follows redirects by default,
|
|
@@ -60,7 +89,11 @@ const fetchRemote = async (location, options) => {
|
|
|
60
89
|
const reason = denialReason(current, options);
|
|
61
90
|
if (reason !== null)
|
|
62
91
|
throw new Error(`refusing to follow redirect (${reason}): ${current}`);
|
|
63
|
-
const response = await fetch(current, {
|
|
92
|
+
const response = await fetch(current, {
|
|
93
|
+
redirect: 'manual',
|
|
94
|
+
// Cap the wait for a response so a stalling host can't hang resolution forever.
|
|
95
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
96
|
+
});
|
|
64
97
|
if (response.status >= 300 && response.status < 400) {
|
|
65
98
|
const next = response.headers.get('location');
|
|
66
99
|
if (!next)
|
|
@@ -73,7 +106,7 @@ const fetchRemote = async (location, options) => {
|
|
|
73
106
|
const parse = options.parse ?? ((c) => JSON.parse(c));
|
|
74
107
|
// Parse against the original request location so the caller's format sniffing
|
|
75
108
|
// (e.g. `.yaml` vs `.json`) and any relative refs key off a stable identity.
|
|
76
|
-
return parse(await response
|
|
109
|
+
return parse(await readCapped(response), location);
|
|
77
110
|
}
|
|
78
111
|
throw new Error(`too many redirects (>${MAX_REDIRECTS}): ${location}`);
|
|
79
112
|
};
|
|
@@ -88,6 +121,12 @@ const denialReason = (location, options) => {
|
|
|
88
121
|
catch {
|
|
89
122
|
return 'the URL is invalid';
|
|
90
123
|
}
|
|
124
|
+
// Only http(s) may be fetched. Without this, a redirect to `file:///etc/passwd`
|
|
125
|
+
// or a `data:` URL passes every host check below (their `hostname` is empty, so
|
|
126
|
+
// `isPrivateHost('')` is false) and Bun's `fetch` would happily read the file.
|
|
127
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
128
|
+
return `unsupported URL protocol "${url.protocol}" (only http and https are allowed)`;
|
|
129
|
+
}
|
|
91
130
|
const allow = options.allowedHosts;
|
|
92
131
|
// An explicit allow-list entry is an intentional opt-in and bypasses the
|
|
93
132
|
// private-host guard; otherwise refuse non-public targets by default.
|
|
@@ -248,7 +287,7 @@ const resolveAt = (node, baseLocation, docCache, refCache, origins) => {
|
|
|
248
287
|
return resolved;
|
|
249
288
|
const siblings = {};
|
|
250
289
|
for (const key of siblingKeys)
|
|
251
|
-
siblings
|
|
290
|
+
assignKey(siblings, key, resolveAt(obj[key], baseLocation, docCache, refCache, origins));
|
|
252
291
|
const existingAllOf = Array.isArray(siblings['allOf']) ? siblings['allOf'] : [];
|
|
253
292
|
const merged = { ...siblings, allOf: [...existingAllOf, resolved] };
|
|
254
293
|
// Stamp the wrapper too, so origin lookups resolve for a `$ref`-with-siblings node.
|
|
@@ -258,7 +297,7 @@ const resolveAt = (node, baseLocation, docCache, refCache, origins) => {
|
|
|
258
297
|
}
|
|
259
298
|
const result = {};
|
|
260
299
|
for (const key of Object.keys(obj)) {
|
|
261
|
-
result
|
|
300
|
+
assignKey(result, key, resolveAt(obj[key], baseLocation, docCache, refCache, origins));
|
|
262
301
|
}
|
|
263
302
|
return result;
|
|
264
303
|
};
|
package/dist/resolve-refs.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { getByPointer, pointerToPath } from './get-by-pointer.js';
|
|
2
|
+
import { assignKey } from './safe-assign.js';
|
|
2
3
|
// A ref currently mid-resolution is marked with this sentinel; revisiting it
|
|
3
4
|
// means we have looped, so we return `{}` instead of recursing forever.
|
|
4
5
|
const CYCLE = Symbol('cycle');
|
|
@@ -9,11 +10,11 @@ const CYCLE = Symbol('cycle');
|
|
|
9
10
|
* files, HTTP) are left untouched — callers that need those should use
|
|
10
11
|
* `resolveRefsFromFile`.
|
|
11
12
|
*/
|
|
12
|
-
const resolveInternal = (node, root, cache, origins) => {
|
|
13
|
+
const resolveInternal = (node, root, cache, origins, errors) => {
|
|
13
14
|
if (node === null || typeof node !== 'object')
|
|
14
15
|
return node;
|
|
15
16
|
if (Array.isArray(node))
|
|
16
|
-
return node.map((item) => resolveInternal(item, root, cache, origins));
|
|
17
|
+
return node.map((item) => resolveInternal(item, root, cache, origins, errors));
|
|
17
18
|
const obj = node;
|
|
18
19
|
if (typeof obj['$ref'] === 'string') {
|
|
19
20
|
const ref = obj['$ref'];
|
|
@@ -26,7 +27,16 @@ const resolveInternal = (node, root, cache, origins) => {
|
|
|
26
27
|
}
|
|
27
28
|
else {
|
|
28
29
|
cache.set(ref, CYCLE);
|
|
29
|
-
|
|
30
|
+
const pointed = getByPointer(root, ref.slice(1));
|
|
31
|
+
if (pointed === undefined) {
|
|
32
|
+
// An internal pointer that resolves to nothing (a typo'd or missing
|
|
33
|
+
// definition) was previously inlined as literal `undefined` with no trace.
|
|
34
|
+
// Record it and keep the original `$ref` node so the failure is visible.
|
|
35
|
+
errors.push({ message: `Cannot resolve internal $ref "${ref}"`, path: pointerToPath(ref.slice(1)) });
|
|
36
|
+
cache.set(ref, obj);
|
|
37
|
+
return obj;
|
|
38
|
+
}
|
|
39
|
+
target = resolveInternal(pointed, root, cache, origins, errors);
|
|
30
40
|
cache.set(ref, target);
|
|
31
41
|
// Stamp the inlined node with the path it was defined at (see resolveAt).
|
|
32
42
|
// First-write-wins so the deepest definition stamps before any outer ref that
|
|
@@ -45,7 +55,7 @@ const resolveInternal = (node, root, cache, origins) => {
|
|
|
45
55
|
return target;
|
|
46
56
|
const siblings = {};
|
|
47
57
|
for (const key of siblingKeys)
|
|
48
|
-
siblings
|
|
58
|
+
assignKey(siblings, key, resolveInternal(obj[key], root, cache, origins, errors));
|
|
49
59
|
const existingAllOf = Array.isArray(siblings['allOf']) ? siblings['allOf'] : [];
|
|
50
60
|
const merged = { ...siblings, allOf: [...existingAllOf, target] };
|
|
51
61
|
// Stamp the wrapper too, so a consumer mapping the resolved node back to its
|
|
@@ -56,7 +66,7 @@ const resolveInternal = (node, root, cache, origins) => {
|
|
|
56
66
|
}
|
|
57
67
|
const result = {};
|
|
58
68
|
for (const key of Object.keys(obj)) {
|
|
59
|
-
result
|
|
69
|
+
assignKey(result, key, resolveInternal(obj[key], root, cache, origins, errors));
|
|
60
70
|
}
|
|
61
71
|
return result;
|
|
62
72
|
};
|
|
@@ -67,6 +77,7 @@ const resolveInternal = (node, root, cache, origins) => {
|
|
|
67
77
|
*/
|
|
68
78
|
export const resolveRefs = (data, options = {}) => {
|
|
69
79
|
const origins = options.trackOrigins ? new Map() : undefined;
|
|
70
|
-
const
|
|
71
|
-
|
|
80
|
+
const errors = [];
|
|
81
|
+
const resolved = resolveInternal(data, data, new Map(), origins, errors);
|
|
82
|
+
return origins ? { resolved, errors, origins } : { resolved, errors };
|
|
72
83
|
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Assigns `value` under `key` on a rebuilt object without letting a `__proto__`
|
|
3
|
+
* key hit the prototype setter. Ref resolution rebuilds every object node of a
|
|
4
|
+
* document — including remote/external content — so a plain `target[key] = value`
|
|
5
|
+
* would let a `{ "__proto__": … }` node corrupt the rebuilt object's prototype.
|
|
6
|
+
* Defining it as an own data property preserves the key verbatim instead.
|
|
7
|
+
*/
|
|
8
|
+
export declare const assignKey: (target: Record<string, unknown>, key: string, value: unknown) => void;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Assigns `value` under `key` on a rebuilt object without letting a `__proto__`
|
|
3
|
+
* key hit the prototype setter. Ref resolution rebuilds every object node of a
|
|
4
|
+
* document — including remote/external content — so a plain `target[key] = value`
|
|
5
|
+
* would let a `{ "__proto__": … }` node corrupt the rebuilt object's prototype.
|
|
6
|
+
* Defining it as an own data property preserves the key verbatim instead.
|
|
7
|
+
*/
|
|
8
|
+
export const assignKey = (target, key, value) => {
|
|
9
|
+
if (key === '__proto__') {
|
|
10
|
+
Object.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true });
|
|
11
|
+
}
|
|
12
|
+
else {
|
|
13
|
+
target[key] = value;
|
|
14
|
+
}
|
|
15
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amritk/resolve-refs",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.3",
|
|
4
4
|
"description": "Resolve and inline JSON Schema / OpenAPI $refs — internal, cross-file, and remote — with session caching and a default-deny SSRF guard.",
|
|
5
5
|
"module": "./dist/index.js",
|
|
6
6
|
"type": "module",
|