From 8c92f5744cd9585f551e3fd431956e456bf726df Mon Sep 17 00:00:00 2001 From: Fabien 'egg' O'Carroll Date: Wed, 29 Sep 2021 12:01:40 +0200 Subject: [PATCH] Added express-dynamic-redirects module (#337) refs https://github.com/TryGhost/Team/issues/1091 The Offers feature needs to be able to add and remove redirects to Ghost - which is very similar to the custom redirects functionality. Here we've pulled out the core of the dynamic redirect part of custom redirects so that it can be used by both features and have code shared between them. --- ghost/express-dynamic-redirects/.eslintrc.js | 6 + ghost/express-dynamic-redirects/LICENSE | 21 +++ ghost/express-dynamic-redirects/README.md | 34 +++++ ghost/express-dynamic-redirects/index.js | 1 + .../lib/DynamicRedirectManager.js | 144 ++++++++++++++++++ ghost/express-dynamic-redirects/package.json | 31 ++++ .../test/.eslintrc.js | 6 + .../test/DynamicRedirectManager.test.js | 79 ++++++++++ 8 files changed, 322 insertions(+) create mode 100644 ghost/express-dynamic-redirects/.eslintrc.js create mode 100644 ghost/express-dynamic-redirects/LICENSE create mode 100644 ghost/express-dynamic-redirects/README.md create mode 100644 ghost/express-dynamic-redirects/index.js create mode 100644 ghost/express-dynamic-redirects/lib/DynamicRedirectManager.js create mode 100644 ghost/express-dynamic-redirects/package.json create mode 100644 ghost/express-dynamic-redirects/test/.eslintrc.js create mode 100644 ghost/express-dynamic-redirects/test/DynamicRedirectManager.test.js diff --git a/ghost/express-dynamic-redirects/.eslintrc.js b/ghost/express-dynamic-redirects/.eslintrc.js new file mode 100644 index 0000000000..c9c1bcb522 --- /dev/null +++ b/ghost/express-dynamic-redirects/.eslintrc.js @@ -0,0 +1,6 @@ +module.exports = { + plugins: ['ghost'], + extends: [ + 'plugin:ghost/node' + ] +}; diff --git a/ghost/express-dynamic-redirects/LICENSE b/ghost/express-dynamic-redirects/LICENSE new file mode 100644 index 0000000000..366ae5f624 --- /dev/null +++ b/ghost/express-dynamic-redirects/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013-2021 Ghost Foundation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/ghost/express-dynamic-redirects/README.md b/ghost/express-dynamic-redirects/README.md new file mode 100644 index 0000000000..6b132606e1 --- /dev/null +++ b/ghost/express-dynamic-redirects/README.md @@ -0,0 +1,34 @@ +# Express Dynamic Redirects + +## Install + +`npm install @tryghost/express-dynamic-redirects --save` + +or + +`yarn add @tryghost/express-dynamic-redirects` + + +## Usage + + +## Develop + +This is a mono repository, managed with [lerna](https://lernajs.io/). + +Follow the instructions for the top-level repo. +1. `git clone` this repo & `cd` into it as usual +2. Run `yarn` to install top-level dependencies. + + +## Run + +- `yarn dev` + + +## Test + +- `yarn lint` run just eslint +- `yarn test` run lint and tests + + diff --git a/ghost/express-dynamic-redirects/index.js b/ghost/express-dynamic-redirects/index.js new file mode 100644 index 0000000000..9862861fc3 --- /dev/null +++ b/ghost/express-dynamic-redirects/index.js @@ -0,0 +1 @@ +module.exports = require('./lib/DynamicRedirectManager'); diff --git a/ghost/express-dynamic-redirects/lib/DynamicRedirectManager.js b/ghost/express-dynamic-redirects/lib/DynamicRedirectManager.js new file mode 100644 index 0000000000..0ac7f022b7 --- /dev/null +++ b/ghost/express-dynamic-redirects/lib/DynamicRedirectManager.js @@ -0,0 +1,144 @@ +const express = require('express'); +const {parse: parseURL, format: formatURL} = require('url'); +const {parse: parseQuerystring, stringify: formatQuerystring} = require('querystring'); + +class DynamicRedirectManager { + /** + * @param {object} config + * @param {number} config.permanentMaxAge + */ + constructor(config, urlUtils) { + /** @private */ + this.config = config; + /** @private */ + this.urlUtils = urlUtils; + /** @private */ + this.router = express.Router(); + /** @private @type {string[]} */ + this.redirectIds = []; + /** @private @type {Object.} */ + this.redirects = {}; + + this.handleRequest = this.handleRequest.bind(this); + } + + /** + * @private + * @param {string} string + * @returns {RegExp} + */ + buildRegex(string) { + let flags = ''; + + if (string.startsWith('/') && string.endsWith('/i')) { + string = string.slice(1, -2); + flags += 'i'; + } + + if (string.endsWith('/')) { + string = string.slice(0, -1); + } + + if (!string.endsWith('$')) { + string += '/?$'; + } + + return new RegExp(string, flags); + } + + /** + * @private + * @param {string} redirectId + * @returns {void} + */ + setupRedirect(redirectId) { + const {fromRegex, to, options: {permanent}} = this.redirects[redirectId]; + + this.router.get(fromRegex, (req, res) => { + const maxAge = permanent ? this.config.permanentMaxAge : 0; + const toURL = parseURL(to); + const toURLParams = parseQuerystring(toURL.query); + const currentURL = parseURL(req.url); + const currentURLParams = parseQuerystring(currentURL.query); + const params = Object.assign({}, currentURLParams, toURLParams); + const search = formatQuerystring(params); + + toURL.pathname = currentURL.pathname.replace(fromRegex, toURL.pathname); + toURL.search = search !== '' ? `?${search}` : null; + + /** + * Only if the url is internal should we prepend the Ghost subdirectory + * @see https://github.com/TryGhost/Ghost/issues/10776 + */ + if (!toURL.hostname) { + toURL.pathname = this.urlUtils.urlJoin(this.urlUtils.getSubdir(), toURL.pathname); + } + + res.set({ + 'Cache-Control': `public, max-age=${maxAge}` + }); + + res.redirect(permanent ? 301 : 302, formatURL(toURL)); + }); + } + + /** + * @param {string} from + * @param {string} to + * @param {object} options + * @param {boolean} options.permanent + * + * @returns {string} The redirect ID + */ + addRedirect(from, to, options) { + const fromRegex = this.buildRegex(from); + const redirectId = from; + + this.redirectIds.push(redirectId); + this.redirects[redirectId] = { + fromRegex, + to, + options + }; + + this.setupRedirect(redirectId); + + return redirectId; + } + + /** + * @param {string} redirectId + * @returns {void} + */ + removeRedirect(redirectId) { + this.redirectIds.splice(this.redirectIds.indexOf(redirectId), 1); + delete this.redirects[redirectId]; + + this.router = express.Router(); + this.redirectIds.forEach(id => this.setupRedirect(id)); + + return; + } + + /** + * @returns {void} + */ + removeAllRedirects() { + this.redirectIds = []; + this.redirects = {}; + this.router = express.Router(); + } + + /** + * @param {express.Request} req + * @param {express.Response} res + * @param {express.NextFunction} next + * + * @returns {void} + */ + handleRequest(req, res, next) { + this.router(req, res, next); + } +} + +module.exports = DynamicRedirectManager; diff --git a/ghost/express-dynamic-redirects/package.json b/ghost/express-dynamic-redirects/package.json new file mode 100644 index 0000000000..c3dbac2ebf --- /dev/null +++ b/ghost/express-dynamic-redirects/package.json @@ -0,0 +1,31 @@ +{ + "name": "@tryghost/express-dynamic-redirects", + "version": "0.0.0", + "repository": "https://github.com/TryGhost/Members/tree/main/packages/express-dynamic-redirects", + "author": "Ghost Foundation", + "license": "MIT", + "main": "index.js", + "scripts": { + "dev": "echo \"Implement me!\"", + "test": "NODE_ENV=testing c8 --check-coverage mocha './test/**/*.test.js'", + "lint": "eslint . --ext .js --cache", + "posttest": "yarn lint" + }, + "files": [ + "index.js", + "lib" + ], + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "c8": "7.9.0", + "mocha": "9.1.2", + "should": "13.2.3", + "sinon": "11.1.2" + }, + "dependencies": {}, + "peerDependencies": { + "express": "^4.17.1" + } +} diff --git a/ghost/express-dynamic-redirects/test/.eslintrc.js b/ghost/express-dynamic-redirects/test/.eslintrc.js new file mode 100644 index 0000000000..829b601eb0 --- /dev/null +++ b/ghost/express-dynamic-redirects/test/.eslintrc.js @@ -0,0 +1,6 @@ +module.exports = { + plugins: ['ghost'], + extends: [ + 'plugin:ghost/test' + ] +}; diff --git a/ghost/express-dynamic-redirects/test/DynamicRedirectManager.test.js b/ghost/express-dynamic-redirects/test/DynamicRedirectManager.test.js new file mode 100644 index 0000000000..57b65a6fbf --- /dev/null +++ b/ghost/express-dynamic-redirects/test/DynamicRedirectManager.test.js @@ -0,0 +1,79 @@ +const should = require('should'); +const DynamicRedirectManager = require('../'); + +const urlUtils = { + getSubdir() { + return ''; + }, + urlJoin(...parts) { + let url = parts.join('/'); + return url.replace(/(^|[^:])\/\/+/g, '$1/'); + } +}; + +describe('DynamicRedirectManager', function () { + it('Prioritises the query params of the redirect', function () { + const manager = new DynamicRedirectManager({permanentMaxAge: 100}, urlUtils); + + manager.addRedirect('/test-params', '/result?q=abc', {permanent: true}); + + const req = { + method: 'GET', + url: '/test-params/?q=123&lang=js' + }; + + let headers = null; + let status = null; + let location = null; + const res = { + set(_headers) { + headers = _headers; + }, + redirect(_status, _location) { + status = _status; + location = _location; + } + }; + + manager.handleRequest(req, res, function next() { + should.fail(true, false, 'next should not have been called'); + }); + + should.equal(headers['Cache-Control'], 'public, max-age=100'); + should.equal(status, 301); + should.equal(location, '/result?q=abc&lang=js'); + }); + + it('Allows redirects to be removed', function () { + const manager = new DynamicRedirectManager({permanentMaxAge: 100}, urlUtils); + + const id = manager.addRedirect('/test-params', '/result?q=abc', {permanent: true}); + manager.removeRedirect(id); + + const req = { + method: 'GET', + url: '/test-params/?q=123&lang=js' + }; + + let headers = null; + let status = null; + let location = null; + const res = { + set(_headers) { + headers = _headers; + }, + redirect(_status, _location) { + status = _status; + location = _location; + } + }; + + manager.handleRequest(req, res, function next() { + should.ok(true, 'next should have been called'); + }); + + should.equal(headers, null); + should.equal(status, null); + should.equal(location, null); + }); +});