Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat!: v1 #1

Merged
merged 2 commits into from
Jan 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 115 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,115 @@
# lib_template
Template repository for bootstrap new libraries faster
# fastify-ip

---

`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.

## How it works?

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:
```
'x-client-ip' // Most common
'x-forwarded-for' // Mostly used by proxies
'cf-connecting-ip' // Cloudflare
'Cf-Pseudo-IPv4' // Cloudflare
'fastly-client-ip'
'true-client-ip' // Akamai and Cloudflare
'x-real-ip' // Nginx
'x-cluser-client-ip' // Rackspace LB
'forwarded-for'
'x-forwarded'
'forwarded'
'x-appengine-user-ip' // GCP App Engine
```

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.

>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.

## Setup

Install by running `npm install fastify-ip`.

Then register the plugin to your fastify instance:

```js
const fastify = require('fastify')({
logger: true
})

fastify.register(require('fastify-racing'), {
order: ['x-my-ip-header'],
strict: false
})
```

### Options

- `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.

- `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`.


### API

The plugin will decorate the Request object with a set of utils that can be handy for managing IPs.

- `isIP(pseudo: string): boolean` - It will return `true` if a given string is a valid IPv4 or IPv6, or `false` otherwise.
- `isIPv4(pseudo: string): boolean` - Similar to `isIP` but will validate of the given string is a valid `IPv4`.
- `isIPv6(pseudo: string): boolean` - Similar to `isIP` but will validate of the given string is a valid `IPv6`.
- `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.

## How to use it?

**JavaScript**

```js
app.get('/', (req, reply) => {
req.log.info({ ip: req.ip }, 'my ip!')
req.log.info({ isValid: req.isIP('hello!') } /* false */)
req.log.info({ isIPv4: req.isIPv4('127.0.0.1') })
req.log.info({ isIPv6: req.isIPv6('::1') })
req.log.info({ version: req.inferIPVersion('127.0.0.1') /* 4 */ })
req.log.info({ version: req.inferIPVersion('::1') /* 6 */ })
req.log.info({ version: req.inferIPVersion('asd') /* 0 */ })

reply.send(req.ip)
})
```

**TypeScript**

```ts
app.post('/', (request: FastifyRequest, reply: FastifyReply) => {
req.log.info({ ip: req.ip }, 'my ip!')
req.log.info({ isValid: req.isIP('hello!') } /* false */)
req.log.info({ isIPv4: req.isIPv4('127.0.0.1') })
req.log.info({ isIPv6: req.isIPv6('::1') })
req.log.info({ version: req.inferIPVersion('127.0.0.1') /* 4 */ })
req.log.info({ version: req.inferIPVersion('::1') /* 6 */ })
req.log.info({ version: req.inferIPVersion('asd') /* 0 */ })

reply.send(req.ip)
});
```

## Type Definitions

```ts
export interface FastifyIPOptions {
order?: string[] | string;
strict?: boolean;
}

declare module 'fastify' {
interface FastifyRequest {
isIP(pseudo: string): boolean;
isIPv4(pseudo: string): boolean;
isIPv6(pseudo: string): boolean;
inferIPVersion(pseudo: string): 0 | 4 | 6;
}
}
```


> See [test](test/index.test.js) for more examples.
20 changes: 20 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,21 @@
/// <reference types="node" />
import { FastifyPluginCallback } from 'fastify';

export interface FastifyIPOptions {
order?: string[] | string;
strict?: boolean;
}

declare module 'fastify' {
interface FastifyRequest {
isIP(pseudo: string): boolean;
isIPv4(pseudo: string): boolean;
isIPv6(pseudo: string): boolean;
inferIPVersion(pseudo: string): 0 | 4 | 6;
}
}

declare const FastifyIP: FastifyPluginCallback<FastifyIPOptions>;

export default FastifyIP;
export { FastifyIPOptions, FastifyIP };
79 changes: 79 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1 +1,80 @@
'use strict'
const fp = require('fastify-plugin')
const { inferIPVersion, isIP, isIPv4, isIPv6 } = require('./lib/ip')

const plugin = fp(fastifyIp, {
fastify: '4.x',
name: 'fastify-ip'
})

function fastifyIp (instance, options, done) {
const { order: inputOrder, strict } = options
/*! Based on request-ip#https://github.com/pbojinov/request-ip/blob/9501cdf6e73059cc70fc6890adb086348d7cca46/src/index.js.
MIT License. 2022 Petar Bojinov - [email protected] */
// Default headers
/** @type {string[]} */
let headersOrder = [
'x-client-ip', // Most common
'x-forwarded-for', // Mostly used by proxies
'cf-connecting-ip', // Cloudflare
'Cf-Pseudo-IPv4', // Cloudflare
'fastly-client-ip',
'true-client-ip', // Akamai and Cloudflare
'x-real-ip', // Nginx
'x-cluser-client-ip', // Rackspace LB
'forwarded-for',
'x-forwarded',
'forwarded',
'x-appengine-user-ip' // GCP App Engine
]

if (inputOrder != null) {
if (Array.isArray(inputOrder) && inputOrder.length > 0) {
headersOrder = strict
? [].concat(inputOrder)
: [...new Set([].concat(inputOrder, headersOrder))]
} else if (typeof inputOrder === 'string' && inputOrder.length > 0) {
headersOrder = strict ? [inputOrder] : (headersOrder.unshift(inputOrder), headersOrder)
} else {
done(new Error('invalid order option'))
}
}

// Utility methods
instance.decorateRequest('isIP', isIP)
instance.decorateRequest('isIPv4', isIPv4)
instance.decorateRequest('isIPv6', isIPv6)
instance.decorateRequest('inferIPVersion', inferIPVersion)
instance.decorateRequest('_fastifyip', '')

// Core method
instance.decorateRequest('ip', {
getter: function () {
if (this._fastifyip !== '') return this._fastifyip

// AWS Api Gateway + Lambda
if (this.raw.requestContext != null) {
const pseudoIP = this.raw.requestContext.identity?.sourceIp
if (pseudoIP != null && this.isIP(pseudoIP)) {
this._fastifyip = pseudoIP
}
} else {
for (const headerKey of headersOrder) {
const value = this.headers[headerKey]
if (value != null && this.isIP(value)) {
this._fastifyip = value
break
}
}
}

return this._fastifyip
}
})

done()
}

module.exports = plugin
module.exports.default = plugin
module.exports.fastifyIp = plugin
46 changes: 46 additions & 0 deletions lib/ip.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*! Based on ip-regex#https://github.com/sindresorhus/ip-regex/blob/main/index.js#LL1-L34.
MIT License. Sindre Sorhus <[email protected]> (https://sindresorhus.com) */
const v4 =
'(?: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}'

const v6segment = '[a-fA-F\\d]{1,4}'

const v6 = `
(?:
(?:${v6segment}:){7}(?:${v6segment}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
(?:${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
(?:${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
(?:${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
(?:${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
(?:${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
(?:${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
(?::(?:(?::${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
)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
`
.replace(/\s*\/\/.*$/gm, '')
.replace(/\n/g, '')
.trim()

// Pre-compile only the exact regexes because adding a global flag make regexes stateful
const v46Exact = new RegExp(`(?:^${v4}$)|(?:^${v6}$)`)
const v4Exact = new RegExp(`^${v4}$`)
const v6Exact = new RegExp(`^${v6}$`)

module.exports = {
isIP (ip = '') {
return v46Exact.test(ip)
},
isIPv4 (ip = '') {
return v4Exact.test(ip)
},
isIPv6 (ip = '') {
return v6Exact.test(ip)
},
inferIPVersion (pseudo = '') {
let result = 0
if (this.isIPv4(pseudo)) result = 4
else if (this.isIPv6(pseudo)) result = 6

return result
}
}
13 changes: 8 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "<lib_name>",
"name": "fastify-ip",
"version": "0.0.0",
"description": "<description>",
"description": "Infer the request's IP based on custom headers on Fastify",
"main": "index.js",
"types": "index.d.ts",
"scripts": {
Expand All @@ -17,16 +17,18 @@
"keywords": [],
"repository": {
"type": "git",
"url": "git+https://github.com/metcoder95/<lib_name>.git"
"url": "git+https://github.com/metcoder95/fastify-ip.git"
},
"readme": "https://github.com/metcoder95/<lib_name>/blob/main/README.md",
"readme": "https://github.com/metcoder95/fastify-ip/blob/main/README.md",
"bugs": {
"url": "https://github.com/metcoder95/<lib_name>/issues"
"url": "https://github.com/metcoder95/fastify-ip/issues"
},
"author": "metcoder95 <[email protected]>",
"license": "MIT",
"devDependencies": {
"@faker-js/faker": "^7.6.0",
"@types/node": "^14.17.6",
"fastify": "^4.11.0",
"husky": "^7.0.2",
"snazzy": "^9.0.0",
"standard": "^16.0.3",
Expand All @@ -35,6 +37,7 @@
"typescript": "^4.4"
},
"dependencies": {
"fastify-plugin": "^4.4.0"
},
"tsd": {
"directory": "test"
Expand Down
Loading