kane-internal-token
v0.2.1
Published
Koa middleware to restrict access to internal APIs using a shared secret
Downloads
3
Maintainers
Readme
Kane Internal Token
This is a simple Koa middleware which only purpose is to intercept the request to see if it was coming from another internal API.
Requirements
You need to execute node
version 6
at least.
Installation
# npm
npm install --save kane-internal-token
# yarn
yarn add kane-internal-token
Usage
This package will look for a variable that contains the shared secret in the following order:
- the
request.header
object (by defaultx-internal-token
) - the
request.query
object (by defaultINTERNAL_TOKEN
)
It will then use the found value and compare it with the local variable (named INTERNAL_TOKEN
by default) stored as an environment variable (remember that this value must be protected and never stored on a public or unsafe location).
const Koa = require("koa");
const {internalToken} = require("kane-internal-token");
const app = new Koa();
app.use(internalToken());
This will add the boolean "isInternal" in production only (using NODE_ENV
)
indicating if the shared secret is matched:
if (ctx.state.isInternal) {
// do stuff
}
By default if both tokens mismatch an error response is returned. You can prevent that using the options
parameter:
// check the `defaults` object in index.js
const opts = {
wrongTokenAsError: false
};
app.use(internalToken(opts));
There's also an utility function to retrieve the token value as an header object to pass on a request to an internal API:
// it could be any HTTP client
const axios = require("axios");
const {internalHeader} = require("kane-internal-token");
const header = internalHeader();
const instance = axios.create({
baseURL: "https://internal-api.example.com/",
headers: header
});
Linting
Made using eslint
. To enforce rules to be applied, use yarn lint:fix
.
Testing
Invoke yarn test
.
Contributing
First, install the dependencies using yarn
:
yarn install --frozen-lockfile
Verify that your project is configured correctly by launching tests:
yarn test
Before you start coding make sure that you've read our CONTRIBUTING
guide!