@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.
- package/dist/get-by-pointer.d.ts +6 -4
- package/dist/get-by-pointer.js +23 -25
- package/dist/index.d.ts +0 -1
- package/dist/is-private-host.d.ts +0 -1
- package/dist/resolve-refs-from-file.d.ts +0 -1
- package/dist/resolve-refs-from-file.js +36 -18
- package/dist/resolve-refs.d.ts +0 -1
- package/dist/resolve-refs.js +30 -10
- package/dist/types.d.ts +0 -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 -55
- package/src/index.ts +0 -5
- package/src/is-private-host.test.ts +0 -64
- package/src/is-private-host.ts +0 -91
- package/src/resolve-refs-from-file.test.ts +0 -246
- package/src/resolve-refs-from-file.ts +0 -289
- package/src/resolve-refs.test.ts +0 -78
- package/src/resolve-refs.ts +0 -72
- package/src/types.ts +0 -88
|
@@ -1,246 +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('omits the origin map unless trackOrigins is set', async () => {
|
|
48
|
-
writeFileSync(join(dir, 'root.json'), JSON.stringify({ a: { $ref: '#/b' }, b: { value: 1 } }))
|
|
49
|
-
|
|
50
|
-
const result = await resolveRefsFromFile(join(dir, 'root.json'))
|
|
51
|
-
|
|
52
|
-
expect(result.origins).toBeUndefined()
|
|
53
|
-
})
|
|
54
|
-
|
|
55
|
-
it('stamps inlined nodes with their origin document and in-file path', async () => {
|
|
56
|
-
const petPath = join(dir, 'pet.json')
|
|
57
|
-
const apiPath = join(dir, 'api.json')
|
|
58
|
-
writeFileSync(petPath, JSON.stringify({ Pet: { type: 'object', properties: { name: { type: 'string' } } } }))
|
|
59
|
-
writeFileSync(
|
|
60
|
-
apiPath,
|
|
61
|
-
JSON.stringify({
|
|
62
|
-
components: { schemas: { Pet: { $ref: './pet.json#/Pet' }, Pet2: { $ref: './pet.json#/Pet' } } },
|
|
63
|
-
widget: { type: 'object' },
|
|
64
|
-
useWidget: { $ref: '#/widget' },
|
|
65
|
-
}),
|
|
66
|
-
)
|
|
67
|
-
|
|
68
|
-
const { resolved, origins } = await resolveRefsFromFile(apiPath, { trackOrigins: true })
|
|
69
|
-
expect(origins).toBeDefined()
|
|
70
|
-
const tree = resolved as {
|
|
71
|
-
components: { schemas: { Pet: object; Pet2: object } }
|
|
72
|
-
useWidget: object
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
// The cross-file node is stamped with pet.json and its in-file path; both call
|
|
76
|
-
// sites share the one inlined object, so the stamp identifies the definition.
|
|
77
|
-
expect(tree.components.schemas.Pet).toBe(tree.components.schemas.Pet2)
|
|
78
|
-
expect(origins?.get(tree.components.schemas.Pet)).toEqual({ location: petPath, pointer: ['Pet'] })
|
|
79
|
-
|
|
80
|
-
// An internal ref is stamped against the root document at the target path.
|
|
81
|
-
expect(origins?.get(tree.useWidget)).toEqual({ location: apiPath, pointer: ['widget'] })
|
|
82
|
-
})
|
|
83
|
-
|
|
84
|
-
it('keeps the definition origin when a node is reached through a chained ref (first-write-wins)', async () => {
|
|
85
|
-
const petPath = join(dir, 'pet.json')
|
|
86
|
-
const apiPath = join(dir, 'api.json')
|
|
87
|
-
writeFileSync(petPath, JSON.stringify({ Pet: { type: 'object' } }))
|
|
88
|
-
writeFileSync(
|
|
89
|
-
apiPath,
|
|
90
|
-
JSON.stringify({
|
|
91
|
-
components: { schemas: { Pet: { $ref: './pet.json#/Pet' } } },
|
|
92
|
-
// Resolves through the internal ref to the same pet.json object.
|
|
93
|
-
alias: { $ref: '#/components/schemas/Pet' },
|
|
94
|
-
}),
|
|
95
|
-
)
|
|
96
|
-
|
|
97
|
-
const { resolved, origins } = await resolveRefsFromFile(apiPath, { trackOrigins: true })
|
|
98
|
-
const tree = resolved as { components: { schemas: { Pet: object } }; alias: object }
|
|
99
|
-
|
|
100
|
-
// `alias` resolves through to the same object; its origin stays the pet.json
|
|
101
|
-
// definition rather than the intermediate root-document pointer.
|
|
102
|
-
expect(tree.alias).toBe(tree.components.schemas.Pet)
|
|
103
|
-
expect(origins?.get(tree.alias)).toEqual({ location: petPath, pointer: ['Pet'] })
|
|
104
|
-
})
|
|
105
|
-
|
|
106
|
-
it('records an error and degrades to {} when a referenced file is missing', async () => {
|
|
107
|
-
writeFileSync(join(dir, 'api.json'), JSON.stringify({ x: { $ref: './missing.json#/Nope' } }))
|
|
108
|
-
|
|
109
|
-
const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'))
|
|
110
|
-
|
|
111
|
-
// The missing document degrades to {}, so the pointer into it misses and the
|
|
112
|
-
// ref resolves to undefined — the important part is that we recorded the
|
|
113
|
-
// failure instead of throwing.
|
|
114
|
-
expect((resolved as { x: unknown }).x).toBeUndefined()
|
|
115
|
-
expect(errors.length).toBeGreaterThan(0)
|
|
116
|
-
})
|
|
117
|
-
|
|
118
|
-
it('refuses a remote $ref to a private host by default (SSRF guard)', async () => {
|
|
119
|
-
const fetchSpy = vi.spyOn(globalThis, 'fetch')
|
|
120
|
-
writeFileSync(
|
|
121
|
-
join(dir, 'api.json'),
|
|
122
|
-
JSON.stringify({ x: { $ref: 'http://169.254.169.254/latest/meta-data#/foo' } }),
|
|
123
|
-
)
|
|
124
|
-
|
|
125
|
-
const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'))
|
|
126
|
-
|
|
127
|
-
// The refused document degrades to {}, so the pointer into it misses.
|
|
128
|
-
expect((resolved as { x: unknown }).x).toBeUndefined()
|
|
129
|
-
expect(errors[0]?.message).toMatch(/Refusing to resolve remote \$ref/)
|
|
130
|
-
// The guard is syntactic — we never even attempt the request.
|
|
131
|
-
expect(fetchSpy).not.toHaveBeenCalled()
|
|
132
|
-
})
|
|
133
|
-
|
|
134
|
-
it('refuses any remote $ref when remote resolution is disabled', async () => {
|
|
135
|
-
const fetchSpy = vi.spyOn(globalThis, 'fetch')
|
|
136
|
-
writeFileSync(join(dir, 'api.json'), JSON.stringify({ x: { $ref: 'https://example.com/s.json#/Foo' } }))
|
|
137
|
-
|
|
138
|
-
const { errors } = await resolveRefsFromFile(join(dir, 'api.json'), { remote: false })
|
|
139
|
-
|
|
140
|
-
expect(errors[0]?.message).toMatch(/remote \$ref resolution is disabled/)
|
|
141
|
-
expect(fetchSpy).not.toHaveBeenCalled()
|
|
142
|
-
})
|
|
143
|
-
|
|
144
|
-
it('uses a custom parse callback to load non-JSON (e.g. YAML) documents', async () => {
|
|
145
|
-
// Real YAML that JSON.parse would reject — a custom callback handles it.
|
|
146
|
-
writeFileSync(join(dir, 'contact.yaml'), 'type: object\nproperties:\n name:\n type: string\n')
|
|
147
|
-
writeFileSync(join(dir, 'api.json'), JSON.stringify({ contact: { $ref: './contact.yaml' } }))
|
|
148
|
-
|
|
149
|
-
const parse = (content: string, location: string): unknown => {
|
|
150
|
-
if (/\.ya?ml$/i.test(location)) return { type: 'object', properties: { name: { type: 'string' } } }
|
|
151
|
-
return JSON.parse(content) as unknown
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'), { parse })
|
|
155
|
-
|
|
156
|
-
expect(errors).toEqual([])
|
|
157
|
-
expect(resolved).toMatchObject({ contact: { type: 'object', properties: { name: { type: 'string' } } } })
|
|
158
|
-
})
|
|
159
|
-
|
|
160
|
-
it('fetches an allow-listed remote $ref and caches it for the session', async () => {
|
|
161
|
-
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
|
162
|
-
new Response(JSON.stringify({ Foo: { type: 'string' } }), {
|
|
163
|
-
status: 200,
|
|
164
|
-
headers: { 'content-type': 'application/json' },
|
|
165
|
-
}),
|
|
166
|
-
)
|
|
167
|
-
writeFileSync(
|
|
168
|
-
join(dir, 'api.json'),
|
|
169
|
-
JSON.stringify({
|
|
170
|
-
a: { $ref: 'https://api.example.com/s.json#/Foo' },
|
|
171
|
-
b: { $ref: 'https://api.example.com/s.json#/Foo' },
|
|
172
|
-
}),
|
|
173
|
-
)
|
|
174
|
-
|
|
175
|
-
const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'), {
|
|
176
|
-
allowedHosts: ['api.example.com'],
|
|
177
|
-
})
|
|
178
|
-
|
|
179
|
-
expect(errors).toEqual([])
|
|
180
|
-
expect(resolved).toMatchObject({ a: { type: 'string' }, b: { type: 'string' } })
|
|
181
|
-
// Both refs hit the same document, which is fetched and cached exactly once.
|
|
182
|
-
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
|
183
|
-
})
|
|
184
|
-
|
|
185
|
-
it('refuses a redirect that lands on a private host (SSRF via redirect)', async () => {
|
|
186
|
-
const fetchSpy = vi
|
|
187
|
-
.spyOn(globalThis, 'fetch')
|
|
188
|
-
.mockResolvedValue(
|
|
189
|
-
new Response(null, { status: 302, headers: { location: 'http://169.254.169.254/latest/meta-data' } }),
|
|
190
|
-
)
|
|
191
|
-
writeFileSync(join(dir, 'api.json'), JSON.stringify({ x: { $ref: 'https://api.example.com/s.json#/Foo' } }))
|
|
192
|
-
|
|
193
|
-
const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'), {
|
|
194
|
-
allowedHosts: ['api.example.com'],
|
|
195
|
-
})
|
|
196
|
-
|
|
197
|
-
expect((resolved as { x: unknown }).x).toBeUndefined()
|
|
198
|
-
expect(errors[0]?.message).toMatch(/refusing to follow redirect/i)
|
|
199
|
-
// The initial host was allowed, so the first request happened — but the
|
|
200
|
-
// redirect target was re-checked and refused before any second request.
|
|
201
|
-
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
|
202
|
-
expect(fetchSpy).toHaveBeenCalledWith('https://api.example.com/s.json', { redirect: 'manual' })
|
|
203
|
-
})
|
|
204
|
-
|
|
205
|
-
it('follows a redirect to another allowed host', async () => {
|
|
206
|
-
const fetchSpy = vi
|
|
207
|
-
.spyOn(globalThis, 'fetch')
|
|
208
|
-
.mockResolvedValueOnce(
|
|
209
|
-
new Response(null, { status: 301, headers: { location: 'https://cdn.example.com/s.json' } }),
|
|
210
|
-
)
|
|
211
|
-
.mockResolvedValueOnce(new Response(JSON.stringify({ Foo: { type: 'string' } }), { status: 200 }))
|
|
212
|
-
writeFileSync(join(dir, 'api.json'), JSON.stringify({ x: { $ref: 'https://api.example.com/s.json#/Foo' } }))
|
|
213
|
-
|
|
214
|
-
const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'), {
|
|
215
|
-
allowedHosts: ['api.example.com', 'cdn.example.com'],
|
|
216
|
-
})
|
|
217
|
-
|
|
218
|
-
expect(errors).toEqual([])
|
|
219
|
-
expect(resolved).toMatchObject({ x: { type: 'string' } })
|
|
220
|
-
expect(fetchSpy).toHaveBeenCalledTimes(2)
|
|
221
|
-
})
|
|
222
|
-
|
|
223
|
-
it('coalesces two concurrent resolves of the same remote URL into one fetch', async () => {
|
|
224
|
-
let resolveFetch: ((r: Response) => void) | undefined
|
|
225
|
-
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(
|
|
226
|
-
() =>
|
|
227
|
-
new Promise<Response>((res) => {
|
|
228
|
-
resolveFetch = res
|
|
229
|
-
}),
|
|
230
|
-
)
|
|
231
|
-
writeFileSync(join(dir, 'api.json'), JSON.stringify({ x: { $ref: 'https://api.example.com/s.json#/Foo' } }))
|
|
232
|
-
|
|
233
|
-
// Two passes start before either fetch settles — they must share one request.
|
|
234
|
-
const pass1 = resolveRefsFromFile(join(dir, 'api.json'), { allowedHosts: ['api.example.com'] })
|
|
235
|
-
const pass2 = resolveRefsFromFile(join(dir, 'api.json'), { allowedHosts: ['api.example.com'] })
|
|
236
|
-
await Promise.resolve()
|
|
237
|
-
resolveFetch?.(new Response(JSON.stringify({ Foo: { type: 'string' } }), { status: 200 }))
|
|
238
|
-
|
|
239
|
-
const [r1, r2] = await Promise.all([pass1, pass2])
|
|
240
|
-
expect(r1.errors).toEqual([])
|
|
241
|
-
expect(r2.errors).toEqual([])
|
|
242
|
-
expect(r1.resolved).toMatchObject({ x: { type: 'string' } })
|
|
243
|
-
expect(r2.resolved).toMatchObject({ x: { type: 'string' } })
|
|
244
|
-
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
|
245
|
-
})
|
|
246
|
-
})
|
|
@@ -1,289 +0,0 @@
|
|
|
1
|
-
import { readFileSync } from 'node:fs'
|
|
2
|
-
import { dirname, resolve as resolvePath } from 'node:path'
|
|
3
|
-
|
|
4
|
-
import { getByPointer, pointerToPath } from './get-by-pointer'
|
|
5
|
-
import { isPrivateHost } from './is-private-host'
|
|
6
|
-
import type { OriginMap, 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
|
-
// In-flight remote loads, keyed by location. Two resolve passes that start at
|
|
49
|
-
// the same time and reach the same URL share a single fetch instead of racing
|
|
50
|
-
// two requests; whichever arrives first installs the promise, the rest await it.
|
|
51
|
-
const inFlight = new Map<string, Promise<unknown>>()
|
|
52
|
-
|
|
53
|
-
/** Drops every cached remote document. Mainly useful for tests/long sessions. */
|
|
54
|
-
export const clearRemoteCache = (): void => {
|
|
55
|
-
remoteCache.clear()
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
// Cap on redirect hops before we give up — generous enough for real services,
|
|
59
|
-
// low enough to stop a redirect loop from spinning forever.
|
|
60
|
-
const MAX_REDIRECTS = 5
|
|
61
|
-
|
|
62
|
-
/**
|
|
63
|
-
* Fetches and parses a remote document, following redirects manually so the
|
|
64
|
-
* SSRF guard is re-applied to every hop. `fetch` follows redirects by default,
|
|
65
|
-
* which would let an allow-listed public URL bounce to a private/loopback
|
|
66
|
-
* address (e.g. the `169.254.169.254` metadata endpoint) — so we set
|
|
67
|
-
* `redirect: 'manual'` and re-run {@link denialReason} on each `Location`.
|
|
68
|
-
*/
|
|
69
|
-
const fetchRemote = async (location: string, options: ResolveOptions): Promise<unknown> => {
|
|
70
|
-
let current = location
|
|
71
|
-
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
|
|
72
|
-
const reason = denialReason(current, options)
|
|
73
|
-
if (reason !== null) throw new Error(`refusing to follow redirect (${reason}): ${current}`)
|
|
74
|
-
|
|
75
|
-
const response = await fetch(current, { redirect: 'manual' })
|
|
76
|
-
if (response.status >= 300 && response.status < 400) {
|
|
77
|
-
const next = response.headers.get('location')
|
|
78
|
-
if (!next) throw new Error(`HTTP ${response.status} redirect with no Location header`)
|
|
79
|
-
current = new URL(next, current).href
|
|
80
|
-
continue
|
|
81
|
-
}
|
|
82
|
-
if (!response.ok) throw new Error(`HTTP ${response.status} ${response.statusText}`)
|
|
83
|
-
|
|
84
|
-
const parse = options.parse ?? ((c: string) => JSON.parse(c) as unknown)
|
|
85
|
-
// Parse against the original request location so the caller's format sniffing
|
|
86
|
-
// (e.g. `.yaml` vs `.json`) and any relative refs key off a stable identity.
|
|
87
|
-
return parse(await response.text(), location)
|
|
88
|
-
}
|
|
89
|
-
throw new Error(`too many redirects (>${MAX_REDIRECTS}): ${location}`)
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
/** Returns why a remote location may not be fetched, or `null` if it is allowed. */
|
|
93
|
-
const denialReason = (location: string, options: ResolveOptions): string | null => {
|
|
94
|
-
if (options.remote === false) return 'remote $ref resolution is disabled'
|
|
95
|
-
|
|
96
|
-
let url: URL
|
|
97
|
-
try {
|
|
98
|
-
url = new URL(location)
|
|
99
|
-
} catch {
|
|
100
|
-
return 'the URL is invalid'
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
const allow = options.allowedHosts
|
|
104
|
-
// An explicit allow-list entry is an intentional opt-in and bypasses the
|
|
105
|
-
// private-host guard; otherwise refuse non-public targets by default.
|
|
106
|
-
if (allow && allow.length > 0) {
|
|
107
|
-
return allow.includes(url.host) ? null : 'host is not in the allow-list'
|
|
108
|
-
}
|
|
109
|
-
if (!options.allowPrivateHosts && isPrivateHost(url.hostname)) {
|
|
110
|
-
return 'host resolves to a private or loopback address (set allowPrivateHosts to permit)'
|
|
111
|
-
}
|
|
112
|
-
return null
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
/**
|
|
116
|
-
* Loads a document into `docCache`, fetching/reading it if needed. Remote
|
|
117
|
-
* documents are additionally cached for the session in `remoteCache`. On
|
|
118
|
-
* failure an error is recorded and the location is cached as `{}` so that
|
|
119
|
-
* pointer lookups degrade gracefully instead of throwing. Returns whether the
|
|
120
|
-
* document loaded successfully.
|
|
121
|
-
*/
|
|
122
|
-
const loadDoc = async (
|
|
123
|
-
location: string,
|
|
124
|
-
docCache: Map<string, unknown>,
|
|
125
|
-
options: ResolveOptions,
|
|
126
|
-
errors: ResolveError[],
|
|
127
|
-
): Promise<boolean> => {
|
|
128
|
-
if (docCache.has(location)) return true
|
|
129
|
-
|
|
130
|
-
if (isRemote(location)) {
|
|
131
|
-
if (remoteCache.has(location)) {
|
|
132
|
-
docCache.set(location, remoteCache.get(location))
|
|
133
|
-
return true
|
|
134
|
-
}
|
|
135
|
-
const reason = denialReason(location, options)
|
|
136
|
-
if (reason !== null) {
|
|
137
|
-
errors.push({ message: `Refusing to resolve remote $ref (${reason}): ${location}`, path: [] })
|
|
138
|
-
docCache.set(location, {})
|
|
139
|
-
return false
|
|
140
|
-
}
|
|
141
|
-
// Coalesce concurrent loads of the same URL onto one in-flight request; the
|
|
142
|
-
// owner (first caller) clears the slot once it settles.
|
|
143
|
-
let pending = inFlight.get(location)
|
|
144
|
-
const owner = pending === undefined
|
|
145
|
-
if (pending === undefined) {
|
|
146
|
-
pending = fetchRemote(location, options)
|
|
147
|
-
inFlight.set(location, pending)
|
|
148
|
-
}
|
|
149
|
-
try {
|
|
150
|
-
const doc = await pending
|
|
151
|
-
remoteCache.set(location, doc)
|
|
152
|
-
docCache.set(location, doc)
|
|
153
|
-
return true
|
|
154
|
-
} catch (err) {
|
|
155
|
-
errors.push({ message: `Failed to fetch ${location}: ${String(err)}`, path: [] })
|
|
156
|
-
docCache.set(location, {})
|
|
157
|
-
return false
|
|
158
|
-
} finally {
|
|
159
|
-
if (owner) inFlight.delete(location)
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
try {
|
|
164
|
-
const parse = options.parse ?? ((c: string) => JSON.parse(c) as unknown)
|
|
165
|
-
docCache.set(location, parse(readFileSync(location, 'utf8'), location))
|
|
166
|
-
return true
|
|
167
|
-
} catch (err) {
|
|
168
|
-
errors.push({ message: String(err), path: [] })
|
|
169
|
-
docCache.set(location, {})
|
|
170
|
-
return false
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
/** Collects the distinct document parts of every `$ref` directly under `node`. */
|
|
175
|
-
const collectRefTargets = (node: unknown, out: Set<string>): Set<string> => {
|
|
176
|
-
if (node === null || typeof node !== 'object') return out
|
|
177
|
-
if (Array.isArray(node)) {
|
|
178
|
-
for (const item of node) collectRefTargets(item, out)
|
|
179
|
-
return out
|
|
180
|
-
}
|
|
181
|
-
const obj = node as Record<string, unknown>
|
|
182
|
-
if (typeof obj['$ref'] === 'string') {
|
|
183
|
-
// A `$ref` object's siblings are ignored on resolution, so we do not recurse
|
|
184
|
-
// into them — mirroring resolveAt's behaviour.
|
|
185
|
-
const { filePart } = splitRef(obj['$ref'])
|
|
186
|
-
if (filePart !== '') out.add(filePart)
|
|
187
|
-
return out
|
|
188
|
-
}
|
|
189
|
-
for (const key of Object.keys(obj)) collectRefTargets(obj[key], out)
|
|
190
|
-
return out
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
/**
|
|
194
|
-
* Walks every reachable document starting from `rootLocation`, loading each one
|
|
195
|
-
* so the synchronous resolve pass can look them up. This is the only async part
|
|
196
|
-
* of resolution: remote documents are fetched here (in dependency order) and
|
|
197
|
-
* cached for the session.
|
|
198
|
-
*/
|
|
199
|
-
const prefetch = async (
|
|
200
|
-
rootLocation: string,
|
|
201
|
-
docCache: Map<string, unknown>,
|
|
202
|
-
options: ResolveOptions,
|
|
203
|
-
errors: ResolveError[],
|
|
204
|
-
): Promise<void> => {
|
|
205
|
-
const seen = new Set<string>([rootLocation])
|
|
206
|
-
const queue: string[] = [rootLocation]
|
|
207
|
-
while (queue.length > 0) {
|
|
208
|
-
const location = queue.shift() as string
|
|
209
|
-
for (const filePart of collectRefTargets(docCache.get(location), new Set())) {
|
|
210
|
-
const target = joinLocation(location, filePart)
|
|
211
|
-
if (seen.has(target)) continue
|
|
212
|
-
seen.add(target)
|
|
213
|
-
await loadDoc(target, docCache, options, errors)
|
|
214
|
-
queue.push(target)
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
/**
|
|
220
|
-
* Single-pass resolver that inlines internal and external (`$ref` to other
|
|
221
|
-
* file/URL) references. Every reachable document has already been loaded into
|
|
222
|
-
* `docCache` by `prefetch`, so this stays synchronous. Refs are resolved once
|
|
223
|
-
* (`refCache`); the CYCLE sentinel short-circuits re-entrant resolution.
|
|
224
|
-
*
|
|
225
|
-
* `baseLocation` is the location of the document `node` belongs to, used to
|
|
226
|
-
* resolve relative refs and `#/...` pointers within it.
|
|
227
|
-
*/
|
|
228
|
-
const resolveAt = (
|
|
229
|
-
node: unknown,
|
|
230
|
-
baseLocation: string,
|
|
231
|
-
docCache: Map<string, unknown>,
|
|
232
|
-
refCache: Map<string, CacheValue>,
|
|
233
|
-
origins: OriginMap | undefined,
|
|
234
|
-
): unknown => {
|
|
235
|
-
if (node === null || typeof node !== 'object') return node
|
|
236
|
-
if (Array.isArray(node)) {
|
|
237
|
-
return node.map((item) => resolveAt(item, baseLocation, docCache, refCache, origins))
|
|
238
|
-
}
|
|
239
|
-
const obj = node as Record<string, unknown>
|
|
240
|
-
if (typeof obj['$ref'] === 'string') {
|
|
241
|
-
const { filePart, pointer } = splitRef(obj['$ref'])
|
|
242
|
-
const targetLocation = filePart === '' ? baseLocation : joinLocation(baseLocation, filePart)
|
|
243
|
-
const targetRoot = docCache.get(targetLocation) ?? {}
|
|
244
|
-
|
|
245
|
-
const cacheKey = `${targetLocation}#${pointer}`
|
|
246
|
-
if (refCache.has(cacheKey)) {
|
|
247
|
-
const cached = refCache.get(cacheKey)
|
|
248
|
-
return cached === CYCLE ? {} : cached
|
|
249
|
-
}
|
|
250
|
-
refCache.set(cacheKey, CYCLE)
|
|
251
|
-
const target = pointer ? getByPointer(targetRoot, pointer) : targetRoot
|
|
252
|
-
const resolved = resolveAt(target, targetLocation, docCache, refCache, origins)
|
|
253
|
-
refCache.set(cacheKey, resolved)
|
|
254
|
-
// Stamp the inlined node with where it was defined so a consumer can map a
|
|
255
|
-
// resolved-tree node back to its source document/path. Only objects/arrays are
|
|
256
|
-
// stamped (primitives can't key the map). First-write-wins: resolution recurses
|
|
257
|
-
// to the deepest `$ref` before returning, so the *definition* site stamps first;
|
|
258
|
-
// an outer ref that merely points (transitively) at the same object must not
|
|
259
|
-
// overwrite it with an intermediate location.
|
|
260
|
-
if (origins && resolved !== null && typeof resolved === 'object' && !origins.has(resolved)) {
|
|
261
|
-
origins.set(resolved, { location: targetLocation, pointer: pointerToPath(pointer) })
|
|
262
|
-
}
|
|
263
|
-
return resolved
|
|
264
|
-
}
|
|
265
|
-
const result: Record<string, unknown> = {}
|
|
266
|
-
for (const key of Object.keys(obj)) {
|
|
267
|
-
result[key] = resolveAt(obj[key], baseLocation, docCache, refCache, origins)
|
|
268
|
-
}
|
|
269
|
-
return result
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
/**
|
|
273
|
-
* Resolves `$ref`s in a document on disk (or at a URL), including cross-file
|
|
274
|
-
* and remote refs. Remote documents are fetched on the fly and cached in memory
|
|
275
|
-
* for the session; `options` governs whether/which remote hosts are allowed.
|
|
276
|
-
*/
|
|
277
|
-
export const resolveRefsFromFile = async (filename: string, options: ResolveOptions = {}): Promise<ResolveResult> => {
|
|
278
|
-
const rootLocation = isRemote(filename) ? filename : resolvePath(filename)
|
|
279
|
-
const errors: ResolveError[] = []
|
|
280
|
-
const docCache = new Map<string, unknown>()
|
|
281
|
-
|
|
282
|
-
if (!(await loadDoc(rootLocation, docCache, options, errors))) {
|
|
283
|
-
return { resolved: {}, errors }
|
|
284
|
-
}
|
|
285
|
-
await prefetch(rootLocation, docCache, options, errors)
|
|
286
|
-
const origins: OriginMap | undefined = options.trackOrigins ? new Map() : undefined
|
|
287
|
-
const resolved = resolveAt(docCache.get(rootLocation), rootLocation, docCache, new Map(), origins)
|
|
288
|
-
return origins ? { resolved, errors, origins } : { resolved, errors }
|
|
289
|
-
}
|
package/src/resolve-refs.test.ts
DELETED
|
@@ -1,78 +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
|
-
|
|
51
|
-
it('omits the origin map unless trackOrigins is set', () => {
|
|
52
|
-
const result = resolveRefs({ a: { $ref: '#/$defs/x' }, $defs: { x: { type: 'string' } } })
|
|
53
|
-
expect(result.origins).toBeUndefined()
|
|
54
|
-
})
|
|
55
|
-
|
|
56
|
-
it('stamps each inlined node with its in-document origin path', () => {
|
|
57
|
-
const { resolved, origins } = resolveRefs(
|
|
58
|
-
{
|
|
59
|
-
properties: { a: { $ref: '#/$defs/x' }, b: { $ref: '#/$defs/x' } },
|
|
60
|
-
$defs: { x: { type: 'object', properties: { id: { type: 'string' } } } },
|
|
61
|
-
},
|
|
62
|
-
{ trackOrigins: true },
|
|
63
|
-
)
|
|
64
|
-
const tree = resolved as { properties: { a: object; b: object } }
|
|
65
|
-
// Repeated refs share one object, stamped once with the definition path.
|
|
66
|
-
expect(tree.properties.a).toBe(tree.properties.b)
|
|
67
|
-
expect(origins?.get(tree.properties.a)).toEqual({ location: '', pointer: ['$defs', 'x'] })
|
|
68
|
-
})
|
|
69
|
-
|
|
70
|
-
it('decodes pointer escapes and array indices in origin paths', () => {
|
|
71
|
-
const { resolved, origins } = resolveRefs(
|
|
72
|
-
{ ref: { $ref: '#/a~1b/c~0d/0' }, 'a/b': { 'c~d': [{ type: 'number' }] } },
|
|
73
|
-
{ trackOrigins: true },
|
|
74
|
-
)
|
|
75
|
-
const node = (resolved as { ref: object }).ref
|
|
76
|
-
expect(origins?.get(node)).toEqual({ location: '', pointer: ['a/b', 'c~d', 0] })
|
|
77
|
-
})
|
|
78
|
-
})
|
package/src/resolve-refs.ts
DELETED
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
import { getByPointer, pointerToPath } from './get-by-pointer'
|
|
2
|
-
import type { OriginMap, 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
|
-
/** Options for the in-memory resolver. */
|
|
10
|
-
export type ResolveRefsOptions = {
|
|
11
|
-
/**
|
|
12
|
-
* Record a per-node origin map on the result (`origins`). For every object or
|
|
13
|
-
* array inlined in place of a `$ref`, the map records the in-document path it
|
|
14
|
-
* was defined at (the `location` is `''`, the single in-memory document).
|
|
15
|
-
* Defaults to `false`.
|
|
16
|
-
*/
|
|
17
|
-
trackOrigins?: boolean
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* Single-pass internal-only `$ref` resolver. Each unique ref string is resolved
|
|
22
|
-
* exactly once (the `cache`); revisiting a ref that is still mid-resolution
|
|
23
|
-
* means a cycle, so we return `{}` (the CYCLE sentinel). Non-`#` refs (external
|
|
24
|
-
* files, HTTP) are left untouched — callers that need those should use
|
|
25
|
-
* `resolveRefsFromFile`.
|
|
26
|
-
*/
|
|
27
|
-
const resolveInternal = (
|
|
28
|
-
node: unknown,
|
|
29
|
-
root: unknown,
|
|
30
|
-
cache: Map<string, CacheValue>,
|
|
31
|
-
origins: OriginMap | undefined,
|
|
32
|
-
): unknown => {
|
|
33
|
-
if (node === null || typeof node !== 'object') return node
|
|
34
|
-
if (Array.isArray(node)) return node.map((item) => resolveInternal(item, root, cache, origins))
|
|
35
|
-
|
|
36
|
-
const obj = node as Record<string, unknown>
|
|
37
|
-
if (typeof obj['$ref'] === 'string') {
|
|
38
|
-
const ref = obj['$ref']
|
|
39
|
-
if (!ref.startsWith('#')) return obj // external ref — leave as-is
|
|
40
|
-
if (cache.has(ref)) {
|
|
41
|
-
const cached = cache.get(ref)
|
|
42
|
-
return cached === CYCLE ? {} : cached
|
|
43
|
-
}
|
|
44
|
-
cache.set(ref, CYCLE)
|
|
45
|
-
const resolved = resolveInternal(getByPointer(root, ref.slice(1)), root, cache, origins)
|
|
46
|
-
cache.set(ref, resolved)
|
|
47
|
-
// Stamp the inlined node with the path it was defined at (see resolveAt).
|
|
48
|
-
// First-write-wins so the deepest definition stamps before any outer ref that
|
|
49
|
-
// transitively points at the same object. Primitives can't key the map.
|
|
50
|
-
if (origins && resolved !== null && typeof resolved === 'object' && !origins.has(resolved)) {
|
|
51
|
-
origins.set(resolved, { location: '', pointer: pointerToPath(ref.slice(1)) })
|
|
52
|
-
}
|
|
53
|
-
return resolved
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
const result: Record<string, unknown> = {}
|
|
57
|
-
for (const key of Object.keys(obj)) {
|
|
58
|
-
result[key] = resolveInternal(obj[key], root, cache, origins)
|
|
59
|
-
}
|
|
60
|
-
return result
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* Resolves all internal (`#/...`) `$ref`s in an in-memory document, inlining
|
|
65
|
-
* each target. External and remote refs are left as-is. Cycles are broken with
|
|
66
|
-
* an empty object so the result is always finite.
|
|
67
|
-
*/
|
|
68
|
-
export const resolveRefs = (data: unknown, options: ResolveRefsOptions = {}): ResolveResult => {
|
|
69
|
-
const origins: OriginMap | undefined = options.trackOrigins ? new Map() : undefined
|
|
70
|
-
const resolved = resolveInternal(data, data, new Map(), origins)
|
|
71
|
-
return origins ? { resolved, errors: [], origins } : { resolved, errors: [] }
|
|
72
|
-
}
|