Feat: refactor routes.js express entrypoint config

Feat: express config script refactor

Feat: add state and settingsCache files
This commit is contained in:
Cesar 2021-01-08 16:08:31 +00:00 committed by Josh Harvey
parent c3f8f98c26
commit 85235eaa13
22 changed files with 807 additions and 1 deletions

View file

@ -0,0 +1,19 @@
const pairing = require('../pairing')
const authorize = function (req, res, next) {
const deviceId = req.deviceId
return pairing.isPaired(deviceId)
.then(deviceName => {
if (deviceName) {
req.deviceId = deviceId
req.deviceName = deviceName
return next()
}
return res.status(403).json({ error: 'Forbidden' })
})
.catch(next)
}
module.exports = authorize

12
lib/middlewares/ca.js Normal file
View file

@ -0,0 +1,12 @@
const pairing = require('../pairing')
function ca (req, res) {
console.log("ca")
const token = req.query.token
return pairing.authorizeCaDownload(token)
.then(ca => res.json({ ca }))
.catch(() => res.status(403).json({ error: 'forbidden' }))
}
module.exports = ca

View file

@ -0,0 +1,15 @@
const logger = require('../logger')
function errorHandler (err, req, res, next) {
const statusCode = err.name === 'HTTPError'
? err.code || 500
: 500
const json = { error: err.message }
if (statusCode >= 400) logger.error(err)
return res.status(statusCode).json(json)
}
module.exports = errorHandler

View file

@ -0,0 +1,27 @@
const state = require('./state')
const logger = require('../logger')
const CLOCK_SKEW = 60 * 1000
const REQUEST_TTL = 3 * 60 * 1000
const THROTTLE_CLOCK_SKEW = 60 * 1000
function filterOldRequests (req, res, next) {
const deviceTime = req.deviceTime
const deviceId = req.deviceId
const timestamp = Date.now()
const delta = timestamp - Date.parse(deviceTime)
const shouldTrigger = !state.canLogClockSkewMap[deviceId] ||
timestamp - state.canLogClockSkewMap[deviceId] >= THROTTLE_CLOCK_SKEW
if (delta > CLOCK_SKEW && shouldTrigger) {
state.canLogClockSkewMap[deviceId] = timestamp
logger.error('Clock skew with lamassu-machine[%s] too high [%ss], adjust lamassu-machine clock',
req.deviceName, (delta / 1000).toFixed(2))
}
if (delta > REQUEST_TTL) return res.status(408).json({ error: 'stale' })
next()
}
module.exports = filterOldRequests

20
lib/middlewares/pair.js Normal file
View file

@ -0,0 +1,20 @@
const pairing = require('../pairing')
function pair (req, res, next) {
console.log("pair")
const token = req.query.token
const deviceId = req.deviceId
const model = req.query.model
return pairing.pair(token, deviceId, model)
.then(valid => {
if (valid) {
return res.json({ status: 'paired' })
}
throw httpError('Pairing failed')
})
.catch(next)
}
module.exports = pair

View file

@ -0,0 +1,22 @@
const _ = require('lodash/fp')
function sha256 (buf) {
const crypto = require('crypto')
const hash = crypto.createHash('sha256')
hash.update(buf)
return hash.digest('hex').toString('hex')
}
const populateDeviceId = function (req, res, next) {
const deviceId = _.isFunction(req.connection.getPeerCertificate)
? sha256(req.connection.getPeerCertificate().raw)
: null
req.deviceId = deviceId
req.deviceTime = req.get('date')
next()
}
module.exports = populateDeviceId

View file

@ -0,0 +1,42 @@
const state = require('./state')
const settingsCache = require('./settingsCache')
const newSettingsLoader = require('../new-settings-loader')
const helpers = require('../route-helpers')
const SETTINGS_CACHE_REFRESH = 60 * 60 * 1000
const populateSettings = function (req, res, next) {
const versionId = req.headers['config-version']
if (versionId !== state.oldVersionId) {
state.oldVersionId = versionId
}
// Clear cache every hour
if (Date.now() - settingsCache.getTimestamp() > SETTINGS_CACHE_REFRESH) {
settingsCache.clearCache()
}
if (!versionId && settingsCache.getCache()) {
req.settings = settingsCache.getCache()
return next()
}
if (!versionId && !settingsCache.getCache()) {
return newSettingsLoader.loadLatest()
.then(settings => {
settingsCache.setCache(settings)
settingsCache.setTimestamp(Date.now())
req.settings = settings
})
.then(() => next())
.catch(next)
}
newSettingsLoader.load(versionId)
.then(settings => { req.settings = settings })
.then(() => helpers.updateDeviceConfigVersion(versionId))
.then(() => next())
.catch(next)
}
module.exports = populateSettings

View file

@ -0,0 +1,19 @@
const state = require('./state')
const getTimestamp = () => state.settingsCache.timestamp
const getCache = () => state.settingsCache.cache
const setTimestamp = (newTimestamp) => state.settingsCache.timestamp = newTimestamp
const setCache = (newCache) => state.settingsCache.cache = newCache
const clearCache = () => state.settingsCache.cache = null
module.exports = {
getTimestamp,
getCache,
setTimestamp,
setCache,
clearCache
}

12
lib/middlewares/state.js Normal file
View file

@ -0,0 +1,12 @@
module.exports = function () {
return {
oldVersionId: "unset",
settingsCache: {},
canLogClockSkewMap: {},
canGetLastSeenMap: {},
pids: {},
reboots: {},
shutdowns: {},
restartServicesMap: {}
}
}()