Compare commits
219 Commits
Author | SHA1 | Date | |
---|---|---|---|
2e63d13dd4 | |||
af6ed735d5 | |||
7d38f29ef3 | |||
0df26d4367 | |||
f9a6e2d748 | |||
1cb6302750 | |||
f336f25535 | |||
5d6b707440 | |||
622ad2ff20 | |||
dd23efd28d | |||
0ddf68a919 | |||
ec08ca51f5 | |||
29688d1379 | |||
c83f6fa278 | |||
60333b0a59 | |||
1aa409907b | |||
adee6afc76 | |||
4a0792142f | |||
f1b810a4fa | |||
96b5877c5f | |||
6d627f67f7 | |||
9af968b8e7 | |||
b3ba0c21e8 | |||
ef707a5870 | |||
6ca14edb38 | |||
5a5686b6b9 | |||
2080f419cb | |||
659aae297b | |||
fcd0f61b5c | |||
7ee35a98e3 | |||
ea0f6d2270 | |||
621ad9e681 | |||
7cea5773ee | |||
a2cb56ba65 | |||
408b793149 | |||
f6c3d2d3d0 | |||
422eb5ec40 | |||
45390c4389 | |||
0f2e6d688c | |||
3bd7b70c19 | |||
07a82a09be | |||
23253a2731 | |||
be31a9b553 | |||
a1051f78e8 | |||
aa756bd698 | |||
ff4f44d6fc | |||
63ebad06ea | |||
31e15b65ec | |||
266895ccc5 | |||
dc3d56771b | |||
38601a41bb | |||
a53e6f1019 | |||
3de35f3b2c | |||
b9210d891e | |||
133d5a47e0 | |||
f2f4e47893 | |||
e47436608f | |||
128f8203ac | |||
c7697eca84 | |||
71b5237cd4 | |||
2df2f0ceaf | |||
2b266ca779 | |||
c2547036fd | |||
a8131ece26 | |||
ad8c667dec | |||
942e0649c8 | |||
59625167b4 | |||
385d984727 | |||
a959c2ad0e | |||
88f5436c9a | |||
06101cd1b1 | |||
438d65107d | |||
233b26c308 | |||
ba787729e8 | |||
4854d7c38d | |||
e841bda003 | |||
477b930a37 | |||
935bd95723 | |||
0e33ea4eb5 | |||
6181065963 | |||
1a586dcbd7 | |||
ee03224561 | |||
483cbb3634 | |||
c77b31b72c | |||
8cb8fa1a52 | |||
8e5bb12edb | |||
9be9a426ad | |||
32d875aed9 | |||
4747462cff | |||
70f69ef1ea | |||
2be1c57dd7 | |||
58bd6b4a85 | |||
63e1cd48e8 | |||
5150ddc18e | |||
4bee483954 | |||
4328d4365f | |||
21e9d0fd0d | |||
6c0c65bb1a | |||
23f61eb60b | |||
a4ad6c59c1 | |||
e67eff0fcc | |||
e5db2e171c | |||
7389072841 | |||
9dd56a9362 | |||
1e7c45918e | |||
49b65508a5 | |||
3e66debb01 | |||
f1bb1702c1 | |||
5abc0d8a14 | |||
9150e8c5fc | |||
8e4d3b7565 | |||
459ee7130f | |||
ceede84774 | |||
70bdf074a1 | |||
3eb4b576a7 | |||
c1f2c64e8b | |||
4ba943ee59 | |||
4c50e9a556 | |||
f2428412bb | |||
f114968298 | |||
def6644e80 | |||
c85f3da924 | |||
6cdb23ed66 | |||
0adb32e7e9 | |||
5d65e1668b | |||
632015a7bd | |||
972ee2af54 | |||
9b1ff5eed8 | |||
0739d1093a | |||
ee4f7fc48d | |||
f6e656361b | |||
e51c2a88cc | |||
7f8112930d | |||
b5c83b5c75 | |||
63ce1a44a4 | |||
759f70b84d | |||
45ce56b118 | |||
0cc7184e58 | |||
392e241208 | |||
32c6d77178 | |||
2c4316d2d3 | |||
62e6387c1d | |||
7fe22e962a | |||
3f1f718308 | |||
ce94d283c1 | |||
a1c4f3c341 | |||
8087bab197 | |||
db63e7bf79 | |||
2615a0ebd4 | |||
d5d77af98d | |||
1f1bf77807 | |||
d4269d290d | |||
e05e5ede55 | |||
b6c7f13baa | |||
055d328bd0 | |||
20b9a220fc | |||
2170fe3518 | |||
04b13e53b9 | |||
f1a4fae704 | |||
5ee5147606 | |||
748c6e14e4 | |||
f018957de4 | |||
a6583b037c | |||
3ab4144c9a | |||
0d2885ace4 | |||
1723275215 | |||
977d8b0310 | |||
5bb065f82b | |||
942b812f97 | |||
59a025b308 | |||
458e7d6b58 | |||
7b0f824d29 | |||
b5796b86d5 | |||
1f8ea59221 | |||
d717568572 | |||
28d050851f | |||
acbd109985 | |||
cc38a6d10e | |||
748b07efe2 | |||
be4fd0978a | |||
4521010b82 | |||
bd1f1a4c1c | |||
d3bdd56660 | |||
c38a7c4c32 | |||
858628196a | |||
4910679058 | |||
97db2012ca | |||
0ee13b4e06 | |||
21f5882fa3 | |||
48b43f9f0d | |||
d3d476fd53 | |||
b80b8a0a20 | |||
384943f697 | |||
e9239ed978 | |||
baf1844866 | |||
0b3d7f8a06 | |||
c38a2745e9 | |||
a0f39d1c5b | |||
c67ac868a5 | |||
90e1a0453e | |||
d7765fb5dc | |||
0fdd17b430 | |||
0562de6aa1 | |||
7b550a35aa | |||
fb66aac6e7 | |||
208790cfcf | |||
5978bbaf66 | |||
1c47eafe5f | |||
69e3a71354 | |||
21e92bf0c1 | |||
d732e6e7aa | |||
5fdfcdb407 | |||
49e2e90bda | |||
b8e53e7b42 | |||
1136841b3d | |||
42cbc51d22 | |||
2d16403ad1 | |||
afe847499a | |||
f980bb70b4 |
66
.gitea/workflows/default_nottags.yaml
Normal file
66
.gitea/workflows/default_nottags.yaml
Normal file
@ -0,0 +1,66 @@
|
||||
name: Default (not tags)
|
||||
|
||||
on:
|
||||
push:
|
||||
tags-ignore:
|
||||
- '**'
|
||||
|
||||
env:
|
||||
IMAGE: code.foss.global/host.today/ht-docker-node:npmci
|
||||
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@/${{gitea.repository}}.git
|
||||
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
|
||||
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
|
||||
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
|
||||
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
|
||||
|
||||
jobs:
|
||||
security:
|
||||
runs-on: ubuntu-latest
|
||||
continue-on-error: true
|
||||
container:
|
||||
image: ${{ env.IMAGE }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Install pnpm and npmci
|
||||
run: |
|
||||
pnpm install -g pnpm
|
||||
pnpm install -g @ship.zone/npmci
|
||||
|
||||
- name: Run npm prepare
|
||||
run: npmci npm prepare
|
||||
|
||||
- name: Audit production dependencies
|
||||
run: |
|
||||
npmci command npm config set registry https://registry.npmjs.org
|
||||
npmci command pnpm audit --audit-level=high --prod
|
||||
continue-on-error: true
|
||||
|
||||
- name: Audit development dependencies
|
||||
run: |
|
||||
npmci command npm config set registry https://registry.npmjs.org
|
||||
npmci command pnpm audit --audit-level=high --dev
|
||||
continue-on-error: true
|
||||
|
||||
test:
|
||||
if: ${{ always() }}
|
||||
needs: security
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: ${{ env.IMAGE }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Test stable
|
||||
run: |
|
||||
npmci node install stable
|
||||
npmci npm install
|
||||
npmci npm test
|
||||
|
||||
- name: Test build
|
||||
run: |
|
||||
npmci node install stable
|
||||
npmci npm install
|
||||
npmci npm build
|
124
.gitea/workflows/default_tags.yaml
Normal file
124
.gitea/workflows/default_tags.yaml
Normal file
@ -0,0 +1,124 @@
|
||||
name: Default (tags)
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- '*'
|
||||
|
||||
env:
|
||||
IMAGE: code.foss.global/host.today/ht-docker-node:npmci
|
||||
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@/${{gitea.repository}}.git
|
||||
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
|
||||
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
|
||||
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
|
||||
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
|
||||
|
||||
jobs:
|
||||
security:
|
||||
runs-on: ubuntu-latest
|
||||
continue-on-error: true
|
||||
container:
|
||||
image: ${{ env.IMAGE }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Prepare
|
||||
run: |
|
||||
pnpm install -g pnpm
|
||||
pnpm install -g @ship.zone/npmci
|
||||
npmci npm prepare
|
||||
|
||||
- name: Audit production dependencies
|
||||
run: |
|
||||
npmci command npm config set registry https://registry.npmjs.org
|
||||
npmci command pnpm audit --audit-level=high --prod
|
||||
continue-on-error: true
|
||||
|
||||
- name: Audit development dependencies
|
||||
run: |
|
||||
npmci command npm config set registry https://registry.npmjs.org
|
||||
npmci command pnpm audit --audit-level=high --dev
|
||||
continue-on-error: true
|
||||
|
||||
test:
|
||||
if: ${{ always() }}
|
||||
needs: security
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: ${{ env.IMAGE }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Prepare
|
||||
run: |
|
||||
pnpm install -g pnpm
|
||||
pnpm install -g @ship.zone/npmci
|
||||
npmci npm prepare
|
||||
|
||||
- name: Test stable
|
||||
run: |
|
||||
npmci node install stable
|
||||
npmci npm install
|
||||
npmci npm test
|
||||
|
||||
- name: Test build
|
||||
run: |
|
||||
npmci node install stable
|
||||
npmci npm install
|
||||
npmci npm build
|
||||
|
||||
release:
|
||||
needs: test
|
||||
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: ${{ env.IMAGE }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Prepare
|
||||
run: |
|
||||
pnpm install -g pnpm
|
||||
pnpm install -g @ship.zone/npmci
|
||||
npmci npm prepare
|
||||
|
||||
- name: Release
|
||||
run: |
|
||||
npmci node install stable
|
||||
npmci npm publish
|
||||
|
||||
metadata:
|
||||
needs: test
|
||||
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: ${{ env.IMAGE }}
|
||||
continue-on-error: true
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Prepare
|
||||
run: |
|
||||
pnpm install -g pnpm
|
||||
pnpm install -g @ship.zone/npmci
|
||||
npmci npm prepare
|
||||
|
||||
- name: Code quality
|
||||
run: |
|
||||
npmci command npm install -g typescript
|
||||
npmci npm install
|
||||
|
||||
- name: Trigger
|
||||
run: npmci trigger
|
||||
|
||||
- name: Build docs and upload artifacts
|
||||
run: |
|
||||
npmci node install stable
|
||||
npmci npm install
|
||||
pnpm install -g @git.zone/tsdoc
|
||||
npmci command tsdoc
|
||||
continue-on-error: true
|
3
.gitignore
vendored
3
.gitignore
vendored
@ -3,7 +3,6 @@
|
||||
# artifacts
|
||||
coverage/
|
||||
public/
|
||||
pages/
|
||||
|
||||
# installs
|
||||
node_modules/
|
||||
@ -17,4 +16,4 @@ node_modules/
|
||||
dist/
|
||||
dist_*/
|
||||
|
||||
# custom
|
||||
#------# custom
|
128
.gitlab-ci.yml
128
.gitlab-ci.yml
@ -1,128 +0,0 @@
|
||||
# gitzone ci_default
|
||||
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
|
||||
|
||||
cache:
|
||||
paths:
|
||||
- .npmci_cache/
|
||||
key: '$CI_BUILD_STAGE'
|
||||
|
||||
stages:
|
||||
- security
|
||||
- test
|
||||
- release
|
||||
- metadata
|
||||
|
||||
before_script:
|
||||
- npm install -g @shipzone/npmci
|
||||
|
||||
# ====================
|
||||
# security stage
|
||||
# ====================
|
||||
auditProductionDependencies:
|
||||
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
|
||||
stage: security
|
||||
script:
|
||||
- npmci npm prepare
|
||||
- npmci command npm install --production --ignore-scripts
|
||||
- npmci command npm config set registry https://registry.npmjs.org
|
||||
- npmci command npm audit --audit-level=high --only=prod --production
|
||||
tags:
|
||||
- docker
|
||||
allow_failure: true
|
||||
|
||||
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
|
||||
# ====================
|
||||
|
||||
testStable:
|
||||
stage: test
|
||||
script:
|
||||
- npmci npm prepare
|
||||
- npmci node install stable
|
||||
- npmci npm install
|
||||
- npmci npm test
|
||||
coverage: /\d+.?\d+?\%\s*coverage/
|
||||
tags:
|
||||
- docker
|
||||
|
||||
testBuild:
|
||||
stage: test
|
||||
script:
|
||||
- npmci npm prepare
|
||||
- npmci node install stable
|
||||
- npmci npm install
|
||||
- npmci command npm run build
|
||||
coverage: /\d+.?\d+?\%\s*coverage/
|
||||
tags:
|
||||
- docker
|
||||
|
||||
release:
|
||||
stage: release
|
||||
script:
|
||||
- npmci node install stable
|
||||
- npmci npm publish
|
||||
only:
|
||||
- tags
|
||||
tags:
|
||||
- lossless
|
||||
- docker
|
||||
- notpriv
|
||||
|
||||
# ====================
|
||||
# metadata stage
|
||||
# ====================
|
||||
codequality:
|
||||
stage: metadata
|
||||
allow_failure: true
|
||||
only:
|
||||
- tags
|
||||
script:
|
||||
- npmci command npm install -g typescript
|
||||
- npmci npm prepare
|
||||
- npmci npm install
|
||||
tags:
|
||||
- lossless
|
||||
- docker
|
||||
- priv
|
||||
|
||||
trigger:
|
||||
stage: metadata
|
||||
script:
|
||||
- npmci trigger
|
||||
only:
|
||||
- tags
|
||||
tags:
|
||||
- lossless
|
||||
- docker
|
||||
- notpriv
|
||||
|
||||
pages:
|
||||
stage: metadata
|
||||
script:
|
||||
- npmci node install stable
|
||||
- npmci npm prepare
|
||||
- npmci npm install
|
||||
- npmci command npm run buildDocs
|
||||
tags:
|
||||
- lossless
|
||||
- docker
|
||||
- notpriv
|
||||
only:
|
||||
- tags
|
||||
artifacts:
|
||||
expire_in: 1 week
|
||||
paths:
|
||||
- public
|
||||
allow_failure: true
|
19
assets/certs/cert.pem
Normal file
19
assets/certs/cert.pem
Normal file
@ -0,0 +1,19 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDCzCCAfOgAwIBAgIUPU4tviz3ZvsMDjCz1NZRT16b0Y4wDQYJKoZIhvcNAQEL
|
||||
BQAwFTETMBEGA1UEAwwKcHVzaC5yb2NrczAeFw0yNTAyMDMyMzA5MzRaFw0yNjAy
|
||||
MDMyMzA5MzRaMBUxEzARBgNVBAMMCnB1c2gucm9ja3MwggEiMA0GCSqGSIb3DQEB
|
||||
AQUAA4IBDwAwggEKAoIBAQCZMkBYD/pYLBv9MiyHTLRT24kQyPeJBtZqryibi1jk
|
||||
BT1ZgNl3yo5U6kjj/nYBU/oy7M4OFC0xyaJQ4wpvLHu7xzREqwT9N9WcDcxaahUi
|
||||
P8+PsjGyznPrtXa1ASzGAYMNvXyWWp3351UWZHMEs6eY/Y7i8m4+0NwP5h8RNBCF
|
||||
KSFS41Ee9rNAMCnQSHZv1vIzKeVYPmYnCVmL7X2kQb+gS6Rvq5sEGLLKMC5QtTwI
|
||||
rdkPGpx4xZirIyf8KANbt0sShwUDpiCSuOCtpze08jMzoHLG9Nv97cJQjb/BhiES
|
||||
hLL+YjfAUFjq0rQ38zFKLJ87QB9Jym05mY6IadGQLXVXAgMBAAGjUzBRMB0GA1Ud
|
||||
DgQWBBQjpowWjrql/Eo2EVjl29xcjuCgkTAfBgNVHSMEGDAWgBQjpowWjrql/Eo2
|
||||
EVjl29xcjuCgkTAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAY
|
||||
44vqbaf6ewFrZC0f3Kk4A10lC6qjWkcDFfw+JE8nzt+4+xPqp1eWgZKF2rONyAv2
|
||||
nG41Xygt19ByancXLU44KB24LX8F1GV5Oo7CGBA+xtoSPc0JulXw9fGclZDC6XiR
|
||||
P/+vhGgCHicbfP2O+N00pOifrTtf2tmOT4iPXRRo4TxmPzuCd+ZJTlBhPlKCmICq
|
||||
yGdAiEo6HsSiP+M5qVlNx8s57MhQYk5TpgmI6FU4mO7zfDfSatFonlg+aDbrnaqJ
|
||||
v/+km02M+oB460GmKwsSTnThHZgLNCLiKqD8bdziiCQjx5u0GjLI6468o+Aehb8l
|
||||
l/x9vWTTk/QKq41X5hFk
|
||||
-----END CERTIFICATE-----
|
28
assets/certs/key.pem
Normal file
28
assets/certs/key.pem
Normal file
@ -0,0 +1,28 @@
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCZMkBYD/pYLBv9
|
||||
MiyHTLRT24kQyPeJBtZqryibi1jkBT1ZgNl3yo5U6kjj/nYBU/oy7M4OFC0xyaJQ
|
||||
4wpvLHu7xzREqwT9N9WcDcxaahUiP8+PsjGyznPrtXa1ASzGAYMNvXyWWp3351UW
|
||||
ZHMEs6eY/Y7i8m4+0NwP5h8RNBCFKSFS41Ee9rNAMCnQSHZv1vIzKeVYPmYnCVmL
|
||||
7X2kQb+gS6Rvq5sEGLLKMC5QtTwIrdkPGpx4xZirIyf8KANbt0sShwUDpiCSuOCt
|
||||
pze08jMzoHLG9Nv97cJQjb/BhiEShLL+YjfAUFjq0rQ38zFKLJ87QB9Jym05mY6I
|
||||
adGQLXVXAgMBAAECggEARGCBBq1PBHbfoUH5TQSIAlvdEEBa9+602lZG7jIioVfT
|
||||
W7Uem5Ctuan+kcDcY9hbNsqqZ+9KgsvoJmlIGXoF2jjeE/4vUmRO9AHWoc5yk2Be
|
||||
4NjcxN3QMLdEfiLBnLlFCOd4CdX1ZxZ6TG3WRpV3a1pVIeeqHGB1sKT6Xd/atcwG
|
||||
RvpiXzu0SutGxVb6WE9r6hovZ4fVERCyCRczUGrUH5ICbxf6E7L4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/l4wZl5+g==
|
||||
-----END PRIVATE KEY-----
|
393
changelog.md
Normal file
393
changelog.md
Normal file
@ -0,0 +1,393 @@
|
||||
# Changelog
|
||||
|
||||
## 2025-03-01 - 3.20.0 - feat(PortProxy)
|
||||
Enhance PortProxy with advanced connection cleanup and logging
|
||||
|
||||
- Introduced `cleanupConnection` method for improved connection management.
|
||||
- Added logging for connection cleanup including special conditions.
|
||||
- Implemented parity check to clean up connections when outgoing side closes but incoming remains active.
|
||||
- Improved logging during interval checks for active connections and their durations.
|
||||
|
||||
## 2025-03-01 - 3.19.0 - feat(PortProxy)
|
||||
Enhance PortProxy with default blocked IPs
|
||||
|
||||
- Introduced defaultBlockedIPs in IPortProxySettings to handle globally blocked IPs.
|
||||
- Added logic for merging domain-specific and default allowed and blocked IPs for effective IP filtering.
|
||||
- Refactored helper functions for IP and port range checks to improve modularity in PortProxy.
|
||||
|
||||
## 2025-02-27 - 3.18.2 - fix(portproxy)
|
||||
Fixed typographical errors in comments within PortProxy class.
|
||||
|
||||
- Corrected typographical errors in comments within the PortProxy class.
|
||||
|
||||
## 2025-02-27 - 3.18.1 - fix(PortProxy)
|
||||
Refactor and enhance PortProxy test cases and handling
|
||||
|
||||
- Refactored test cases in test/test.portproxy.ts for clarity and added coverage.
|
||||
- Improved TCP server helper functions for better flexibility.
|
||||
- Fixed issues with domain handling in PortProxy configuration.
|
||||
- Introduced round-robin logic for multi-IP domains in PortProxy.
|
||||
- Ensured proper cleanup and stopping of test servers in the test suite.
|
||||
|
||||
## 2025-02-27 - 3.18.0 - feat(PortProxy)
|
||||
Add SNI-based renegotiation handling in PortProxy
|
||||
|
||||
- Introduced a new field 'lockedDomain' in IConnectionRecord to store initial SNI.
|
||||
- Enhanced connection management by enforcing termination if rehandshake is detected with different SNI.
|
||||
|
||||
## 2025-02-27 - 3.17.1 - fix(PortProxy)
|
||||
Fix handling of SNI re-negotiation in PortProxy
|
||||
|
||||
- Removed connection locking to the initially negotiated SNI
|
||||
- Improved handling of SNI during renegotiation in PortProxy
|
||||
|
||||
## 2025-02-27 - 3.17.0 - feat(smartproxy)
|
||||
Enhance description clarity and improve SNI handling with domain locking.
|
||||
|
||||
- Improved package description in package.json, readme.md, and npmextra.json for better clarity and keyword optimization.
|
||||
- Enhanced SNI handling in PortProxy by adding domain locking and extra checks to terminate connections if a different SNI is detected post-handshake.
|
||||
- Refactored readme.md to better explain the usage and functionalities of the proxy features including SSL redirection, WebSocket handling, and dynamic routing.
|
||||
|
||||
## 2025-02-27 - 3.16.9 - fix(portproxy)
|
||||
Extend domain input validation to support string arrays in port proxy configurations.
|
||||
|
||||
- Modify IDomainConfig interface to allow domain specification as string array.
|
||||
- Update connection setup logic to handle multiple domain patterns.
|
||||
- Enhance domain rejection logging to include all domain patterns.
|
||||
|
||||
## 2025-02-27 - 3.16.8 - fix(PortProxy)
|
||||
Fix IP filtering for domain and global default allowed lists and improve port-based routing logic.
|
||||
|
||||
- Improved logic to prioritize domain-specific allowed IPs over global defaults.
|
||||
- Fixed port-based rules application to handle global port ranges more effectively.
|
||||
- Enhanced rejection handling for unauthorized IP addresses in both domain-specific and default global lists.
|
||||
|
||||
## 2025-02-27 - 3.16.7 - fix(PortProxy)
|
||||
Improved IP validation logic in PortProxy to ensure correct domain matching and fallback
|
||||
|
||||
- Refactored the setupConnection function inside PortProxy to enhance IP address validation.
|
||||
- Domain-specific allowed IP preference is applied before default list lookup.
|
||||
- Removed redundant condition checks to streamline connection rejection paths.
|
||||
|
||||
## 2025-02-27 - 3.16.6 - fix(PortProxy)
|
||||
Optimize connection cleanup logic in PortProxy by removing unnecessary delays.
|
||||
|
||||
- Removed multiple await plugins.smartdelay.delayFor(0) calls.
|
||||
- Improved performance by ensuring timely resource release during connection termination.
|
||||
|
||||
## 2025-02-27 - 3.16.5 - fix(PortProxy)
|
||||
Improved connection cleanup process with added asynchronous delays
|
||||
|
||||
- Connection cleanup now includes asynchronous delays for reliable order of operations.
|
||||
|
||||
## 2025-02-27 - 3.16.4 - fix(PortProxy)
|
||||
Fix and enhance port proxy handling
|
||||
|
||||
- Ensure that all created proxy servers are correctly checked for listening state.
|
||||
- Corrected the handling of ports and domain configurations within port proxy setups.
|
||||
- Expanded test coverage for handling multiple concurrent and chained proxy connections.
|
||||
|
||||
## 2025-02-27 - 3.16.3 - fix(PortProxy)
|
||||
Refactored PortProxy to support multiple listening ports and improved modularity.
|
||||
|
||||
- Updated PortProxy to allow multiple listening ports with flexible configuration.
|
||||
- Moved helper functions for IP and port range checks outside the class for cleaner code structure.
|
||||
|
||||
## 2025-02-27 - 3.16.2 - fix(PortProxy)
|
||||
Fix port-based routing logic in PortProxy
|
||||
|
||||
- Optimized the handling and checking of local ports in the global port range.
|
||||
- Fixed the logic for rejecting or accepting connections based on predefined port ranges.
|
||||
- Improved handling of the default and specific domain configurations during port-based connections.
|
||||
|
||||
## 2025-02-27 - 3.16.1 - fix(core)
|
||||
Updated minor version numbers in dependencies for patch release.
|
||||
|
||||
- No specific file changes detected.
|
||||
- Dependencies versioning adjusted for stability.
|
||||
|
||||
## 2025-02-27 - 3.16.0 - feat(PortProxy)
|
||||
Enhancements made to PortProxy settings and capabilities
|
||||
|
||||
- Added 'forwardAllGlobalRanges' and 'targetIP' to IPortProxySettings.
|
||||
- Improved PortProxy to forward connections based on domain-specific configurations.
|
||||
- Added comprehensive handling for global port-range based connection forwarding.
|
||||
- Enabled forwarding of all connections on global port ranges directly to global target IP.
|
||||
|
||||
## 2025-02-27 - 3.15.0 - feat(classes.portproxy)
|
||||
Add support for port range-based routing with enhanced IP and port validation.
|
||||
|
||||
- Introduced globalPortRanges in IPortProxySettings for routing based on port ranges.
|
||||
- Improved connection handling with port range and domain configuration validations.
|
||||
- Updated connection logging to include the local port information.
|
||||
|
||||
## 2025-02-26 - 3.14.2 - fix(PortProxy)
|
||||
Fix cleanup timer reset for PortProxy
|
||||
|
||||
- Resolved an issue where the cleanup timer in the PortProxy class did not reset correctly if both incoming and outgoing data events were triggered without clearing flags.
|
||||
|
||||
## 2025-02-26 - 3.14.1 - fix(PortProxy)
|
||||
Increased default maxConnectionLifetime for PortProxy to 600000 ms
|
||||
|
||||
- Updated PortProxy settings to extend default maxConnectionLifetime to 10 minutes.
|
||||
|
||||
## 2025-02-26 - 3.14.0 - feat(PortProxy)
|
||||
Introduce max connection lifetime feature
|
||||
|
||||
- Added an optional maxConnectionLifetime setting for PortProxy.
|
||||
- Forces cleanup of long-lived connections based on inactivity or lifetime limit.
|
||||
|
||||
## 2025-02-25 - 3.13.0 - feat(core)
|
||||
Add support for tagging iptables rules with comments and cleaning them up on process exit
|
||||
|
||||
- Extended IPTablesProxy class to include tagging rules with unique comments.
|
||||
- Added feature to clean up iptables rules via comments during process exit.
|
||||
|
||||
## 2025-02-24 - 3.12.0 - feat(IPTablesProxy)
|
||||
Introduce IPTablesProxy class for managing iptables NAT rules
|
||||
|
||||
- Added IPTablesProxy class to facilitate basic port forwarding using iptables.
|
||||
- Introduced IIpTableProxySettings interface for configuring IPTablesProxy.
|
||||
- Implemented start and stop methods for managing iptables rules dynamically.
|
||||
|
||||
## 2025-02-24 - 3.11.0 - feat(Port80Handler)
|
||||
Add automatic certificate issuance with ACME client
|
||||
|
||||
- Implemented automatic certificate issuance using 'acme-client' for Port80Handler.
|
||||
- Converts account key and CSR from Buffers to strings for processing.
|
||||
- Implemented HTTP-01 challenge handling for certificate acquisition.
|
||||
- New certificates are fetched and added dynamically.
|
||||
|
||||
## 2025-02-24 - 3.10.5 - fix(portproxy)
|
||||
Fix incorrect import path in test file
|
||||
|
||||
- Change import path from '../ts/smartproxy.portproxy.js' to '../ts/classes.portproxy.js' in test/test.portproxy.ts
|
||||
|
||||
## 2025-02-23 - 3.10.4 - fix(PortProxy)
|
||||
Refactor connection tracking to utilize unified records in PortProxy
|
||||
|
||||
- Implemented a unified record system for tracking incoming and outgoing connections.
|
||||
- Replaced individual connection tracking sets with a Set of IConnectionRecord.
|
||||
- Improved logging of connection activities and statistics.
|
||||
|
||||
## 2025-02-23 - 3.10.3 - fix(PortProxy)
|
||||
Refactor and optimize PortProxy for improved readability and maintainability
|
||||
|
||||
- Simplified and clarified inline comments.
|
||||
- Optimized the extractSNI function for better readability.
|
||||
- Streamlined the cleanup process for connections in PortProxy.
|
||||
- Improved handling and logging of incoming and outgoing connections.
|
||||
|
||||
## 2025-02-23 - 3.10.2 - fix(PortProxy)
|
||||
Fix connection handling to include timeouts for SNI-enabled connections.
|
||||
|
||||
- Added initial data timeout for SNI-enabled connections to improve connection handling.
|
||||
- Cleared timeout once data is received to prevent premature socket closure.
|
||||
|
||||
## 2025-02-22 - 3.10.1 - fix(PortProxy)
|
||||
Improve socket cleanup logic to prevent potential resource leaks
|
||||
|
||||
- Updated socket cleanup in PortProxy to ensure sockets are forcefully destroyed if not already destroyed.
|
||||
|
||||
## 2025-02-22 - 3.10.0 - feat(smartproxy.portproxy)
|
||||
Enhance PortProxy with detailed connection statistics and termination tracking
|
||||
|
||||
- Added tracking of termination statistics for incoming and outgoing connections
|
||||
- Enhanced logging to include detailed termination statistics
|
||||
- Introduced helpers to update and log termination stats
|
||||
- Retained detailed connection duration and active connection logging
|
||||
|
||||
## 2025-02-22 - 3.9.4 - fix(PortProxy)
|
||||
Ensure proper cleanup on connection rejection in PortProxy
|
||||
|
||||
- Added cleanup calls after socket end in connection rejection scenarios within PortProxy
|
||||
|
||||
## 2025-02-21 - 3.9.3 - fix(PortProxy)
|
||||
Fix handling of optional outgoing socket in PortProxy
|
||||
|
||||
- Refactored the cleanUpSockets function to correctly handle cases where the outgoing socket may be undefined.
|
||||
- Ensured correct handling of socket events with non-null assertions where applicable.
|
||||
- Improved robustness in connection establishment and cleanup processes.
|
||||
|
||||
## 2025-02-21 - 3.9.2 - fix(PortProxy)
|
||||
Improve timeout handling for port proxy connections
|
||||
|
||||
- Added console logging for both incoming and outgoing side timeouts in the PortProxy class.
|
||||
- Updated the timeout event handlers to ensure proper cleanup of connections.
|
||||
|
||||
## 2025-02-21 - 3.9.1 - fix(dependencies)
|
||||
Ensure correct ordering of dependencies and improve logging format.
|
||||
|
||||
- Reorder dependencies in package.json for better readability.
|
||||
- Use pretty-ms for displaying time durations in logs.
|
||||
|
||||
## 2025-02-21 - 3.9.0 - feat(smartproxy.portproxy)
|
||||
Add logging of connection durations to PortProxy
|
||||
|
||||
- Track start times for incoming and outgoing connections.
|
||||
- Log duration of longest running incoming and outgoing connections every 10 seconds.
|
||||
|
||||
## 2025-02-21 - 3.8.1 - fix(plugins)
|
||||
Simplified plugin import structure across codebase
|
||||
|
||||
- Consolidated plugin imports under a single 'plugins.ts' file.
|
||||
- Replaced individual plugin imports in smartproxy files with the consolidated plugin imports.
|
||||
- Fixed error handling for early socket errors in PortProxy setup.
|
||||
|
||||
## 2025-02-21 - 3.8.0 - feat(PortProxy)
|
||||
Add active connection tracking and logging in PortProxy
|
||||
|
||||
- Implemented a feature to track active incoming connections in PortProxy.
|
||||
- Active connections are now logged every 10 seconds for monitoring purposes.
|
||||
- Refactored connection handling to ensure proper cleanup and logging.
|
||||
|
||||
## 2025-02-21 - 3.7.3 - fix(portproxy)
|
||||
Fix handling of connections in PortProxy to improve stability and performance.
|
||||
|
||||
- Improved IP normalization and matching
|
||||
- Better SNI extraction and handling for TLS
|
||||
- Streamlined connection handling with robust error management
|
||||
|
||||
## 2025-02-21 - 3.7.2 - fix(PortProxy)
|
||||
Improve SNICallback and connection handling in PortProxy
|
||||
|
||||
- Fixed SNICallback to create minimal TLS context for SNI.
|
||||
- Changed connection setup to use net.connect for raw passthrough.
|
||||
|
||||
## 2025-02-21 - 3.7.1 - fix(smartproxy.portproxy)
|
||||
Optimize SNI handling by simplifying context creation
|
||||
|
||||
- Removed unnecessary SecureContext creation for SNI requests in PortProxy
|
||||
- Improved handling of SNI passthrough by acknowledging requests without context creation
|
||||
|
||||
## 2025-02-21 - 3.7.0 - feat(PortProxy)
|
||||
Add optional source IP preservation support in PortProxy
|
||||
|
||||
- Added a feature to optionally preserve the client's source IP when proxying connections.
|
||||
- Enhanced test cases to include scenarios for source IP preservation.
|
||||
|
||||
## 2025-02-21 - 3.6.0 - feat(PortProxy)
|
||||
Add feature to preserve original client IP through chained proxies
|
||||
|
||||
- Added support to bind local address in PortProxy to preserve original client IP.
|
||||
- Implemented test for chained proxies to ensure client IP is preserved.
|
||||
|
||||
## 2025-02-21 - 3.5.0 - feat(PortProxy)
|
||||
Enhance PortProxy to support domain-specific target IPs
|
||||
|
||||
- Introduced support for domain-specific target IP configurations in PortProxy.
|
||||
- Updated connection handling to prioritize domain-specific target IPs if provided.
|
||||
- Added tests to verify forwarding based on domain-specific target IPs.
|
||||
|
||||
## 2025-02-21 - 3.4.4 - fix(PortProxy)
|
||||
Fixed handling of SNI domain connections and IP allowance checks
|
||||
|
||||
- Improved logic for handling SNI domain checks, ensuring IPs are correctly verified.
|
||||
- Fixed issue where default allowed IPs were not being checked correctly for non-SNI connections.
|
||||
- Revised the SNICallback behavior to handle connections more gracefully when domain configurations are unavailable.
|
||||
|
||||
## 2025-02-21 - 3.4.3 - fix(PortProxy)
|
||||
Fixed indentation issue and ensured proper cleanup of sockets in PortProxy
|
||||
|
||||
- Fixed inconsistent indentation in IP allowance check.
|
||||
- Ensured proper cleanup of sockets on connection end in PortProxy.
|
||||
|
||||
## 2025-02-21 - 3.4.2 - fix(smartproxy)
|
||||
Enhance SSL/TLS handling with SNI and error logging
|
||||
|
||||
- Improved handling for SNI-enabled and non-SNI connections
|
||||
- Added detailed logging for connection establishment and rejections
|
||||
- Introduced error logging for TLS client errors and server errors
|
||||
|
||||
## 2025-02-21 - 3.4.1 - fix(PortProxy)
|
||||
Normalize IP addresses for port proxy to handle IPv4-mapped IPv6 addresses.
|
||||
|
||||
- Improved IP normalization logic in PortProxy to support IPv4-mapped IPv6 addresses.
|
||||
- Updated isAllowed function to expand patterns for better matching accuracy.
|
||||
|
||||
## 2025-02-21 - 3.4.0 - feat(PortProxy)
|
||||
Enhanced PortProxy with custom target host and improved testing
|
||||
|
||||
- PortProxy constructor now accepts 'fromPort', 'toPort', and optional 'toHost' directly from settings
|
||||
- Refactored test cases to cover forwarding to the custom host
|
||||
- Added support to handle multiple concurrent connections
|
||||
- Refactored internal connection handling logic to utilize default configurations
|
||||
|
||||
## 2025-02-21 - 3.3.1 - fix(PortProxy)
|
||||
fixed import usage of net and tls libraries for PortProxy
|
||||
|
||||
- Corrected the use of plugins for importing 'tls' and 'net' libraries in the PortProxy module.
|
||||
- Updated the constructor of PortProxy to accept combined tls options with ProxySettings.
|
||||
|
||||
## 2025-02-21 - 3.3.0 - feat(PortProxy)
|
||||
Enhanced PortProxy with domain and IP filtering, SNI support, and minimatch integration
|
||||
|
||||
- Added new ProxySettings interface to configure domain patterns, SNI, and default allowed IPs.
|
||||
- Integrated minimatch to filter allowed IPs and domains.
|
||||
- Enabled SNI support for PortProxy connections.
|
||||
- Updated port proxy test to accommodate new settings.
|
||||
|
||||
## 2025-02-04 - 3.2.0 - feat(testing)
|
||||
Added a comprehensive test suite for the PortProxy class
|
||||
|
||||
- Set up a test environment for PortProxy using net.Server.
|
||||
- Test coverage includes starting and stopping the proxy, handling TCP connections, concurrent connections, and timeouts.
|
||||
- Ensures proper resource cleanup after tests.
|
||||
|
||||
## 2025-02-04 - 3.1.4 - fix(core)
|
||||
No uncommitted changes. Preparing for potential minor improvements or bug fixes.
|
||||
|
||||
|
||||
## 2025-02-04 - 3.1.3 - fix(networkproxy)
|
||||
Refactor and improve WebSocket handling and request processing
|
||||
|
||||
- Improved error handling in WebSocket connection and request processing.
|
||||
- Refactored the WebSocket handling in NetworkProxy to use a unified error logging mechanism.
|
||||
|
||||
## 2025-02-04 - 3.1.2 - fix(core)
|
||||
Refactor certificate handling across the project
|
||||
|
||||
- Moved certificate keys and certs to the assets/certs directory.
|
||||
- Updated test utilities to load certificates from the central location.
|
||||
- Cleaned up redundant code and improved error logging regarding certificates.
|
||||
- Ensured correct handling of host header in ProxyRouter class.
|
||||
|
||||
## 2025-02-03 - 3.1.1 - fix(workflow)
|
||||
Update Gitea workflow paths and dependencies
|
||||
|
||||
- Updated registry paths for npmci image and repositories in Gitea workflow files.
|
||||
- Fixed dependency paths in package.json.
|
||||
- Completed adding typescript to the list of devDependencies.
|
||||
|
||||
## 2024-10-07 - 3.1.0 - feat(NetworkProxy)
|
||||
Introduce WebSocket heartbeat to maintain active connections in NetworkProxy
|
||||
|
||||
- Added heartbeat mechanism to WebSocket connections to ensure they remain active.
|
||||
- Terminating WebSocket if no pong is received for 5 minutes.
|
||||
- Set up heartbeat interval to run every 1 minute for connection checks.
|
||||
|
||||
## 2024-10-07 - 3.0.61 - fix(networkproxy)
|
||||
Improve error handling for proxy requests
|
||||
|
||||
- Wrapped proxy request logic in a try-catch block to handle errors gracefully.
|
||||
- Improved error handling for WebSocket communication by checking errors before attempting to send messages.
|
||||
- Added logging for error cases to aid in debugging.
|
||||
|
||||
## 2024-05-29 - 3.0.60 - various updates
|
||||
Maintenance updates and adjustments.
|
||||
|
||||
- Updated project description
|
||||
- Updated tsconfig settings
|
||||
- Updated npmextra.json with new githost info
|
||||
|
||||
## 2023-07-27 - 3.0.58 to 3.0.59 - core improvements
|
||||
Improvements and internal restructuring.
|
||||
|
||||
- Switch to a new organizational scheme
|
||||
- Core updates and adjustments
|
||||
|
||||
## 2022-07-29 - 2.0.16 to 3.0.0 - major transition
|
||||
This release marks a major transition with several breaking changes.
|
||||
|
||||
- BREAKING CHANGE: switched core to ESM (EcmaScript Module)
|
||||
- Major core updates
|
@ -2,17 +2,37 @@
|
||||
"gitzone": {
|
||||
"projectType": "npm",
|
||||
"module": {
|
||||
"githost": "gitlab.com",
|
||||
"gitscope": "pushrocks",
|
||||
"githost": "code.foss.global",
|
||||
"gitscope": "push.rocks",
|
||||
"gitrepo": "smartproxy",
|
||||
"description": "a proxy for handling high workloads of proxying",
|
||||
"npmPackagename": "@pushrocks/smartproxy",
|
||||
"description": "A powerful proxy package that effectively handles high traffic, with features such as SSL/TLS support, port proxying, WebSocket handling, and dynamic routing with authentication options.",
|
||||
"npmPackagename": "@push.rocks/smartproxy",
|
||||
"license": "MIT",
|
||||
"projectDomain": "push.rocks"
|
||||
"projectDomain": "push.rocks",
|
||||
"keywords": [
|
||||
"proxy",
|
||||
"network",
|
||||
"traffic management",
|
||||
"SSL",
|
||||
"TLS",
|
||||
"WebSocket",
|
||||
"port proxying",
|
||||
"dynamic routing",
|
||||
"authentication",
|
||||
"real-time applications",
|
||||
"high workload",
|
||||
"HTTPS",
|
||||
"reverse proxy",
|
||||
"server",
|
||||
"network security"
|
||||
]
|
||||
}
|
||||
},
|
||||
"npmci": {
|
||||
"npmGlobalTools": [],
|
||||
"npmAccessLevel": "public"
|
||||
},
|
||||
"tsdoc": {
|
||||
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
|
||||
}
|
||||
}
|
14982
package-lock.json
generated
14982
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
65
package.json
65
package.json
@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "@pushrocks/smartproxy",
|
||||
"version": "3.0.11",
|
||||
"name": "@push.rocks/smartproxy",
|
||||
"version": "3.20.0",
|
||||
"private": false,
|
||||
"description": "a proxy for handling high workloads of proxying",
|
||||
"description": "A powerful proxy package that effectively handles high traffic, with features such as SSL/TLS support, port proxying, WebSocket handling, and dynamic routing with authentication options.",
|
||||
"main": "dist_ts/index.js",
|
||||
"typings": "dist_ts/index.d.ts",
|
||||
"type": "module",
|
||||
@ -15,19 +15,26 @@
|
||||
"buildDocs": "tsdoc"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@gitzone/tsbuild": "^2.1.63",
|
||||
"@gitzone/tstest": "^1.0.72",
|
||||
"@pushrocks/tapbundle": "^5.0.4",
|
||||
"@types/node": "^18.6.2"
|
||||
"@git.zone/tsbuild": "^2.1.66",
|
||||
"@git.zone/tsrun": "^1.2.44",
|
||||
"@git.zone/tstest": "^1.0.77",
|
||||
"@push.rocks/tapbundle": "^5.5.6",
|
||||
"@types/node": "^22.13.0",
|
||||
"typescript": "^5.7.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@pushrocks/lik": "^6.0.0",
|
||||
"@pushrocks/smartpromise": "^3.1.7",
|
||||
"@pushrocks/smartrequest": "^2.0.0",
|
||||
"@pushrocks/smartstring": "^4.0.2",
|
||||
"@tsclass/tsclass": "^4.0.17",
|
||||
"@types/ws": "^8.5.3",
|
||||
"ws": "^8.8.1"
|
||||
"@push.rocks/lik": "^6.1.0",
|
||||
"@push.rocks/smartdelay": "^3.0.5",
|
||||
"@push.rocks/smartpromise": "^4.2.2",
|
||||
"@push.rocks/smartrequest": "^2.0.23",
|
||||
"@push.rocks/smartstring": "^4.0.15",
|
||||
"@tsclass/tsclass": "^4.4.0",
|
||||
"@types/minimatch": "^5.1.2",
|
||||
"@types/ws": "^8.5.14",
|
||||
"acme-client": "^5.4.0",
|
||||
"minimatch": "^9.0.3",
|
||||
"pretty-ms": "^9.2.0",
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"files": [
|
||||
"ts/**/*",
|
||||
@ -43,5 +50,33 @@
|
||||
],
|
||||
"browserslist": [
|
||||
"last 1 chrome versions"
|
||||
]
|
||||
],
|
||||
"keywords": [
|
||||
"proxy",
|
||||
"network",
|
||||
"traffic management",
|
||||
"SSL",
|
||||
"TLS",
|
||||
"WebSocket",
|
||||
"port proxying",
|
||||
"dynamic routing",
|
||||
"authentication",
|
||||
"real-time applications",
|
||||
"high workload",
|
||||
"HTTPS",
|
||||
"reverse proxy",
|
||||
"server",
|
||||
"network security"
|
||||
],
|
||||
"homepage": "https://code.foss.global/push.rocks/smartproxy#readme",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://code.foss.global/push.rocks/smartproxy.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://code.foss.global/push.rocks/smartproxy/issues"
|
||||
},
|
||||
"pnpm": {
|
||||
"overrides": {}
|
||||
}
|
||||
}
|
||||
|
9892
pnpm-lock.yaml
generated
Normal file
9892
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
1
readme.hints.md
Normal file
1
readme.hints.md
Normal file
@ -0,0 +1 @@
|
||||
|
261
readme.md
261
readme.md
@ -1,41 +1,244 @@
|
||||
# @pushrocks/smartproxy
|
||||
a proxy for handling high workloads of proxying
|
||||
# @push.rocks/smartproxy
|
||||
|
||||
## Availabililty and Links
|
||||
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smartproxy)
|
||||
* [gitlab.com (source)](https://gitlab.com/pushrocks/smartproxy)
|
||||
* [github.com (source mirror)](https://github.com/pushrocks/smartproxy)
|
||||
* [docs (typedoc)](https://pushrocks.gitlab.io/smartproxy/)
|
||||
A robust and versatile proxy package designed to handle high workloads, offering features like SSL redirection, port proxying, WebSocket support, and customizable routing and authentication.
|
||||
|
||||
## Status for master
|
||||
## Install
|
||||
|
||||
Status Category | Status Badge
|
||||
-- | --
|
||||
GitLab Pipelines | [](https://lossless.cloud)
|
||||
GitLab Pipline Test Coverage | [](https://lossless.cloud)
|
||||
npm | [](https://lossless.cloud)
|
||||
Snyk | [](https://lossless.cloud)
|
||||
TypeScript Support | [](https://lossless.cloud)
|
||||
node Support | [](https://nodejs.org/dist/latest-v10.x/docs/api/)
|
||||
Code Style | [](https://lossless.cloud)
|
||||
PackagePhobia (total standalone install weight) | [](https://lossless.cloud)
|
||||
PackagePhobia (package size on registry) | [](https://lossless.cloud)
|
||||
BundlePhobia (total size when bundled) | [](https://lossless.cloud)
|
||||
Platform support | [](https://lossless.cloud) [](https://lossless.cloud)
|
||||
To install `@push.rocks/smartproxy`, run the following command in your project's root directory:
|
||||
|
||||
```bash
|
||||
npm install @push.rocks/smartproxy --save
|
||||
```
|
||||
|
||||
This will add `@push.rocks/smartproxy` to your project's dependencies.
|
||||
|
||||
## Usage
|
||||
|
||||
## Contribution
|
||||
`@push.rocks/smartproxy` is a comprehensive package that provides advanced functionalities for handling proxy tasks efficiently, including SSL redirection, port proxying, WebSocket support, and dynamic routing with authentication capabilities. Here is an extensive guide on how to utilize these features effectively, ensuring robust and secure proxy operations.
|
||||
|
||||
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). :)
|
||||
### Initial Setup
|
||||
|
||||
## Contribution
|
||||
Before exploring the advanced features of `smartproxy`, you need to set up a basic proxy server. This setup serves as the foundation for incorporating additional functionalities later on:
|
||||
|
||||
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). :)
|
||||
```typescript
|
||||
import { NetworkProxy } from '@push.rocks/smartproxy';
|
||||
|
||||
For further information read the linked docs at the top of this readme.
|
||||
// Create an instance of NetworkProxy with the desired configuration
|
||||
const myNetworkProxy = new NetworkProxy({ port: 443 });
|
||||
|
||||
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
|
||||
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
|
||||
// Define reverse proxy configurations for the domains you wish to proxy
|
||||
const proxyConfigs = [
|
||||
{
|
||||
destinationIp: '127.0.0.1',
|
||||
destinationPort: '3000',
|
||||
hostName: 'example.com',
|
||||
privateKey: `-----BEGIN PRIVATE KEY-----
|
||||
PRIVATE_KEY_CONTENT
|
||||
-----END PRIVATE KEY-----`,
|
||||
publicKey: `-----BEGIN CERTIFICATE-----
|
||||
CERTIFICATE_CONTENT
|
||||
-----END CERTIFICATE-----`,
|
||||
},
|
||||
// Additional configurations can be added here
|
||||
];
|
||||
|
||||
[](https://maintainedby.lossless.com)
|
||||
// Start the network proxy to enable forwarding
|
||||
await myNetworkProxy.start();
|
||||
|
||||
// Apply the configurations you defined earlier
|
||||
await myNetworkProxy.updateProxyConfigs(proxyConfigs);
|
||||
|
||||
// Optionally, you can set default headers to be included in all responses
|
||||
await myNetworkProxy.addDefaultHeaders({
|
||||
'X-Powered-By': 'smartproxy',
|
||||
});
|
||||
```
|
||||
|
||||
### Configuring SSL Redirection
|
||||
|
||||
A critical feature of modern proxy servers is the ability to redirect HTTP traffic to secure HTTPS endpoints. The `SslRedirect` class in `smartproxy` simplifies this process by automatically redirecting requests from HTTP port 80 to HTTPS:
|
||||
|
||||
```typescript
|
||||
import { SslRedirect } from '@push.rocks/smartproxy';
|
||||
|
||||
// Create an SslRedirect instance to listen on port 80
|
||||
const mySslRedirect = new SslRedirect(80);
|
||||
|
||||
// Start the redirect to enforce HTTPS
|
||||
await mySslRedirect.start();
|
||||
|
||||
// To stop HTTP redirection, use the following command:
|
||||
await mySslRedirect.stop();
|
||||
```
|
||||
|
||||
### Managing Port Proxying
|
||||
|
||||
Port proxying is essential for forwarding traffic from one port to another, an important feature for services that require dynamic port changes without downtime. Smartproxy's `PortProxy` class efficiently handles these scenarios:
|
||||
|
||||
```typescript
|
||||
import { PortProxy } from '@push.rocks/smartproxy';
|
||||
|
||||
// Set up a PortProxy to forward traffic from port 5000 to 3000
|
||||
const myPortProxy = new PortProxy(5000, 3000);
|
||||
|
||||
// Initiate the port proxy
|
||||
await myPortProxy.start();
|
||||
|
||||
// To halt the port proxy, execute:
|
||||
await myPortProxy.stop();
|
||||
```
|
||||
|
||||
For more intricate setups—such as forwarding based on specific domain rules or IP allowances—smartproxy allows detailed configurations:
|
||||
|
||||
```typescript
|
||||
import { PortProxy } from '@push.rocks/smartproxy';
|
||||
|
||||
// Configure complex port proxy rules
|
||||
const advancedPortProxy = new PortProxy({
|
||||
fromPort: 6000,
|
||||
toPort: 3000,
|
||||
domains: [
|
||||
{
|
||||
domain: 'api.example.com',
|
||||
allowedIPs: ['192.168.0.*', '127.0.0.1'],
|
||||
targetIP: '192.168.1.100'
|
||||
}
|
||||
// Additional domain rules can be added as needed
|
||||
],
|
||||
sniEnabled: true, // Server Name Indication (SNI) support
|
||||
defaultAllowedIPs: ['*'],
|
||||
});
|
||||
|
||||
// Activate the proxy with conditional rules
|
||||
await advancedPortProxy.start();
|
||||
```
|
||||
|
||||
### WebSocket Handling
|
||||
|
||||
With real-time applications becoming more prevalent, effective WebSocket handling is crucial in a proxy server. Smartproxy natively incorporates WebSocket support to manage WebSocket traffic securely and efficiently:
|
||||
|
||||
```typescript
|
||||
import { NetworkProxy } from '@push.rocks/smartproxy';
|
||||
|
||||
// Create a NetworkProxy instance for WebSocket traffic
|
||||
const wsNetworkProxy = new NetworkProxy({ port: 443 });
|
||||
|
||||
// Define proxy configurations targeted for WebSocket traffic
|
||||
const websocketConfig = [
|
||||
{
|
||||
destinationIp: '127.0.0.1',
|
||||
destinationPort: '8080',
|
||||
hostName: 'socket.example.com',
|
||||
// Include SSL details if necessary
|
||||
}
|
||||
];
|
||||
|
||||
// Start the proxy and apply WebSocket settings
|
||||
await wsNetworkProxy.start();
|
||||
await wsNetworkProxy.updateProxyConfigs(websocketConfig);
|
||||
|
||||
// Set heartbeat intervals to maintain WebSocket connections
|
||||
wsNetworkProxy.heartbeatInterval = setInterval(() => {
|
||||
// Logic for connection health checks
|
||||
}, 60000); // every minute
|
||||
|
||||
// Capture and handle server errors for resiliency
|
||||
wsNetworkProxy.httpsServer.on('error', (error) => console.log('Server Error:', error));
|
||||
```
|
||||
|
||||
### Advanced Routing and Custom Features
|
||||
|
||||
Smartproxy shines with its dynamic routing capabilities, allowing for custom and advanced request routing based on the request's destination. This enables extensive flexibility, such as directing API requests or facilitating intricate B2B integrations:
|
||||
|
||||
```typescript
|
||||
import { NetworkProxy } from '@push.rocks/smartproxy';
|
||||
|
||||
// Instantiate a proxy with dynamic routing
|
||||
const routeProxy = new NetworkProxy({ port: 8443 });
|
||||
|
||||
routeProxy.router.setNewProxyConfigs([
|
||||
{
|
||||
destinationIp: '192.168.1.150',
|
||||
destinationPort: '80',
|
||||
hostName: 'dynamic.example.com',
|
||||
authentication: {
|
||||
type: 'Basic',
|
||||
user: 'admin',
|
||||
pass: 'password123'
|
||||
}
|
||||
}
|
||||
]);
|
||||
|
||||
// Activate the routing proxy
|
||||
await routeProxy.start();
|
||||
```
|
||||
|
||||
For those who require granular traffic control, integrating tools like `iptables` offers additional power over network management:
|
||||
|
||||
```typescript
|
||||
import { IPTablesProxy } from '@push.rocks/smartproxy';
|
||||
|
||||
// Set up IPTables for sophisticated network traffic management
|
||||
const iptablesProxy = new IPTablesProxy({
|
||||
fromPort: 8081,
|
||||
toPort: 8080,
|
||||
deleteOnExit: true // Clean up rules when the server shuts down
|
||||
});
|
||||
|
||||
// Enable routing through IPTables
|
||||
await iptablesProxy.start();
|
||||
```
|
||||
|
||||
### Integrating SSL and HTTP/HTTPS Credentials
|
||||
|
||||
Handling sensitive data like SSL keys and certificates securely is crucial in proxy configurations:
|
||||
|
||||
```typescript
|
||||
import { loadDefaultCertificates } from '@push.rocks/smartproxy';
|
||||
|
||||
try {
|
||||
const { privateKey, publicKey } = loadDefaultCertificates(); // Adjust path if necessary
|
||||
console.log('SSL certificates loaded successfully.');
|
||||
// Use these credentials in your configurations
|
||||
} catch (error) {
|
||||
console.error('Error loading certificates:', error);
|
||||
}
|
||||
```
|
||||
|
||||
### Testing and Validation
|
||||
|
||||
Smartproxy supports extensive testing to ensure your proxy configurations operate as expected. Leveraging `tap` alongside TypeScript testing frameworks supports quality assurance:
|
||||
|
||||
```typescript
|
||||
import { expect, tap } from '@push.rocks/tapbundle';
|
||||
import { NetworkProxy } from '@push.rocks/smartproxy';
|
||||
|
||||
tap.test('Check proxied request returns status 200', async () => {
|
||||
// Testing logic
|
||||
});
|
||||
|
||||
tap.start();
|
||||
```
|
||||
|
||||
### Conclusion
|
||||
|
||||
`@push.rocks/smartproxy` is designed for both simple and complex proxying demands, offering tools for high-performance and secure proxy management across diverse environments. Its efficient configurations are capable of supporting SSL redirection, WebSocket traffic, dynamic routing, and other advanced functionalities, making it indispensable for developers seeking robust and adaptable proxy solutions. By integrating these capabilities with ease of use, `smartproxy` stands out as an essential tool in modern software architecture.
|
||||
|
||||
## License and Legal Information
|
||||
|
||||
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
|
||||
|
||||
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
|
||||
|
||||
### Trademarks
|
||||
|
||||
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
|
||||
|
||||
### Company Information
|
||||
|
||||
Task Venture Capital GmbH
|
||||
Registered at District court Bremen HRB 35230 HB, Germany
|
||||
|
||||
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
|
||||
|
||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
||||
|
@ -1,27 +0,0 @@
|
||||
-----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
|
||||
KrhAveXfEw7tAOEHiYicmAdIFtyzh++ZWb8mgbBeqij1MP/76Jv+cc0lUqpfRo/A
|
||||
qytAsPAILuyL1o1jh28JHcq+v+WYn/FEhjUlH6emhGKGlsAjhUPjzK8MEshNolhj
|
||||
t2UXw9WB5B2xWvrqlNMy0F3NAZBkZ/+k21HZo6FmVi+q6OEGcOo7wJt6wrH/lko9
|
||||
LxX96GC1JoN1Pfr2FoTKy1WHzrSfyGmDIUCrbaYQ58UuMOR+5eIPPdkf/030u5eX
|
||||
xXhF2fBujD57E2zQGh/l2MrOjamcSo0+wYhOqlX3WNdaKNAzPqloBnF6w7eqLYde
|
||||
h9He39ySmxjENwv3miOjEP1sBeMBSRfL/ckEonfK5uJgYA5nVMQ3ojUeDMZzLfFE
|
||||
Ue2WHt+uPyYk7mMZfOrK2uHzI2/Coqj7lbfRodFwj+fCArYBck2NZannDPKA6X8V
|
||||
TzJTbTCteOUUJTrcfZ0gGhGkF4nYLmX5OI+TPqrDJf0fZ+mzAEHzDDVXcBYpYRDr
|
||||
r8d9QwrK+WaqVi2ofbMfMByVF72jgeJNa4nxwT9bVbu/Q1T2Lt+YPb4pQ7yCoUgS
|
||||
JNj2Dr5H0XoLFFnvuvzcRbhlJ9J67JzR+7g=
|
||||
-----END CERTIFICATE-----
|
37
test/helpers/certificates.ts
Normal file
37
test/helpers/certificates.ts
Normal file
@ -0,0 +1,37 @@
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import * as tls from 'tls';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
export interface TestCertificates {
|
||||
privateKey: string;
|
||||
publicKey: string;
|
||||
}
|
||||
|
||||
export function loadTestCertificates(): TestCertificates {
|
||||
const certPath = path.join(__dirname, '..', '..', 'assets', 'certs', 'cert.pem');
|
||||
const keyPath = path.join(__dirname, '..', '..', 'assets', 'certs', 'key.pem');
|
||||
|
||||
// Read certificates
|
||||
const publicKey = fs.readFileSync(certPath, 'utf8');
|
||||
const privateKey = fs.readFileSync(keyPath, 'utf8');
|
||||
|
||||
// Validate certificates
|
||||
try {
|
||||
// Try to create a secure context with the certificates
|
||||
tls.createSecureContext({
|
||||
cert: publicKey,
|
||||
key: privateKey
|
||||
});
|
||||
} catch (error) {
|
||||
throw new Error(`Invalid certificates: ${error.message}`);
|
||||
}
|
||||
|
||||
return {
|
||||
privateKey,
|
||||
publicKey
|
||||
};
|
||||
}
|
52
test/key.pem
52
test/key.pem
@ -1,52 +0,0 @@
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIIJRQIBADANBgkqhkiG9w0BAQEFAASCCS8wggkrAgEAAoICAQDi2F/0kQr96mhe
|
||||
3yEWvy2mRHOZoSSBtIqg6Bre4ZcMu901/cHNIjFnynNGFl9Se61yZbW2F3PfCt7+
|
||||
kQlHug1Cx+LFssvz+hLlB5cqJQZfRKx92DhbROygtxG9r7UBmx/fwx+JQ+HOHX9R
|
||||
b+szLBZqxrNDBFl2SRdviconYgVnHbaqcAPj/lK6D6x94qgUEX+vMjbIruuiCe3u
|
||||
RbYse/quzAednVnY/+BuGVn8SEb2EVVFnBEsOxxYpy5ZzGR48O3YnWkM2oPpJhrp
|
||||
mMYLcARMnDmIQDVstD1i+MM2lVhx/pm9xKKUgWNJC7lyz2xRscZ4pOtLkfN94leH
|
||||
U98nIvxfQe7tQFKN9K52yjdtoT0UaIEUFbZyddkoNka1Xx6r+rE96046BLT2lVs0
|
||||
/rnTxZUFH6vP3z9UNktmpxtnZSk67Pj6QAqZtgT0amXEpBlk7vBYSjHsyJ3+5R1y
|
||||
oSjhAqeejq6M67NDOflrag5LSTkeTe4dqk0laVb1gjcse18AOlgf7pw5H79zclYH
|
||||
NAnoAPua683MD2ZZd4eovEww/imSZvui3NlisSSh1SomABDFxiEaHpewI98n8P1E
|
||||
3vfg4lyCV5VcUjwrPjnkfEJbX1c1/PXqTtPqSqFn/pI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DNUhn7P/UJkGFkx+yUSGFUZdLsM
|
||||
orfBWUCPXSzPttmXBJbO+Nr+rP+86KvgdI/AT0vYFNdINomEjxsfpaxjOAaW0wfz
|
||||
8jCyWKoZ0gJNEeK32GO5UA7dcgBHD3vQWa3lijo8COsznboaJe7M6PQpa/2S2H3+
|
||||
4P5msQKCAQEAx7NP3y+5ttfTd/eQ7/cg1/0y2WxvpOYNLt6MWz4rPWyD6QwidzTG
|
||||
pjuQFQ5Ods+BwJ/Jbirb7l4GMAxfIbEPAkPTHpvswO0xcncSYxl0sSP/WIA6sbcM
|
||||
dp7B/scdORC8Y6i8oPdCyxyCTd2SBrmGr2krAXmQquT72eusyP5E8HFhCy1iYt22
|
||||
aL68dZLv9/sRAF08t9Wy+eYjD/hCj67t7uGCZQT8wJbKr8aJcjwVwJgghh+3EydK
|
||||
h+7fBVO49PLL0NWy+8GT8y7a04calFfLvZEA2UMaunBis3dE1KMFfJL/0JO+sKnF
|
||||
2TkK01XDDJURK5Lhuvc7WrK2rSJ/fK+0GA==
|
||||
-----END PRIVATE KEY-----
|
250
test/test.portproxy.ts
Normal file
250
test/test.portproxy.ts
Normal file
@ -0,0 +1,250 @@
|
||||
import { expect, tap } from '@push.rocks/tapbundle';
|
||||
import * as net from 'net';
|
||||
import { PortProxy } from '../ts/classes.portproxy.js';
|
||||
|
||||
let testServer: net.Server;
|
||||
let portProxy: PortProxy;
|
||||
const TEST_SERVER_PORT = 4000;
|
||||
const PROXY_PORT = 4001;
|
||||
const TEST_DATA = 'Hello through port proxy!';
|
||||
|
||||
// Helper: Creates a test TCP server that listens on a given port and host.
|
||||
function createTestServer(port: number, host: string = 'localhost'): Promise<net.Server> {
|
||||
return new Promise((resolve) => {
|
||||
const server = net.createServer((socket) => {
|
||||
socket.on('data', (data) => {
|
||||
// Echo the received data back with a prefix.
|
||||
socket.write(`Echo: ${data.toString()}`);
|
||||
});
|
||||
socket.on('error', (error) => {
|
||||
console.error(`[Test Server] Socket error on ${host}:${port}:`, error);
|
||||
});
|
||||
});
|
||||
server.listen(port, host, () => {
|
||||
console.log(`[Test Server] Listening on ${host}:${port}`);
|
||||
resolve(server);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Helper: Creates a test client connection.
|
||||
function createTestClient(port: number, data: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const client = new net.Socket();
|
||||
let response = '';
|
||||
client.connect(port, 'localhost', () => {
|
||||
console.log('[Test Client] Connected to server');
|
||||
client.write(data);
|
||||
});
|
||||
client.on('data', (chunk) => {
|
||||
response += chunk.toString();
|
||||
client.end();
|
||||
});
|
||||
client.on('end', () => resolve(response));
|
||||
client.on('error', (error) => reject(error));
|
||||
});
|
||||
}
|
||||
|
||||
// SETUP: Create a test server and a PortProxy instance.
|
||||
tap.test('setup port proxy test environment', async () => {
|
||||
testServer = await createTestServer(TEST_SERVER_PORT);
|
||||
portProxy = new PortProxy({
|
||||
fromPort: PROXY_PORT,
|
||||
toPort: TEST_SERVER_PORT,
|
||||
targetIP: 'localhost',
|
||||
domainConfigs: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1'],
|
||||
globalPortRanges: []
|
||||
});
|
||||
});
|
||||
|
||||
// Test that the proxy starts and its servers are listening.
|
||||
tap.test('should start port proxy', async () => {
|
||||
await portProxy.start();
|
||||
expect((portProxy as any).netServers.every((server: net.Server) => server.listening)).toBeTrue();
|
||||
});
|
||||
|
||||
// Test basic TCP forwarding.
|
||||
tap.test('should forward TCP connections and data to localhost', async () => {
|
||||
const response = await createTestClient(PROXY_PORT, TEST_DATA);
|
||||
expect(response).toEqual(`Echo: ${TEST_DATA}`);
|
||||
});
|
||||
|
||||
// Test proxy with a custom target host.
|
||||
tap.test('should forward TCP connections to custom host', async () => {
|
||||
const customHostProxy = new PortProxy({
|
||||
fromPort: PROXY_PORT + 1,
|
||||
toPort: TEST_SERVER_PORT,
|
||||
targetIP: '127.0.0.1',
|
||||
domainConfigs: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1'],
|
||||
globalPortRanges: []
|
||||
});
|
||||
|
||||
await customHostProxy.start();
|
||||
const response = await createTestClient(PROXY_PORT + 1, TEST_DATA);
|
||||
expect(response).toEqual(`Echo: ${TEST_DATA}`);
|
||||
await customHostProxy.stop();
|
||||
});
|
||||
|
||||
// Test forced domain routing via port-range configuration.
|
||||
// In this test, we want to forward to a different IP (using '127.0.0.2')
|
||||
// while keeping the same port. We create a test server on '127.0.0.2'.
|
||||
tap.test('should forward connections based on domain-specific target IP (forced domain via port-range)', async () => {
|
||||
const forcedProxyPort = PROXY_PORT + 2;
|
||||
// Create a test server listening on '127.0.0.2' at forcedProxyPort.
|
||||
const testServer2 = await createTestServer(forcedProxyPort, '127.0.0.2');
|
||||
|
||||
const domainProxy = new PortProxy({
|
||||
fromPort: forcedProxyPort,
|
||||
toPort: TEST_SERVER_PORT, // default target port (unused for forced domain)
|
||||
targetIP: 'localhost',
|
||||
domainConfigs: [{
|
||||
domains: ['forced.test'],
|
||||
allowedIPs: ['127.0.0.1'],
|
||||
targetIPs: ['127.0.0.2'], // Use a different IP than the default.
|
||||
portRanges: [{ from: forcedProxyPort, to: forcedProxyPort }]
|
||||
}],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1'],
|
||||
globalPortRanges: [{ from: forcedProxyPort, to: forcedProxyPort }]
|
||||
});
|
||||
|
||||
await domainProxy.start();
|
||||
|
||||
// When connecting to forcedProxyPort, forced domain handling triggers,
|
||||
// so the proxy will connect to '127.0.0.2' on the same port.
|
||||
const response = await createTestClient(forcedProxyPort, TEST_DATA);
|
||||
expect(response).toEqual(`Echo: ${TEST_DATA}`);
|
||||
|
||||
await domainProxy.stop();
|
||||
await new Promise<void>((resolve) => testServer2.close(() => resolve()));
|
||||
});
|
||||
|
||||
// Test handling of multiple concurrent connections.
|
||||
tap.test('should handle multiple concurrent connections', async () => {
|
||||
const concurrentRequests = 5;
|
||||
const requests = Array(concurrentRequests).fill(null).map((_, i) =>
|
||||
createTestClient(PROXY_PORT, `${TEST_DATA} ${i + 1}`)
|
||||
);
|
||||
const responses = await Promise.all(requests);
|
||||
responses.forEach((response, i) => {
|
||||
expect(response).toEqual(`Echo: ${TEST_DATA} ${i + 1}`);
|
||||
});
|
||||
});
|
||||
|
||||
// Test connection timeout handling.
|
||||
tap.test('should handle connection timeouts', async () => {
|
||||
const client = new net.Socket();
|
||||
await new Promise<void>((resolve) => {
|
||||
client.connect(PROXY_PORT, 'localhost', () => {
|
||||
// Do not send any data to trigger a timeout.
|
||||
client.on('close', () => resolve());
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Test stopping the port proxy.
|
||||
tap.test('should stop port proxy', async () => {
|
||||
await portProxy.stop();
|
||||
expect((portProxy as any).netServers.every((server: net.Server) => !server.listening)).toBeTrue();
|
||||
});
|
||||
|
||||
// Test chained proxies with and without source IP preservation.
|
||||
tap.test('should support optional source IP preservation in chained proxies', async () => {
|
||||
// Chained proxies without IP preservation.
|
||||
const firstProxyDefault = new PortProxy({
|
||||
fromPort: PROXY_PORT + 4,
|
||||
toPort: PROXY_PORT + 5,
|
||||
targetIP: 'localhost',
|
||||
domainConfigs: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1', '::ffff:127.0.0.1'],
|
||||
globalPortRanges: []
|
||||
});
|
||||
const secondProxyDefault = new PortProxy({
|
||||
fromPort: PROXY_PORT + 5,
|
||||
toPort: TEST_SERVER_PORT,
|
||||
targetIP: 'localhost',
|
||||
domainConfigs: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1', '::ffff:127.0.0.1'],
|
||||
globalPortRanges: []
|
||||
});
|
||||
await secondProxyDefault.start();
|
||||
await firstProxyDefault.start();
|
||||
const response1 = await createTestClient(PROXY_PORT + 4, TEST_DATA);
|
||||
expect(response1).toEqual(`Echo: ${TEST_DATA}`);
|
||||
await firstProxyDefault.stop();
|
||||
await secondProxyDefault.stop();
|
||||
|
||||
// Chained proxies with IP preservation.
|
||||
const firstProxyPreserved = new PortProxy({
|
||||
fromPort: PROXY_PORT + 6,
|
||||
toPort: PROXY_PORT + 7,
|
||||
targetIP: 'localhost',
|
||||
domainConfigs: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1'],
|
||||
preserveSourceIP: true,
|
||||
globalPortRanges: []
|
||||
});
|
||||
const secondProxyPreserved = new PortProxy({
|
||||
fromPort: PROXY_PORT + 7,
|
||||
toPort: TEST_SERVER_PORT,
|
||||
targetIP: 'localhost',
|
||||
domainConfigs: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1'],
|
||||
preserveSourceIP: true,
|
||||
globalPortRanges: []
|
||||
});
|
||||
await secondProxyPreserved.start();
|
||||
await firstProxyPreserved.start();
|
||||
const response2 = await createTestClient(PROXY_PORT + 6, TEST_DATA);
|
||||
expect(response2).toEqual(`Echo: ${TEST_DATA}`);
|
||||
await firstProxyPreserved.stop();
|
||||
await secondProxyPreserved.stop();
|
||||
});
|
||||
|
||||
// Test round-robin behavior for multiple target IPs in a domain config.
|
||||
tap.test('should use round robin for multiple target IPs in domain config', async () => {
|
||||
const domainConfig = {
|
||||
domains: ['rr.test'],
|
||||
allowedIPs: ['127.0.0.1'],
|
||||
targetIPs: ['hostA', 'hostB']
|
||||
} as any;
|
||||
|
||||
const proxyInstance = new PortProxy({
|
||||
fromPort: 0,
|
||||
toPort: 0,
|
||||
targetIP: 'localhost',
|
||||
domainConfigs: [domainConfig],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: [],
|
||||
globalPortRanges: []
|
||||
});
|
||||
|
||||
const firstTarget = (proxyInstance as any).getTargetIP(domainConfig);
|
||||
const secondTarget = (proxyInstance as any).getTargetIP(domainConfig);
|
||||
expect(firstTarget).toEqual('hostA');
|
||||
expect(secondTarget).toEqual('hostB');
|
||||
});
|
||||
|
||||
// CLEANUP: Tear down the test server.
|
||||
tap.test('cleanup port proxy test environment', async () => {
|
||||
await new Promise<void>((resolve) => testServer.close(() => resolve()));
|
||||
});
|
||||
|
||||
process.on('exit', () => {
|
||||
if (testServer) {
|
||||
testServer.close();
|
||||
}
|
||||
if (portProxy && (portProxy as any).netServers) {
|
||||
portProxy.stop();
|
||||
}
|
||||
});
|
||||
|
||||
export default tap.start();
|
490
test/test.ts
490
test/test.ts
@ -1,116 +1,422 @@
|
||||
import { expect, tap } from '@pushrocks/tapbundle';
|
||||
import { expect, tap } from '@push.rocks/tapbundle';
|
||||
import * as smartproxy from '../ts/index.js';
|
||||
import { loadTestCertificates } from './helpers/certificates.js';
|
||||
import * as https from 'https';
|
||||
import * as http from 'http';
|
||||
import { WebSocket, WebSocketServer } from 'ws';
|
||||
|
||||
let testProxy: smartproxy.NetworkProxy;
|
||||
let testServer: http.Server;
|
||||
let wsServer: WebSocketServer;
|
||||
let testCertificates: { privateKey: string; publicKey: string };
|
||||
|
||||
tap.test('first test', async () => {
|
||||
// Helper function to make HTTPS requests
|
||||
async function makeHttpsRequest(
|
||||
options: https.RequestOptions,
|
||||
): Promise<{ statusCode: number; headers: http.IncomingHttpHeaders; body: string }> {
|
||||
console.log('[TEST] Making HTTPS request:', {
|
||||
hostname: options.hostname,
|
||||
port: options.port,
|
||||
path: options.path,
|
||||
method: options.method,
|
||||
headers: options.headers,
|
||||
});
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = https.request(options, (res) => {
|
||||
console.log('[TEST] Received HTTPS response:', {
|
||||
statusCode: res.statusCode,
|
||||
headers: res.headers,
|
||||
});
|
||||
let data = '';
|
||||
res.on('data', (chunk) => (data += chunk));
|
||||
res.on('end', () => {
|
||||
console.log('[TEST] Response completed:', { data });
|
||||
resolve({
|
||||
statusCode: res.statusCode!,
|
||||
headers: res.headers,
|
||||
body: data,
|
||||
});
|
||||
});
|
||||
});
|
||||
req.on('error', (error) => {
|
||||
console.error('[TEST] Request error:', error);
|
||||
reject(error);
|
||||
});
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
// Setup test environment
|
||||
tap.test('setup test environment', async () => {
|
||||
// Load and validate certificates
|
||||
console.log('[TEST] Loading and validating certificates');
|
||||
testCertificates = loadTestCertificates();
|
||||
console.log('[TEST] Certificates loaded and validated');
|
||||
|
||||
// Create a test HTTP server
|
||||
testServer = http.createServer((req, res) => {
|
||||
console.log('[TEST SERVER] Received HTTP request:', {
|
||||
url: req.url,
|
||||
method: req.method,
|
||||
headers: req.headers,
|
||||
});
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.end('Hello from test server!');
|
||||
});
|
||||
|
||||
// Handle WebSocket upgrade requests
|
||||
testServer.on('upgrade', (request, socket, head) => {
|
||||
console.log('[TEST SERVER] Received WebSocket upgrade request:', {
|
||||
url: request.url,
|
||||
method: request.method,
|
||||
headers: {
|
||||
host: request.headers.host,
|
||||
upgrade: request.headers.upgrade,
|
||||
connection: request.headers.connection,
|
||||
'sec-websocket-key': request.headers['sec-websocket-key'],
|
||||
'sec-websocket-version': request.headers['sec-websocket-version'],
|
||||
'sec-websocket-protocol': request.headers['sec-websocket-protocol'],
|
||||
},
|
||||
});
|
||||
|
||||
if (request.headers.upgrade?.toLowerCase() !== 'websocket') {
|
||||
console.log('[TEST SERVER] Not a WebSocket upgrade request');
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[TEST SERVER] Handling WebSocket upgrade');
|
||||
wsServer.handleUpgrade(request, socket, head, (ws) => {
|
||||
console.log('[TEST SERVER] WebSocket connection upgraded');
|
||||
wsServer.emit('connection', ws, request);
|
||||
});
|
||||
});
|
||||
|
||||
// Create a WebSocket server (for the test HTTP server)
|
||||
console.log('[TEST SERVER] Creating WebSocket server');
|
||||
wsServer = new WebSocketServer({
|
||||
noServer: true,
|
||||
perMessageDeflate: false,
|
||||
clientTracking: true,
|
||||
handleProtocols: () => 'echo-protocol',
|
||||
});
|
||||
|
||||
wsServer.on('connection', (ws, request) => {
|
||||
console.log('[TEST SERVER] WebSocket connection established:', {
|
||||
url: request.url,
|
||||
headers: {
|
||||
host: request.headers.host,
|
||||
upgrade: request.headers.upgrade,
|
||||
connection: request.headers.connection,
|
||||
'sec-websocket-key': request.headers['sec-websocket-key'],
|
||||
'sec-websocket-version': request.headers['sec-websocket-version'],
|
||||
'sec-websocket-protocol': request.headers['sec-websocket-protocol'],
|
||||
},
|
||||
});
|
||||
|
||||
// Set up connection timeout
|
||||
const connectionTimeout = setTimeout(() => {
|
||||
console.error('[TEST SERVER] WebSocket connection timed out');
|
||||
ws.terminate();
|
||||
}, 5000);
|
||||
|
||||
// Clear timeout when connection is properly closed
|
||||
const clearConnectionTimeout = () => {
|
||||
clearTimeout(connectionTimeout);
|
||||
};
|
||||
|
||||
ws.on('message', (message) => {
|
||||
const msg = message.toString();
|
||||
console.log('[TEST SERVER] Received message:', msg);
|
||||
try {
|
||||
const response = `Echo: ${msg}`;
|
||||
console.log('[TEST SERVER] Sending response:', response);
|
||||
ws.send(response);
|
||||
// Clear timeout on successful message exchange
|
||||
clearConnectionTimeout();
|
||||
} catch (error) {
|
||||
console.error('[TEST SERVER] Error sending message:', error);
|
||||
}
|
||||
});
|
||||
|
||||
ws.on('error', (error) => {
|
||||
console.error('[TEST SERVER] WebSocket error:', error);
|
||||
clearConnectionTimeout();
|
||||
});
|
||||
|
||||
ws.on('close', (code, reason) => {
|
||||
console.log('[TEST SERVER] WebSocket connection closed:', {
|
||||
code,
|
||||
reason: reason.toString(),
|
||||
wasClean: code === 1000 || code === 1001,
|
||||
});
|
||||
clearConnectionTimeout();
|
||||
});
|
||||
|
||||
ws.on('ping', (data) => {
|
||||
try {
|
||||
console.log('[TEST SERVER] Received ping, sending pong');
|
||||
ws.pong(data);
|
||||
} catch (error) {
|
||||
console.error('[TEST SERVER] Error sending pong:', error);
|
||||
}
|
||||
});
|
||||
|
||||
ws.on('pong', (data) => {
|
||||
console.log('[TEST SERVER] Received pong');
|
||||
});
|
||||
});
|
||||
|
||||
wsServer.on('error', (error) => {
|
||||
console.error('Test server: WebSocket server error:', error);
|
||||
});
|
||||
|
||||
wsServer.on('headers', (headers) => {
|
||||
console.log('Test server: WebSocket headers:', headers);
|
||||
});
|
||||
|
||||
wsServer.on('close', () => {
|
||||
console.log('Test server: WebSocket server closed');
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => testServer.listen(3000, resolve));
|
||||
console.log('Test server listening on port 3000');
|
||||
});
|
||||
|
||||
tap.test('should create proxy instance', async () => {
|
||||
testProxy = new smartproxy.NetworkProxy({
|
||||
port: 3001,
|
||||
});
|
||||
expect(testProxy).toBeInstanceOf(smartproxy.NetworkProxy);
|
||||
expect(testProxy).toEqual(testProxy); // Instance equality check
|
||||
});
|
||||
|
||||
tap.test('should start the testproxy', async () => {
|
||||
tap.test('should start the proxy server', async () => {
|
||||
// Ensure any previous server is closed
|
||||
if (testProxy && testProxy.httpsServer) {
|
||||
await new Promise<void>((resolve) =>
|
||||
testProxy.httpsServer.close(() => resolve())
|
||||
);
|
||||
}
|
||||
|
||||
console.log('[TEST] Starting the proxy server');
|
||||
await testProxy.start();
|
||||
});
|
||||
console.log('[TEST] Proxy server started');
|
||||
|
||||
tap.test('should supply reverse proxy config', async () => {
|
||||
testProxy.updateProxyConfigs([
|
||||
// Configure proxy with test certificates
|
||||
// Awaiting the update ensures that the SNI context is added before any requests come in.
|
||||
await testProxy.updateProxyConfigs([
|
||||
{
|
||||
destinationIp: '127.0.0.1',
|
||||
destinationPort: '3000',
|
||||
hostName: 'push.rocks',
|
||||
privateKey: `-----BEGIN PRIVATE KEY-----
|
||||
MIIJRQIBADANBgkqhkiG9w0BAQEFAASCCS8wggkrAgEAAoICAQDi2F/0kQr96mhe
|
||||
3yEWvy2mRHOZoSSBtIqg6Bre4ZcMu901/cHNIjFnynNGFl9Se61yZbW2F3PfCt7+
|
||||
kQlHug1Cx+LFssvz+hLlB5cqJQZfRKx92DhbROygtxG9r7UBmx/fwx+JQ+HOHX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/fK+0GA==
|
||||
-----END PRIVATE KEY-----
|
||||
`,
|
||||
publicKey: `-----BEGIN CERTIFICATE-----
|
||||
MIIEljCCAn4CCQDY+ZbC9FASVjANBgkqhkiG9w0BAQsFADANMQswCQYDVQQGEwJE
|
||||
RTAeFw0xOTA5MjAxNjAxNDRaFw0yMDA5MTkxNjAxNDRaMA0xCzAJBgNVBAYTAkRF
|
||||
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA4thf9JEK/epoXt8hFr8t
|
||||
pkRzmaEkgbSKoOga3uGXDLvdNf3BzSIxZ8pzRhZfUnutcmW1thdz3wre/pEJR7oN
|
||||
QsfixbLL8/oS5QeXKiUGX0Ssfdg4W0TsoLcRva+1AZsf38MfiUPhzh1/UW/rMywW
|
||||
asazQwRZdkkXb4nKJ2IFZx22qnAD4/5Sug+sfeKoFBF/rzI2yK7rognt7kW2LHv6
|
||||
rswHnZ1Z2P/gbhlZ/EhG9hFVRZwRLDscWKcuWcxkePDt2J1pDNqD6SYa6ZjGC3AE
|
||||
TJw5iEA1bLQ9YvjDNpVYcf6ZvcSilIFjSQu5cs9sUbHGeKTrS5HzfeJXh1PfJyL8
|
||||
X0Hu7UBSjfSudso3baE9FGiBFBW2cnXZKDZGtV8eq/qxPetOOgS09pVbNP6508WV
|
||||
BR+rz98/VDZLZqcbZ2UpOuz4+kAKmbYE9GplxKQZZO7wWEox7Mid/uUdcqEo4QKn
|
||||
no6ujOuzQzn5a2oOS0k5Hk3uHapNJWlW9YI3LHtfADpYH+6cOR+/c3JWBzQJ6AD7
|
||||
muvNzA9mWXeHqLxMMP4pkmb7otzZYrEkodUqJgAQxcYhGh6XsCPfJ/D9RN734OJc
|
||||
gleVXFI8Kz455HxCW19XNfz16k7T6kqhZ/6SOBbkxEuqg7oEthAP109ZZzgx4oDo
|
||||
hQsw24TjLkI4SPIc7nr60UUCAwEAATANBgkqhkiG9w0BAQsFAAOCAgEAu0+zrg0C
|
||||
mlSv4Yi24OwB7TBvx+WHesl1IilCUdTiiUMo3NumvsU9Dr3Jkd0jGqYI0eyH4gIt
|
||||
KrhAveXfEw7tAOEHiYicmAdIFtyzh++ZWb8mgbBeqij1MP/76Jv+cc0lUqpfRo/A
|
||||
qytAsPAILuyL1o1jh28JHcq+v+WYn/FEhjUlH6emhGKGlsAjhUPjzK8MEshNolhj
|
||||
t2UXw9WB5B2xWvrqlNMy0F3NAZBkZ/+k21HZo6FmVi+q6OEGcOo7wJt6wrH/lko9
|
||||
LxX96GC1JoN1Pfr2FoTKy1WHzrSfyGmDIUCrbaYQ58UuMOR+5eIPPdkf/030u5eX
|
||||
xXhF2fBujD57E2zQGh/l2MrOjamcSo0+wYhOqlX3WNdaKNAzPqloBnF6w7eqLYde
|
||||
h9He39ySmxjENwv3miOjEP1sBeMBSRfL/ckEonfK5uJgYA5nVMQ3ojUeDMZzLfFE
|
||||
Ue2WHt+uPyYk7mMZfOrK2uHzI2/Coqj7lbfRodFwj+fCArYBck2NZannDPKA6X8V
|
||||
TzJTbTCteOUUJTrcfZ0gGhGkF4nYLmX5OI+TPqrDJf0fZ+mzAEHzDDVXcBYpYRDr
|
||||
r8d9QwrK+WaqVi2ofbMfMByVF72jgeJNa4nxwT9bVbu/Q1T2Lt+YPb4pQ7yCoUgS
|
||||
JNj2Dr5H0XoLFFnvuvzcRbhlJ9J67JzR+7g=
|
||||
-----END CERTIFICATE-----
|
||||
`,
|
||||
publicKey: testCertificates.publicKey,
|
||||
privateKey: testCertificates.privateKey,
|
||||
},
|
||||
]);
|
||||
|
||||
console.log('[TEST] Proxy configuration updated');
|
||||
});
|
||||
|
||||
tap.test('should wait for 60 seconds', async (tools) => {
|
||||
await tools.delayFor(10000);
|
||||
tap.test('should route HTTPS requests based on host header', async () => {
|
||||
// IMPORTANT: Connect to localhost (where the proxy is listening) but use the Host header "push.rocks"
|
||||
const response = await makeHttpsRequest({
|
||||
hostname: 'localhost', // changed from 'push.rocks' to 'localhost'
|
||||
port: 3001,
|
||||
path: '/',
|
||||
method: 'GET',
|
||||
headers: {
|
||||
host: 'push.rocks', // virtual host for routing
|
||||
},
|
||||
rejectUnauthorized: false,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toEqual(200);
|
||||
expect(response.body).toEqual('Hello from test server!');
|
||||
});
|
||||
|
||||
tap.test('should close the testproxy', async () => {
|
||||
tap.test('should handle unknown host headers', async () => {
|
||||
// Connect to localhost but use an unknown host header.
|
||||
const response = await makeHttpsRequest({
|
||||
hostname: 'localhost', // connecting to localhost
|
||||
port: 3001,
|
||||
path: '/',
|
||||
method: 'GET',
|
||||
headers: {
|
||||
host: 'unknown.host', // this should not match any proxy config
|
||||
},
|
||||
rejectUnauthorized: false,
|
||||
});
|
||||
|
||||
// Expect a 404 response with the appropriate error message.
|
||||
expect(response.statusCode).toEqual(404);
|
||||
expect(response.body).toEqual('This route is not available on this server.');
|
||||
});
|
||||
|
||||
tap.test('should support WebSocket connections', async () => {
|
||||
console.log('\n[TEST] ====== WebSocket Test Started ======');
|
||||
console.log('[TEST] Test server port:', 3000);
|
||||
console.log('[TEST] Proxy server port:', 3001);
|
||||
console.log('\n[TEST] Starting WebSocket test');
|
||||
|
||||
// Reconfigure proxy with test certificates if necessary
|
||||
await testProxy.updateProxyConfigs([
|
||||
{
|
||||
destinationIp: '127.0.0.1',
|
||||
destinationPort: '3000',
|
||||
hostName: 'push.rocks',
|
||||
publicKey: testCertificates.publicKey,
|
||||
privateKey: testCertificates.privateKey,
|
||||
},
|
||||
]);
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
console.log('[TEST] Creating WebSocket client');
|
||||
|
||||
// IMPORTANT: Connect to localhost but specify the SNI servername and Host header as "push.rocks"
|
||||
const wsUrl = 'wss://localhost:3001'; // changed from 'wss://push.rocks:3001'
|
||||
console.log('[TEST] Creating WebSocket connection to:', wsUrl);
|
||||
|
||||
const ws = new WebSocket(wsUrl, {
|
||||
rejectUnauthorized: false, // Accept self-signed certificates
|
||||
handshakeTimeout: 5000,
|
||||
perMessageDeflate: false,
|
||||
headers: {
|
||||
Host: 'push.rocks', // required for SNI and routing on the proxy
|
||||
Connection: 'Upgrade',
|
||||
Upgrade: 'websocket',
|
||||
'Sec-WebSocket-Version': '13',
|
||||
},
|
||||
protocol: 'echo-protocol',
|
||||
agent: new https.Agent({
|
||||
rejectUnauthorized: false, // Also needed for the underlying HTTPS connection
|
||||
}),
|
||||
});
|
||||
|
||||
console.log('[TEST] WebSocket client created');
|
||||
|
||||
let resolved = false;
|
||||
const cleanup = () => {
|
||||
if (!resolved) {
|
||||
resolved = true;
|
||||
try {
|
||||
console.log('[TEST] Cleaning up WebSocket connection');
|
||||
ws.close();
|
||||
resolve();
|
||||
} catch (error) {
|
||||
console.error('[TEST] Error during cleanup:', error);
|
||||
reject(error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
console.error('[TEST] WebSocket test timed out');
|
||||
cleanup();
|
||||
reject(new Error('WebSocket test timed out after 5 seconds'));
|
||||
}, 5000);
|
||||
|
||||
// Connection establishment events
|
||||
ws.on('upgrade', (response) => {
|
||||
console.log('[TEST] WebSocket upgrade response received:', {
|
||||
headers: response.headers,
|
||||
statusCode: response.statusCode,
|
||||
});
|
||||
});
|
||||
|
||||
ws.on('open', () => {
|
||||
console.log('[TEST] WebSocket connection opened');
|
||||
try {
|
||||
console.log('[TEST] Sending test message');
|
||||
ws.send('Hello WebSocket');
|
||||
} catch (error) {
|
||||
console.error('[TEST] Error sending message:', error);
|
||||
cleanup();
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
|
||||
ws.on('message', (message) => {
|
||||
console.log('[TEST] Received message:', message.toString());
|
||||
if (
|
||||
message.toString() === 'Hello WebSocket' ||
|
||||
message.toString() === 'Echo: Hello WebSocket'
|
||||
) {
|
||||
console.log('[TEST] Message received correctly');
|
||||
clearTimeout(timeout);
|
||||
cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
ws.on('error', (error) => {
|
||||
console.error('[TEST] WebSocket error:', error);
|
||||
cleanup();
|
||||
reject(error);
|
||||
});
|
||||
|
||||
ws.on('close', (code, reason) => {
|
||||
console.log('[TEST] WebSocket connection closed:', {
|
||||
code,
|
||||
reason: reason.toString(),
|
||||
});
|
||||
cleanup();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
tap.test('should handle custom headers', async () => {
|
||||
await testProxy.addDefaultHeaders({
|
||||
'X-Proxy-Header': 'test-value',
|
||||
});
|
||||
|
||||
const response = await makeHttpsRequest({
|
||||
hostname: 'localhost', // changed to 'localhost'
|
||||
port: 3001,
|
||||
path: '/',
|
||||
method: 'GET',
|
||||
headers: {
|
||||
host: 'push.rocks', // still routing to push.rocks
|
||||
},
|
||||
rejectUnauthorized: false,
|
||||
});
|
||||
|
||||
expect(response.headers['x-proxy-header']).toEqual('test-value');
|
||||
});
|
||||
|
||||
tap.test('cleanup', async () => {
|
||||
console.log('[TEST] Starting cleanup');
|
||||
|
||||
// Clean up all servers
|
||||
console.log('[TEST] Terminating WebSocket clients');
|
||||
wsServer.clients.forEach((client) => {
|
||||
client.terminate();
|
||||
});
|
||||
|
||||
console.log('[TEST] Closing WebSocket server');
|
||||
await new Promise<void>((resolve) =>
|
||||
wsServer.close(() => {
|
||||
console.log('[TEST] WebSocket server closed');
|
||||
resolve();
|
||||
})
|
||||
);
|
||||
|
||||
console.log('[TEST] Closing test server');
|
||||
await new Promise<void>((resolve) =>
|
||||
testServer.close(() => {
|
||||
console.log('[TEST] Test server closed');
|
||||
resolve();
|
||||
})
|
||||
);
|
||||
|
||||
console.log('[TEST] Stopping proxy');
|
||||
await testProxy.stop();
|
||||
console.log('[TEST] Cleanup complete');
|
||||
});
|
||||
|
||||
tap.start();
|
||||
process.on('exit', () => {
|
||||
console.log('[TEST] Shutting down test server');
|
||||
testServer.close(() => console.log('[TEST] Test server shut down'));
|
||||
wsServer.close(() => console.log('[TEST] WebSocket server shut down'));
|
||||
testProxy.stop().then(() => console.log('[TEST] Proxy server stopped'));
|
||||
});
|
||||
|
||||
tap.start();
|
@ -1,8 +1,8 @@
|
||||
/**
|
||||
* autocreated commitinfo by @pushrocks/commitinfo
|
||||
* autocreated commitinfo by @push.rocks/commitinfo
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@pushrocks/smartproxy',
|
||||
version: '3.0.11',
|
||||
description: 'a proxy for handling high workloads of proxying'
|
||||
name: '@push.rocks/smartproxy',
|
||||
version: '3.20.0',
|
||||
description: 'A powerful proxy package that effectively handles high traffic, with features such as SSL/TLS support, port proxying, WebSocket handling, and dynamic routing with authentication options.'
|
||||
}
|
||||
|
183
ts/classes.iptablesproxy.ts
Normal file
183
ts/classes.iptablesproxy.ts
Normal file
@ -0,0 +1,183 @@
|
||||
import { exec, execSync } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
/**
|
||||
* Settings for IPTablesProxy.
|
||||
*/
|
||||
export interface IIpTableProxySettings {
|
||||
fromPort: number;
|
||||
toPort: number;
|
||||
toHost?: string; // Target host for proxying; defaults to 'localhost'
|
||||
preserveSourceIP?: boolean; // If true, the original source IP is preserved.
|
||||
deleteOnExit?: boolean; // If true, clean up marked iptables rules before process exit.
|
||||
}
|
||||
|
||||
/**
|
||||
* IPTablesProxy sets up iptables NAT rules to forward TCP traffic.
|
||||
* It only supports basic port forwarding and uses iptables comments to tag rules.
|
||||
*/
|
||||
export class IPTablesProxy {
|
||||
public settings: IIpTableProxySettings;
|
||||
private rulesInstalled: boolean = false;
|
||||
private ruleTag: string;
|
||||
|
||||
constructor(settings: IIpTableProxySettings) {
|
||||
this.settings = {
|
||||
...settings,
|
||||
toHost: settings.toHost || 'localhost',
|
||||
};
|
||||
// Generate a unique identifier for the rules added by this instance.
|
||||
this.ruleTag = `IPTablesProxy:${Date.now()}:${Math.random().toString(36).substr(2, 5)}`;
|
||||
|
||||
// If deleteOnExit is true, register cleanup handlers.
|
||||
if (this.settings.deleteOnExit) {
|
||||
const cleanup = () => {
|
||||
try {
|
||||
IPTablesProxy.cleanSlateSync();
|
||||
} catch (err) {
|
||||
console.error('Error cleaning iptables rules on exit:', err);
|
||||
}
|
||||
};
|
||||
process.on('exit', cleanup);
|
||||
process.on('SIGINT', () => {
|
||||
cleanup();
|
||||
process.exit();
|
||||
});
|
||||
process.on('SIGTERM', () => {
|
||||
cleanup();
|
||||
process.exit();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up iptables rules for port forwarding.
|
||||
* The rules are tagged with a unique comment so that they can be identified later.
|
||||
*/
|
||||
public async start(): Promise<void> {
|
||||
const dnatCmd = `iptables -t nat -A PREROUTING -p tcp --dport ${this.settings.fromPort} ` +
|
||||
`-j DNAT --to-destination ${this.settings.toHost}:${this.settings.toPort} ` +
|
||||
`-m comment --comment "${this.ruleTag}:DNAT"`;
|
||||
try {
|
||||
await execAsync(dnatCmd);
|
||||
console.log(`Added iptables rule: ${dnatCmd}`);
|
||||
this.rulesInstalled = true;
|
||||
} catch (err) {
|
||||
console.error(`Failed to add iptables DNAT rule: ${err}`);
|
||||
throw err;
|
||||
}
|
||||
|
||||
// If preserveSourceIP is false, add a MASQUERADE rule.
|
||||
if (!this.settings.preserveSourceIP) {
|
||||
const masqueradeCmd = `iptables -t nat -A POSTROUTING -p tcp -d ${this.settings.toHost} ` +
|
||||
`--dport ${this.settings.toPort} -j MASQUERADE ` +
|
||||
`-m comment --comment "${this.ruleTag}:MASQ"`;
|
||||
try {
|
||||
await execAsync(masqueradeCmd);
|
||||
console.log(`Added iptables rule: ${masqueradeCmd}`);
|
||||
} catch (err) {
|
||||
console.error(`Failed to add iptables MASQUERADE rule: ${err}`);
|
||||
// Roll back the DNAT rule if MASQUERADE fails.
|
||||
try {
|
||||
const rollbackCmd = `iptables -t nat -D PREROUTING -p tcp --dport ${this.settings.fromPort} ` +
|
||||
`-j DNAT --to-destination ${this.settings.toHost}:${this.settings.toPort} ` +
|
||||
`-m comment --comment "${this.ruleTag}:DNAT"`;
|
||||
await execAsync(rollbackCmd);
|
||||
this.rulesInstalled = false;
|
||||
} catch (rollbackErr) {
|
||||
console.error(`Rollback failed: ${rollbackErr}`);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the iptables rules that were added in start(), by matching the unique comment.
|
||||
*/
|
||||
public async stop(): Promise<void> {
|
||||
if (!this.rulesInstalled) return;
|
||||
|
||||
const dnatDelCmd = `iptables -t nat -D PREROUTING -p tcp --dport ${this.settings.fromPort} ` +
|
||||
`-j DNAT --to-destination ${this.settings.toHost}:${this.settings.toPort} ` +
|
||||
`-m comment --comment "${this.ruleTag}:DNAT"`;
|
||||
try {
|
||||
await execAsync(dnatDelCmd);
|
||||
console.log(`Removed iptables rule: ${dnatDelCmd}`);
|
||||
} catch (err) {
|
||||
console.error(`Failed to remove iptables DNAT rule: ${err}`);
|
||||
}
|
||||
|
||||
if (!this.settings.preserveSourceIP) {
|
||||
const masqueradeDelCmd = `iptables -t nat -D POSTROUTING -p tcp -d ${this.settings.toHost} ` +
|
||||
`--dport ${this.settings.toPort} -j MASQUERADE ` +
|
||||
`-m comment --comment "${this.ruleTag}:MASQ"`;
|
||||
try {
|
||||
await execAsync(masqueradeDelCmd);
|
||||
console.log(`Removed iptables rule: ${masqueradeDelCmd}`);
|
||||
} catch (err) {
|
||||
console.error(`Failed to remove iptables MASQUERADE rule: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
this.rulesInstalled = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Asynchronously cleans up any iptables rules in the nat table that were added by this module.
|
||||
* It looks for rules with comments containing "IPTablesProxy:".
|
||||
*/
|
||||
public static async cleanSlate(): Promise<void> {
|
||||
try {
|
||||
const { stdout } = await execAsync('iptables-save -t nat');
|
||||
const lines = stdout.split('\n');
|
||||
const proxyLines = lines.filter(line => line.includes('IPTablesProxy:'));
|
||||
for (const line of proxyLines) {
|
||||
const trimmedLine = line.trim();
|
||||
if (trimmedLine.startsWith('-A')) {
|
||||
// Replace the "-A" with "-D" to form a deletion command.
|
||||
const deleteRule = trimmedLine.replace('-A', '-D');
|
||||
const cmd = `iptables -t nat ${deleteRule}`;
|
||||
try {
|
||||
await execAsync(cmd);
|
||||
console.log(`Cleaned up iptables rule: ${cmd}`);
|
||||
} catch (err) {
|
||||
console.error(`Failed to remove iptables rule: ${cmd}`, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`Failed to run iptables-save: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronously cleans up any iptables rules in the nat table that were added by this module.
|
||||
* It looks for rules with comments containing "IPTablesProxy:".
|
||||
* This method is intended for use in process exit handlers.
|
||||
*/
|
||||
public static cleanSlateSync(): void {
|
||||
try {
|
||||
const stdout = execSync('iptables-save -t nat').toString();
|
||||
const lines = stdout.split('\n');
|
||||
const proxyLines = lines.filter(line => line.includes('IPTablesProxy:'));
|
||||
for (const line of proxyLines) {
|
||||
const trimmedLine = line.trim();
|
||||
if (trimmedLine.startsWith('-A')) {
|
||||
const deleteRule = trimmedLine.replace('-A', '-D');
|
||||
const cmd = `iptables -t nat ${deleteRule}`;
|
||||
try {
|
||||
execSync(cmd);
|
||||
console.log(`Cleaned up iptables rule: ${cmd}`);
|
||||
} catch (err) {
|
||||
console.error(`Failed to remove iptables rule: ${cmd}`, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`Failed to run iptables-save: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
369
ts/classes.networkproxy.ts
Normal file
369
ts/classes.networkproxy.ts
Normal file
@ -0,0 +1,369 @@
|
||||
import * as plugins from './plugins.js';
|
||||
import { ProxyRouter } from './classes.router.js';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
export interface INetworkProxyOptions {
|
||||
port: number;
|
||||
}
|
||||
|
||||
interface IWebSocketWithHeartbeat extends plugins.wsDefault {
|
||||
lastPong: number;
|
||||
}
|
||||
|
||||
export class NetworkProxy {
|
||||
public options: INetworkProxyOptions;
|
||||
public proxyConfigs: plugins.tsclass.network.IReverseProxyConfig[] = [];
|
||||
public httpsServer: plugins.https.Server;
|
||||
public router = new ProxyRouter();
|
||||
public socketMap = new plugins.lik.ObjectMap<plugins.net.Socket>();
|
||||
public defaultHeaders: { [key: string]: string } = {};
|
||||
public heartbeatInterval: NodeJS.Timeout;
|
||||
private defaultCertificates: { key: string; cert: string };
|
||||
|
||||
public alreadyAddedReverseConfigs: {
|
||||
[hostName: string]: plugins.tsclass.network.IReverseProxyConfig;
|
||||
} = {};
|
||||
|
||||
constructor(optionsArg: INetworkProxyOptions) {
|
||||
this.options = optionsArg;
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const certPath = path.join(__dirname, '..', 'assets', 'certs');
|
||||
|
||||
try {
|
||||
this.defaultCertificates = {
|
||||
key: fs.readFileSync(path.join(certPath, 'key.pem'), 'utf8'),
|
||||
cert: fs.readFileSync(path.join(certPath, 'cert.pem'), 'utf8')
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error loading certificates:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async start() {
|
||||
// Instead of marking the callback async (which Node won't await),
|
||||
// we call our async handler and catch errors.
|
||||
this.httpsServer = plugins.https.createServer(
|
||||
{
|
||||
key: this.defaultCertificates.key,
|
||||
cert: this.defaultCertificates.cert
|
||||
},
|
||||
(originRequest, originResponse) => {
|
||||
this.handleRequest(originRequest, originResponse).catch((error) => {
|
||||
console.error('Unhandled error in request handler:', error);
|
||||
try {
|
||||
originResponse.end();
|
||||
} catch (err) {
|
||||
// ignore errors during cleanup
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// Enable websockets
|
||||
const wsServer = new plugins.ws.WebSocketServer({ server: this.httpsServer });
|
||||
|
||||
// Set up the heartbeat interval
|
||||
this.heartbeatInterval = setInterval(() => {
|
||||
wsServer.clients.forEach((ws: plugins.wsDefault) => {
|
||||
const wsIncoming = ws as IWebSocketWithHeartbeat;
|
||||
if (!wsIncoming.lastPong) {
|
||||
wsIncoming.lastPong = Date.now();
|
||||
}
|
||||
if (Date.now() - wsIncoming.lastPong > 5 * 60 * 1000) {
|
||||
console.log('Terminating websocket due to missing pong for 5 minutes.');
|
||||
wsIncoming.terminate();
|
||||
} else {
|
||||
wsIncoming.ping();
|
||||
}
|
||||
});
|
||||
}, 60000); // runs every 1 minute
|
||||
|
||||
wsServer.on(
|
||||
'connection',
|
||||
(wsIncoming: IWebSocketWithHeartbeat, reqArg: plugins.http.IncomingMessage) => {
|
||||
console.log(
|
||||
`wss proxy: got connection for wsc for https://${reqArg.headers.host}${reqArg.url}`,
|
||||
);
|
||||
|
||||
wsIncoming.lastPong = Date.now();
|
||||
wsIncoming.on('pong', () => {
|
||||
wsIncoming.lastPong = Date.now();
|
||||
});
|
||||
|
||||
let wsOutgoing: plugins.wsDefault;
|
||||
const outGoingDeferred = plugins.smartpromise.defer();
|
||||
|
||||
// --- Improvement 2: Only call routeReq once ---
|
||||
const wsDestinationConfig = this.router.routeReq(reqArg);
|
||||
if (!wsDestinationConfig) {
|
||||
wsIncoming.terminate();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
wsOutgoing = new plugins.wsDefault(
|
||||
`ws://${wsDestinationConfig.destinationIp}:${wsDestinationConfig.destinationPort}${reqArg.url}`,
|
||||
);
|
||||
console.log('wss proxy: initiated outgoing proxy');
|
||||
wsOutgoing.on('open', async () => {
|
||||
outGoingDeferred.resolve();
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error initiating outgoing WebSocket:', err);
|
||||
wsIncoming.terminate();
|
||||
return;
|
||||
}
|
||||
|
||||
wsIncoming.on('message', async (message, isBinary) => {
|
||||
try {
|
||||
await outGoingDeferred.promise;
|
||||
wsOutgoing.send(message, { binary: isBinary });
|
||||
} catch (error) {
|
||||
console.error('Error sending message to wsOutgoing:', error);
|
||||
}
|
||||
});
|
||||
|
||||
wsOutgoing.on('message', async (message, isBinary) => {
|
||||
try {
|
||||
wsIncoming.send(message, { binary: isBinary });
|
||||
} catch (error) {
|
||||
console.error('Error sending message to wsIncoming:', error);
|
||||
}
|
||||
});
|
||||
|
||||
const terminateWsOutgoing = () => {
|
||||
if (wsOutgoing) {
|
||||
wsOutgoing.terminate();
|
||||
console.log('Terminated outgoing ws.');
|
||||
}
|
||||
};
|
||||
wsIncoming.on('error', terminateWsOutgoing);
|
||||
wsIncoming.on('close', terminateWsOutgoing);
|
||||
|
||||
const terminateWsIncoming = () => {
|
||||
if (wsIncoming) {
|
||||
wsIncoming.terminate();
|
||||
console.log('Terminated incoming ws.');
|
||||
}
|
||||
};
|
||||
wsOutgoing.on('error', terminateWsIncoming);
|
||||
wsOutgoing.on('close', terminateWsIncoming);
|
||||
},
|
||||
);
|
||||
|
||||
this.httpsServer.keepAliveTimeout = 600 * 1000;
|
||||
this.httpsServer.headersTimeout = 600 * 1000;
|
||||
|
||||
this.httpsServer.on('connection', (connection: plugins.net.Socket) => {
|
||||
this.socketMap.add(connection);
|
||||
console.log(`Added connection. Now ${this.socketMap.getArray().length} sockets connected.`);
|
||||
const cleanupConnection = () => {
|
||||
if (this.socketMap.checkForObject(connection)) {
|
||||
this.socketMap.remove(connection);
|
||||
console.log(`Removed connection. ${this.socketMap.getArray().length} sockets remaining.`);
|
||||
connection.destroy();
|
||||
}
|
||||
};
|
||||
connection.on('close', cleanupConnection);
|
||||
connection.on('error', cleanupConnection);
|
||||
connection.on('end', cleanupConnection);
|
||||
connection.on('timeout', cleanupConnection);
|
||||
});
|
||||
|
||||
this.httpsServer.listen(this.options.port);
|
||||
console.log(
|
||||
`NetworkProxy -> OK: now listening for new connections on port ${this.options.port}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal async handler for processing HTTP/HTTPS requests.
|
||||
*/
|
||||
private async handleRequest(
|
||||
originRequest: plugins.http.IncomingMessage,
|
||||
originResponse: plugins.http.ServerResponse,
|
||||
): Promise<void> {
|
||||
const endOriginReqRes = (
|
||||
statusArg: number = 404,
|
||||
messageArg: string = 'This route is not available on this server.',
|
||||
headers: plugins.http.OutgoingHttpHeaders = {},
|
||||
) => {
|
||||
originResponse.writeHead(statusArg, messageArg);
|
||||
originResponse.end(messageArg);
|
||||
if (originRequest.socket !== originResponse.socket) {
|
||||
console.log('hey, something is strange.');
|
||||
}
|
||||
originResponse.destroy();
|
||||
};
|
||||
|
||||
console.log(
|
||||
`got request: ${originRequest.headers.host}${plugins.url.parse(originRequest.url).path}`,
|
||||
);
|
||||
const destinationConfig = this.router.routeReq(originRequest);
|
||||
|
||||
if (!destinationConfig) {
|
||||
console.log(
|
||||
`${originRequest.headers.host} can't be routed properly. Terminating request.`,
|
||||
);
|
||||
endOriginReqRes();
|
||||
return;
|
||||
}
|
||||
|
||||
// authentication
|
||||
if (destinationConfig.authentication) {
|
||||
const authInfo = destinationConfig.authentication;
|
||||
switch (authInfo.type) {
|
||||
case 'Basic': {
|
||||
const authHeader = originRequest.headers.authorization;
|
||||
if (!authHeader) {
|
||||
return endOriginReqRes(401, 'Authentication required', {
|
||||
'WWW-Authenticate': 'Basic realm="Access to the staging site", charset="UTF-8"',
|
||||
});
|
||||
}
|
||||
if (!authHeader.includes('Basic ')) {
|
||||
return endOriginReqRes(401, 'Authentication required', {
|
||||
'WWW-Authenticate': 'Basic realm="Access to the staging site", charset="UTF-8"',
|
||||
});
|
||||
}
|
||||
const authStringBase64 = authHeader.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 endOriginReqRes(403, 'Forbidden: Wrong credentials');
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return endOriginReqRes(
|
||||
403,
|
||||
'Forbidden: unsupported authentication method configured. Please report to the admin.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let destinationUrl: string;
|
||||
if (destinationConfig) {
|
||||
destinationUrl = `http://${destinationConfig.destinationIp}:${destinationConfig.destinationPort}${originRequest.url}`;
|
||||
} else {
|
||||
return endOriginReqRes();
|
||||
}
|
||||
console.log(destinationUrl);
|
||||
try {
|
||||
const proxyResponse = await plugins.smartrequest.request(
|
||||
destinationUrl,
|
||||
{
|
||||
method: originRequest.method,
|
||||
headers: {
|
||||
...originRequest.headers,
|
||||
'X-Forwarded-Host': originRequest.headers.host,
|
||||
'X-Forwarded-Proto': 'https',
|
||||
},
|
||||
keepAlive: true,
|
||||
},
|
||||
true, // streaming (keepAlive)
|
||||
(proxyRequest) => {
|
||||
originRequest.on('data', (data) => {
|
||||
proxyRequest.write(data);
|
||||
});
|
||||
originRequest.on('end', () => {
|
||||
proxyRequest.end();
|
||||
});
|
||||
originRequest.on('error', () => {
|
||||
proxyRequest.end();
|
||||
});
|
||||
originRequest.on('close', () => {
|
||||
proxyRequest.end();
|
||||
});
|
||||
originRequest.on('timeout', () => {
|
||||
proxyRequest.end();
|
||||
originRequest.destroy();
|
||||
});
|
||||
proxyRequest.on('error', () => {
|
||||
endOriginReqRes();
|
||||
});
|
||||
},
|
||||
);
|
||||
originResponse.statusCode = proxyResponse.statusCode;
|
||||
console.log(proxyResponse.statusCode);
|
||||
for (const defaultHeader of Object.keys(this.defaultHeaders)) {
|
||||
originResponse.setHeader(defaultHeader, this.defaultHeaders[defaultHeader]);
|
||||
}
|
||||
for (const header of Object.keys(proxyResponse.headers)) {
|
||||
originResponse.setHeader(header, proxyResponse.headers[header]);
|
||||
}
|
||||
proxyResponse.on('data', (data) => {
|
||||
originResponse.write(data);
|
||||
});
|
||||
proxyResponse.on('end', () => {
|
||||
originResponse.end();
|
||||
});
|
||||
proxyResponse.on('error', () => {
|
||||
originResponse.destroy();
|
||||
});
|
||||
proxyResponse.on('close', () => {
|
||||
originResponse.end();
|
||||
});
|
||||
proxyResponse.on('timeout', () => {
|
||||
originResponse.end();
|
||||
originResponse.destroy();
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error while processing request:', error);
|
||||
endOriginReqRes(502, 'Bad Gateway: Error processing the request');
|
||||
}
|
||||
}
|
||||
|
||||
public async updateProxyConfigs(
|
||||
proxyConfigsArg: plugins.tsclass.network.IReverseProxyConfig[],
|
||||
) {
|
||||
console.log(`got new proxy configs`);
|
||||
this.proxyConfigs = proxyConfigsArg;
|
||||
this.router.setNewProxyConfigs(proxyConfigsArg);
|
||||
for (const hostCandidate of this.proxyConfigs) {
|
||||
const existingHostNameConfig = this.alreadyAddedReverseConfigs[hostCandidate.hostName];
|
||||
|
||||
if (!existingHostNameConfig) {
|
||||
this.alreadyAddedReverseConfigs[hostCandidate.hostName] = hostCandidate;
|
||||
} else {
|
||||
if (
|
||||
existingHostNameConfig.publicKey === hostCandidate.publicKey &&
|
||||
existingHostNameConfig.privateKey === hostCandidate.privateKey
|
||||
) {
|
||||
continue;
|
||||
} else {
|
||||
this.alreadyAddedReverseConfigs[hostCandidate.hostName] = hostCandidate;
|
||||
}
|
||||
}
|
||||
|
||||
this.httpsServer.addContext(hostCandidate.hostName, {
|
||||
cert: hostCandidate.publicKey,
|
||||
key: hostCandidate.privateKey,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public async addDefaultHeaders(headersArg: { [key: string]: string }) {
|
||||
for (const headerKey of Object.keys(headersArg)) {
|
||||
this.defaultHeaders[headerKey] = headersArg[headerKey];
|
||||
}
|
||||
}
|
||||
|
||||
public async stop() {
|
||||
const done = plugins.smartpromise.defer();
|
||||
this.httpsServer.close(() => {
|
||||
done.resolve();
|
||||
});
|
||||
for (const socket of this.socketMap.getArray()) {
|
||||
socket.destroy();
|
||||
}
|
||||
await done.promise;
|
||||
clearInterval(this.heartbeatInterval);
|
||||
console.log('NetworkProxy -> OK: Server has been stopped and all connections closed.');
|
||||
}
|
||||
}
|
214
ts/classes.port80handler.ts
Normal file
214
ts/classes.port80handler.ts
Normal file
@ -0,0 +1,214 @@
|
||||
import * as http from 'http';
|
||||
import * as acme from 'acme-client';
|
||||
|
||||
interface IDomainCertificate {
|
||||
certObtained: boolean;
|
||||
obtainingInProgress: boolean;
|
||||
certificate?: string;
|
||||
privateKey?: string;
|
||||
challengeToken?: string;
|
||||
challengeKeyAuthorization?: string;
|
||||
}
|
||||
|
||||
export class Port80Handler {
|
||||
private domainCertificates: Map<string, IDomainCertificate>;
|
||||
private server: http.Server;
|
||||
private acmeClient: acme.Client | null = null;
|
||||
private accountKey: string | null = null;
|
||||
|
||||
constructor() {
|
||||
this.domainCertificates = new Map<string, IDomainCertificate>();
|
||||
|
||||
// Create and start an HTTP server on port 80.
|
||||
this.server = http.createServer((req, res) => this.handleRequest(req, res));
|
||||
this.server.listen(80, () => {
|
||||
console.log('Port80Handler is listening on port 80');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a domain to be managed.
|
||||
* @param domain The domain to add.
|
||||
*/
|
||||
public addDomain(domain: string): void {
|
||||
if (!this.domainCertificates.has(domain)) {
|
||||
this.domainCertificates.set(domain, { certObtained: false, obtainingInProgress: false });
|
||||
console.log(`Domain added: ${domain}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a domain from management.
|
||||
* @param domain The domain to remove.
|
||||
*/
|
||||
public removeDomain(domain: string): void {
|
||||
if (this.domainCertificates.delete(domain)) {
|
||||
console.log(`Domain removed: ${domain}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazy initialization of the ACME client.
|
||||
* Uses Let’s Encrypt’s production directory (for testing you might switch to staging).
|
||||
*/
|
||||
private async getAcmeClient(): Promise<acme.Client> {
|
||||
if (this.acmeClient) {
|
||||
return this.acmeClient;
|
||||
}
|
||||
// Generate a new account key and convert Buffer to string.
|
||||
this.accountKey = (await acme.forge.createPrivateKey()).toString();
|
||||
this.acmeClient = new acme.Client({
|
||||
directoryUrl: acme.directory.letsencrypt.production, // Use production for a real certificate
|
||||
// For testing, you could use:
|
||||
// directoryUrl: acme.directory.letsencrypt.staging,
|
||||
accountKey: this.accountKey,
|
||||
});
|
||||
// Create a new account. Make sure to update the contact email.
|
||||
await this.acmeClient.createAccount({
|
||||
termsOfServiceAgreed: true,
|
||||
contact: ['mailto:admin@example.com'],
|
||||
});
|
||||
return this.acmeClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles incoming HTTP requests on port 80.
|
||||
* If the request is for an ACME challenge, it responds with the key authorization.
|
||||
* If the domain has a certificate, it redirects to HTTPS; otherwise, it initiates certificate issuance.
|
||||
*/
|
||||
private handleRequest(req: http.IncomingMessage, res: http.ServerResponse): void {
|
||||
const hostHeader = req.headers.host;
|
||||
if (!hostHeader) {
|
||||
res.statusCode = 400;
|
||||
res.end('Bad Request: Host header is missing');
|
||||
return;
|
||||
}
|
||||
// Extract domain (ignoring any port in the Host header)
|
||||
const domain = hostHeader.split(':')[0];
|
||||
|
||||
// If the request is for an ACME HTTP-01 challenge, handle it.
|
||||
if (req.url && req.url.startsWith('/.well-known/acme-challenge/')) {
|
||||
this.handleAcmeChallenge(req, res, domain);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.domainCertificates.has(domain)) {
|
||||
res.statusCode = 404;
|
||||
res.end('Domain not configured');
|
||||
return;
|
||||
}
|
||||
|
||||
const domainInfo = this.domainCertificates.get(domain)!;
|
||||
|
||||
// If certificate exists, redirect to HTTPS on port 443.
|
||||
if (domainInfo.certObtained) {
|
||||
const redirectUrl = `https://${domain}:443${req.url}`;
|
||||
res.statusCode = 301;
|
||||
res.setHeader('Location', redirectUrl);
|
||||
res.end(`Redirecting to ${redirectUrl}`);
|
||||
} else {
|
||||
// Trigger certificate issuance if not already running.
|
||||
if (!domainInfo.obtainingInProgress) {
|
||||
domainInfo.obtainingInProgress = true;
|
||||
this.obtainCertificate(domain).catch(err => {
|
||||
console.error(`Error obtaining certificate for ${domain}:`, err);
|
||||
});
|
||||
}
|
||||
res.statusCode = 503;
|
||||
res.end('Certificate issuance in progress, please try again later.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Serves the ACME HTTP-01 challenge response.
|
||||
*/
|
||||
private handleAcmeChallenge(req: http.IncomingMessage, res: http.ServerResponse, domain: string): void {
|
||||
const domainInfo = this.domainCertificates.get(domain);
|
||||
if (!domainInfo) {
|
||||
res.statusCode = 404;
|
||||
res.end('Domain not configured');
|
||||
return;
|
||||
}
|
||||
// The token is the last part of the URL.
|
||||
const urlParts = req.url?.split('/');
|
||||
const token = urlParts ? urlParts[urlParts.length - 1] : '';
|
||||
if (domainInfo.challengeToken === token && domainInfo.challengeKeyAuthorization) {
|
||||
res.statusCode = 200;
|
||||
res.setHeader('Content-Type', 'text/plain');
|
||||
res.end(domainInfo.challengeKeyAuthorization);
|
||||
console.log(`Served ACME challenge response for ${domain}`);
|
||||
} else {
|
||||
res.statusCode = 404;
|
||||
res.end('Challenge token not found');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Uses acme-client to perform a full ACME HTTP-01 challenge to obtain a certificate.
|
||||
* On success, it stores the certificate and key in memory and clears challenge data.
|
||||
*/
|
||||
private async obtainCertificate(domain: string): Promise<void> {
|
||||
try {
|
||||
const client = await this.getAcmeClient();
|
||||
|
||||
// Create a new order for the domain.
|
||||
const order = await client.createOrder({
|
||||
identifiers: [{ type: 'dns', value: domain }],
|
||||
});
|
||||
|
||||
// Get the authorizations for the order.
|
||||
const authorizations = await client.getAuthorizations(order);
|
||||
for (const authz of authorizations) {
|
||||
const challenge = authz.challenges.find(ch => ch.type === 'http-01');
|
||||
if (!challenge) {
|
||||
throw new Error('HTTP-01 challenge not found');
|
||||
}
|
||||
// Get the key authorization for the challenge.
|
||||
const keyAuthorization = await client.getChallengeKeyAuthorization(challenge);
|
||||
const domainInfo = this.domainCertificates.get(domain)!;
|
||||
domainInfo.challengeToken = challenge.token;
|
||||
domainInfo.challengeKeyAuthorization = keyAuthorization;
|
||||
|
||||
// Notify the ACME server that the challenge is ready.
|
||||
// The acme-client examples show that verifyChallenge takes three arguments:
|
||||
// (authorization, challenge, keyAuthorization). However, the official TypeScript
|
||||
// types appear to be out-of-sync. As a workaround, we cast client to 'any'.
|
||||
await (client as any).verifyChallenge(authz, challenge, keyAuthorization);
|
||||
|
||||
await client.completeChallenge(challenge);
|
||||
// Wait until the challenge is validated.
|
||||
await client.waitForValidStatus(challenge);
|
||||
console.log(`HTTP-01 challenge completed for ${domain}`);
|
||||
}
|
||||
|
||||
// Generate a CSR and a new private key for the domain.
|
||||
// Convert the resulting Buffers to strings.
|
||||
const [csrBuffer, privateKeyBuffer] = await acme.forge.createCsr({
|
||||
commonName: domain,
|
||||
});
|
||||
const csr = csrBuffer.toString();
|
||||
const privateKey = privateKeyBuffer.toString();
|
||||
|
||||
// Finalize the order and obtain the certificate.
|
||||
await client.finalizeOrder(order, csr);
|
||||
const certificate = await client.getCertificate(order);
|
||||
|
||||
const domainInfo = this.domainCertificates.get(domain)!;
|
||||
domainInfo.certificate = certificate;
|
||||
domainInfo.privateKey = privateKey;
|
||||
domainInfo.certObtained = true;
|
||||
domainInfo.obtainingInProgress = false;
|
||||
delete domainInfo.challengeToken;
|
||||
delete domainInfo.challengeKeyAuthorization;
|
||||
|
||||
console.log(`Certificate obtained for ${domain}`);
|
||||
// In a production system, persist the certificate and key and reload your TLS server.
|
||||
} catch (error) {
|
||||
console.error(`Error during certificate issuance for ${domain}:`, error);
|
||||
const domainInfo = this.domainCertificates.get(domain);
|
||||
if (domainInfo) {
|
||||
domainInfo.obtainingInProgress = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
537
ts/classes.portproxy.ts
Normal file
537
ts/classes.portproxy.ts
Normal file
@ -0,0 +1,537 @@
|
||||
import * as plugins from './plugins.js';
|
||||
|
||||
/** Domain configuration with per-domain allowed port ranges */
|
||||
export interface IDomainConfig {
|
||||
domains: string[]; // Glob patterns for domain(s)
|
||||
allowedIPs: string[]; // Glob patterns for allowed IPs
|
||||
blockedIPs?: string[]; // Glob patterns for blocked IPs
|
||||
targetIPs?: string[]; // If multiple targetIPs are given, use round robin.
|
||||
portRanges?: Array<{ from: number; to: number }>; // Optional port ranges
|
||||
}
|
||||
|
||||
/** Port proxy settings including global allowed port ranges */
|
||||
export interface IPortProxySettings extends plugins.tls.TlsOptions {
|
||||
fromPort: number;
|
||||
toPort: number;
|
||||
targetIP?: string; // Global target host to proxy to, defaults to 'localhost'
|
||||
domainConfigs: IDomainConfig[];
|
||||
sniEnabled?: boolean;
|
||||
defaultAllowedIPs?: string[];
|
||||
defaultBlockedIPs?: string[];
|
||||
preserveSourceIP?: boolean;
|
||||
maxConnectionLifetime?: number; // (ms) force cleanup of long-lived connections
|
||||
globalPortRanges: Array<{ from: number; to: number }>; // Global allowed port ranges
|
||||
forwardAllGlobalRanges?: boolean; // When true, forwards all connections on global port ranges to the global targetIP
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the SNI (Server Name Indication) from a TLS ClientHello packet.
|
||||
* @param buffer - Buffer containing the TLS ClientHello.
|
||||
* @returns The server name if found, otherwise undefined.
|
||||
*/
|
||||
function extractSNI(buffer: Buffer): string | undefined {
|
||||
let offset = 0;
|
||||
if (buffer.length < 5) return undefined;
|
||||
|
||||
const recordType = buffer.readUInt8(0);
|
||||
if (recordType !== 22) return undefined; // 22 = handshake
|
||||
|
||||
const recordLength = buffer.readUInt16BE(3);
|
||||
if (buffer.length < 5 + recordLength) return undefined;
|
||||
|
||||
offset = 5;
|
||||
const handshakeType = buffer.readUInt8(offset);
|
||||
if (handshakeType !== 1) return undefined; // 1 = ClientHello
|
||||
|
||||
offset += 4; // Skip handshake header (type + length)
|
||||
offset += 2 + 32; // Skip client version and random
|
||||
|
||||
const sessionIDLength = buffer.readUInt8(offset);
|
||||
offset += 1 + sessionIDLength; // Skip session ID
|
||||
|
||||
const cipherSuitesLength = buffer.readUInt16BE(offset);
|
||||
offset += 2 + cipherSuitesLength; // Skip cipher suites
|
||||
|
||||
const compressionMethodsLength = buffer.readUInt8(offset);
|
||||
offset += 1 + compressionMethodsLength; // Skip compression methods
|
||||
|
||||
if (offset + 2 > buffer.length) return undefined;
|
||||
const extensionsLength = buffer.readUInt16BE(offset);
|
||||
offset += 2;
|
||||
const extensionsEnd = offset + extensionsLength;
|
||||
|
||||
while (offset + 4 <= extensionsEnd) {
|
||||
const extensionType = buffer.readUInt16BE(offset);
|
||||
const extensionLength = buffer.readUInt16BE(offset + 2);
|
||||
offset += 4;
|
||||
if (extensionType === 0x0000) { // SNI extension
|
||||
if (offset + 2 > buffer.length) return undefined;
|
||||
const sniListLength = buffer.readUInt16BE(offset);
|
||||
offset += 2;
|
||||
const sniListEnd = offset + sniListLength;
|
||||
while (offset + 3 < sniListEnd) {
|
||||
const nameType = buffer.readUInt8(offset++);
|
||||
const nameLen = buffer.readUInt16BE(offset);
|
||||
offset += 2;
|
||||
if (nameType === 0) { // host_name
|
||||
if (offset + nameLen > buffer.length) return undefined;
|
||||
return buffer.toString('utf8', offset, offset + nameLen);
|
||||
}
|
||||
offset += nameLen;
|
||||
}
|
||||
break;
|
||||
} else {
|
||||
offset += extensionLength;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
interface IConnectionRecord {
|
||||
incoming: plugins.net.Socket;
|
||||
outgoing: plugins.net.Socket | null;
|
||||
incomingStartTime: number;
|
||||
outgoingStartTime?: number;
|
||||
outgoingClosedTime?: number;
|
||||
lockedDomain?: string; // New field to lock this connection to the initial SNI
|
||||
connectionClosed: boolean;
|
||||
cleanupTimer?: NodeJS.Timeout; // Timer to force cleanup after max lifetime/inactivity
|
||||
}
|
||||
|
||||
// Helper: Check if a port falls within any of the given port ranges.
|
||||
const isPortInRanges = (port: number, ranges: Array<{ from: number; to: number }>): boolean => {
|
||||
return ranges.some(range => port >= range.from && port <= range.to);
|
||||
};
|
||||
|
||||
// Helper: Check if a given IP matches any of the glob patterns.
|
||||
const isAllowed = (ip: string, patterns: string[]): boolean => {
|
||||
const normalizeIP = (ip: string): string[] => {
|
||||
if (ip.startsWith('::ffff:')) {
|
||||
const ipv4 = ip.slice(7);
|
||||
return [ip, ipv4];
|
||||
}
|
||||
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(ip)) {
|
||||
return [ip, `::ffff:${ip}`];
|
||||
}
|
||||
return [ip];
|
||||
};
|
||||
const normalizedIPVariants = normalizeIP(ip);
|
||||
const expandedPatterns = patterns.flatMap(normalizeIP);
|
||||
return normalizedIPVariants.some(ipVariant =>
|
||||
expandedPatterns.some(pattern => plugins.minimatch(ipVariant, pattern))
|
||||
);
|
||||
};
|
||||
|
||||
// Helper: Check if an IP is allowed considering allowed and blocked glob patterns.
|
||||
const isGlobIPAllowed = (ip: string, allowed: string[], blocked: string[] = []): boolean => {
|
||||
if (blocked.length > 0 && isAllowed(ip, blocked)) return false;
|
||||
return isAllowed(ip, allowed);
|
||||
};
|
||||
|
||||
export class PortProxy {
|
||||
private netServers: plugins.net.Server[] = [];
|
||||
settings: IPortProxySettings;
|
||||
// Unified record tracking each connection pair.
|
||||
private connectionRecords: Set<IConnectionRecord> = new Set();
|
||||
private connectionLogger: NodeJS.Timeout | null = null;
|
||||
|
||||
// Map to track round robin indices for each domain config.
|
||||
private domainTargetIndices: Map<IDomainConfig, number> = new Map();
|
||||
|
||||
private terminationStats: {
|
||||
incoming: Record<string, number>;
|
||||
outgoing: Record<string, number>;
|
||||
} = {
|
||||
incoming: {},
|
||||
outgoing: {},
|
||||
};
|
||||
|
||||
constructor(settingsArg: IPortProxySettings) {
|
||||
this.settings = {
|
||||
...settingsArg,
|
||||
targetIP: settingsArg.targetIP || 'localhost',
|
||||
maxConnectionLifetime: settingsArg.maxConnectionLifetime || 600000,
|
||||
};
|
||||
}
|
||||
|
||||
private incrementTerminationStat(side: 'incoming' | 'outgoing', reason: string): void {
|
||||
this.terminationStats[side][reason] = (this.terminationStats[side][reason] || 0) + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans up a connection record if not already cleaned up.
|
||||
* Destroys both incoming and outgoing sockets, clears timers, and removes the record.
|
||||
* Logs the cleanup event.
|
||||
*/
|
||||
private cleanupConnection(record: IConnectionRecord, special: boolean = false): void {
|
||||
if (!record.connectionClosed) {
|
||||
record.connectionClosed = true;
|
||||
if (record.cleanupTimer) {
|
||||
clearTimeout(record.cleanupTimer);
|
||||
}
|
||||
if (!record.incoming.destroyed) {
|
||||
record.incoming.destroy();
|
||||
}
|
||||
if (record.outgoing && !record.outgoing.destroyed) {
|
||||
record.outgoing.destroy();
|
||||
}
|
||||
this.connectionRecords.delete(record);
|
||||
const remoteIP = record.incoming.remoteAddress || 'unknown';
|
||||
if (special) {
|
||||
console.log(`Special parity cleanup: Connection from ${remoteIP} cleaned up due to duration difference.`);
|
||||
} else {
|
||||
console.log(`Connection from ${remoteIP} terminated. Active connections: ${this.connectionRecords.size}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private getTargetIP(domainConfig: IDomainConfig): string {
|
||||
if (domainConfig.targetIPs && domainConfig.targetIPs.length > 0) {
|
||||
const currentIndex = this.domainTargetIndices.get(domainConfig) || 0;
|
||||
const ip = domainConfig.targetIPs[currentIndex % domainConfig.targetIPs.length];
|
||||
this.domainTargetIndices.set(domainConfig, currentIndex + 1);
|
||||
return ip;
|
||||
}
|
||||
return this.settings.targetIP!;
|
||||
}
|
||||
|
||||
public async start() {
|
||||
// Define a unified connection handler for all listening ports.
|
||||
const connectionHandler = (socket: plugins.net.Socket) => {
|
||||
const remoteIP = socket.remoteAddress || '';
|
||||
const localPort = socket.localPort; // The port on which this connection was accepted.
|
||||
const connectionRecord: IConnectionRecord = {
|
||||
incoming: socket,
|
||||
outgoing: null,
|
||||
incomingStartTime: Date.now(),
|
||||
connectionClosed: false,
|
||||
};
|
||||
this.connectionRecords.add(connectionRecord);
|
||||
console.log(`New connection from ${remoteIP} on port ${localPort}. Active connections: ${this.connectionRecords.size}`);
|
||||
|
||||
let initialDataReceived = false;
|
||||
let incomingTerminationReason: string | null = null;
|
||||
let outgoingTerminationReason: string | null = null;
|
||||
|
||||
// Local cleanup function that delegates to the class method.
|
||||
const cleanupOnce = () => {
|
||||
this.cleanupConnection(connectionRecord);
|
||||
};
|
||||
|
||||
// Helper to reject an incoming connection.
|
||||
const rejectIncomingConnection = (reason: string, logMessage: string) => {
|
||||
console.log(logMessage);
|
||||
socket.end();
|
||||
if (incomingTerminationReason === null) {
|
||||
incomingTerminationReason = reason;
|
||||
this.incrementTerminationStat('incoming', reason);
|
||||
}
|
||||
cleanupOnce();
|
||||
};
|
||||
|
||||
socket.on('error', (err: Error) => {
|
||||
const errorMessage = initialDataReceived
|
||||
? `(Immediate) Incoming socket error from ${remoteIP}: ${err.message}`
|
||||
: `(Premature) Incoming socket error from ${remoteIP} before data received: ${err.message}`;
|
||||
console.log(errorMessage);
|
||||
});
|
||||
|
||||
const handleError = (side: 'incoming' | 'outgoing') => (err: Error) => {
|
||||
const code = (err as any).code;
|
||||
let reason = 'error';
|
||||
if (code === 'ECONNRESET') {
|
||||
reason = 'econnreset';
|
||||
console.log(`ECONNRESET on ${side} side from ${remoteIP}: ${err.message}`);
|
||||
} else {
|
||||
console.log(`Error on ${side} side from ${remoteIP}: ${err.message}`);
|
||||
}
|
||||
if (side === 'incoming' && incomingTerminationReason === null) {
|
||||
incomingTerminationReason = reason;
|
||||
this.incrementTerminationStat('incoming', reason);
|
||||
} else if (side === 'outgoing' && outgoingTerminationReason === null) {
|
||||
outgoingTerminationReason = reason;
|
||||
this.incrementTerminationStat('outgoing', reason);
|
||||
}
|
||||
cleanupOnce();
|
||||
};
|
||||
|
||||
const handleClose = (side: 'incoming' | 'outgoing') => () => {
|
||||
console.log(`Connection closed on ${side} side from ${remoteIP}`);
|
||||
if (side === 'incoming' && incomingTerminationReason === null) {
|
||||
incomingTerminationReason = 'normal';
|
||||
this.incrementTerminationStat('incoming', 'normal');
|
||||
} else if (side === 'outgoing' && outgoingTerminationReason === null) {
|
||||
outgoingTerminationReason = 'normal';
|
||||
this.incrementTerminationStat('outgoing', 'normal');
|
||||
// Record the time when outgoing socket closed.
|
||||
connectionRecord.outgoingClosedTime = Date.now();
|
||||
}
|
||||
cleanupOnce();
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets up the connection to the target host.
|
||||
* @param serverName - The SNI hostname (unused when forcedDomain is provided).
|
||||
* @param initialChunk - Optional initial data chunk.
|
||||
* @param forcedDomain - If provided, overrides SNI/domain lookup (used for port-based routing).
|
||||
* @param overridePort - If provided, use this port for the outgoing connection (typically the same as the incoming port).
|
||||
*/
|
||||
const setupConnection = (serverName: string, initialChunk?: Buffer, forcedDomain?: IDomainConfig, overridePort?: number) => {
|
||||
// If a forcedDomain is provided (port-based routing), use it; otherwise, use SNI-based lookup.
|
||||
const domainConfig = forcedDomain
|
||||
? forcedDomain
|
||||
: (serverName ? this.settings.domainConfigs.find(config =>
|
||||
config.domains.some(d => plugins.minimatch(serverName, d))
|
||||
) : undefined);
|
||||
|
||||
// Effective IP check: merge allowed IPs with default allowed, and remove blocked IPs.
|
||||
if (domainConfig) {
|
||||
const effectiveAllowedIPs: string[] = [
|
||||
...domainConfig.allowedIPs,
|
||||
...(this.settings.defaultAllowedIPs || [])
|
||||
];
|
||||
const effectiveBlockedIPs: string[] = [
|
||||
...(domainConfig.blockedIPs || []),
|
||||
...(this.settings.defaultBlockedIPs || [])
|
||||
];
|
||||
if (!isGlobIPAllowed(remoteIP, effectiveAllowedIPs, effectiveBlockedIPs)) {
|
||||
return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed for domain ${domainConfig.domains.join(', ')}`);
|
||||
}
|
||||
} else if (this.settings.defaultAllowedIPs) {
|
||||
if (!isGlobIPAllowed(remoteIP, this.settings.defaultAllowedIPs, this.settings.defaultBlockedIPs || [])) {
|
||||
return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed by default allowed list`);
|
||||
}
|
||||
}
|
||||
|
||||
const targetHost = domainConfig ? this.getTargetIP(domainConfig) : this.settings.targetIP!;
|
||||
const connectionOptions: plugins.net.NetConnectOpts = {
|
||||
host: targetHost,
|
||||
port: overridePort !== undefined ? overridePort : this.settings.toPort,
|
||||
};
|
||||
if (this.settings.preserveSourceIP) {
|
||||
connectionOptions.localAddress = remoteIP.replace('::ffff:', '');
|
||||
}
|
||||
|
||||
const targetSocket = plugins.net.connect(connectionOptions);
|
||||
connectionRecord.outgoing = targetSocket;
|
||||
connectionRecord.outgoingStartTime = Date.now();
|
||||
|
||||
console.log(
|
||||
`Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
||||
`${serverName ? ` (SNI: ${serverName})` : forcedDomain ? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})` : ''}`
|
||||
);
|
||||
|
||||
if (initialChunk) {
|
||||
socket.unshift(initialChunk);
|
||||
}
|
||||
socket.setTimeout(120000);
|
||||
socket.pipe(targetSocket);
|
||||
targetSocket.pipe(socket);
|
||||
|
||||
// Attach error and close handlers.
|
||||
socket.on('error', handleError('incoming'));
|
||||
targetSocket.on('error', handleError('outgoing'));
|
||||
socket.on('close', handleClose('incoming'));
|
||||
targetSocket.on('close', handleClose('outgoing'));
|
||||
socket.on('timeout', () => {
|
||||
console.log(`Timeout on incoming side from ${remoteIP}`);
|
||||
if (incomingTerminationReason === null) {
|
||||
incomingTerminationReason = 'timeout';
|
||||
this.incrementTerminationStat('incoming', 'timeout');
|
||||
}
|
||||
cleanupOnce();
|
||||
});
|
||||
targetSocket.on('timeout', () => {
|
||||
console.log(`Timeout on outgoing side from ${remoteIP}`);
|
||||
if (outgoingTerminationReason === null) {
|
||||
outgoingTerminationReason = 'timeout';
|
||||
this.incrementTerminationStat('outgoing', 'timeout');
|
||||
}
|
||||
cleanupOnce();
|
||||
});
|
||||
socket.on('end', handleClose('incoming'));
|
||||
targetSocket.on('end', handleClose('outgoing'));
|
||||
|
||||
// Initialize a cleanup timer for max connection lifetime.
|
||||
if (this.settings.maxConnectionLifetime) {
|
||||
let incomingActive = false;
|
||||
let outgoingActive = false;
|
||||
const resetCleanupTimer = () => {
|
||||
if (this.settings.maxConnectionLifetime) {
|
||||
if (connectionRecord.cleanupTimer) {
|
||||
clearTimeout(connectionRecord.cleanupTimer);
|
||||
}
|
||||
connectionRecord.cleanupTimer = setTimeout(() => {
|
||||
console.log(`Connection from ${remoteIP} exceeded max lifetime with inactivity (${this.settings.maxConnectionLifetime}ms), forcing cleanup.`);
|
||||
cleanupOnce();
|
||||
}, this.settings.maxConnectionLifetime);
|
||||
}
|
||||
};
|
||||
|
||||
resetCleanupTimer();
|
||||
|
||||
socket.on('data', () => {
|
||||
incomingActive = true;
|
||||
if (incomingActive && outgoingActive) {
|
||||
resetCleanupTimer();
|
||||
incomingActive = false;
|
||||
outgoingActive = false;
|
||||
}
|
||||
});
|
||||
targetSocket.on('data', () => {
|
||||
outgoingActive = true;
|
||||
if (incomingActive && outgoingActive) {
|
||||
resetCleanupTimer();
|
||||
incomingActive = false;
|
||||
outgoingActive = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// --- PORT RANGE-BASED HANDLING ---
|
||||
// Only apply port-based rules if the incoming port is within one of the global port ranges.
|
||||
if (this.settings.globalPortRanges && isPortInRanges(localPort, this.settings.globalPortRanges)) {
|
||||
if (this.settings.forwardAllGlobalRanges) {
|
||||
if (this.settings.defaultAllowedIPs && !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) {
|
||||
console.log(`Connection from ${remoteIP} rejected: IP ${remoteIP} not allowed in global default allowed list.`);
|
||||
socket.end();
|
||||
return;
|
||||
}
|
||||
console.log(`Port-based connection from ${remoteIP} on port ${localPort} forwarded to global target IP ${this.settings.targetIP}.`);
|
||||
setupConnection('', undefined, {
|
||||
domains: ['global'],
|
||||
allowedIPs: this.settings.defaultAllowedIPs || [],
|
||||
blockedIPs: this.settings.defaultBlockedIPs || [],
|
||||
targetIPs: [this.settings.targetIP!],
|
||||
portRanges: []
|
||||
}, localPort);
|
||||
return;
|
||||
} else {
|
||||
// Attempt to find a matching forced domain config based on the local port.
|
||||
const forcedDomain = this.settings.domainConfigs.find(
|
||||
domain => domain.portRanges && domain.portRanges.length > 0 && isPortInRanges(localPort, domain.portRanges)
|
||||
);
|
||||
if (forcedDomain) {
|
||||
if (!isAllowed(remoteIP, forcedDomain.allowedIPs)) {
|
||||
console.log(`Connection from ${remoteIP} rejected: IP not allowed for domain ${forcedDomain.domains.join(', ')} on port ${localPort}.`);
|
||||
socket.end();
|
||||
return;
|
||||
}
|
||||
console.log(`Port-based connection from ${remoteIP} on port ${localPort} matched domain ${forcedDomain.domains.join(', ')}.`);
|
||||
setupConnection('', undefined, forcedDomain, localPort);
|
||||
return;
|
||||
}
|
||||
// Fall through to SNI/default handling if no forced domain config is found.
|
||||
}
|
||||
}
|
||||
|
||||
// --- FALLBACK: SNI-BASED HANDLING (or default when SNI is disabled) ---
|
||||
if (this.settings.sniEnabled) {
|
||||
socket.setTimeout(5000, () => {
|
||||
console.log(`Initial data timeout for ${remoteIP}`);
|
||||
socket.end();
|
||||
cleanupOnce();
|
||||
});
|
||||
|
||||
socket.once('data', (chunk: Buffer) => {
|
||||
socket.setTimeout(0);
|
||||
initialDataReceived = true;
|
||||
const serverName = extractSNI(chunk) || '';
|
||||
// Lock the connection to the negotiated SNI.
|
||||
connectionRecord.lockedDomain = serverName;
|
||||
console.log(`Received connection from ${remoteIP} with SNI: ${serverName}`);
|
||||
// Delay adding the renegotiation listener until the next tick,
|
||||
// so the initial ClientHello is not reprocessed.
|
||||
setImmediate(() => {
|
||||
socket.on('data', (renegChunk: Buffer) => {
|
||||
if (renegChunk.length > 0 && renegChunk.readUInt8(0) === 22) {
|
||||
const newSNI = extractSNI(renegChunk);
|
||||
if (newSNI && newSNI !== connectionRecord.lockedDomain) {
|
||||
console.log(`Rehandshake detected with different SNI: ${newSNI} vs locked ${connectionRecord.lockedDomain}. Terminating connection.`);
|
||||
cleanupOnce();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
setupConnection(serverName, chunk);
|
||||
});
|
||||
} else {
|
||||
initialDataReceived = true;
|
||||
if (!this.settings.defaultAllowedIPs || !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) {
|
||||
return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`);
|
||||
}
|
||||
setupConnection('');
|
||||
}
|
||||
};
|
||||
|
||||
// --- SETUP LISTENERS ---
|
||||
// Determine which ports to listen on.
|
||||
const listeningPorts = new Set<number>();
|
||||
if (this.settings.globalPortRanges && this.settings.globalPortRanges.length > 0) {
|
||||
// Listen on every port defined by the global ranges.
|
||||
for (const range of this.settings.globalPortRanges) {
|
||||
for (let port = range.from; port <= range.to; port++) {
|
||||
listeningPorts.add(port);
|
||||
}
|
||||
}
|
||||
// Also ensure the default fromPort is listened to if it isn't already in the ranges.
|
||||
listeningPorts.add(this.settings.fromPort);
|
||||
} else {
|
||||
listeningPorts.add(this.settings.fromPort);
|
||||
}
|
||||
|
||||
// Create a server for each port.
|
||||
for (const port of listeningPorts) {
|
||||
const server = plugins.net
|
||||
.createServer(connectionHandler)
|
||||
.on('error', (err: Error) => {
|
||||
console.log(`Server Error on port ${port}: ${err.message}`);
|
||||
});
|
||||
server.listen(port, () => {
|
||||
console.log(`PortProxy -> OK: Now listening on port ${port}${this.settings.sniEnabled ? ' (SNI passthrough enabled)' : ''}`);
|
||||
});
|
||||
this.netServers.push(server);
|
||||
}
|
||||
|
||||
// Log active connection count, longest running durations, and run parity checks every 10 seconds.
|
||||
this.connectionLogger = setInterval(() => {
|
||||
const now = Date.now();
|
||||
let maxIncoming = 0;
|
||||
let maxOutgoing = 0;
|
||||
for (const record of this.connectionRecords) {
|
||||
maxIncoming = Math.max(maxIncoming, now - record.incomingStartTime);
|
||||
if (record.outgoingStartTime) {
|
||||
maxOutgoing = Math.max(maxOutgoing, now - record.outgoingStartTime);
|
||||
}
|
||||
// Parity check: if outgoing socket closed and incoming remains active for >1 minute, trigger special cleanup.
|
||||
if (record.outgoingClosedTime && !record.incoming.destroyed && (now - record.outgoingClosedTime > 60000)) {
|
||||
const remoteIP = record.incoming.remoteAddress || 'unknown';
|
||||
console.log(`Parity check triggered: Incoming socket for ${remoteIP} has been active >1 minute after outgoing closed.`);
|
||||
this.cleanupConnection(record, true);
|
||||
}
|
||||
}
|
||||
console.log(
|
||||
`(Interval Log) Active connections: ${this.connectionRecords.size}. ` +
|
||||
`Longest running incoming: ${plugins.prettyMs(maxIncoming)}, outgoing: ${plugins.prettyMs(maxOutgoing)}. ` +
|
||||
`Termination stats (incoming): ${JSON.stringify(this.terminationStats.incoming)}, ` +
|
||||
`(outgoing): ${JSON.stringify(this.terminationStats.outgoing)}`
|
||||
);
|
||||
}, 10000);
|
||||
}
|
||||
|
||||
public async stop() {
|
||||
// Close all servers.
|
||||
const closePromises: Promise<void>[] = this.netServers.map(
|
||||
server =>
|
||||
new Promise<void>((resolve) => {
|
||||
server.close(() => resolve());
|
||||
})
|
||||
);
|
||||
if (this.connectionLogger) {
|
||||
clearInterval(this.connectionLogger);
|
||||
this.connectionLogger = null;
|
||||
}
|
||||
await Promise.all(closePromises);
|
||||
}
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
import * as plugins from './smartproxy.plugins.js';
|
||||
import * as plugins from './plugins.js';
|
||||
|
||||
export class ProxyRouter {
|
||||
public reverseProxyConfigs: plugins.tsclass.network.IReverseProxyConfig[] = [];
|
||||
@ -16,17 +16,18 @@ export class ProxyRouter {
|
||||
*/
|
||||
public routeReq(req: plugins.http.IncomingMessage): plugins.tsclass.network.IReverseProxyConfig {
|
||||
const originalHost = req.headers.host;
|
||||
if (!originalHost) {
|
||||
console.error('No host header found in request');
|
||||
return undefined;
|
||||
}
|
||||
// Strip port from host if present
|
||||
const hostWithoutPort = originalHost.split(':')[0];
|
||||
const correspodingReverseProxyConfig = this.reverseProxyConfigs.find((reverseConfig) => {
|
||||
return reverseConfig.hostName === originalHost;
|
||||
return reverseConfig.hostName === hostWithoutPort;
|
||||
});
|
||||
if (!correspodingReverseProxyConfig) {
|
||||
console.error(`No config found for host: ${hostWithoutPort}`);
|
||||
}
|
||||
return correspodingReverseProxyConfig;
|
||||
}
|
||||
|
||||
public routeWs(ws: plugins.wsDefault) {
|
||||
const originalHost = plugins.url.parse(ws.url).host;
|
||||
const correspodingReverseProxyConfig = this.reverseProxyConfigs.find((reverseConfig) => {
|
||||
return reverseConfig.hostName === originalHost;
|
||||
});
|
||||
return correspodingReverseProxyConfig.destinationIp;
|
||||
}
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
import * as plugins from './smartproxy.plugins.js';
|
||||
import * as plugins from './plugins.js';
|
||||
|
||||
export class SslRedirect {
|
||||
httpServer: plugins.http.Server;
|
||||
@ -29,4 +29,4 @@ export class SslRedirect {
|
||||
});
|
||||
await done.promise;
|
||||
}
|
||||
}
|
||||
}
|
30
ts/helpers.certificates.ts
Normal file
30
ts/helpers.certificates.ts
Normal file
@ -0,0 +1,30 @@
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export interface ICertificates {
|
||||
privateKey: string;
|
||||
publicKey: string;
|
||||
}
|
||||
|
||||
export function loadDefaultCertificates(): ICertificates {
|
||||
try {
|
||||
const certPath = path.join(__dirname, '..', 'assets', 'certs');
|
||||
const privateKey = fs.readFileSync(path.join(certPath, 'key.pem'), 'utf8');
|
||||
const publicKey = fs.readFileSync(path.join(certPath, 'cert.pem'), 'utf8');
|
||||
|
||||
if (!privateKey || !publicKey) {
|
||||
throw new Error('Failed to load default certificates');
|
||||
}
|
||||
|
||||
return {
|
||||
privateKey,
|
||||
publicKey
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error loading default certificates:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
@ -1,3 +1,5 @@
|
||||
export * from './smartproxy.classes.networkproxy.js';
|
||||
export * from './smartproxy.portproxy.js';
|
||||
export * from './smartproxy.classes.sslredirect.js'
|
||||
export * from './classes.iptablesproxy.js';
|
||||
export * from './classes.networkproxy.js';
|
||||
export * from './classes.portproxy.js';
|
||||
export * from './classes.port80handler.js';
|
||||
export * from './classes.sslredirect.js';
|
||||
|
30
ts/plugins.ts
Normal file
30
ts/plugins.ts
Normal file
@ -0,0 +1,30 @@
|
||||
// node native scope
|
||||
import * as http from 'http';
|
||||
import * as https from 'https';
|
||||
import * as net from 'net';
|
||||
import * as tls from 'tls';
|
||||
import * as url from 'url';
|
||||
|
||||
export { http, https, net, tls, url };
|
||||
|
||||
// tsclass scope
|
||||
import * as tsclass from '@tsclass/tsclass';
|
||||
|
||||
export { tsclass };
|
||||
|
||||
// pushrocks scope
|
||||
import * as lik from '@push.rocks/lik';
|
||||
import * as smartdelay from '@push.rocks/smartdelay';
|
||||
import * as smartpromise from '@push.rocks/smartpromise';
|
||||
import * as smartrequest from '@push.rocks/smartrequest';
|
||||
import * as smartstring from '@push.rocks/smartstring';
|
||||
|
||||
export { lik, smartdelay, smartrequest, smartpromise, smartstring };
|
||||
|
||||
// third party scope
|
||||
import prettyMs from 'pretty-ms';
|
||||
import * as ws from 'ws';
|
||||
import wsDefault from 'ws';
|
||||
import { minimatch } from 'minimatch';
|
||||
|
||||
export { prettyMs, ws, wsDefault, minimatch };
|
@ -1,337 +0,0 @@
|
||||
import * as plugins from './smartproxy.plugins.js';
|
||||
import { ProxyRouter } from './smartproxy.classes.router.js';
|
||||
|
||||
export interface INetworkProxyOptions {
|
||||
port: number;
|
||||
}
|
||||
|
||||
export class NetworkProxy {
|
||||
// INSTANCE
|
||||
public options: INetworkProxyOptions;
|
||||
public proxyConfigs: plugins.tsclass.network.IReverseProxyConfig[] = [];
|
||||
public httpsServer: plugins.https.Server;
|
||||
public router = new ProxyRouter();
|
||||
public socketMap = new plugins.lik.ObjectMap<plugins.net.Socket>();
|
||||
public defaultHeaders: { [key: string]: string } = {};
|
||||
|
||||
public alreadyAddedReverseConfigs: {
|
||||
[hostName: string]: plugins.tsclass.network.IReverseProxyConfig;
|
||||
} = {};
|
||||
|
||||
constructor(optionsArg: INetworkProxyOptions) {
|
||||
this.options = optionsArg;
|
||||
}
|
||||
|
||||
/**
|
||||
* starts the proxyInstance
|
||||
*/
|
||||
public async start() {
|
||||
this.httpsServer = plugins.https.createServer(
|
||||
// ================
|
||||
// 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
|
||||
3yEWvy2mRHOZoSSBtIqg6Bre4ZcMu901/cHNIjFnynNGFl9Se61yZbW2F3PfCt7+
|
||||
kQlHug1Cx+LFssvz+hLlB5cqJQZfRKx92DhbROygtxG9r7UBmx/fwx+JQ+HOHX9R
|
||||
b+szLBZqxrNDBFl2SRdviconYgVnHbaqcAPj/lK6D6x94qgUEX+vMjbIruuiCe3u
|
||||
RbYse/quzAednVnY/+BuGVn8SEb2EVVFnBEsOxxYpy5ZzGR48O3YnWkM2oPpJhrp
|
||||
mMYLcARMnDmIQDVstD1i+MM2lVhx/pm9xKKUgWNJC7lyz2xRscZ4pOtLkfN94leH
|
||||
U98nIvxfQe7tQFKN9K52yjdtoT0UaIEUFbZyddkoNka1Xx6r+rE96046BLT2lVs0
|
||||
/rnTxZUFH6vP3z9UNktmpxtnZSk67Pj6QAqZtgT0amXEpBlk7vBYSjHsyJ3+5R1y
|
||||
oSjhAqeejq6M67NDOflrag5LSTkeTe4dqk0laVb1gjcse18AOlgf7pw5H79zclYH
|
||||
NAnoAPua683MD2ZZd4eovEww/imSZvui3NlisSSh1SomABDFxi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9TK+0lMWoD1yAkUa4+DVDz
|
||||
z2naf466wKWfnRvnEAVJcu+hqizxrqySzlH4GDNUhn7P/UJkGFkx+yUSGFUZdLsM
|
||||
orfBWUCPXSzPttmXBJbO+Nr+rP+86KvgdI/AT0vYFNdINomEjxsfpaxjOAaW0wfz
|
||||
8jCyWKoZ0gJNEeK32GO5UA7dcgBHD3vQWa3lijo8COsznboaJe7M6PQpa/2S2H3+
|
||||
4P5msQKCAQEAx7NP3y+5ttfTd/eQ7/cg1/0y2WxvpOYNLt6MWz4rPWyD6QwidzTG
|
||||
pjuQFQ5Ods+BwJ/Jbirb7l4GMAxfIbEPAkPTHpvswO0xcncSYxl0sSP/WIA6sbcM
|
||||
dp7B/scdORC8Y6i8oPdCyxyCTd2SBrmGr2krAXmQquT72eusyP5E8HFhCy1iYt22
|
||||
aL68dZLv9/sRAF08t9Wy+eYjD/hCj67t7uGCZQT8wJbKr8aJcjwVwJgghh+3EydK
|
||||
h+7fBVO49PLL0NWy+8GT8y7a04calFfLvZEA2UMaunBis3dE1KMFfJL/0JO+sKnF
|
||||
2TkK01XDDJURK5Lhuvc7WrK2rSJ/fK+0GA==
|
||||
-----END PRIVATE KEY-----
|
||||
`,
|
||||
cert: `-----BEGIN CERTIFICATE-----
|
||||
MIIEljCCAn4CCQDY+ZbC9FASVjANBgkqhkiG9w0BAQsFADANMQswCQYDVQQGEwJE
|
||||
RTAeFw0xOTA5MjAxNjAxNDRaFw0yMDA5MTkxNjAxNDRaMA0xCzAJBgNVBAYTAkRF
|
||||
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA4thf9JEK/epoXt8hFr8t
|
||||
pkRzmaEkgbSKoOga3uGXDLvdNf3BzSIxZ8pzRhZfUnutcmW1thdz3wre/pEJR7oN
|
||||
QsfixbLL8/oS5QeXKiUGX0Ssfdg4W0TsoLcRva+1AZsf38MfiUPhzh1/UW/rMywW
|
||||
asazQwRZdkkXb4nKJ2IFZx22qnAD4/5Sug+sf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eDMZzLfFE
|
||||
Ue2WHt+uPyYk7mMZfOrK2uHzI2/Coqj7lbfRodFwj+fCArYBck2NZannDPKA6X8V
|
||||
TzJTbTCteOUUJTrcfZ0gGhGkF4nYLmX5OI+TPqrDJf0fZ+mzAEHzDDVXcBYpYRDr
|
||||
r8d9QwrK+WaqVi2ofbMfMByVF72jgeJNa4nxwT9bVbu/Q1T2Lt+YPb4pQ7yCoUgS
|
||||
JNj2Dr5H0XoLFFnvuvzcRbhlJ9J67JzR+7g=
|
||||
-----END CERTIFICATE-----
|
||||
`,
|
||||
},
|
||||
async (req, res) => {
|
||||
/**
|
||||
* endRequest function
|
||||
* can be used to prematurely end a request
|
||||
*/
|
||||
const endRequest = (
|
||||
statusArg: number = 404,
|
||||
messageArg: string = 'This route is not available on this server.',
|
||||
headers: plugins.http.OutgoingHttpHeaders = {}
|
||||
) => {
|
||||
res.writeHead(statusArg, messageArg);
|
||||
res.end(messageArg);
|
||||
};
|
||||
|
||||
console.log('got request');
|
||||
const destinationConfig = this.router.routeReq(req);
|
||||
|
||||
if (!destinationConfig) {
|
||||
console.log(`${req.headers.host} can't be routed properly. Terminating request.`);
|
||||
endRequest();
|
||||
return;
|
||||
}
|
||||
|
||||
// authentication
|
||||
if (destinationConfig.authentication) {
|
||||
const authInfo = destinationConfig.authentication;
|
||||
switch (authInfo.type) {
|
||||
case 'Basic':
|
||||
const authHeader = req.headers.authorization;
|
||||
if (authHeader) {
|
||||
if (!authHeader.includes('Basic ')) {
|
||||
return endRequest(401, 'Authentication required', {
|
||||
'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.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let destinationUrl: string;
|
||||
if (destinationConfig) {
|
||||
destinationUrl = `http://${destinationConfig.destinationIp}:${destinationConfig.destinationPort}${req.url}`;
|
||||
} else {
|
||||
return endRequest();
|
||||
}
|
||||
console.log(destinationUrl);
|
||||
const response = await plugins.smartrequest.request(
|
||||
destinationUrl,
|
||||
{
|
||||
method: req.method,
|
||||
headers: req.headers,
|
||||
keepAlive: true,
|
||||
},
|
||||
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 defaultHeader of Object.keys(this.defaultHeaders)) {
|
||||
res.setHeader(defaultHeader, this.defaultHeaders[defaultHeader]);
|
||||
}
|
||||
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();
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
// Enable websockets
|
||||
const wss = new plugins.ws.WebSocketServer({ server: this.httpsServer });
|
||||
wss.on('connection', (ws: plugins.wsDefault) => {
|
||||
console.log('got connection for wsc');
|
||||
const wscConnected = plugins.smartpromise.defer();
|
||||
|
||||
const wsc = new plugins.wsDefault(this.router.routeWs(ws), {
|
||||
headers: {
|
||||
Host: ws.url,
|
||||
},
|
||||
});
|
||||
wsc.on('open', () => {
|
||||
wscConnected.resolve();
|
||||
});
|
||||
|
||||
ws.on('message', async (message) => {
|
||||
await wscConnected.promise;
|
||||
wsc.emit('message', message);
|
||||
});
|
||||
wsc.on('message', (message) => {
|
||||
ws.emit('message', message);
|
||||
});
|
||||
|
||||
// handle closing
|
||||
const cleanUp = () => {
|
||||
ws.removeAllListeners();
|
||||
ws.close();
|
||||
ws.terminate();
|
||||
wsc.removeAllListeners();
|
||||
wsc.close();
|
||||
wsc.terminate();
|
||||
};
|
||||
|
||||
ws.on('close', (message) => {
|
||||
cleanUp();
|
||||
});
|
||||
wsc.on('close', (message) => {
|
||||
cleanUp();
|
||||
});
|
||||
});
|
||||
this.httpsServer.keepAliveTimeout = 61000;
|
||||
this.httpsServer.headersTimeout = 65000;
|
||||
|
||||
this.httpsServer.on('connection', (connection: plugins.net.Socket) => {
|
||||
connection.setTimeout(10000);
|
||||
this.socketMap.add(connection);
|
||||
console.log(`added connection. now ${this.socketMap.getArray().length} sockets connected.`);
|
||||
const cleanupConnection = () => {
|
||||
if (this.socketMap.checkForObject(connection)) {
|
||||
this.socketMap.remove(connection);
|
||||
console.log(`removed connection. ${this.socketMap.getArray().length} sockets remaining.`);
|
||||
connection.end(() => {
|
||||
connection.destroy();
|
||||
console.log(`socket successfully destroyed`);
|
||||
});
|
||||
}
|
||||
};
|
||||
connection.on('close', () => {
|
||||
cleanupConnection();
|
||||
});
|
||||
connection.on('error', () => {
|
||||
cleanupConnection();
|
||||
});
|
||||
connection.on('end', () => {
|
||||
cleanupConnection();
|
||||
});
|
||||
connection.on('timeout', () => {
|
||||
cleanupConnection();
|
||||
});
|
||||
});
|
||||
|
||||
this.httpsServer.listen(this.options.port);
|
||||
console.log(
|
||||
`ProxyWorker -> OK: now listening for new connections on port ${this.options.port}`
|
||||
);
|
||||
}
|
||||
|
||||
public async updateProxyConfigs(proxyConfigsArg: plugins.tsclass.network.IReverseProxyConfig[]) {
|
||||
this.proxyConfigs = proxyConfigsArg;
|
||||
this.router.setNewProxyConfigs(proxyConfigsArg);
|
||||
for (const hostCandidate of this.proxyConfigs) {
|
||||
// console.log(hostCandidate);
|
||||
|
||||
const existingHostNameConfig = this.alreadyAddedReverseConfigs[hostCandidate.hostName];
|
||||
|
||||
if (!existingHostNameConfig) {
|
||||
this.alreadyAddedReverseConfigs[hostCandidate.hostName] = hostCandidate;
|
||||
} else {
|
||||
if (
|
||||
existingHostNameConfig.publicKey === hostCandidate.publicKey &&
|
||||
existingHostNameConfig.privateKey === hostCandidate.privateKey
|
||||
) {
|
||||
continue;
|
||||
} else {
|
||||
this.alreadyAddedReverseConfigs[hostCandidate.hostName] = hostCandidate;
|
||||
}
|
||||
}
|
||||
|
||||
this.httpsServer.addContext(hostCandidate.hostName, {
|
||||
cert: hostCandidate.publicKey,
|
||||
key: hostCandidate.privateKey,
|
||||
});
|
||||
this.httpsServer;
|
||||
}
|
||||
}
|
||||
|
||||
public async addDefaultHeaders(headersArg: { [key: string]: string }) {
|
||||
for (const headerKey of Object.keys(headersArg)) {
|
||||
this.defaultHeaders[headerKey] = headersArg[headerKey];
|
||||
}
|
||||
}
|
||||
|
||||
public async stop() {
|
||||
const done = plugins.smartpromise.defer();
|
||||
this.httpsServer.close(() => {
|
||||
done.resolve();
|
||||
});
|
||||
await this.socketMap.forEach(async (socket) => {
|
||||
socket.destroy();
|
||||
});
|
||||
await done.promise;
|
||||
}
|
||||
}
|
@ -1,26 +0,0 @@
|
||||
// node native scope
|
||||
import * as http from 'http';
|
||||
import * as https from 'https';
|
||||
import * as net from 'net';
|
||||
import * as url from 'url';
|
||||
|
||||
export { http, https, net, url };
|
||||
|
||||
// tsclass scope
|
||||
import * as tsclass from '@tsclass/tsclass';
|
||||
|
||||
export { tsclass };
|
||||
|
||||
// pushrocks scope
|
||||
import * as lik from '@pushrocks/lik';
|
||||
import * as smartpromise from '@pushrocks/smartpromise';
|
||||
import * as smartrequest from '@pushrocks/smartrequest';
|
||||
import * as smartstring from '@pushrocks/smartstring';
|
||||
|
||||
export { lik, smartrequest, smartpromise, smartstring };
|
||||
|
||||
// third party scope
|
||||
import * as ws from 'ws';
|
||||
import wsDefault from 'ws';
|
||||
|
||||
export { wsDefault, ws };
|
@ -1,70 +0,0 @@
|
||||
import * as plugins from './smartproxy.plugins.js';
|
||||
import * as net from 'net';
|
||||
|
||||
export class PortProxy {
|
||||
netServer: plugins.net.Server;
|
||||
fromPort: number;
|
||||
toPort: number;
|
||||
|
||||
constructor(fromPortArg: number, toPortArg: number) {
|
||||
this.fromPort = fromPortArg;
|
||||
this.toPort = toPortArg;
|
||||
}
|
||||
|
||||
public async start() {
|
||||
const cleanUpSockets = (from: plugins.net.Socket, to: plugins.net.Socket) => {
|
||||
from.end();
|
||||
to.end();
|
||||
from.removeAllListeners();
|
||||
to.removeAllListeners();
|
||||
from.unpipe();
|
||||
to.unpipe();
|
||||
from.destroy();
|
||||
to.destroy();
|
||||
};
|
||||
this.netServer = net
|
||||
.createServer((from) => {
|
||||
const to = net.createConnection({
|
||||
host: 'localhost',
|
||||
port: this.toPort,
|
||||
});
|
||||
from.setTimeout(120000);
|
||||
from.pipe(to);
|
||||
to.pipe(from);
|
||||
from.on('error', () => {
|
||||
cleanUpSockets(from, to);
|
||||
});
|
||||
to.on('error', () => {
|
||||
cleanUpSockets(from, to);
|
||||
});
|
||||
from.on('close', () => {
|
||||
cleanUpSockets(from, to);
|
||||
});
|
||||
to.on('close', () => {
|
||||
cleanUpSockets(from, to);
|
||||
});
|
||||
from.on('timeout', () => {
|
||||
cleanUpSockets(from, to);
|
||||
});
|
||||
to.on('timeout', () => {
|
||||
cleanUpSockets(from, to);
|
||||
});
|
||||
from.on('end', () => {
|
||||
cleanUpSockets(from, to);
|
||||
});
|
||||
to.on('end', () => {
|
||||
cleanUpSockets(from, to);
|
||||
});
|
||||
})
|
||||
.listen(this.fromPort);
|
||||
console.log(`PortProxy -> OK: Now listening on port ${this.fromPort}`);
|
||||
}
|
||||
|
||||
public async stop() {
|
||||
const done = plugins.smartpromise.defer();
|
||||
this.netServer.close(() => {
|
||||
done.resolve();
|
||||
});
|
||||
await done.promise;
|
||||
}
|
||||
}
|
@ -3,8 +3,14 @@
|
||||
"experimentalDecorators": true,
|
||||
"useDefineForClassFields": false,
|
||||
"target": "ES2022",
|
||||
"module": "ES2022",
|
||||
"moduleResolution": "nodenext",
|
||||
"esModuleInterop": true
|
||||
}
|
||||
}
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"esModuleInterop": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {}
|
||||
},
|
||||
"exclude": [
|
||||
"dist_*/**/*.d.ts"
|
||||
]
|
||||
}
|
Reference in New Issue
Block a user