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.
This commit is contained in:
Fabien 'egg' O'Carroll 2021-09-29 12:01:40 +02:00 committed by GitHub
parent dad54a25b1
commit 8c92f5744c
8 changed files with 322 additions and 0 deletions

View File

@ -0,0 +1,6 @@
module.exports = {
plugins: ['ghost'],
extends: [
'plugin:ghost/node'
]
};

View File

@ -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.

View File

@ -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

View File

@ -0,0 +1 @@
module.exports = require('./lib/DynamicRedirectManager');

View File

@ -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.<string, {fromRegex: RegExp, to: string, options: {permanent: boolean}}>} */
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;

View File

@ -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"
}
}

View File

@ -0,0 +1,6 @@
module.exports = {
plugins: ['ghost'],
extends: [
'plugin:ghost/test'
]
};

View File

@ -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);
});
});