Skip to content

Commit 203fd89

Browse files
authoredJan 13, 2023
feat!: v1 (#1)
1 parent 1db5dbe commit 203fd89

File tree

6 files changed

+609
-7
lines changed

6 files changed

+609
-7
lines changed
 

‎README.md

+115-2
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,115 @@
1-
# lib_template
2-
Template repository for bootstrap new libraries faster
1+
# fastify-ip
2+
3+
---
4+
5+
`fastify-racing` is a plugin which allows to infer the incoming request's IP based on a custom subset of well known headers used by different providers or technologies that possible sits in-front of your fastify application.
6+
7+
## How it works?
8+
9+
The plugin will make a best-effort to infer the request's IP based on a subset of well-known headers, which looks as follows:
10+
```
11+
'x-client-ip' // Most common
12+
'x-forwarded-for' // Mostly used by proxies
13+
'cf-connecting-ip' // Cloudflare
14+
'Cf-Pseudo-IPv4' // Cloudflare
15+
'fastly-client-ip'
16+
'true-client-ip' // Akamai and Cloudflare
17+
'x-real-ip' // Nginx
18+
'x-cluser-client-ip' // Rackspace LB
19+
'forwarded-for'
20+
'x-forwarded'
21+
'forwarded'
22+
'x-appengine-user-ip' // GCP App Engine
23+
```
24+
25+
The plugin will use a FIFO strategy to infer the right IP. This can be customised by passing a custom order property that includes your custom headers.
26+
27+
>Note: It is important to remark that this does not alters the `Request#ips` behaviour for inferring IPs when setting the `FastifyOptions#trustProxy` to `true`. It rather allows you to infer the IP of a given request by headers out of the common spec or standard.
28+
29+
## Setup
30+
31+
Install by running `npm install fastify-ip`.
32+
33+
Then register the plugin to your fastify instance:
34+
35+
```js
36+
const fastify = require('fastify')({
37+
logger: true
38+
})
39+
40+
fastify.register(require('fastify-racing'), {
41+
order: ['x-my-ip-header'],
42+
strict: false
43+
})
44+
```
45+
46+
### Options
47+
48+
- `order` - `string[] | string` - **optional**: Array of custom headers or single custom header to be appended to the prior list of well-known headers. The headers passed will be prepend to the default headers list. It can also be used to alter the order of the list as deduplication of header names is made while loading the plugin.
49+
50+
- `strict` - `boolean` - **optional**: Indicates whether to override the default list of well-known headers and replace it with the header(s) passed through the `order` option. If set to `true` without `order` property being provided, will not take any effect on the plugin. Default `false`.
51+
52+
53+
### API
54+
55+
The plugin will decorate the Request object with a set of utils that can be handy for managing IPs.
56+
57+
- `isIP(pseudo: string): boolean` - It will return `true` if a given string is a valid IPv4 or IPv6, or `false` otherwise.
58+
- `isIPv4(pseudo: string): boolean` - Similar to `isIP` but will validate of the given string is a valid `IPv4`.
59+
- `isIPv6(pseudo: string): boolean` - Similar to `isIP` but will validate of the given string is a valid `IPv6`.
60+
- `inferIPVersion(pseudo: string): 0 | 4 | 6` - It will try to infer the IPv of a given IP, returning `4` for `IPv4` and `6` for `IPv6`, will return `0` if the given string does not match any of the IPv.
61+
62+
## How to use it?
63+
64+
**JavaScript**
65+
66+
```js
67+
app.get('/', (req, reply) => {
68+
req.log.info({ ip: req.ip }, 'my ip!')
69+
req.log.info({ isValid: req.isIP('hello!') } /* false */)
70+
req.log.info({ isIPv4: req.isIPv4('127.0.0.1') })
71+
req.log.info({ isIPv6: req.isIPv6('::1') })
72+
req.log.info({ version: req.inferIPVersion('127.0.0.1') /* 4 */ })
73+
req.log.info({ version: req.inferIPVersion('::1') /* 6 */ })
74+
req.log.info({ version: req.inferIPVersion('asd') /* 0 */ })
75+
76+
reply.send(req.ip)
77+
})
78+
```
79+
80+
**TypeScript**
81+
82+
```ts
83+
app.post('/', (request: FastifyRequest, reply: FastifyReply) => {
84+
req.log.info({ ip: req.ip }, 'my ip!')
85+
req.log.info({ isValid: req.isIP('hello!') } /* false */)
86+
req.log.info({ isIPv4: req.isIPv4('127.0.0.1') })
87+
req.log.info({ isIPv6: req.isIPv6('::1') })
88+
req.log.info({ version: req.inferIPVersion('127.0.0.1') /* 4 */ })
89+
req.log.info({ version: req.inferIPVersion('::1') /* 6 */ })
90+
req.log.info({ version: req.inferIPVersion('asd') /* 0 */ })
91+
92+
reply.send(req.ip)
93+
});
94+
```
95+
96+
## Type Definitions
97+
98+
```ts
99+
export interface FastifyIPOptions {
100+
order?: string[] | string;
101+
strict?: boolean;
102+
}
103+
104+
declare module 'fastify' {
105+
interface FastifyRequest {
106+
isIP(pseudo: string): boolean;
107+
isIPv4(pseudo: string): boolean;
108+
isIPv6(pseudo: string): boolean;
109+
inferIPVersion(pseudo: string): 0 | 4 | 6;
110+
}
111+
}
112+
```
113+
114+
115+
> See [test](test/index.test.js) for more examples.

‎index.d.ts

+20
Original file line numberDiff line numberDiff line change
@@ -1 +1,21 @@
11
/// <reference types="node" />
2+
import { FastifyPluginCallback } from 'fastify';
3+
4+
export interface FastifyIPOptions {
5+
order?: string[] | string;
6+
strict?: boolean;
7+
}
8+
9+
declare module 'fastify' {
10+
interface FastifyRequest {
11+
isIP(pseudo: string): boolean;
12+
isIPv4(pseudo: string): boolean;
13+
isIPv6(pseudo: string): boolean;
14+
inferIPVersion(pseudo: string): 0 | 4 | 6;
15+
}
16+
}
17+
18+
declare const FastifyIP: FastifyPluginCallback<FastifyIPOptions>;
19+
20+
export default FastifyIP;
21+
export { FastifyIPOptions, FastifyIP };

‎index.js

+79
Original file line numberDiff line numberDiff line change
@@ -1 +1,80 @@
11
'use strict'
2+
const fp = require('fastify-plugin')
3+
const { inferIPVersion, isIP, isIPv4, isIPv6 } = require('./lib/ip')
4+
5+
const plugin = fp(fastifyIp, {
6+
fastify: '4.x',
7+
name: 'fastify-ip'
8+
})
9+
10+
function fastifyIp (instance, options, done) {
11+
const { order: inputOrder, strict } = options
12+
/*! Based on request-ip#https://github.com/pbojinov/request-ip/blob/9501cdf6e73059cc70fc6890adb086348d7cca46/src/index.js.
13+
MIT License. 2022 Petar Bojinov - petarbojinov+github@gmail.com */
14+
// Default headers
15+
/** @type {string[]} */
16+
let headersOrder = [
17+
'x-client-ip', // Most common
18+
'x-forwarded-for', // Mostly used by proxies
19+
'cf-connecting-ip', // Cloudflare
20+
'Cf-Pseudo-IPv4', // Cloudflare
21+
'fastly-client-ip',
22+
'true-client-ip', // Akamai and Cloudflare
23+
'x-real-ip', // Nginx
24+
'x-cluser-client-ip', // Rackspace LB
25+
'forwarded-for',
26+
'x-forwarded',
27+
'forwarded',
28+
'x-appengine-user-ip' // GCP App Engine
29+
]
30+
31+
if (inputOrder != null) {
32+
if (Array.isArray(inputOrder) && inputOrder.length > 0) {
33+
headersOrder = strict
34+
? [].concat(inputOrder)
35+
: [...new Set([].concat(inputOrder, headersOrder))]
36+
} else if (typeof inputOrder === 'string' && inputOrder.length > 0) {
37+
headersOrder = strict ? [inputOrder] : (headersOrder.unshift(inputOrder), headersOrder)
38+
} else {
39+
done(new Error('invalid order option'))
40+
}
41+
}
42+
43+
// Utility methods
44+
instance.decorateRequest('isIP', isIP)
45+
instance.decorateRequest('isIPv4', isIPv4)
46+
instance.decorateRequest('isIPv6', isIPv6)
47+
instance.decorateRequest('inferIPVersion', inferIPVersion)
48+
instance.decorateRequest('_fastifyip', '')
49+
50+
// Core method
51+
instance.decorateRequest('ip', {
52+
getter: function () {
53+
if (this._fastifyip !== '') return this._fastifyip
54+
55+
// AWS Api Gateway + Lambda
56+
if (this.raw.requestContext != null) {
57+
const pseudoIP = this.raw.requestContext.identity?.sourceIp
58+
if (pseudoIP != null && this.isIP(pseudoIP)) {
59+
this._fastifyip = pseudoIP
60+
}
61+
} else {
62+
for (const headerKey of headersOrder) {
63+
const value = this.headers[headerKey]
64+
if (value != null && this.isIP(value)) {
65+
this._fastifyip = value
66+
break
67+
}
68+
}
69+
}
70+
71+
return this._fastifyip
72+
}
73+
})
74+
75+
done()
76+
}
77+
78+
module.exports = plugin
79+
module.exports.default = plugin
80+
module.exports.fastifyIp = plugin

‎lib/ip.js

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*! Based on ip-regex#https://github.com/sindresorhus/ip-regex/blob/main/index.js#LL1-L34.
2+
MIT License. Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) */
3+
const v4 =
4+
'(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}'
5+
6+
const v6segment = '[a-fA-F\\d]{1,4}'
7+
8+
const v6 = `
9+
(?:
10+
(?:${v6segment}:){7}(?:${v6segment}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
11+
(?:${v6segment}:){6}(?:${v4}|:${v6segment}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
12+
(?:${v6segment}:){5}(?::${v4}|(?::${v6segment}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4
13+
(?:${v6segment}:){4}(?:(?::${v6segment}){0,1}:${v4}|(?::${v6segment}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4
14+
(?:${v6segment}:){3}(?:(?::${v6segment}){0,2}:${v4}|(?::${v6segment}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4
15+
(?:${v6segment}:){2}(?:(?::${v6segment}){0,3}:${v4}|(?::${v6segment}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
16+
(?:${v6segment}:){1}(?:(?::${v6segment}){0,4}:${v4}|(?::${v6segment}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
17+
(?::(?:(?::${v6segment}){0,5}:${v4}|(?::${v6segment}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
18+
)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
19+
`
20+
.replace(/\s*\/\/.*$/gm, '')
21+
.replace(/\n/g, '')
22+
.trim()
23+
24+
// Pre-compile only the exact regexes because adding a global flag make regexes stateful
25+
const v46Exact = new RegExp(`(?:^${v4}$)|(?:^${v6}$)`)
26+
const v4Exact = new RegExp(`^${v4}$`)
27+
const v6Exact = new RegExp(`^${v6}$`)
28+
29+
module.exports = {
30+
isIP (ip = '') {
31+
return v46Exact.test(ip)
32+
},
33+
isIPv4 (ip = '') {
34+
return v4Exact.test(ip)
35+
},
36+
isIPv6 (ip = '') {
37+
return v6Exact.test(ip)
38+
},
39+
inferIPVersion (pseudo = '') {
40+
let result = 0
41+
if (this.isIPv4(pseudo)) result = 4
42+
else if (this.isIPv6(pseudo)) result = 6
43+
44+
return result
45+
}
46+
}

‎package.json

+8-5
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
2-
"name": "<lib_name>",
2+
"name": "fastify-ip",
33
"version": "0.0.0",
4-
"description": "<description>",
4+
"description": "Infer the request's IP based on custom headers on Fastify",
55
"main": "index.js",
66
"types": "index.d.ts",
77
"scripts": {
@@ -17,16 +17,18 @@
1717
"keywords": [],
1818
"repository": {
1919
"type": "git",
20-
"url": "git+https://github.com/metcoder95/<lib_name>.git"
20+
"url": "git+https://github.com/metcoder95/fastify-ip.git"
2121
},
22-
"readme": "https://github.com/metcoder95/<lib_name>/blob/main/README.md",
22+
"readme": "https://github.com/metcoder95/fastify-ip/blob/main/README.md",
2323
"bugs": {
24-
"url": "https://github.com/metcoder95/<lib_name>/issues"
24+
"url": "https://github.com/metcoder95/fastify-ip/issues"
2525
},
2626
"author": "metcoder95 <me@metcoder.dev>",
2727
"license": "MIT",
2828
"devDependencies": {
29+
"@faker-js/faker": "^7.6.0",
2930
"@types/node": "^14.17.6",
31+
"fastify": "^4.11.0",
3032
"husky": "^7.0.2",
3133
"snazzy": "^9.0.0",
3234
"standard": "^16.0.3",
@@ -35,6 +37,7 @@
3537
"typescript": "^4.4"
3638
},
3739
"dependencies": {
40+
"fastify-plugin": "^4.4.0"
3841
},
3942
"tsd": {
4043
"directory": "test"

‎test/index.test.js

+341
Original file line numberDiff line numberDiff line change
@@ -1 +1,342 @@
11
'use strict'
2+
const { faker } = require('@faker-js/faker')
3+
const tap = require('tap')
4+
const fastify = require('fastify')
5+
6+
const plugin = require('../')
7+
8+
tap.plan(2)
9+
10+
tap.test('Plugin#Decoration', scope => {
11+
scope.plan(5)
12+
13+
scope.test('Should decorate the request', async t => {
14+
const app = fastify()
15+
16+
app.register(plugin)
17+
18+
app.get('/', (req, reply) => {
19+
t.type(req.isIP, 'function')
20+
t.type(req.isIPv4, 'function')
21+
t.type(req.isIPv6, 'function')
22+
t.type(req.inferIPVersion, 'function')
23+
t.type(req._fastifyip, 'string')
24+
25+
reply.send('')
26+
})
27+
28+
t.plan(5)
29+
30+
await app.inject('/')
31+
})
32+
33+
scope.test('#isIP - Should return boolean', async t => {
34+
const app = fastify()
35+
36+
app.register(plugin)
37+
38+
app.get('/', (req, reply) => {
39+
t.ok(req.isIP(faker.internet.ipv4()))
40+
t.ok(req.isIP(faker.internet.ipv6()))
41+
t.notOk(req.isIP('xyz'))
42+
43+
reply.send('')
44+
})
45+
46+
t.plan(3)
47+
48+
await app.inject({
49+
path: '/'
50+
})
51+
})
52+
53+
scope.test('#isIPv4 - Should return boolean', async t => {
54+
const app = fastify()
55+
56+
app.register(plugin)
57+
58+
app.get('/', (req, reply) => {
59+
t.ok(req.isIPv4(faker.internet.ipv4()))
60+
t.notOk(req.isIPv4(faker.internet.ipv6()))
61+
t.notOk(req.isIPv4('xyz'))
62+
63+
reply.send('')
64+
})
65+
66+
t.plan(3)
67+
68+
await app.inject({
69+
path: '/'
70+
})
71+
})
72+
73+
scope.test('#isIPv6 - Should return boolean IP', async t => {
74+
const app = fastify()
75+
76+
app.register(plugin)
77+
78+
app.get('/', (req, reply) => {
79+
t.ok(req.isIPv6(faker.internet.ipv6()))
80+
t.notOk(req.isIPv6(faker.internet.ipv4()))
81+
t.notOk(req.isIPv6('xyz'))
82+
83+
reply.send('')
84+
})
85+
86+
t.plan(3)
87+
88+
await app.inject({
89+
path: '/'
90+
})
91+
})
92+
93+
scope.test('#inferIPVersion - Should return boolean IP', async t => {
94+
const app = fastify()
95+
96+
app.register(plugin)
97+
98+
app.get('/', (req, reply) => {
99+
t.equal(req.inferIPVersion(faker.internet.ipv6()), 6)
100+
t.equal(req.inferIPVersion(faker.internet.ipv4()), 4)
101+
t.equal(req.inferIPVersion('zsdc'), 0)
102+
103+
reply.send('')
104+
})
105+
106+
t.plan(3)
107+
108+
await app.inject({
109+
path: '/'
110+
})
111+
})
112+
})
113+
114+
tap.test('Plugin#Request IP', scope => {
115+
scope.plan(6)
116+
117+
scope.test('Should infer the header based on default priority', async t => {
118+
const app = fastify()
119+
const expectedIP = faker.internet.ip()
120+
const secondaryIP = faker.internet.ip()
121+
122+
app.register(plugin)
123+
124+
app.get('/', (req, reply) => {
125+
t.equal(req.ip, expectedIP)
126+
t.equal(req._fastifyip, expectedIP)
127+
128+
reply.send('')
129+
})
130+
131+
t.plan(2)
132+
133+
await app.inject({
134+
path: '/',
135+
headers: {
136+
'x-client-ip': expectedIP,
137+
'cf-connecting-ip': secondaryIP
138+
}
139+
})
140+
})
141+
142+
scope.test(
143+
'Should infer the header based on custom priority <Array>',
144+
async t => {
145+
const app = fastify()
146+
const expectedIP = faker.internet.ip()
147+
const fallbackIP = faker.internet.ipv6()
148+
149+
app.register(plugin, { order: ['x-custom-remote-ip'] })
150+
151+
app.get('/', (req, reply) => {
152+
t.equal(req.ip, expectedIP)
153+
t.equal(req._fastifyip, expectedIP)
154+
155+
reply.send('')
156+
})
157+
158+
app.get('/fallback', (req, reply) => {
159+
t.equal(req.ip, fallbackIP)
160+
t.equal(req._fastifyip, fallbackIP)
161+
162+
reply.send('')
163+
})
164+
165+
t.plan(4)
166+
167+
await app.inject({
168+
path: '/',
169+
headers: {
170+
'cf-connecting-ip': fallbackIP,
171+
'x-client-ip': faker.internet.ipv6(),
172+
'x-custom-remote-ip': expectedIP
173+
}
174+
})
175+
176+
await app.inject({
177+
path: '/fallback',
178+
headers: {
179+
'cf-connecting-ip': fallbackIP
180+
}
181+
})
182+
}
183+
)
184+
185+
scope.test(
186+
'Should infer the header based on custom priority <Array> (strict)',
187+
async t => {
188+
const app = fastify()
189+
const expectedIP = faker.internet.ip()
190+
const fallbackIP = faker.internet.ipv6()
191+
192+
app.register(plugin, { order: ['x-custom-remote-ip'], strict: true })
193+
194+
app.get('/', (req, reply) => {
195+
t.equal(req.ip, expectedIP)
196+
t.equal(req._fastifyip, expectedIP)
197+
198+
reply.send('')
199+
})
200+
201+
app.get('/fallback', (req, reply) => {
202+
t.equal(req.ip, '')
203+
t.equal(req._fastifyip, '')
204+
205+
reply.send('')
206+
})
207+
208+
t.plan(4)
209+
210+
await app.inject({
211+
path: '/',
212+
headers: {
213+
'cf-connecting-ip': fallbackIP,
214+
'x-client-ip': faker.internet.ipv6(),
215+
'x-custom-remote-ip': expectedIP
216+
}
217+
})
218+
219+
await app.inject({
220+
path: '/fallback',
221+
headers: {
222+
'x-client-ip': faker.internet.ipv6(),
223+
'cf-connecting-ip': fallbackIP
224+
}
225+
})
226+
}
227+
)
228+
229+
scope.test(
230+
'Should infer the header based on custom priority <String>',
231+
async t => {
232+
const app = fastify()
233+
const expectedIP = faker.internet.ip()
234+
const fallbackIP = faker.internet.ipv6()
235+
236+
app.register(plugin, { order: 'x-custom-remote-ip' })
237+
238+
app.get('/', (req, reply) => {
239+
t.equal(req.ip, expectedIP)
240+
t.equal(req._fastifyip, expectedIP)
241+
242+
reply.send('')
243+
})
244+
245+
app.get('/fallback', (req, reply) => {
246+
t.equal(req.ip, fallbackIP)
247+
t.equal(req._fastifyip, fallbackIP)
248+
249+
reply.send('')
250+
})
251+
252+
t.plan(4)
253+
254+
await app.inject({
255+
path: '/',
256+
headers: {
257+
'cf-connecting-ip': fallbackIP,
258+
'x-client-ip': faker.internet.ipv6(),
259+
'x-custom-remote-ip': expectedIP
260+
}
261+
})
262+
263+
await app.inject({
264+
path: '/fallback',
265+
headers: {
266+
'cf-connecting-ip': fallbackIP
267+
}
268+
})
269+
}
270+
)
271+
272+
scope.test(
273+
'Should infer the header based on custom priority <String> (strict)',
274+
async t => {
275+
const app = fastify()
276+
const expectedIP = faker.internet.ip()
277+
const fallbackIP = faker.internet.ipv6()
278+
279+
app.register(plugin, { order: 'x-custom-remote-ip', strict: true })
280+
281+
app.get('/', (req, reply) => {
282+
t.equal(req.ip, expectedIP)
283+
t.equal(req._fastifyip, expectedIP)
284+
285+
reply.send('')
286+
})
287+
288+
app.get('/fallback', (req, reply) => {
289+
t.equal(req.ip, '')
290+
t.equal(req._fastifyip, '')
291+
292+
reply.send('')
293+
})
294+
295+
t.plan(4)
296+
297+
await app.inject({
298+
path: '/',
299+
headers: {
300+
'cf-connecting-ip': fallbackIP,
301+
'x-client-ip': faker.internet.ipv6(),
302+
'x-custom-remote-ip': expectedIP
303+
}
304+
})
305+
306+
await app.inject({
307+
path: '/fallback',
308+
headers: {
309+
'cf-connecting-ip': fallbackIP
310+
}
311+
})
312+
}
313+
)
314+
315+
scope.test(
316+
'Should discard the IP if invalid format and fallback into the following in the order',
317+
async t => {
318+
const app = fastify()
319+
const expectedIP = faker.internet.ip()
320+
const fallbackIP = 'abc'
321+
322+
app.register(plugin)
323+
324+
app.get('/', (req, reply) => {
325+
t.equal(req.ip, expectedIP)
326+
t.equal(req._fastifyip, expectedIP)
327+
328+
reply.send('')
329+
})
330+
331+
t.plan(2)
332+
333+
await app.inject({
334+
path: '/',
335+
headers: {
336+
'x-appengine-user-ip': expectedIP,
337+
'x-real-ip': fallbackIP
338+
}
339+
})
340+
}
341+
)
342+
})

0 commit comments

Comments
 (0)
Please sign in to comment.