diff --git a/lib/hydro.js b/lib/hydro.js index 6ef062e7e7bc..2f246a09d9b3 100644 --- a/lib/hydro.js +++ b/lib/hydro.js @@ -21,6 +21,13 @@ module.exports = class Hydro { this.schemas = SCHEMAS } + /** + * Can check if it can actually send to Hydro + */ + maySend () { + return Boolean(this.secret && this.endpoint) + } + /** * Generate a SHA256 hash of the payload using the secret * to authenticate with Hydro diff --git a/middleware/index.js b/middleware/index.js index 225abb7c8935..98106e419ce6 100644 --- a/middleware/index.js +++ b/middleware/index.js @@ -16,6 +16,9 @@ module.exports = function (app) { app.use(require('morgan')('dev', { skip: (req, res) => !isDevelopment })) app.use(require('./rate-limit')) if (isDevelopment) app.use(require('./webpack')) + app.use(require('./cookie-parser')) + app.use(require('./req-utils')) + app.use(require('./record-redirect')) app.use(require('./redirects/external')) app.use(require('./redirects/help-to-docs')) app.use(require('./set-fastly-cache-headers')) @@ -24,9 +27,7 @@ module.exports = function (app) { app.use(require('./cors')) app.use(require('./csp')) app.use(require('helmet')()) - app.use(require('./req-utils')) app.use(require('./robots')) - app.use(require('./cookie-parser')) app.use(express.json()) // Must come before ./csrf app.use(require('./csrf')) app.use(require('./handle-csrf-errors')) diff --git a/middleware/record-redirect.js b/middleware/record-redirect.js new file mode 100644 index 000000000000..564f0d37d652 --- /dev/null +++ b/middleware/record-redirect.js @@ -0,0 +1,27 @@ +const { v4: uuidv4 } = require('uuid') +const { inRange } = require('lodash') + +module.exports = function (req, res, next) { + if (!req.hydro.maySend()) return next() + + res.on('finish', async function recordRedirect () { + if (!inRange(res.statusCode, 300, 400)) return + const schemaName = req.hydro.schemas.redirect + const redirectEvent = { + context: { + user: req.cookies['_docs-events'] || uuidv4(), + event_id: uuidv4(), + version: '1.0.0', + created: new Date().toISOString(), + path: req.path, + referrer: req.get('referer') + }, + redirect_from: req.originalUrl, + redirect_to: res.get('location') + } + const hydroRes = await req.hydro.publish(schemaName, redirectEvent) + if (!hydroRes.ok) console.log('Failed to record redirect to Hydro') + }) + + return next() +}