Front Channel API Helpers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Validate that the request is from Front | |
* | |
* Concatenate the request body + timestamp, delimited with a colon. | |
* Take SHA256 HMAC and validate it's equal to the X-Front-Signature | |
* In the Request Header | |
* | |
* In production, we recommend loading Channel Type secret from a configuration file. | |
* | |
* @param {Request} req: Incoming request from Front. | |
* @param {string} channelTypeSecret: Secret Key of your Channel Type. Was given to you when your Channel Type was created. | |
* @returns {boolean} Boolean denoting whether or not request is from Front. | |
*/ | |
function isRequestFromFront(req: Request, channelTypeSecret: string): boolean { | |
const timestamp = req.headers['x-front-request-timestamp']; | |
const rawBody = JSON.stringify(req.body); | |
const baseString = `${timestamp}:${rawBody}`; | |
const hmac = crypto.createHmac('sha256', channelTypeSecret) | |
.update(baseString) | |
.digest('base64'); | |
return hmac === req.headers['x-front-signature']; | |
} | |
/** | |
* Creates a JSON web token | |
* | |
* jwt is your preferred JWT library found at https://jwt.io/ | |
* In production, we recommend loading Channel Type ID and secret from a configuration file. | |
* | |
* @param {string} channelTypeId: ID of your Channel Type. Was given to you when your Channel Type was created. | |
* @param {string} channelTypeSecret: Secret Key of your Channel Type. Was given to you when your Channel Type was created. | |
* @param {number} channelId: Incoming request from Front. | |
* @returns {string} Signed JSON web token | |
*/ | |
function buildToken(channelTypeId: string, channelTypeSecret: string, channelId: number) { | |
// Mark token to expire within 5 seconds for security (small usage window) | |
const exp = Math.floor(new Date().valueOf() / 1000) + 5; | |
// Can be any string, can be used by your system to identify tokens | |
const jsonWebTokenId = 'abc123'; | |
const payload = { | |
iss: channelTypeId, | |
jti: jsonWebTokenId, | |
sub: channelId, | |
exp | |
}; | |
return jwt.sign(payload, channelTypeSecret); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment