fast-uri 2.4.2 → 2.4.4

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.
@@ -17,6 +17,9 @@ on:
17
17
 
18
18
  jobs:
19
19
  test:
20
+ permissions:
21
+ contents: write
22
+ pull-requests: write
20
23
  uses: fastify/workflows/.github/workflows/plugins-ci.yml@v3
21
24
  with:
22
25
  license-check: true
package/index.js CHANGED
@@ -14,7 +14,12 @@ function normalize (uri, options) {
14
14
 
15
15
  function resolve (baseURI, relativeURI, options) {
16
16
  const schemelessOptions = Object.assign({ scheme: 'null' }, options)
17
- const resolved = resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true)
17
+ const { parsed: baseParsed, malformedAuthorityOrPort: baseMalformed } = parseWithStatus(baseURI, schemelessOptions)
18
+ const { parsed: relativeParsed, malformedAuthorityOrPort: relativeMalformed } = parseWithStatus(relativeURI, schemelessOptions)
19
+ if (baseMalformed || relativeMalformed) {
20
+ throw new Error(baseParsed.error || relativeParsed.error || 'URI is malformed.')
21
+ }
22
+ const resolved = resolveComponents(baseParsed, relativeParsed, schemelessOptions, true)
18
23
  return serialize(resolved, { ...schemelessOptions, skipEscape: true })
19
24
  }
20
25
 
@@ -181,6 +186,19 @@ function nonSimpleDomain (value) {
181
186
 
182
187
  const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u
183
188
 
189
+ // Captures the authority component (between "//" and the next "/", "?" or "#"),
190
+ // with or without a scheme prefix, for the literal-backslash rejection below.
191
+ const AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/
192
+
193
+ // Captures the leading authority-introducer region after an optional scheme: a
194
+ // run of forward slashes, backslashes, and the characters the WHATWG URL parser
195
+ // removes before parsing (TAB U+0009, LF U+000A, CR U+000D). A valid introducer
196
+ // is exactly "//". Node treats "\\" as "/" on special schemes and strips those
197
+ // characters first, so forms like "\\", "/\", "\/", "/<TAB>/", or a leading
198
+ // "<TAB>//" reach an authority in Node while fast-uri's URI_PARSE folds them into
199
+ // the path group (host confusion / SSRF / redirect bypass).
200
+ const AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\t\n\r]*)/
201
+
184
202
  function getParseError (parsed, matches) {
185
203
  if (matches[2] !== undefined && parsed.path && parsed.path[0] !== '/') {
186
204
  return 'URI path must start with "/" when authority is present.'
@@ -209,6 +227,41 @@ function parseWithStatus (uri, opts) {
209
227
  let isIP = false
210
228
  if (options.reference === 'suffix') uri = (options.scheme ? options.scheme + ':' : '') + '//' + uri
211
229
 
230
+ // A literal backslash (U+005C) is not a valid RFC 3986 URI character and is
231
+ // not an authority delimiter. Reject it in the authority rather than
232
+ // rewriting it: normalizing "\" -> "/" (WHATWG error recovery) could silently
233
+ // change the resource identified by an otherwise-invalid input, and lets "\"
234
+ // act as a host delimiter here while Node's native URL parses a different
235
+ // host (SSRF / redirect / origin-allowlist bypass). Percent-encoded %5C is
236
+ // untouched and remains valid encoded data.
237
+ const authorityMatch = uri.match(AUTHORITY_PREFIX)
238
+ if (authorityMatch !== null && authorityMatch[1].indexOf('\\') !== -1) {
239
+ parsed.error = 'URI authority must not contain a literal backslash.'
240
+ malformedAuthorityOrPort = true
241
+ }
242
+
243
+ // Reject a malformed or whitespace-smuggled authority introducer. fast-uri
244
+ // only recognizes a literal "//"; anything else in the leading separator run
245
+ // (a backslash, or a "//" that appears only after removing the TAB/LF/CR that
246
+ // Node strips) means the authority fast-uri parses differs from the one Node's
247
+ // URL resolves. Reject rather than rewrite, mirroring the literal-backslash
248
+ // guard above. Percent-encoded forms (%5C, %09) are untouched, valid data.
249
+ const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION)
250
+ if (introducerMatch !== null) {
251
+ const region = introducerMatch[1]
252
+ const normalizedRegion = region.replace(/[\t\n\r]/g, '')
253
+ // Two or more leading separators introduce an authority.
254
+ if (normalizedRegion.length >= 2) {
255
+ if (normalizedRegion.slice(0, 2) !== '//') {
256
+ parsed.error = parsed.error || 'URI authority must not contain a literal backslash.'
257
+ malformedAuthorityOrPort = true
258
+ } else if (region.length !== normalizedRegion.length) {
259
+ parsed.error = parsed.error || 'URI authority introducer must not contain whitespace.'
260
+ malformedAuthorityOrPort = true
261
+ }
262
+ }
263
+ }
264
+
212
265
  const matches = uri.match(URI_PARSE)
213
266
 
214
267
  if (matches) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "fast-uri",
3
3
  "description": "Dependency free RFC 3986 URI toolbox",
4
- "version": "2.4.2",
4
+ "version": "2.4.4",
5
5
  "main": "index.js",
6
6
  "type": "commonjs",
7
7
  "types": "types/index.d.ts",
@@ -160,3 +160,201 @@ test('parse canonicalises IDN / Unicode hosts to their ASCII form', (t) => {
160
160
  t.equal(parsed.host, expectedHost, `host canonicalised to ASCII: ${description}`)
161
161
  })
162
162
  })
163
+
164
+ test('parse rejects a literal backslash in the authority as malformed (RFC 3986)', (t) => {
165
+ // Regression for the host-confusion bypass: a literal "\" is invalid RFC 3986
166
+ // syntax and must be flagged malformed, not silently rewritten. Otherwise "\"
167
+ // acts as a host delimiter here while Node's native URL parses a different
168
+ // host, defeating a host-based SSRF/redirect/origin allowlist.
169
+ const cases = [
170
+ 'http://evil.com\\@allowed.com',
171
+ 'https://169.254.169.254\\@trusted.example.com',
172
+ 'http://127.0.0.1\\@public.example.com',
173
+ 'https://attacker.com\\@api.internal',
174
+ 'http://a\\@b',
175
+ 'ws://evil.com\\@allowed.com/chat',
176
+ 'wss://evil.com\\@allowed.com/chat',
177
+ 'http://evil.com\\%40allowed.com',
178
+ '//evil.com\\@allowed.com'
179
+ ]
180
+
181
+ t.plan(cases.length)
182
+
183
+ cases.forEach((input) => {
184
+ t.equal(
185
+ fastURI.parse(input).error,
186
+ 'URI authority must not contain a literal backslash.',
187
+ input
188
+ )
189
+ })
190
+ })
191
+
192
+ test('normalize does not canonicalize a literal-backslash URI into a different valid URL', (t) => {
193
+ const cases = [
194
+ 'http://evil.com\\@allowed.com',
195
+ 'https://attacker.com\\@api.internal'
196
+ ]
197
+
198
+ t.plan(cases.length)
199
+
200
+ cases.forEach((input) => {
201
+ t.equal(fastURI.normalize(input), input, input)
202
+ })
203
+ })
204
+
205
+ test('parse leaves percent-encoded %5C untouched as encoded data (not rejected)', (t) => {
206
+ // Only the literal "\" byte is rejected; %5C stays valid encoded data and
207
+ // does not diverge from the native URL parser, so it must not be flagged.
208
+ const input = 'http://evil.com%5C@allowed.com'
209
+ const parsed = fastURI.parse(input)
210
+
211
+ t.plan(2)
212
+ t.notOk(parsed.error, '%5C is valid encoded data, not malformed')
213
+ t.equal(parsed.host, new URL(input).hostname, '%5C host matches native URL (no divergence)')
214
+ })
215
+
216
+ test('parse does not reject a literal backslash in the query or fragment', (t) => {
217
+ // The rejection is scoped to the authority/path (the host-confusion surface);
218
+ // a backslash after "?"/"#" is normalized as encoded data as before.
219
+ const parsed = fastURI.parse('http://host.example.com/?x=\\y#z\\w')
220
+
221
+ t.plan(2)
222
+ t.notOk(parsed.error, 'backslash in query/fragment does not mark the URI malformed')
223
+ t.equal(parsed.host, 'host.example.com', 'host parsed normally')
224
+ })
225
+
226
+ test('parse rejects a malformed authority introducer (\\\\, /\\, \\/) in place of //', (t) => {
227
+ // Regression: "\\", "/\\", "\\/" after the scheme colon are not valid authority
228
+ // introducers. Node's URL treats "\\" as interchangeable with "/" on special
229
+ // schemes, so "http:\\\\evil.com/path" would be parsed as host "evil.com" by
230
+ // Node, but fast-uri must reject it as malformed to prevent SSRF/redirect bypass.
231
+ const cases = [
232
+ 'http:\\\\evil.com/path',
233
+ 'http:/\\evil.com/path',
234
+ 'http:\\/evil.com/path',
235
+ 'ws:\\\\evil.com/chat',
236
+ 'wss:\\\\evil.com/chat',
237
+ 'ftp:\\\\evil.com/',
238
+ '\\\\evil.com/path'
239
+ ]
240
+
241
+ t.plan(cases.length)
242
+
243
+ cases.forEach((input) => {
244
+ t.equal(
245
+ fastURI.parse(input).error,
246
+ 'URI authority must not contain a literal backslash.',
247
+ input
248
+ )
249
+ })
250
+ })
251
+
252
+ test('normalize does not canonicalize a malformed-authority-introducer URI', (t) => {
253
+ const cases = [
254
+ 'http:\\\\evil.com/path',
255
+ 'http:/\\evil.com/path'
256
+ ]
257
+
258
+ t.plan(cases.length)
259
+
260
+ cases.forEach((input) => {
261
+ t.equal(fastURI.normalize(input), input, input)
262
+ })
263
+ })
264
+
265
+ test('equal returns false for malformed-authority-introducer URIs', (t) => {
266
+ const pairs = [
267
+ ['http:\\\\evil.com/path', 'http://evil.com/path'],
268
+ ['http:/\\evil.com/path', 'http://evil.com/path']
269
+ ]
270
+
271
+ t.plan(pairs.length)
272
+
273
+ pairs.forEach(([left, right]) => {
274
+ t.equal(fastURI.equal(left, right), false, `${left} != ${right}`)
275
+ })
276
+ })
277
+
278
+ test('resolve throws on malformed authority introducer', (t) => {
279
+ // resolve() returns a plain string with no error field, so the only safe
280
+ // behavior is to throw when either component has a malformed authority.
281
+ const pairs = [
282
+ ['https://allowed.com/', '\\\\evil.com/path'],
283
+ ['\\\\evil.com/path', 'https://allowed.com/'],
284
+ ['https://allowed.com/', 'http:/\\evil.com/path'],
285
+ ['https://allowed.com/', 'http:\\/evil.com/path']
286
+ ]
287
+
288
+ t.plan(pairs.length)
289
+
290
+ pairs.forEach(([base, rel]) => {
291
+ t.throws(
292
+ () => fastURI.resolve(base, rel),
293
+ /URI authority must not contain a literal backslash/,
294
+ `${base} + ${rel}`
295
+ )
296
+ })
297
+ })
298
+
299
+ test('parse rejects a whitespace-split authority introducer (TAB, LF, CR)', (t) => {
300
+ // The WHATWG URL parser removes TAB (U+0009), LF (U+000A) and CR (U+000D) from
301
+ // the input before parsing, so a stripped character wedged into the introducer
302
+ // ("/<TAB>\\", "/<TAB>/", or a leading "<TAB>//") reaches an authority in Node
303
+ // while fast-uri would otherwise fold it into the path. These must be rejected
304
+ // like the adjacent "\\", "/\\", "\\/" forms.
305
+ const cases = [
306
+ { input: '/\t\\evil.com/path', expectedError: 'URI authority must not contain a literal backslash.' },
307
+ { input: '/\t/evil.com/path', expectedError: 'URI authority introducer must not contain whitespace.' },
308
+ { input: '/\n\\evil.com/path', expectedError: 'URI authority must not contain a literal backslash.' },
309
+ { input: '/\r\\evil.com/path', expectedError: 'URI authority must not contain a literal backslash.' },
310
+ { input: '\t//evil.com/path', expectedError: 'URI authority introducer must not contain whitespace.' },
311
+ { input: '\t/\\evil.com/path', expectedError: 'URI authority must not contain a literal backslash.' },
312
+ { input: 'https:/\t/evil.com/path', expectedError: 'URI authority introducer must not contain whitespace.' }
313
+ ]
314
+
315
+ t.plan(cases.length)
316
+
317
+ cases.forEach(({ input, expectedError }) => {
318
+ t.equal(fastURI.parse(input).error, expectedError, JSON.stringify(input))
319
+ })
320
+ })
321
+
322
+ test('resolve throws on a whitespace-split authority introducer', (t) => {
323
+ const pairs = [
324
+ ['https://allowed.com/', '/\t\\evil.com/path'],
325
+ ['https://allowed.com/', '/\t/evil.com/path'],
326
+ ['https://allowed.com/', '/\n\\evil.com/path'],
327
+ ['/\t/evil.com/path', 'https://allowed.com/']
328
+ ]
329
+
330
+ t.plan(pairs.length)
331
+
332
+ pairs.forEach(([base, rel]) => {
333
+ t.throws(
334
+ () => fastURI.resolve(base, rel),
335
+ /URI authority (must not contain a literal backslash|introducer must not contain whitespace)/,
336
+ `${JSON.stringify(base)} + ${JSON.stringify(rel)}`
337
+ )
338
+ })
339
+ })
340
+
341
+ test('parse does not reject valid authority introducer patterns', (t) => {
342
+ // No false positives: "//" introducer and scheme-less "//" must be valid.
343
+ const cases = [
344
+ 'http://good.com/',
345
+ 'https://good.com/',
346
+ 'ws://good.com/chat',
347
+ 'wss://good.com/chat',
348
+ 'ftp://good.com/',
349
+ '//good.com/path',
350
+ '/absolute/path',
351
+ 'relative/path'
352
+ ]
353
+
354
+ t.plan(cases.length)
355
+
356
+ cases.forEach((input) => {
357
+ const parsed = fastURI.parse(input)
358
+ t.notOk(parsed.error, input)
359
+ })
360
+ })