Compare commits

...

22 Commits

Author SHA1 Message Date
da060fa986 2.0.4 2021-02-02 15:55:26 +00:00
df001e13f3 fix(core): update 2021-02-02 15:55:25 +00:00
ef7e54be34 2.0.3 2021-02-02 00:53:58 +00:00
d800b6ed6e fix(core): update 2021-02-02 00:53:57 +00:00
af42598464 2.0.2 2020-02-23 19:04:53 +00:00
93b1048cb7 fix(core): update 2020-02-23 19:04:53 +00:00
29549b126e 2.0.1 2020-02-23 19:03:26 +00:00
736113eb4e fix(core): update 2020-02-23 19:03:25 +00:00
3b2d140836 2.0.0 2020-02-07 19:36:13 +00:00
70690f6400 BREAKING CHANGE(API): updateReversConfigs -> updateReverseConfigs 2020-02-07 19:36:12 +00:00
ae561e3e88 1.0.38 2020-02-07 16:06:12 +00:00
8a02a0c506 fix(core): update 2020-02-07 16:06:11 +00:00
58ec01526a 1.0.37 2020-02-07 13:04:12 +00:00
1c3619040c fix(core): update 2020-02-07 13:04:11 +00:00
0eabdcde28 1.0.36 2020-02-07 12:43:38 +00:00
3f935b3a03 fix(core): update 2020-02-07 12:43:37 +00:00
c7b8b6ff66 1.0.35 2019-11-03 03:06:56 +01:00
a9815c61d2 fix(core): update 2019-11-03 03:06:56 +01:00
82730877ce 1.0.34 2019-11-03 03:05:49 +01:00
b68b143a3f fix(core): update 2019-11-03 03:05:49 +01:00
3e7416574d 1.0.33 2019-11-03 03:04:23 +01:00
7f843bef50 fix(core): update 2019-11-03 03:04:23 +01:00
13 changed files with 10512 additions and 1094 deletions

4
.gitignore vendored
View File

@ -15,8 +15,6 @@ node_modules/
# builds # builds
dist/ dist/
dist_web/ dist_*/
dist_serve/
dist_ts_web/
# custom # custom

View File

@ -1,18 +1,16 @@
# gitzone ci_default # gitzone ci_default
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
variables:
GIT_STRATEGY: clone
cache: cache:
paths: paths:
- .npmci_cache/ - .npmci_cache/
key: "$CI_BUILD_STAGE" key: '$CI_BUILD_STAGE'
stages: stages:
- security - security
- test - test
- release - release
- metadata - metadata
# ==================== # ====================
# security stage # security stage
@ -20,21 +18,36 @@ stages:
mirror: mirror:
stage: security stage: security
script: script:
- npmci git mirror - npmci git mirror
only:
- tags
tags: tags:
- docker - lossless
- notpriv - docker
- notpriv
snyk: auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security stage: security
script: script:
- npmci npm prepare - npmci npm prepare
- npmci command npm install -g snyk - npmci command npm install --production --ignore-scripts
- npmci command npm install --ignore-scripts - npmci command npm config set registry https://registry.npmjs.org
- npmci command snyk test - npmci command npm audit --audit-level=high --only=prod --production
tags: tags:
- docker - docker
- notpriv
auditDevDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=dev
tags:
- docker
allow_failure: true
# ==================== # ====================
# test stage # test stage
@ -43,37 +56,36 @@ snyk:
testStable: testStable:
stage: test stage: test
script: script:
- npmci npm prepare - npmci npm prepare
- npmci node install stable - npmci node install stable
- npmci npm install - npmci npm install
- npmci npm test - npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/ coverage: /\d+.?\d+?\%\s*coverage/
tags: tags:
- docker - docker
- priv
testBuild: testBuild:
stage: test stage: test
script: script:
- npmci npm prepare - npmci npm prepare
- npmci node install lts - npmci node install stable
- npmci npm install - npmci npm install
- npmci command npm run build - npmci command npm run build
coverage: /\d+.?\d+?\%\s*coverage/ coverage: /\d+.?\d+?\%\s*coverage/
tags: tags:
- docker - docker
- notpriv
release: release:
stage: release stage: release
script: script:
- npmci node install lts - npmci node install stable
- npmci npm publish - npmci npm publish
only: only:
- tags - tags
tags: tags:
- docker - lossless
- notpriv - docker
- notpriv
# ==================== # ====================
# metadata stage # metadata stage
@ -81,35 +93,39 @@ release:
codequality: codequality:
stage: metadata stage: metadata
allow_failure: true allow_failure: true
only:
- tags
script: script:
- npmci command npm install -g tslint typescript - npmci command npm install -g tslint typescript
- npmci npm prepare
- npmci npm install - npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts" - npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags: tags:
- docker - lossless
- priv - docker
- priv
trigger: trigger:
stage: metadata stage: metadata
script: script:
- npmci trigger - npmci trigger
only: only:
- tags - tags
tags: tags:
- docker - lossless
- notpriv - docker
- notpriv
pages: pages:
image: hosttoday/ht-docker-dbase:npmci
services:
- docker:18-dind
stage: metadata stage: metadata
script: script:
- npmci node install lts
- npmci command npm install -g @gitzone/tsdoc - npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare - npmci npm prepare
- npmci npm install - npmci npm install
- npmci command tsdoc - npmci command tsdoc
tags: tags:
- lossless
- docker - docker
- notpriv - notpriv
only: only:
@ -117,5 +133,5 @@ pages:
artifacts: artifacts:
expire_in: 1 week expire_in: 1 week
paths: paths:
- public - public
allow_failure: true allow_failure: true

26
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,26 @@
{
"json.schemas": [
{
"fileMatch": ["/npmextra.json"],
"schema": {
"type": "object",
"properties": {
"npmci": {
"type": "object",
"description": "settings for npmci"
},
"gitzone": {
"type": "object",
"description": "settings for gitzone",
"properties": {
"projectType": {
"type": "string",
"enum": ["website", "element", "service", "npm", "wcc"]
}
}
}
}
}
}
]
}

View File

@ -1,5 +1,6 @@
{ {
"gitzone": { "gitzone": {
"projectType": "npm",
"module": { "module": {
"githost": "gitlab.com", "githost": "gitlab.com",
"gitscope": "pushrocks", "gitscope": "pushrocks",

11140
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,10 +1,10 @@
{ {
"name": "@pushrocks/smartproxy", "name": "@pushrocks/smartproxy",
"version": "1.0.32", "version": "2.0.4",
"private": false, "private": false,
"description": "a proxy for handling high workloads of proxying", "description": "a proxy for handling high workloads of proxying",
"main": "dist/index.js", "main": "dist_ts/index.js",
"typings": "dist/index.d.ts", "typings": "dist_ts/index.d.ts",
"author": "Lossless GmbH", "author": "Lossless GmbH",
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
@ -13,33 +13,38 @@
"format": "(gitzone format)" "format": "(gitzone format)"
}, },
"devDependencies": { "devDependencies": {
"@gitzone/tsbuild": "^2.1.17", "@gitzone/tsbuild": "^2.1.25",
"@gitzone/tstest": "^1.0.15", "@gitzone/tstest": "^1.0.52",
"@pushrocks/tapbundle": "^3.0.13", "@pushrocks/tapbundle": "^3.2.10",
"@types/node": "^12.7.8", "@types/node": "^14.14.22",
"tslint": "^5.20.0", "tslint": "^6.1.3",
"tslint-config-prettier": "^1.15.0" "tslint-config-prettier": "^1.15.0"
}, },
"dependencies": { "dependencies": {
"@pushrocks/lik": "^3.0.11", "@pushrocks/lik": "^4.0.20",
"@pushrocks/smartnetwork": "^1.1.14", "@pushrocks/smartnetwork": "^1.1.22",
"@pushrocks/smartpromise": "^3.0.5", "@pushrocks/smartpromise": "^3.1.3",
"@pushrocks/smartrequest": "^1.1.35", "@pushrocks/smartrequest": "^1.1.51",
"@pushrocks/smartspawn": "^2.0.9", "@pushrocks/smartspawn": "^2.0.9",
"@pushrocks/smartstring": "^3.0.24",
"@pushrocks/smartsystem": "^2.0.9", "@pushrocks/smartsystem": "^2.0.9",
"@tsclass/tsclass": "^2.0.6", "@tsclass/tsclass": "^3.0.29",
"@types/ws": "^6.0.3", "@types/ws": "^7.4.0",
"ws": "^7.1.2" "ws": "^7.4.2"
}, },
"files": [ "files": [
"ts/*", "ts/**/*",
"ts_web/*", "ts_web/**/*",
"dist/*", "dist/**/*",
"dist_web/*", "dist_*/**/*",
"dist_ts_web/*", "dist_ts/**/*",
"assets/*", "dist_ts_web/**/*",
"assets/**/*",
"cli.js", "cli.js",
"npmextra.json", "npmextra.json",
"readme.md" "readme.md"
],
"browserslist": [
"last 1 chrome versions"
] ]
} }

View File

@ -8,16 +8,31 @@ a proxy for handling high workloads of proxying
* [docs (typedoc)](https://pushrocks.gitlab.io/smartproxy/) * [docs (typedoc)](https://pushrocks.gitlab.io/smartproxy/)
## Status for master ## Status for master
[![build status](https://gitlab.com/pushrocks/smartproxy/badges/master/build.svg)](https://gitlab.com/pushrocks/smartproxy/commits/master)
[![coverage report](https://gitlab.com/pushrocks/smartproxy/badges/master/coverage.svg)](https://gitlab.com/pushrocks/smartproxy/commits/master) Status Category | Status Badge
[![npm downloads per month](https://img.shields.io/npm/dm/@pushrocks/smartproxy.svg)](https://www.npmjs.com/package/@pushrocks/smartproxy) -- | --
[![Known Vulnerabilities](https://snyk.io/test/npm/@pushrocks/smartproxy/badge.svg)](https://snyk.io/test/npm/@pushrocks/smartproxy) GitLab Pipelines | [![pipeline status](https://gitlab.com/pushrocks/smartproxy/badges/master/pipeline.svg)](https://lossless.cloud)
[![TypeScript](https://img.shields.io/badge/TypeScript->=%203.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/) GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/pushrocks/smartproxy/badges/master/coverage.svg)](https://lossless.cloud)
[![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/) npm | [![npm downloads per month](https://badgen.net/npm/dy/@pushrocks/smartproxy)](https://lossless.cloud)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-prettier-ff69b4.svg)](https://prettier.io/) Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/pushrocks/smartproxy)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@pushrocks/smartproxy)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@pushrocks/smartproxy)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@pushrocks/smartproxy)](https://lossless.cloud)
Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](https://lossless.cloud)
## Usage ## Usage
## Contribution
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
## Contribution
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
For further information read the linked docs at the top of this readme. For further information read the linked docs at the top of this readme.
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh) > MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)

View File

@ -4,7 +4,7 @@ import * as smartproxy from '../ts/index';
let testProxy: smartproxy.SmartProxy; let testProxy: smartproxy.SmartProxy;
tap.test('first test', async () => { tap.test('first test', async () => {
testProxy = new smartproxy.SmartProxy(); testProxy = new smartproxy.SmartProxy({});
}); });
tap.test('should start the testproxy', async () => { tap.test('should start the testproxy', async () => {
@ -12,11 +12,12 @@ tap.test('should start the testproxy', async () => {
}); });
tap.test('should supply reverse proxy config', async () => { tap.test('should supply reverse proxy config', async () => {
testProxy.updateReversConfigs([{ testProxy.updateReverseConfigs([
destinationIp: 'localhost', {
destinationPort: '3000', destinationIp: 'localhost',
hostName: 'central.eu', destinationPort: '3000',
privateKey: `-----BEGIN PRIVATE KEY----- hostName: 'push.rocks',
privateKey: `-----BEGIN PRIVATE KEY-----
MIIJRQIBADANBgkqhkiG9w0BAQEFAASCCS8wggkrAgEAAoICAQDi2F/0kQr96mhe MIIJRQIBADANBgkqhkiG9w0BAQEFAASCCS8wggkrAgEAAoICAQDi2F/0kQr96mhe
3yEWvy2mRHOZoSSBtIqg6Bre4ZcMu901/cHNIjFnynNGFl9Se61yZbW2F3PfCt7+ 3yEWvy2mRHOZoSSBtIqg6Bre4ZcMu901/cHNIjFnynNGFl9Se61yZbW2F3PfCt7+
kQlHug1Cx+LFssvz+hLlB5cqJQZfRKx92DhbROygtxG9r7UBmx/fwx+JQ+HOHX9R kQlHug1Cx+LFssvz+hLlB5cqJQZfRKx92DhbROygtxG9r7UBmx/fwx+JQ+HOHX9R
@ -69,7 +70,7 @@ h+7fBVO49PLL0NWy+8GT8y7a04calFfLvZEA2UMaunBis3dE1KMFfJL/0JO+sKnF
2TkK01XDDJURK5Lhuvc7WrK2rSJ/fK+0GA== 2TkK01XDDJURK5Lhuvc7WrK2rSJ/fK+0GA==
-----END PRIVATE KEY----- -----END PRIVATE KEY-----
`, `,
publicKey: `-----BEGIN CERTIFICATE----- publicKey: `-----BEGIN CERTIFICATE-----
MIIEljCCAn4CCQDY+ZbC9FASVjANBgkqhkiG9w0BAQsFADANMQswCQYDVQQGEwJE MIIEljCCAn4CCQDY+ZbC9FASVjANBgkqhkiG9w0BAQsFADANMQswCQYDVQQGEwJE
RTAeFw0xOTA5MjAxNjAxNDRaFw0yMDA5MTkxNjAxNDRaMA0xCzAJBgNVBAYTAkRF RTAeFw0xOTA5MjAxNjAxNDRaFw0yMDA5MTkxNjAxNDRaMA0xCzAJBgNVBAYTAkRF
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA4thf9JEK/epoXt8hFr8t MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA4thf9JEK/epoXt8hFr8t
@ -96,12 +97,13 @@ TzJTbTCteOUUJTrcfZ0gGhGkF4nYLmX5OI+TPqrDJf0fZ+mzAEHzDDVXcBYpYRDr
r8d9QwrK+WaqVi2ofbMfMByVF72jgeJNa4nxwT9bVbu/Q1T2Lt+YPb4pQ7yCoUgS r8d9QwrK+WaqVi2ofbMfMByVF72jgeJNa4nxwT9bVbu/Q1T2Lt+YPb4pQ7yCoUgS
JNj2Dr5H0XoLFFnvuvzcRbhlJ9J67JzR+7g= JNj2Dr5H0XoLFFnvuvzcRbhlJ9J67JzR+7g=
-----END CERTIFICATE----- -----END CERTIFICATE-----
` `,
}]); },
]);
}); });
tap.test('should wait for 60 seconds', async tools => { tap.test('should wait for 60 seconds', async (tools) => {
await tools.delayFor(60000); await tools.delayFor(10000);
}); });
tap.test('should close the testproxy', async () => { tap.test('should close the testproxy', async () => {

View File

@ -7,14 +7,21 @@ export class ProxyWorker {
public httpsServer: plugins.https.Server; // | plugins.http.Server; public httpsServer: plugins.https.Server; // | plugins.http.Server;
public port = 8001; public port = 8001;
public router = new SmartproxyRouter(); public router = new SmartproxyRouter();
public socketMap = new plugins.lik.Objectmap<plugins.net.Socket>(); public socketMap = new plugins.lik.ObjectMap<plugins.net.Socket>();
/** /**
* starts the proxyInstance * starts the proxyInstance
*/ */
public async start() { public async start() {
this.httpsServer = plugins.https.createServer({ this.httpsServer = plugins.https.createServer(
key: `-----BEGIN PRIVATE KEY----- // ================
// Spotted this keypair in the code?
// Don't get exited:
// It is an invalid default keypair.
// For proper requests custom domain level keypairs are used that are provided in the reverse config
// ================
{
key: `-----BEGIN PRIVATE KEY-----
MIIJRQIBADANBgkqhkiG9w0BAQEFAASCCS8wggkrAgEAAoICAQDi2F/0kQr96mhe MIIJRQIBADANBgkqhkiG9w0BAQEFAASCCS8wggkrAgEAAoICAQDi2F/0kQr96mhe
3yEWvy2mRHOZoSSBtIqg6Bre4ZcMu901/cHNIjFnynNGFl9Se61yZbW2F3PfCt7+ 3yEWvy2mRHOZoSSBtIqg6Bre4ZcMu901/cHNIjFnynNGFl9Se61yZbW2F3PfCt7+
kQlHug1Cx+LFssvz+hLlB5cqJQZfRKx92DhbROygtxG9r7UBmx/fwx+JQ+HOHX9R kQlHug1Cx+LFssvz+hLlB5cqJQZfRKx92DhbROygtxG9r7UBmx/fwx+JQ+HOHX9R
@ -67,7 +74,7 @@ h+7fBVO49PLL0NWy+8GT8y7a04calFfLvZEA2UMaunBis3dE1KMFfJL/0JO+sKnF
2TkK01XDDJURK5Lhuvc7WrK2rSJ/fK+0GA== 2TkK01XDDJURK5Lhuvc7WrK2rSJ/fK+0GA==
-----END PRIVATE KEY----- -----END PRIVATE KEY-----
`, `,
cert: `-----BEGIN CERTIFICATE----- cert: `-----BEGIN CERTIFICATE-----
MIIEljCCAn4CCQDY+ZbC9FASVjANBgkqhkiG9w0BAQsFADANMQswCQYDVQQGEwJE MIIEljCCAn4CCQDY+ZbC9FASVjANBgkqhkiG9w0BAQsFADANMQswCQYDVQQGEwJE
RTAeFw0xOTA5MjAxNjAxNDRaFw0yMDA5MTkxNjAxNDRaMA0xCzAJBgNVBAYTAkRF RTAeFw0xOTA5MjAxNjAxNDRaFw0yMDA5MTkxNjAxNDRaMA0xCzAJBgNVBAYTAkRF
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA4thf9JEK/epoXt8hFr8t MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA4thf9JEK/epoXt8hFr8t
@ -94,47 +101,90 @@ TzJTbTCteOUUJTrcfZ0gGhGkF4nYLmX5OI+TPqrDJf0fZ+mzAEHzDDVXcBYpYRDr
r8d9QwrK+WaqVi2ofbMfMByVF72jgeJNa4nxwT9bVbu/Q1T2Lt+YPb4pQ7yCoUgS r8d9QwrK+WaqVi2ofbMfMByVF72jgeJNa4nxwT9bVbu/Q1T2Lt+YPb4pQ7yCoUgS
JNj2Dr5H0XoLFFnvuvzcRbhlJ9J67JzR+7g= JNj2Dr5H0XoLFFnvuvzcRbhlJ9J67JzR+7g=
-----END CERTIFICATE----- -----END CERTIFICATE-----
` `,
}, async (req, res) => { },
console.log('got request'); async (req, res) => {
const destinationConfig = this.router.routeReq(req); console.log('got request');
let destinationUrl: string; const destinationConfig = this.router.routeReq(req);
if (destinationConfig) {
destinationUrl = `http://${destinationConfig.destinationIp}:${destinationConfig.destinationPort}${req.url}`; // endRequest function
} else { const endRequest = (
res.writeHead(404); statusArg: number = 404,
res.end('This route is not available on this server\n'); messageArg: string = 'This route is not available on this server.',
return; headers: plugins.http.OutgoingHttpHeaders = {}
} ) => {
console.log(destinationUrl); res.writeHead(statusArg, messageArg);
const response = await plugins.smartrequest.request( res.end(messageArg);
destinationUrl, };
{
method: req.method, // authentication
headers: req.headers if (destinationConfig.authentication) {
}, const authInfo = destinationConfig.authentication;
true, // lets make this streaming switch (authInfo.type) {
(request) => { case 'Basic':
req.on('data', data => { const authHeader = req.headers.authorization;
request.write(data); if (authHeader) {
}); if (!authHeader.includes('Basic ')) {
req.on('end', data => { return endRequest(401, 'Authentication required', {
request.end(); 'WWW-Authenticate': 'Basic realm="Access to the staging site", charset="UTF-8"',
}); });
}
const authStringBase64 = req.headers.authorization.replace('Basic ', '');
const authString: string = plugins.smartstring.base64.decode(authStringBase64);
const userPassArray = authString.split(':');
const user = userPassArray[0];
const pass = userPassArray[1];
if (user === authInfo.user && pass === authInfo.pass) {
console.log('request successfully authenticated');
} else {
return endRequest(403, 'Forbidden: Wrong credentials');
}
}
break;
default:
return endRequest(
403,
'Forbidden: unsupported authentication method configured. Please report to the admin.'
);
}
} }
);
res.statusCode = response.statusCode; let destinationUrl: string;
console.log(response.statusCode); if (destinationConfig) {
for (const header of Object.keys(response.headers)) { destinationUrl = `http://${destinationConfig.destinationIp}:${destinationConfig.destinationPort}${req.url}`;
res.setHeader(header, response.headers[header]); } else {
return endRequest();
}
console.log(destinationUrl);
const response = await plugins.smartrequest.request(
destinationUrl,
{
method: req.method,
headers: req.headers,
},
true, // lets make this streaming
(request) => {
req.on('data', (data) => {
request.write(data);
});
req.on('end', (data) => {
request.end();
});
}
);
res.statusCode = response.statusCode;
console.log(response.statusCode);
for (const header of Object.keys(response.headers)) {
res.setHeader(header, response.headers[header]);
}
response.on('data', (data) => {
res.write(data);
});
response.on('end', () => {
res.end();
});
} }
response.on('data', data => { );
res.write(data);
});
response.on('end', () => {
res.end();
});
});
// Enable websockets // Enable websockets
const wss = new plugins.ws.Server({ server: this.httpsServer }); const wss = new plugins.ws.Server({ server: this.httpsServer });
@ -144,33 +194,33 @@ JNj2Dr5H0XoLFFnvuvzcRbhlJ9J67JzR+7g=
const wsc = new plugins.wsDefault(this.router.routeWs(ws), { const wsc = new plugins.wsDefault(this.router.routeWs(ws), {
headers: { headers: {
Host: ws.url Host: ws.url,
} },
}); });
wsc.on('open', () => { wsc.on('open', () => {
wscConnected.resolve(); wscConnected.resolve();
}); });
ws.on('message', async message => { ws.on('message', async (message) => {
await wscConnected.promise; await wscConnected.promise;
wsc.emit('message', message); wsc.emit('message', message);
}); });
wsc.on('message', message => { wsc.on('message', (message) => {
ws.emit('message', message); ws.emit('message', message);
}); });
// handle closing // handle closing
ws.on('close', message => { ws.on('close', (message) => {
wsc.close(); wsc.close();
}); });
wsc.on('close', message => { wsc.on('close', (message) => {
ws.close(); ws.close();
}); });
}); });
this.httpsServer.keepAliveTimeout = 61000; this.httpsServer.keepAliveTimeout = 61000;
this.httpsServer.headersTimeout = 65000; this.httpsServer.headersTimeout = 65000;
this.httpsServer.on('connection', connection => { this.httpsServer.on('connection', (connection) => {
this.socketMap.add(connection); this.socketMap.add(connection);
connection.on('close', () => { connection.on('close', () => {
this.socketMap.remove(connection); this.socketMap.remove(connection);
@ -178,10 +228,10 @@ JNj2Dr5H0XoLFFnvuvzcRbhlJ9J67JzR+7g=
}); });
this.httpsServer.listen(this.port); this.httpsServer.listen(this.port);
console.log(`OK: now listening for new connections on port ${this.port}`); console.log(`ProxyWorker -> OK: now listening for new connections on port ${this.port}`);
} }
public async updateProxyConfigs(proxyConfigsArg: plugins.tsclass.IReverseProxyConfig[]) { public async updateProxyConfigs(proxyConfigsArg: plugins.tsclass.network.IReverseProxyConfig[]) {
this.proxyConfigs = proxyConfigsArg; this.proxyConfigs = proxyConfigsArg;
this.router.setNewProxyConfigs(proxyConfigsArg); this.router.setNewProxyConfigs(proxyConfigsArg);
for (const hostCandidate of this.proxyConfigs) { for (const hostCandidate of this.proxyConfigs) {
@ -219,7 +269,7 @@ const proxyWorkerCalls = {
}, },
updateReverseConfigs: async (configArray: plugins.tsclass.network.IReverseProxyConfig[]) => { updateReverseConfigs: async (configArray: plugins.tsclass.network.IReverseProxyConfig[]) => {
await proxyWorkerInstance.updateProxyConfigs(configArray); await proxyWorkerInstance.updateProxyConfigs(configArray);
} },
}; };
export type TProxyWorkerCalls = typeof proxyWorkerCalls; export type TProxyWorkerCalls = typeof proxyWorkerCalls;

View File

@ -16,7 +16,7 @@ export class SmartproxyRouter {
*/ */
public routeReq(req: plugins.http.IncomingMessage): plugins.tsclass.network.IReverseProxyConfig { public routeReq(req: plugins.http.IncomingMessage): plugins.tsclass.network.IReverseProxyConfig {
const originalHost = req.headers.host; const originalHost = req.headers.host;
const correspodingReverseProxyConfig = this.reverseProxyConfigs.find(reverseConfig => { const correspodingReverseProxyConfig = this.reverseProxyConfigs.find((reverseConfig) => {
return reverseConfig.hostName === originalHost; return reverseConfig.hostName === originalHost;
}); });
return correspodingReverseProxyConfig; return correspodingReverseProxyConfig;
@ -24,7 +24,7 @@ export class SmartproxyRouter {
public routeWs(ws: plugins.wsDefault) { public routeWs(ws: plugins.wsDefault) {
const originalHost = plugins.url.parse(ws.url).host; const originalHost = plugins.url.parse(ws.url).host;
const correspodingReverseProxyConfig = this.reverseProxyConfigs.find(reverseConfig => { const correspodingReverseProxyConfig = this.reverseProxyConfigs.find((reverseConfig) => {
return reverseConfig.hostName === originalHost; return reverseConfig.hostName === originalHost;
}); });
return correspodingReverseProxyConfig.destinationIp; return correspodingReverseProxyConfig.destinationIp;

View File

@ -3,13 +3,23 @@ import * as plugins from './smartproxy.plugins';
import { TProxyWorkerCalls } from './smartproxy.classes.proxyworker'; import { TProxyWorkerCalls } from './smartproxy.classes.proxyworker';
import { TPortProxyCalls } from './smartproxy.portproxy'; import { TPortProxyCalls } from './smartproxy.portproxy';
export interface ISmartProxyOptions {
port?: number;
}
export class SmartProxy { export class SmartProxy {
public smartsystem = new plugins.smartsystem.Smartsystem(); public smartsystem = new plugins.smartsystem.Smartsystem();
public reverseConfigs: plugins.tsclass.network.IReverseProxyConfig[] = []; public reverseConfigs: plugins.tsclass.network.IReverseProxyConfig[] = [];
public proxyWorkerFunctions: plugins.smartspawn.ModuleThread<TProxyWorkerCalls>; public proxyWorkerFunctions: plugins.smartspawn.ModuleThread<TProxyWorkerCalls>;
public portProxyFunctions: plugins.smartspawn.ModuleThread<TPortProxyCalls>; public portProxyFunctions: plugins.smartspawn.ModuleThread<TPortProxyCalls>;
public async updateReversConfigs( public options: ISmartProxyOptions;
constructor(optionsArg: ISmartProxyOptions = {}) {
this.options = optionsArg;
}
public async updateReverseConfigs(
reverseConfigsArg: plugins.tsclass.network.IReverseProxyConfig[] reverseConfigsArg: plugins.tsclass.network.IReverseProxyConfig[]
) { ) {
// TODO search for old hostCandidates with that target // TODO search for old hostCandidates with that target
@ -28,6 +38,8 @@ export class SmartProxy {
this.portProxyFunctions = await plugins.smartspawn.spawn<TPortProxyCalls>( this.portProxyFunctions = await plugins.smartspawn.spawn<TPortProxyCalls>(
new plugins.smartspawn.Worker('./smartproxy.portproxy') new plugins.smartspawn.Worker('./smartproxy.portproxy')
); );
await this.portProxyFunctions.start(this.options.port);
await this.proxyWorkerFunctions.start(); await this.proxyWorkerFunctions.start();
console.log('successfully spawned portproxy and proxyworkers!'); console.log('successfully spawned portproxy and proxyworkers!');

View File

@ -16,9 +16,10 @@ import * as lik from '@pushrocks/lik';
import * as smartpromise from '@pushrocks/smartpromise'; import * as smartpromise from '@pushrocks/smartpromise';
import * as smartrequest from '@pushrocks/smartrequest'; import * as smartrequest from '@pushrocks/smartrequest';
import * as smartspawn from '@pushrocks/smartspawn'; import * as smartspawn from '@pushrocks/smartspawn';
import * as smartstring from '@pushrocks/smartstring';
import * as smartsystem from '@pushrocks/smartsystem'; import * as smartsystem from '@pushrocks/smartsystem';
export { lik, smartrequest, smartpromise, smartspawn, smartsystem }; export { lik, smartrequest, smartpromise, smartspawn, smartstring, smartsystem };
// third party scope // third party scope
import * as ws from 'ws'; import * as ws from 'ws';

View File

@ -1,25 +1,53 @@
import * as plugins from './smartproxy.plugins'; import * as plugins from './smartproxy.plugins';
import { expose } from '@pushrocks/smartspawn'; import { expose } from '@pushrocks/smartspawn';
import * as net from 'net'; import * as net from 'net';
const server = net let netServer: plugins.net.Server;
.createServer(from => { let httpServer: plugins.http.Server;
const to = net.createConnection({
host: 'localhost',
port: 8001
});
from.pipe(to);
to.pipe(from);
})
.listen(8000);
const portProxyCalls = { const portProxyCalls = {
start: async (portArg = 8000) => {
httpServer = plugins.http.createServer((request, response) => {
const requestUrl = new URL(request.url, `http://${request.headers.host}`);
const completeUrlWithoutProtocol = `${requestUrl.host}${requestUrl.pathname}${requestUrl.search}`;
const redirectUrl = `https://${completeUrlWithoutProtocol}`;
console.log(`Got http request for http://${completeUrlWithoutProtocol}`);
console.log(`Redirecting to ${redirectUrl}`);
response.writeHead(302, {
Location: redirectUrl,
});
response.end();
});
httpServer.listen(7999);
netServer = net
.createServer((from) => {
const to = net.createConnection({
host: 'localhost',
port: 8001,
});
from.pipe(to);
to.pipe(from);
from.on('error', () => {
from.end(), to.end();
});
to.on('error', () => {
from.end(), to.end();
});
from.on('close', () => {
to.end();
});
})
.listen(portArg);
console.log(`PortProxy -> OK: Now listening on port ${portArg}`);
},
stop: async () => { stop: async () => {
const done = plugins.smartpromise.defer(); const done = plugins.smartpromise.defer();
server.close(() => { httpServer.close(() => {
done.resolve(); netServer.close(() => {
done.resolve();
});
}); });
await done.promise; await done.promise;
} },
}; };
export type TPortProxyCalls = typeof portProxyCalls; export type TPortProxyCalls = typeof portProxyCalls;