forked from simonefonda/yakbak
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
185 lines (150 loc) · 6.04 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
// Copyright 2016 Yahoo Inc.
// Licensed under the terms of the MIT license. Please see LICENSE file in the project root for terms.
var Promise = require('bluebird');
var hash = require('incoming-message-hash');
var assert = require('assert');
var mkdirp = require('mkdirp');
var path = require('path');
var buffer = require('./lib/buffer');
var proxy = require('./lib/proxy');
var record = require('./lib/record');
var curl = require('./lib/curl');
var debug = require('debug')('yakbak:server');
var fs = require('fs');
const parseCookie = str =>
str
.split(';')
.map(v => v.split('='))
.reduce((acc, v) => {
acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());
return acc;
}, {});
/**
* Returns a new yakbak proxy middleware.
* @param {String} host The hostname to proxy to
* @param {Object} opts
* @param {String} opts.dirname The tapes directory
* @param {Boolean} opts.noRecord if true, requests will return a 404 error if the tape doesn't exist
* @param {Boolean} opts.verbose if true, tapes comments will contain request and response body (might get large!)
* @returns {Function}
*/
module.exports = function (host, opts) {
assert(opts.dirname, 'You must provide opts.dirname');
if (opts.verbose) {
debug('Verbose mode active');
}
let defaultNamespace = '',
globalCurrentNamespace = defaultNamespace,
namespaceStats = {'': {errors: [], used: [], orphans: []}};
return function (req, res) {
let currentNamespace = globalCurrentNamespace;
mkdirp.sync(opts.dirname);
return buffer(req).then(function (body) {
var parsedUrl = new URL(req.url, `http://${req.headers.host}`);
if (parsedUrl.pathname === '/yakbak/set-namespace/') {
if (parsedUrl.searchParams.get('namespace') == null) {
debug('Trying to set namespace with no namespace parameter', parsedUrl.searchParams);
throw new NamespaceMethodError('No namespace given. Pass `?namespace=something` to set one.');
}
currentNamespace = parsedUrl.searchParams.get('namespace');
namespaceStats[currentNamespace] = {errors: [], used: [], orphans: []};
debug(`Set namespace to: ${currentNamespace}`);
globalCurrentNamespace = currentNamespace;
throw new NamespaceMethodSuccess(`Namespace set to: ${currentNamespace}`);
} else if (parsedUrl.pathname === '/yakbak/reset-namespace/') {
debug(`Reset namespace to default`);
var previousNamespace = currentNamespace;
currentNamespace = defaultNamespace;
var dirName = path.join(opts.dirname, previousNamespace);
if (fs.existsSync(dirName)) {
fs.readdirSync(dirName).forEach(file => {
if (!namespaceStats[previousNamespace].used.includes(file)) {
namespaceStats[previousNamespace].orphans.push(file);
}
});
}
globalCurrentNamespace = currentNamespace;
throw new NamespaceMethodSuccess(JSON.stringify(namespaceStats[previousNamespace]));
}
// Overwriting the host so the tapename() function will return a stable hashname ignoring the host used
// in the original request. It might be different between local development and ci envs.
req.headers['host'] = 'un-qualsiasi-host';
if (req.headers.cookie?.includes('namespace=')) {
currentNamespace = parseCookie(req.headers.cookie).namespace
namespaceStats[currentNamespace] = {errors: [], used: [], orphans: []};
delete req.headers.cookie //= req.headers.cookie.replace(`namespace=${currentNamespace}`, '')
}
var file = path.join(opts.dirname, currentNamespace, tapename(req, body));
debug('req / file:', req.url, file);
return Promise.try(function () {
return require.resolve(file);
}).catch(ModuleNotFoundError, function (/* err */) {
if (opts.noRecord) {
/* eslint-disable no-console */
console.log(`[${host}] An HTTP request has been made that yakbak does not know how to handle: `);
console.log(`[${host}] namespace: ${currentNamespace}`);
console.log(`[${host}] requested url: ${req.url}`);
console.log(curl.request(req, body));
namespaceStats[currentNamespace].errors.push(req.url);
/* eslint-enable no-console */
throw new RecordingDisabledError('Recording Disabled');
} else {
return proxy(req, body, host).then(function (pres) {
return record(pres.req, body, pres, file, opts.verbose, currentNamespace);
});
}
});
}).then(function (file) {
namespaceStats[currentNamespace].used.push(path.basename(file));
return require(file);
}).then(function (tape) {
return tape(req, res);
}).catch(RecordingDisabledError, function (err) {
res.statusCode = err.status;
res.end(err.message);
}).catch(NamespaceMethodError, function (err) {
res.statusCode = err.status;
res.end(err.message);
}).catch(NamespaceMethodSuccess, function (msg) {
msg.statusCode = msg.status;
res.end(msg.message);
});
};
};
/**
* Returns the tape name for 'req`.
* @param {http.IncomingMessage} req
* @param {Array.<Buffer>} body
* @returns {String}
*/
function tapename(req, body) {
return hash.sync(req, Buffer.concat(body)) + '.js';
}
/**
* Bluebird error predicate for matching module not found errors.
* @param {Error} err
* @returns {Boolean}
*/
function ModuleNotFoundError(err) {
return err.code === 'MODULE_NOT_FOUND';
}
/**
* Error class that is thrown when an unmatched request
* is encountered in noRecord mode
* @constructor
*/
function RecordingDisabledError(message) {
this.message = message;
this.status = 404;
}
RecordingDisabledError.prototype = Object.create(Error.prototype);
function NamespaceMethodSuccess(message) {
this.message = message;
this.status = 200;
}
function NamespaceMethodError(message) {
this.message = message;
this.status = 400;
}
NamespaceMethodSuccess.prototype = Object.create(Error.prototype);
NamespaceMethodError.prototype = Object.create(Error.prototype);