@amritk/resolve-refs 0.2.0 → 0.2.2

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,9 +1,12 @@
1
1
  import type { JsonPath } from './types.js';
2
2
  /**
3
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.
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.
7
10
  */
8
11
  export declare const pointerToPath: (pointer: string) => JsonPath;
9
12
  /**
@@ -13,4 +16,3 @@ export declare const pointerToPath: (pointer: string) => JsonPath;
13
16
  * the path is missing or traverses a non-object.
14
17
  */
15
18
  export declare const getByPointer: (root: unknown, pointer: string) => unknown;
16
- //# sourceMappingURL=get-by-pointer.d.ts.map
@@ -1,8 +1,25 @@
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
+ };
1
15
  /**
2
16
  * 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.
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.
6
23
  */
7
24
  export const pointerToPath = (pointer) => {
8
25
  if (pointer === '' || pointer === '/')
@@ -11,15 +28,8 @@ export const pointerToPath = (pointer) => {
11
28
  .replace(/^\//, '')
12
29
  .split('/')
13
30
  .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;
31
+ const decoded = decodeSegment(segment);
32
+ return /^(0|[1-9]\d*)$/.test(decoded) ? Number(decoded) : decoded;
23
33
  });
24
34
  };
25
35
  /**
@@ -31,19 +41,7 @@ export const pointerToPath = (pointer) => {
31
41
  export const getByPointer = (root, pointer) => {
32
42
  if (pointer === '' || pointer === '/')
33
43
  return root;
34
- const segments = pointer
35
- .replace(/^\//, '')
36
- .split('/')
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
- });
44
+ const segments = pointer.replace(/^\//, '').split('/').map(decodeSegment);
47
45
  let current = root;
48
46
  for (const segment of segments) {
49
47
  if (current === null || typeof current !== 'object')
package/dist/index.d.ts CHANGED
@@ -3,4 +3,3 @@ export { isPrivateHost } from './is-private-host.js';
3
3
  export { type ResolveRefsOptions, resolveRefs } from './resolve-refs.js';
4
4
  export { clearRemoteCache, resolveRefsFromFile } from './resolve-refs-from-file.js';
5
5
  export type { JsonPath, Origin, OriginMap, ResolveError, ResolveOptions, ResolveResult } from './types.js';
6
- //# sourceMappingURL=index.d.ts.map
@@ -7,4 +7,3 @@
7
7
  * when resolving remote `$ref`s.
8
8
  */
9
9
  export declare const isPrivateHost: (hostname: string) => boolean;
10
- //# sourceMappingURL=is-private-host.d.ts.map
@@ -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
@@ -166,15 +166,17 @@ const collectRefTargets = (node, out) => {
166
166
  }
167
167
  const obj = node;
168
168
  if (typeof obj['$ref'] === 'string') {
169
- // A `$ref` object's siblings are ignored on resolution, so we do not recurse
170
- // into them — mirroring resolveAt's behaviour.
171
169
  const { filePart } = splitRef(obj['$ref']);
172
170
  if (filePart !== '')
173
171
  out.add(filePart);
174
- return out;
175
172
  }
176
- for (const key of Object.keys(obj))
173
+ // Recurse into every key — including a `$ref` node's siblings, which apply
174
+ // alongside the referenced schema (2020-12) and may carry their own refs.
175
+ for (const key of Object.keys(obj)) {
176
+ if (key === '$ref')
177
+ continue;
177
178
  collectRefTargets(obj[key], out);
179
+ }
178
180
  return out;
179
181
  };
180
182
  /**
@@ -219,24 +221,40 @@ const resolveAt = (node, baseLocation, docCache, refCache, origins) => {
219
221
  const targetLocation = filePart === '' ? baseLocation : joinLocation(baseLocation, filePart);
220
222
  const targetRoot = docCache.get(targetLocation) ?? {};
221
223
  const cacheKey = `${targetLocation}#${pointer}`;
224
+ let resolved;
222
225
  if (refCache.has(cacheKey)) {
223
226
  const cached = refCache.get(cacheKey);
224
- return cached === CYCLE ? {} : cached;
227
+ resolved = cached === CYCLE ? {} : cached;
225
228
  }
226
- refCache.set(cacheKey, CYCLE);
227
- const target = pointer ? getByPointer(targetRoot, pointer) : targetRoot;
228
- const resolved = resolveAt(target, targetLocation, docCache, refCache, origins);
229
- refCache.set(cacheKey, resolved);
230
- // Stamp the inlined node with where it was defined so a consumer can map a
231
- // resolved-tree node back to its source document/path. Only objects/arrays are
232
- // stamped (primitives can't key the map). First-write-wins: resolution recurses
233
- // to the deepest `$ref` before returning, so the *definition* site stamps first;
234
- // an outer ref that merely points (transitively) at the same object must not
235
- // overwrite it with an intermediate location.
236
- if (origins && resolved !== null && typeof resolved === 'object' && !origins.has(resolved)) {
237
- origins.set(resolved, { location: targetLocation, pointer: pointerToPath(pointer) });
229
+ else {
230
+ refCache.set(cacheKey, CYCLE);
231
+ const target = pointer ? getByPointer(targetRoot, pointer) : targetRoot;
232
+ resolved = resolveAt(target, targetLocation, docCache, refCache, origins);
233
+ refCache.set(cacheKey, resolved);
234
+ // Stamp the inlined node with where it was defined so a consumer can map a
235
+ // resolved-tree node back to its source document/path. Only objects/arrays are
236
+ // stamped (primitives can't key the map). First-write-wins: resolution recurses
237
+ // to the deepest `$ref` before returning, so the *definition* site stamps first;
238
+ // an outer ref that merely points (transitively) at the same object must not
239
+ // overwrite it with an intermediate location.
240
+ if (origins && resolved !== null && typeof resolved === 'object' && !origins.has(resolved)) {
241
+ origins.set(resolved, { location: targetLocation, pointer: pointerToPath(pointer) });
242
+ }
238
243
  }
239
- return resolved;
244
+ // Keywords sibling to `$ref` apply alongside the referenced schema (2020-12),
245
+ // so preserve them by combining both in an `allOf` rather than dropping them.
246
+ const siblingKeys = Object.keys(obj).filter((key) => key !== '$ref');
247
+ if (siblingKeys.length === 0)
248
+ return resolved;
249
+ const siblings = {};
250
+ for (const key of siblingKeys)
251
+ siblings[key] = resolveAt(obj[key], baseLocation, docCache, refCache, origins);
252
+ const existingAllOf = Array.isArray(siblings['allOf']) ? siblings['allOf'] : [];
253
+ const merged = { ...siblings, allOf: [...existingAllOf, resolved] };
254
+ // Stamp the wrapper too, so origin lookups resolve for a `$ref`-with-siblings node.
255
+ if (origins && !origins.has(merged))
256
+ origins.set(merged, { location: targetLocation, pointer: pointerToPath(pointer) });
257
+ return merged;
240
258
  }
241
259
  const result = {};
242
260
  for (const key of Object.keys(obj)) {
@@ -15,4 +15,3 @@ export type ResolveRefsOptions = {
15
15
  * an empty object so the result is always finite.
16
16
  */
17
17
  export declare const resolveRefs: (data: unknown, options?: ResolveRefsOptions) => ResolveResult;
18
- //# sourceMappingURL=resolve-refs.d.ts.map
@@ -19,20 +19,40 @@ const resolveInternal = (node, root, cache, origins) => {
19
19
  const ref = obj['$ref'];
20
20
  if (!ref.startsWith('#'))
21
21
  return obj; // external ref — leave as-is
22
+ let target;
22
23
  if (cache.has(ref)) {
23
24
  const cached = cache.get(ref);
24
- return cached === CYCLE ? {} : cached;
25
+ target = cached === CYCLE ? {} : cached;
25
26
  }
26
- cache.set(ref, CYCLE);
27
- const resolved = resolveInternal(getByPointer(root, ref.slice(1)), root, cache, origins);
28
- cache.set(ref, resolved);
29
- // Stamp the inlined node with the path it was defined at (see resolveAt).
30
- // First-write-wins so the deepest definition stamps before any outer ref that
31
- // transitively points at the same object. Primitives can't key the map.
32
- if (origins && resolved !== null && typeof resolved === 'object' && !origins.has(resolved)) {
33
- origins.set(resolved, { location: '', pointer: pointerToPath(ref.slice(1)) });
27
+ else {
28
+ cache.set(ref, CYCLE);
29
+ target = resolveInternal(getByPointer(root, ref.slice(1)), root, cache, origins);
30
+ cache.set(ref, target);
31
+ // Stamp the inlined node with the path it was defined at (see resolveAt).
32
+ // First-write-wins so the deepest definition stamps before any outer ref that
33
+ // transitively points at the same object. Primitives can't key the map.
34
+ if (origins && target !== null && typeof target === 'object' && !origins.has(target)) {
35
+ origins.set(target, { location: '', pointer: pointerToPath(ref.slice(1)) });
36
+ }
34
37
  }
35
- return resolved;
38
+ // Per JSON Schema 2020-12, keywords sibling to `$ref` are *not* ignored: they
39
+ // apply alongside the referenced schema. Preserve them by combining both in an
40
+ // `allOf` (so a constraint present on both sides is never silently dropped)
41
+ // rather than returning the bare target. The cache always stores the
42
+ // sibling-free target so each occurrence applies its own siblings.
43
+ const siblingKeys = Object.keys(obj).filter((key) => key !== '$ref');
44
+ if (siblingKeys.length === 0)
45
+ return target;
46
+ const siblings = {};
47
+ for (const key of siblingKeys)
48
+ siblings[key] = resolveInternal(obj[key], root, cache, origins);
49
+ const existingAllOf = Array.isArray(siblings['allOf']) ? siblings['allOf'] : [];
50
+ const merged = { ...siblings, allOf: [...existingAllOf, target] };
51
+ // Stamp the wrapper too, so a consumer mapping the resolved node back to its
52
+ // origin finds one for a `$ref`-with-siblings node (not only the inner target).
53
+ if (origins && !origins.has(merged))
54
+ origins.set(merged, { location: '', pointer: pointerToPath(ref.slice(1)) });
55
+ return merged;
36
56
  }
37
57
  const result = {};
38
58
  for (const key of Object.keys(obj)) {
package/dist/types.d.ts CHANGED
@@ -81,4 +81,3 @@ export type ResolveOptions = {
81
81
  */
82
82
  trackOrigins?: boolean;
83
83
  };
84
- //# sourceMappingURL=types.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/resolve-refs",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
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,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 +0,0 @@
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"}
@@ -1 +0,0 @@
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"}
@@ -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,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 +0,0 @@
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 +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;;;;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"}
@@ -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
- })
@@ -1,55 +0,0 @@
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
-
26
- /**
27
- * Walks a JSON Pointer string (RFC 6901) to the value it points to within
28
- * `root`. A bare `''` or `'/'` returns the root document. Segment escapes are
29
- * decoded (`~1` → `/`, `~0` → `~`). Returns `undefined` when any segment along
30
- * the path is missing or traverses a non-object.
31
- */
32
- export const getByPointer = (root: unknown, pointer: string): unknown => {
33
- if (pointer === '' || pointer === '/') return root
34
-
35
- const segments = pointer
36
- .replace(/^\//, '')
37
- .split('/')
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
- })
47
-
48
- let current: unknown = root
49
- for (const segment of segments) {
50
- if (current === null || typeof current !== 'object') return undefined
51
- const key = Array.isArray(current) ? Number(segment) : segment
52
- current = (current as Record<string, unknown>)[key]
53
- }
54
- return current
55
- }
package/src/index.ts DELETED
@@ -1,5 +0,0 @@
1
- export { getByPointer, pointerToPath } from './get-by-pointer'
2
- export { isPrivateHost } from './is-private-host'
3
- export { type ResolveRefsOptions, resolveRefs } from './resolve-refs'
4
- export { clearRemoteCache, resolveRefsFromFile } from './resolve-refs-from-file'
5
- export type { JsonPath, Origin, OriginMap, ResolveError, ResolveOptions, ResolveResult } from './types'
@@ -1,64 +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('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
-
56
- it('allows public hosts', () => {
57
- expect(isPrivateHost('example.com')).toBe(false)
58
- expect(isPrivateHost('8.8.8.8')).toBe(false)
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)
63
- })
64
- })
@@ -1,91 +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
-
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
-
60
- export const isPrivateHost = (hostname: string): boolean => {
61
- const host = hostname.replace(/^\[|\]$/g, '').toLowerCase()
62
- if (host === 'localhost' || host.endsWith('.localhost')) return true
63
-
64
- if (host.includes(':')) {
65
- // --- IPv6 (and IPv4-mapped IPv6) ---
66
- if (host === '::1' || host === '::') return true
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
- }
84
- return false
85
- }
86
-
87
- // --- IPv4 (any inet_aton encoding) ---
88
- const oct = ipv4Octets(host)
89
- if (oct) return isPrivateIpv4(oct[0], oct[1])
90
- return false
91
- }