Seal-Middleware: secure your api endpoint by limiting access over period of time

Yusuf Akhsan H.
2 min readMar 28, 2018

--

Components

Seal-Middleware is a javascript library to generate and validate token, the token will be valid based on the specified time period in miliseconds.

Benefits

To explain this, I will give an example below :

In this case, I implemented seal-middleware, for seal validation that client sent to Fire service built using ExpressJS. I have an endpoint like

https://api.com/data/:seal

And user request to url

https://api.com/data/jhkdjf7898

The task of seal-middleware is to validate whether the token seal above is valid. The token will be valid for a few miliseconds only, depending on the configuration of the developer, if the token is invalid, the request also becomes invalid.

How to Use

Instalation

npm install seal-middleware

Generate Seal

import SealMiddleware from 'seal-middleware' //token only valid for 1 minue / 60ms, since created 
const sealmiddleware = new SealMiddleware('your key', 60000)
const seal = sealmiddleware..generateSeal()

Seal validation

import SealMiddleware from 'seal-middleware' //token only valid for 1 minue / 60ms, since created 
const sealmanager = new SealMiddleware('your key', 60000)
const seal = 'dsjfsd6877234' //check is seal valid // is valid will return boolean
const { is_valid } = seal.validate(seal)

Token Formula

Generator

First we need how much miliseconds token will still valid. And app key, booth is required parameters to use Seal-Middleware.

if(typeof window == 'undefined') {
return Buffer.from(this.key + String(Date.now())).toString('base64')
} else {
return (btoa(this.key + String(Date.now()))).replace(/=/g, '')
}

There a to conditions for generate seal, ie for client side and server side. But they all have the same formula, that is, the timestamp is now + app key, then encode to bash64 and be url friendly.

Validator

First we have to get the timestamp stored in the token. I a way decode base64 of seal token, and then remove app key. Then check whether the current timestamp reductions and the token timestamp are greater than the tolerance limit. if smaller then valid, otherwise not.

validate(seal) { 
const diff = Date.now() - this.getTimestampSeal(seal) if(isNaN(diff) || diff >= this.expired)
return { is_valid: false }
else
return { is_valid: true } }

For more info about that code, please check Seal-Middleware Github repo via the link bellow.

Links

Originally published at busy.org on March 28, 2018.

--

--

Yusuf Akhsan H.

if you do not want to do, don’t do. If you want to do, do it effectively and efficiently.