mockttp
Version:
Mock HTTP server for testing HTTP clients and stubbing webservices
53 lines • 2.2 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSocketMetadata = getSocketMetadata;
exports.getSocketMetadataFromProxyAuth = getSocketMetadataFromProxyAuth;
exports.getSocketMetadataTags = getSocketMetadataTags;
const buffer_1 = require("buffer");
const _ = require("lodash");
const socket_extensions_1 = require("./socket-extensions");
const METADATA_USERNAME = 'metadata';
function getSocketMetadata(existingMetadata = undefined, metadataInput) {
const firstChar = buffer_1.Buffer.isBuffer(metadataInput)
? String.fromCharCode(metadataInput[0])
: metadataInput[0];
// Base64'd json always starts with 'e' (typically eyI), so we can use this fairly
// reliably to detect base64 (and to definitively exclude valid object JSON encoding).
const decodedMetadata = firstChar === 'e'
? buffer_1.Buffer.from(metadataInput.toString('utf8'), 'base64url').toString('utf8')
: metadataInput.toString('utf8');
const jsonMetadata = JSON.parse(decodedMetadata);
if (jsonMetadata && typeof jsonMetadata === 'object') {
return _.merge({}, existingMetadata, jsonMetadata);
}
else {
return existingMetadata;
}
}
;
function getSocketMetadataFromProxyAuth(socket, proxyAuth) {
const existingMetadata = socket[socket_extensions_1.SocketMetadata];
if (!proxyAuth)
return existingMetadata;
const [authType, b64AuthValue] = proxyAuth.split(' ', 2);
if (authType !== 'Basic')
return existingMetadata;
const authValue = buffer_1.Buffer.from(b64AuthValue, 'base64').toString('utf8');
const [username] = authValue.split(':', 1);
if (username !== METADATA_USERNAME)
return existingMetadata;
const password = authValue.slice(username.length + 1);
try {
return getSocketMetadata(existingMetadata, password);
}
catch (e) {
// We just ignore unparseable metadata in proxy auth headers
return existingMetadata;
}
}
function getSocketMetadataTags(metadata) {
if (!metadata)
return [];
return (metadata.tags || []).map((tag) => `socket-metadata:${tag}`);
}
//# sourceMappingURL=socket-metadata.js.map