UNPKG

cranker-router

Version:
110 lines (88 loc) 3.37 kB
const https = require("https"); const assert = require("assert"); const express = require("express"); const fetch = require("node-fetch"); const connectToRouters = require("cranker-connector"); const crankerRouter = require("./server.js"); const cacerts = require("./cacerts.js"); // This test is a suggestion of a typical hosting scenario for cranker // router; an externally hosted routing address which must be // protected with a certificate from an Internet CA, with an // internally hosted cranker connection address, which must be // protected with a self signed or internal certificate. const test = async function () { // Make a CA and a cert for the router address - fake Internet CA const { caCert, caAttrs, caKeyPair, issue: internetMakeCert } = cacerts.makeCa(); const [privateKeyInPem, publicKeyInPem, csrInPem] = cacerts.makeCsr(); const {cert, ca} = internetMakeCert(publicKeyInPem, csrInPem); // Start the router const routerTlsOpts = { key: privateKeyInPem, cert, ca }; // Make a fake 'internal' CA for the cranker connector address const internalCa = cacerts.makeCa(); const [ internalPrivateKeyInPem, internalPublicKeyInPem, internalCSRInPem ] = cacerts.makeCsr(); const { cert: internalCert, ca: internalCaCert } = internalCa.issue(internalPublicKeyInPem, internalCSRInPem); // Start the router const crankerTlsOpts = { key: internalPrivateKeyInPem, cert: internalCert, ca: internalCaCert }; const caAgent = new https.Agent({ca}); const routerObject = await crankerRouter(0, { routerTlsOpts, crankerTlsOpts }); const routerPort = routerObject.getListener().address().port; const crankerPort = routerObject.getCrankerListener().address().port; // Setup a target server const app = express(); app.get("/test", function (req, res) { res.send("hello world"); }); const targetListener = app.listen(0, function () { console.log("listen", targetListener.address().port); }); const targetPort = targetListener.address().port; // Start the cranker connector to connect to the target const connectors = await connectToRouters( [`localhost:${crankerPort}`], "test", `http://localhost:${targetPort}`, { //_do_untls: true, deferConnect: true, agent: new https.Agent({ca: internalCaCert}) } ); connectors.connect(); // Make the global agent have the ca cert - fetch will use this https.globalAgent = caAgent; // Now make a series of requests to the cranker router let i = 0; for (; i < 10; i++) { const response = await fetch(`https://localhost:${routerPort}/test`) .catch(e => { return { error: e} }); // console.log("response status", response.status); assert(response.status === 200, `cert request /test ${i} was not 200: ${response.error}`); const responseBody = await response.text(); assert(responseBody === "hello world"); } assert(i === 10, `https test failed because iterations didn't reach 10`); connectors.close(); routerObject.close(); targetListener.close(); }; test().then() // End