diff --git a/Dockers/xtream-proxy/.dockerignore b/Dockers/xtream-proxy/.dockerignore index c8f8833..4f41a8f 100644 --- a/Dockers/xtream-proxy/.dockerignore +++ b/Dockers/xtream-proxy/.dockerignore @@ -1,3 +1,5 @@ node_modules npm-debug.log -hosts.txt.example +upstreams.json +upstreams.json.example +.git diff --git a/Dockers/xtream-proxy/.gitignore b/Dockers/xtream-proxy/.gitignore index c2658d7..c336432 100644 --- a/Dockers/xtream-proxy/.gitignore +++ b/Dockers/xtream-proxy/.gitignore @@ -1 +1,2 @@ node_modules/ +upstreams.json diff --git a/Dockers/xtream-proxy/Dockerfile b/Dockers/xtream-proxy/Dockerfile index a39f8e0..56d4389 100644 --- a/Dockers/xtream-proxy/Dockerfile +++ b/Dockers/xtream-proxy/Dockerfile @@ -2,10 +2,9 @@ FROM node:22-alpine WORKDIR /app -COPY package.json package-lock.json ./ -RUN npm ci --omit=dev - +COPY package.json ./ COPY server.js ./ +COPY src ./src/ RUN addgroup -g 1001 -S nodejs \ && adduser -S nodejs -u 1001 \ @@ -15,11 +14,15 @@ USER nodejs EXPOSE 8080 -ENV LISTEN_PORT=8080 -ENV HOSTS_FILE=/config/hosts.txt -ENV CHECK_INTERVAL_SEC=30 -ENV PING_TIMEOUT_MS=8000 -ENV HEALTH_PATH=/ +ENV LISTEN_PORT=8080 \ + CONFIG_FILE=/config/upstreams.json \ + PROXY_USERNAME="" \ + PROXY_PASSWORD="" \ + PROBE_INTERVAL_SEC=30 \ + PROBE_TIMEOUT_MS=8000 \ + UPSTREAM_TIMEOUT_MS=15000 \ + ALLOW_BUSY_FALLBACK=1 \ + PROXY_INSECURE_TLS=0 HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \ CMD node -e "require('http').get('http://127.0.0.1:'+(process.env.LISTEN_PORT||8080)+'/health',(r)=>{let d='';r.on('data',c=>d+=c);r.on('end',()=>{try{process.exit(JSON.parse(d).ok?0:1)}catch{process.exit(1)}})}).on('error',()=>process.exit(1))" diff --git a/Dockers/xtream-proxy/docker-compose.example.yml b/Dockers/xtream-proxy/docker-compose.example.yml new file mode 100644 index 0000000..076e8f0 --- /dev/null +++ b/Dockers/xtream-proxy/docker-compose.example.yml @@ -0,0 +1,17 @@ +services: + xtream-proxy: + build: . + container_name: xtream-proxy + ports: + - "8080:8080" + environment: + PROXY_USERNAME: "${PROXY_USERNAME}" + PROXY_PASSWORD: "${PROXY_PASSWORD}" + PROBE_INTERVAL_SEC: "30" + PROBE_TIMEOUT_MS: "8000" + UPSTREAM_TIMEOUT_MS: "15000" + ALLOW_BUSY_FALLBACK: "1" + # PROXY_INSECURE_TLS: "1" # alleen nodig bij self-signed upstream-certificaten + volumes: + - ./upstreams.json:/config/upstreams.json:ro + restart: unless-stopped diff --git a/Dockers/xtream-proxy/hosts.txt.example b/Dockers/xtream-proxy/hosts.txt.example deleted file mode 100644 index 8a4f779..0000000 --- a/Dockers/xtream-proxy/hosts.txt.example +++ /dev/null @@ -1,5 +0,0 @@ -# One base URL per line (scheme + host + optional port). No path required. -# Lines starting with # are ignored. - -http://panel1.example.com:8080 -https://backup.example.com diff --git a/Dockers/xtream-proxy/package-lock.json b/Dockers/xtream-proxy/package-lock.json deleted file mode 100644 index dbdbe7f..0000000 --- a/Dockers/xtream-proxy/package-lock.json +++ /dev/null @@ -1,849 +0,0 @@ -{ - "name": "xtream-proxy", - "version": "1.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "xtream-proxy", - "version": "1.0.0", - "dependencies": { - "express": "^4.21.0", - "ws": "^8.18.0" - } - }, - "node_modules/accepts": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", - "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", - "license": "MIT", - "dependencies": { - "mime-types": "~2.1.34", - "negotiator": "0.6.3" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/array-flatten": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", - "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", - "license": "MIT" - }, - "node_modules/body-parser": { - "version": "1.20.4", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz", - "integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==", - "license": "MIT", - "dependencies": { - "bytes": "~3.1.2", - "content-type": "~1.0.5", - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "~1.2.0", - "http-errors": "~2.0.1", - "iconv-lite": "~0.4.24", - "on-finished": "~2.4.1", - "qs": "~6.14.0", - "raw-body": "~2.5.3", - "type-is": "~1.6.18", - "unpipe": "~1.0.0" - }, - "engines": { - "node": ">= 0.8", - "npm": "1.2.8000 || >= 1.4.16" - } - }, - "node_modules/bytes": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", - "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/call-bind-apply-helpers": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", - "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/call-bound": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", - "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "get-intrinsic": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/content-disposition": { - "version": "0.5.4", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", - "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", - "license": "MIT", - "dependencies": { - "safe-buffer": "5.2.1" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/content-type": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", - "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookie": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", - "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookie-signature": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", - "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", - "license": "MIT" - }, - "node_modules/debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "license": "MIT", - "dependencies": { - "ms": "2.0.0" - } - }, - "node_modules/depd": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", - "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/destroy": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", - "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", - "license": "MIT", - "engines": { - "node": ">= 0.8", - "npm": "1.2.8000 || >= 1.4.16" - } - }, - "node_modules/dunder-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", - "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.1", - "es-errors": "^1.3.0", - "gopd": "^1.2.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/ee-first": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", - "license": "MIT" - }, - "node_modules/encodeurl": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", - "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/es-define-property": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", - "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-errors": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", - "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-object-atoms": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", - "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/escape-html": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", - "license": "MIT" - }, - "node_modules/etag": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/express": { - "version": "4.22.1", - "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz", - "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==", - "license": "MIT", - "dependencies": { - "accepts": "~1.3.8", - "array-flatten": "1.1.1", - "body-parser": "~1.20.3", - "content-disposition": "~0.5.4", - "content-type": "~1.0.4", - "cookie": "~0.7.1", - "cookie-signature": "~1.0.6", - "debug": "2.6.9", - "depd": "2.0.0", - "encodeurl": "~2.0.0", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "finalhandler": "~1.3.1", - "fresh": "~0.5.2", - "http-errors": "~2.0.0", - "merge-descriptors": "1.0.3", - "methods": "~1.1.2", - "on-finished": "~2.4.1", - "parseurl": "~1.3.3", - "path-to-regexp": "~0.1.12", - "proxy-addr": "~2.0.7", - "qs": "~6.14.0", - "range-parser": "~1.2.1", - "safe-buffer": "5.2.1", - "send": "~0.19.0", - "serve-static": "~1.16.2", - "setprototypeof": "1.2.0", - "statuses": "~2.0.1", - "type-is": "~1.6.18", - "utils-merge": "1.0.1", - "vary": "~1.1.2" - }, - "engines": { - "node": ">= 0.10.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/finalhandler": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", - "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", - "license": "MIT", - "dependencies": { - "debug": "2.6.9", - "encodeurl": "~2.0.0", - "escape-html": "~1.0.3", - "on-finished": "~2.4.1", - "parseurl": "~1.3.3", - "statuses": "~2.0.2", - "unpipe": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/forwarded": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", - "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/fresh": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", - "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-intrinsic": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", - "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "es-define-property": "^1.0.1", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.1.1", - "function-bind": "^1.1.2", - "get-proto": "^1.0.1", - "gopd": "^1.2.0", - "has-symbols": "^1.1.0", - "hasown": "^2.0.2", - "math-intrinsics": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", - "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", - "license": "MIT", - "dependencies": { - "dunder-proto": "^1.0.1", - "es-object-atoms": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/gopd": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", - "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-symbols": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", - "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/hasown": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", - "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/http-errors": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", - "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", - "license": "MIT", - "dependencies": { - "depd": "~2.0.0", - "inherits": "~2.0.4", - "setprototypeof": "~1.2.0", - "statuses": "~2.0.2", - "toidentifier": "~1.0.1" - }, - "engines": { - "node": ">= 0.8" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/iconv-lite": { - "version": "0.4.24", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", - "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", - "license": "MIT", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "license": "ISC" - }, - "node_modules/ipaddr.js": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", - "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", - "license": "MIT", - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/math-intrinsics": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", - "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/media-typer": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", - "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/merge-descriptors": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", - "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/methods": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", - "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", - "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", - "license": "MIT", - "bin": { - "mime": "cli.js" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "license": "MIT", - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", - "license": "MIT" - }, - "node_modules/negotiator": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", - "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/object-inspect": { - "version": "1.13.4", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", - "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/on-finished": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", - "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", - "license": "MIT", - "dependencies": { - "ee-first": "1.1.1" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/parseurl": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", - "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/path-to-regexp": { - "version": "0.1.13", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz", - "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==", - "license": "MIT" - }, - "node_modules/proxy-addr": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", - "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", - "license": "MIT", - "dependencies": { - "forwarded": "0.2.0", - "ipaddr.js": "1.9.1" - }, - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/qs": { - "version": "6.14.2", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.2.tgz", - "integrity": "sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q==", - "license": "BSD-3-Clause", - "dependencies": { - "side-channel": "^1.1.0" - }, - "engines": { - "node": ">=0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/range-parser": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", - "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/raw-body": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", - "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", - "license": "MIT", - "dependencies": { - "bytes": "~3.1.2", - "http-errors": "~2.0.1", - "iconv-lite": "~0.4.24", - "unpipe": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "license": "MIT" - }, - "node_modules/send": { - "version": "0.19.2", - "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", - "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==", - "license": "MIT", - "dependencies": { - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "1.2.0", - "encodeurl": "~2.0.0", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "fresh": "~0.5.2", - "http-errors": "~2.0.1", - "mime": "1.6.0", - "ms": "2.1.3", - "on-finished": "~2.4.1", - "range-parser": "~1.2.1", - "statuses": "~2.0.2" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/send/node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "license": "MIT" - }, - "node_modules/serve-static": { - "version": "1.16.3", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz", - "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==", - "license": "MIT", - "dependencies": { - "encodeurl": "~2.0.0", - "escape-html": "~1.0.3", - "parseurl": "~1.3.3", - "send": "~0.19.1" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/setprototypeof": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", - "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", - "license": "ISC" - }, - "node_modules/side-channel": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", - "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "object-inspect": "^1.13.3", - "side-channel-list": "^1.0.0", - "side-channel-map": "^1.0.1", - "side-channel-weakmap": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-list": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", - "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "object-inspect": "^1.13.4" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-map": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", - "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.5", - "object-inspect": "^1.13.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-weakmap": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", - "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.5", - "object-inspect": "^1.13.3", - "side-channel-map": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/statuses": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", - "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/toidentifier": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", - "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", - "license": "MIT", - "engines": { - "node": ">=0.6" - } - }, - "node_modules/type-is": { - "version": "1.6.18", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", - "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", - "license": "MIT", - "dependencies": { - "media-typer": "0.3.0", - "mime-types": "~2.1.24" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/unpipe": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", - "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/utils-merge": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", - "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", - "license": "MIT", - "engines": { - "node": ">= 0.4.0" - } - }, - "node_modules/vary": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", - "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/ws": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz", - "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==", - "license": "MIT", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - } - } -} diff --git a/Dockers/xtream-proxy/package.json b/Dockers/xtream-proxy/package.json index e7bc5a8..b8c3098 100644 --- a/Dockers/xtream-proxy/package.json +++ b/Dockers/xtream-proxy/package.json @@ -1,12 +1,12 @@ { "name": "xtream-proxy", - "version": "1.0.0", + "version": "2.0.0", "private": true, + "description": "Proxies the fastest available upstream from a list of Xtream Codes credentials", "scripts": { "start": "node server.js" }, - "dependencies": { - "express": "^4.21.0", - "ws": "^8.18.0" + "engines": { + "node": ">=20" } } diff --git a/Dockers/xtream-proxy/server.js b/Dockers/xtream-proxy/server.js index 8b25bca..f67a7d8 100644 --- a/Dockers/xtream-proxy/server.js +++ b/Dockers/xtream-proxy/server.js @@ -1,381 +1,65 @@ 'use strict'; -const fs = require('fs'); const http = require('http'); -const https = require('https'); -const express = require('express'); -const WebSocket = require('ws'); +const { settings, validate } = require('./src/settings'); +const { + probeCycle, + startProbing, + stopProbing, +} = require('./src/upstreams'); +const { handleProxy } = require('./src/proxy'); +const { healthPayload } = require('./src/health'); +const { sendText, sendJson } = require('./src/http-utils'); -const LISTEN_PORT = Number(process.env.LISTEN_PORT || 8080); -const HOSTS_FILE = process.env.HOSTS_FILE || '/config/hosts.txt'; -const CHECK_INTERVAL_SEC = Math.max( - 5, - Number(process.env.CHECK_INTERVAL_SEC || 30) || 30 -); -const PING_TIMEOUT_MS = Math.max(1000, Number(process.env.PING_TIMEOUT_MS || 8000)); -const HEALTH_PATH = process.env.HEALTH_PATH || '/'; -const REJECT_UNAUTHORIZED = process.env.PROXY_INSECURE_TLS !== '1'; +const HEALTH_PATHS = new Set(['/health', '/healthz']); -const HOP_BY_HOP = new Set([ - 'connection', - 'keep-alive', - 'proxy-authenticate', - 'proxy-authorization', - 'te', - 'trailers', - 'transfer-encoding', - 'upgrade', -]); - -let currentTarget = null; -let lastStats = { checkedAt: null, results: [], selected: null }; - -function readHostsFile() { - if (!fs.existsSync(HOSTS_FILE)) { - console.error(`Hosts file not found: ${HOSTS_FILE}`); - return []; - } - const raw = fs.readFileSync(HOSTS_FILE, 'utf8'); - const lines = raw.split(/\r?\n/); - const urls = []; - for (const line of lines) { - const t = line.trim(); - if (!t || t.startsWith('#')) continue; - try { - const u = new URL(t); - if (u.protocol !== 'http:' && u.protocol !== 'https:') continue; - const base = `${u.protocol}//${u.host}`; - urls.push(base); - } catch { - console.warn(`Skipping invalid URL line: ${t}`); - } - } - return [...new Set(urls)]; -} - -function pingBase(base, path) { - const HARD_CAP_MS = PING_TIMEOUT_MS + 2000; - - return new Promise((resolve) => { - let url; - try { - const p = path.startsWith('/') ? path : `/${path}`; - url = new URL(p, base.endsWith('/') ? base : `${base}/`); - } catch { - resolve({ base, ok: false, ms: null, error: 'bad_url' }); - return; - } - - let settled = false; - let clientReq = null; - - const finish = (result) => { - if (settled) return; - settled = true; - clearTimeout(hardTimer); - try { - clientReq?.destroy(); - } catch (_) {} - resolve(result); - }; - - const hardTimer = setTimeout(() => { - try { - clientReq?.destroy(); - } catch (_) {} - finish({ base, ok: false, ms: null, error: 'hard_timeout' }); - }, HARD_CAP_MS); - - const lib = url.protocol === 'https:' ? https : http; - const start = Date.now(); - clientReq = lib.request( - { - protocol: url.protocol, - hostname: url.hostname, - port: url.port || (url.protocol === 'https:' ? 443 : 80), - path: url.pathname + url.search, - method: 'GET', - timeout: PING_TIMEOUT_MS, - rejectUnauthorized: REJECT_UNAUTHORIZED, - headers: { - 'User-Agent': 'xtream-proxy-health/1.0', - Connection: 'close', - }, - }, - (res) => { - res.resume(); - res.on('end', () => { - const ms = Date.now() - start; - const ok = res.statusCode >= 200 && res.statusCode < 500; - finish({ base, ok, ms, status: res.statusCode }); - }); - res.on('error', () => { - finish({ base, ok: false, ms: null, error: 'response_error' }); - }); - } - ); - clientReq.on('error', (e) => { - finish({ base, ok: false, ms: null, error: e.code || e.message }); - }); - clientReq.on('timeout', () => { - clientReq.destroy(); - finish({ base, ok: false, ms: null, error: 'timeout' }); - }); - clientReq.end(); - }); -} - -async function pickFastestHost() { - const hosts = readHostsFile(); - if (hosts.length === 0) { - console.warn('No valid hosts in file; keeping previous target if any.'); - lastStats = { - checkedAt: new Date().toISOString(), - results: [], - selected: currentTarget, - }; - return; - } - - const pings = await Promise.all(hosts.map((h) => pingBase(h, HEALTH_PATH))); - const ok = pings.filter((p) => p.ok && typeof p.ms === 'number'); - ok.sort((a, b) => a.ms - b.ms); - - lastStats = { - checkedAt: new Date().toISOString(), - results: pings, - selected: ok[0]?.base ?? currentTarget, - }; - - if (ok[0]) { - const prev = currentTarget; - currentTarget = ok[0].base; - const others = ok.slice(1).map((x) => `${x.base}=${x.ms}ms`).join(', ') || 'none'; - if (prev !== currentTarget) { - console.log(`Upstream switched → ${currentTarget} (${ok[0].ms} ms). Also: ${others}`); - } else { - console.log(`Health check: keeping ${currentTarget} (${ok[0].ms} ms). Others: ${others}`); - } - } else { - console.warn( - 'No host responded successfully; keeping previous target:', - currentTarget || '(none)' - ); - } -} - -let checkTimer = null; -let checkRunning = false; - -function scheduleChecks() { - const delayMs = CHECK_INTERVAL_SEC * 1000; - const tick = async () => { - if (checkRunning) { - console.warn('Health check still running; skipping overlapping run (next in ' + CHECK_INTERVAL_SEC + 's)'); - checkTimer = setTimeout(tick, delayMs); - return; - } - checkRunning = true; - try { - await pickFastestHost(); - } catch (e) { - console.error('Health check error:', e); - } finally { - checkRunning = false; - checkTimer = setTimeout(tick, delayMs); - } - }; - checkTimer = setTimeout(tick, delayMs); -} - -function filterHopByHop(headers) { - const out = Object.create(null); - if (!headers) return out; - for (const [k, v] of Object.entries(headers)) { - if (v === undefined) continue; - if (HOP_BY_HOP.has(k.toLowerCase())) continue; - out[k] = v; - } - return out; -} - -function buildRequestHeaders(req, targetUrl) { - const out = filterHopByHop(req.headers); - const existing = req.headers['x-forwarded-for']; - const client = req.socket.remoteAddress || ''; - out['x-forwarded-for'] = existing ? `${existing}, ${client}` : client; - const xfProto = req.headers['x-forwarded-proto']; - out['x-forwarded-proto'] = typeof xfProto === 'string' && xfProto ? xfProto : 'http'; - const xfHost = req.headers['x-forwarded-host'] || req.headers.host; - if (xfHost) out['x-forwarded-host'] = xfHost; - out.host = targetUrl.host; - return out; -} - -function proxyHttp(req, res) { - const base = currentTarget.replace(/\/$/, ''); - let targetUrl; +const server = http.createServer((req, res) => { + let reqUrl; try { - targetUrl = new URL(req.url, `${base}/`); + reqUrl = new URL(req.url, 'http://proxy.invalid'); } catch { - res.status(400).type('text/plain').send('Bad request URL'); + sendText(res, 400, 'Bad request'); return; } - const lib = targetUrl.protocol === 'https:' ? https : http; - const opts = { - protocol: targetUrl.protocol, - hostname: targetUrl.hostname, - port: targetUrl.port || (targetUrl.protocol === 'https:' ? 443 : 80), - path: targetUrl.pathname + targetUrl.search, - method: req.method, - headers: buildRequestHeaders(req, targetUrl), - rejectUnauthorized: REJECT_UNAUTHORIZED, - }; - - const pReq = lib.request(opts, (pRes) => { - res.writeHead(pRes.statusCode, filterHopByHop(pRes.headers)); - pRes.pipe(res); - }); - - pReq.on('error', (err) => { - if (!res.headersSent) { - res.writeHead(502, { 'Content-Type': 'text/plain' }); - } - res.end(`Upstream error: ${err.message}`); - }); - - req.pipe(pReq); -} - -function toWsUrl(httpBase, reqPath) { - const base = httpBase.replace(/\/$/, ''); - const u = new URL(reqPath, `${base}/`); - const proto = u.protocol === 'https:' ? 'wss:' : 'ws:'; - return `${proto}//${u.host}${u.pathname}${u.search}`; -} - -function buildWsClientHeaders(req, targetWsUrl) { - const u = new URL(targetWsUrl); - const out = filterHopByHop(req.headers); - for (const key of Object.keys(out)) { - if (key.toLowerCase().startsWith('sec-websocket')) { - delete out[key]; - } + if (req.method === 'GET' && HEALTH_PATHS.has(reqUrl.pathname)) { + sendJson(res, 200, healthPayload()); + return; } - delete out.host; - out.host = u.host; - return out; -} -const app = express(); - -app.get('/health', (_req, res) => { - res.json({ - ok: Boolean(currentTarget), - upstream: currentTarget, - intervalSec: CHECK_INTERVAL_SEC, - lastCheck: lastStats, - }); + handleProxy(req, res, reqUrl); }); -app.use((req, res) => { - if (!currentTarget) { - res.status(503).type('text/plain').send('No upstream available yet (hosts file empty or all pings failed).'); - return; - } - proxyHttp(req, res); -}); +function shutdown(signal) { + console.log(`Received ${signal}, shutting down`); + stopProbing(); + server.close(() => process.exit(0)); + setTimeout(() => process.exit(0), 5000).unref(); +} -const server = http.createServer(app); -const wss = new WebSocket.Server({ noServer: true }); - -server.on('upgrade', (req, socket, head) => { - if (!currentTarget) { - socket.write('HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n'); - socket.destroy(); - return; - } - - let upstreamUrl; - try { - upstreamUrl = toWsUrl(currentTarget, req.url); - } catch { - socket.destroy(); - return; - } - - wss.handleUpgrade(req, socket, head, (clientWs) => { - const upstream = new WebSocket(upstreamUrl, { - rejectUnauthorized: REJECT_UNAUTHORIZED, - headers: buildWsClientHeaders(req, upstreamUrl), - }); - - const pending = []; - let upstreamReady = false; - - clientWs.on('message', (data, isBinary) => { - if (upstreamReady && upstream.readyState === WebSocket.OPEN) { - upstream.send(data, { binary: isBinary }); - } else { - pending.push({ data, isBinary }); - } - }); - - upstream.on('open', () => { - upstreamReady = true; - for (const m of pending) { - if (upstream.readyState === WebSocket.OPEN) upstream.send(m.data, { binary: m.isBinary }); - } - pending.length = 0; - - upstream.on('message', (data, isBinary) => { - if (clientWs.readyState === WebSocket.OPEN) clientWs.send(data, { binary: isBinary }); - }); - clientWs.on('ping', (buf) => upstream.ping(buf)); - upstream.on('ping', (buf) => clientWs.ping(buf)); - clientWs.on('pong', (buf) => upstream.pong(buf)); - upstream.on('pong', (buf) => clientWs.pong(buf)); - }); - - const shutdown = () => { - try { - clientWs.terminate(); - } catch (_) {} - try { - upstream.terminate(); - } catch (_) {} - }; - - upstream.on('error', shutdown); - clientWs.on('error', shutdown); - upstream.on('close', shutdown); - clientWs.on('close', shutdown); - }); -}); +process.on('SIGTERM', () => shutdown('SIGTERM')); +process.on('SIGINT', () => shutdown('SIGINT')); async function main() { - await pickFastestHost(); - server.listen(LISTEN_PORT, () => { - console.log(`Xtream proxy listening on :${LISTEN_PORT}`); + try { + validate(); + } catch (e) { + console.error(e.message); + process.exit(1); + } + + await probeCycle(); + + server.listen(settings.listenPort, () => { + console.log(`Xtream proxy listening on :${settings.listenPort}`); + console.log(`Config file: ${settings.configFile}`); console.log( - `Hosts file: ${HOSTS_FILE}, interval: ${CHECK_INTERVAL_SEC}s (from end of each run), health path: ${HEALTH_PATH}` + `Probe interval: ${settings.probeIntervalSec}s, probe timeout: ${settings.probeTimeoutMs}ms` ); - scheduleChecks(); + startProbing(); }); } -function shutdown() { - if (checkTimer) { - clearTimeout(checkTimer); - checkTimer = null; - } - server.close(() => process.exit(0)); -} - -process.on('SIGTERM', shutdown); -process.on('SIGINT', shutdown); - main().catch((e) => { console.error(e); process.exit(1); diff --git a/Dockers/xtream-proxy/src/config.js b/Dockers/xtream-proxy/src/config.js new file mode 100644 index 0000000..3790267 --- /dev/null +++ b/Dockers/xtream-proxy/src/config.js @@ -0,0 +1,92 @@ +'use strict'; + +const fs = require('fs'); +const { settings } = require('./settings'); +const { Upstream } = require('./upstream'); + +let upstreams = []; + +function readConfigEntries() { + const raw = fs.readFileSync(settings.configFile, 'utf8'); + let data; + try { + data = JSON.parse(raw); + } catch (e) { + throw new Error(`invalid JSON: ${e.message}`); + } + if (!Array.isArray(data)) { + throw new Error('expected a JSON array'); + } + + const entries = []; + data.forEach((item, index) => { + if (!item || typeof item !== 'object' || Array.isArray(item)) { + console.warn(`Config entry #${index + 1}: not an object, skipping`); + return; + } + const { url, username, password } = item; + if (typeof url !== 'string' || !url.trim()) { + console.warn(`Config entry #${index + 1}: missing url, skipping`); + return; + } + if (typeof username !== 'string' || !username) { + console.warn(`Config entry #${index + 1}: missing username, skipping`); + return; + } + if (typeof password !== 'string' || !password) { + console.warn(`Config entry #${index + 1}: missing password, skipping`); + return; + } + + let parsed; + try { + parsed = new URL(url); + } catch { + console.warn(`Config entry #${index + 1}: invalid url, skipping`); + return; + } + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { + console.warn(`Config entry #${index + 1}: url must be http(s), skipping`); + return; + } + + entries.push({ url, username, password }); + }); + return entries; +} + +function reloadConfig() { + let entries; + try { + entries = readConfigEntries(); + } catch (e) { + console.error(`Config load failed (${settings.configFile}): ${e.message}`); + return false; + } + + const previous = new Map(upstreams.map((u) => [u.key, u])); + const next = []; + const seen = new Set(); + + for (const entry of entries) { + const upstream = new Upstream(entry); + if (seen.has(upstream.key)) continue; + seen.add(upstream.key); + next.push(previous.get(upstream.key) || upstream); + } + + const removed = upstreams.filter((u) => !seen.has(u.key)).length; + const added = next.filter((u) => !previous.has(u.key)).length; + if (added || removed) { + console.log(`Config reloaded: ${next.length} upstream(s), +${added} / -${removed}`); + } + + upstreams = next; + return true; +} + +function getUpstreams() { + return upstreams; +} + +module.exports = { reloadConfig, getUpstreams }; diff --git a/Dockers/xtream-proxy/src/health.js b/Dockers/xtream-proxy/src/health.js new file mode 100644 index 0000000..02e86cb --- /dev/null +++ b/Dockers/xtream-proxy/src/health.js @@ -0,0 +1,26 @@ +'use strict'; + +const { settings } = require('./settings'); +const { getUpstreams } = require('./config'); +const { + getLastProbeAt, + rankedUpstreams, + describeUpstream, +} = require('./upstreams'); + +function healthPayload() { + const upstreams = getUpstreams(); + const ranked = rankedUpstreams(); + const selected = ranked.find((entry) => !entry.busy) || ranked[0] || null; + + return { + ok: upstreams.some((upstream) => upstream.state.healthy), + configFile: settings.configFile, + probeIntervalSec: settings.probeIntervalSec, + lastProbeAt: getLastProbeAt(), + selected: selected ? describeUpstream(selected.upstream) : null, + upstreams: upstreams.map(describeUpstream), + }; +} + +module.exports = { healthPayload }; diff --git a/Dockers/xtream-proxy/src/http-utils.js b/Dockers/xtream-proxy/src/http-utils.js new file mode 100644 index 0000000..fc5fe7c --- /dev/null +++ b/Dockers/xtream-proxy/src/http-utils.js @@ -0,0 +1,39 @@ +'use strict'; + +function sendText(res, statusCode, text, extraHeaders = {}) { + res.writeHead(statusCode, { + 'Content-Type': 'text/plain; charset=utf-8', + 'Cache-Control': 'no-store', + ...extraHeaders, + }); + res.end(text); +} + +function sendJson(res, statusCode, body) { + const payload = JSON.stringify(body); + res.writeHead(statusCode, { + 'Content-Type': 'application/json; charset=utf-8', + 'Cache-Control': 'no-store', + 'Content-Length': Buffer.byteLength(payload), + }); + res.end(payload); +} + +function firstHeader(value) { + if (Array.isArray(value)) value = value[0]; + if (typeof value !== 'string') return ''; + return value.split(',')[0].trim(); +} + +function getProxyOrigin(req) { + const proto = + firstHeader(req.headers['x-forwarded-proto']) || + (req.socket.encrypted ? 'https' : 'http'); + const host = + firstHeader(req.headers['x-forwarded-host']) || + req.headers.host || + 'localhost'; + return `${proto}://${host}`; +} + +module.exports = { sendText, sendJson, firstHeader, getProxyOrigin }; diff --git a/Dockers/xtream-proxy/src/probe.js b/Dockers/xtream-proxy/src/probe.js new file mode 100644 index 0000000..68d325b --- /dev/null +++ b/Dockers/xtream-proxy/src/probe.js @@ -0,0 +1,154 @@ +'use strict'; + +const http = require('http'); +const https = require('https'); +const { settings } = require('./settings'); +const { baseState, nowIso, buildUpstreamUrl } = require('./upstream'); + +function toInt(value) { + if (value === null || value === undefined || value === '') return null; + const n = Number(value); + return Number.isFinite(n) ? n : null; +} + +function interpretProbe(statusCode, body, elapsedMs) { + const state = { ...baseState(), lastChecked: nowIso() }; + + if (statusCode < 200 || statusCode >= 300) { + state.error = `http_${statusCode}`; + return state; + } + + let json; + try { + json = JSON.parse(body); + } catch { + state.error = 'invalid_json'; + return state; + } + + const info = json && (json.user_info || json.userInfo); + if (!info || typeof info !== 'object') { + state.error = 'no_user_info'; + return state; + } + + state.auth = info.auth === undefined ? null : info.auth; + state.status = info.status === undefined ? null : info.status; + state.activeCons = toInt(info.active_cons); + state.maxCons = toInt(info.max_connections); + + if (state.auth !== null && Number(state.auth) !== 1) { + state.error = 'not_authorized'; + return state; + } + if ( + state.status !== null && + String(state.status).toLowerCase() !== 'active' + ) { + state.error = `status_${state.status}`; + return state; + } + + state.healthy = true; + state.latencyMs = Math.max(0, Math.round(elapsedMs)); + state.busy = + state.maxCons !== null && + state.maxCons > 0 && + state.activeCons !== null && + state.activeCons >= state.maxCons; + + return state; +} + +function probeUpstream(upstream) { + const search = `?${new URLSearchParams({ + username: upstream.username, + password: upstream.password, + }).toString()}`; + const target = buildUpstreamUrl(upstream, '/player_api.php', search); + const lib = target.protocol === 'https:' ? https : http; + const started = Date.now(); + + return new Promise((resolve) => { + let settled = false; + let req = null; + + const finish = (state) => { + if (settled) return; + settled = true; + clearTimeout(hardTimeout); + if (req) { + try { + req.destroy(); + } catch {} + } + resolve(state); + }; + + const hardTimeout = setTimeout( + () => finish({ ...baseState(), lastChecked: nowIso(), error: 'timeout' }), + settings.probeTimeoutMs + 2000 + ); + + try { + req = lib.request( + { + protocol: target.protocol, + hostname: target.hostname, + port: target.port || undefined, + path: `${target.pathname}${target.search}`, + method: 'GET', + headers: { + 'User-Agent': settings.userAgent, + Accept: 'application/json', + 'Accept-Encoding': 'identity', + Connection: 'close', + }, + rejectUnauthorized: settings.rejectUnauthorized, + }, + (res) => { + let body = ''; + res.setEncoding('utf8'); + res.on('data', (chunk) => { + if (body.length < 2_000_000) body += chunk; + }); + res.on('end', () => + finish(interpretProbe(res.statusCode, body, Date.now() - started)) + ); + res.on('error', () => + finish({ + ...baseState(), + lastChecked: nowIso(), + error: 'response_error', + }) + ); + } + ); + } catch (e) { + finish({ + ...baseState(), + lastChecked: nowIso(), + error: e.code || 'request_error', + }); + return; + } + + req.setTimeout(settings.probeTimeoutMs, () => { + try { + req.destroy(); + } catch {} + finish({ ...baseState(), lastChecked: nowIso(), error: 'timeout' }); + }); + req.on('error', (e) => + finish({ + ...baseState(), + lastChecked: nowIso(), + error: e.code || 'request_error', + }) + ); + req.end(); + }); +} + +module.exports = { interpretProbe, probeUpstream }; diff --git a/Dockers/xtream-proxy/src/proxy.js b/Dockers/xtream-proxy/src/proxy.js new file mode 100644 index 0000000..2609230 --- /dev/null +++ b/Dockers/xtream-proxy/src/proxy.js @@ -0,0 +1,245 @@ +'use strict'; + +const http = require('http'); +const https = require('https'); +const { settings } = require('./settings'); +const { getUpstreams } = require('./config'); +const { buildUpstreamUrl } = require('./upstream'); +const { + selectUpstream, + requestProbeSoon, +} = require('./upstreams'); +const { + ReplaceStream, + buildReplacements, + rewriteUrlValue, + shouldRewriteBody, + filterHopByHop, + filterResponseHeaders, + isStreamPath, + extractCreds, + isAuthenticated, + rewritePath, + rewriteSearch, +} = require('./rewrite'); +const { sendText, getProxyOrigin } = require('./http-utils'); + +function nowIso() { + return new Date().toISOString(); +} + +function canRetry(req) { + return req.method === 'GET' || req.method === 'HEAD'; +} + +function markUpstreamFailure(upstream, error) { + upstream.state.healthy = false; + upstream.state.error = error?.code || error?.message || 'request_error'; + upstream.state.lastChecked = nowIso(); + requestProbeSoon(); +} + +function handleProxy(req, res, reqUrl) { + const creds = extractCreds(reqUrl); + + if (!isAuthenticated(creds)) { + sendText(res, 401, 'Unauthorized'); + return; + } + + const streamRequest = isStreamPath(reqUrl.pathname); + const attempted = new Set(); + const upstreamCount = getUpstreams().length; + let currentProxyReq = null; + let currentRelease = null; + let closed = false; + + const releaseCurrent = () => { + if (currentRelease) { + const release = currentRelease; + currentRelease = null; + release(); + } + }; + + res.on('close', () => { + closed = true; + if (!res.writableEnded && currentProxyReq) { + try { + currentProxyReq.destroy(); + } catch {} + } + releaseCurrent(); + }); + + req.on('error', () => { + if (currentProxyReq) { + try { + currentProxyReq.destroy(); + } catch {} + } + releaseCurrent(); + }); + + const attempt = () => { + if (closed || res.headersSent) return; + + const upstream = selectUpstream(attempted); + if (!upstream) { + sendText(res, 503, 'No upstream available', { 'Retry-After': '5' }); + requestProbeSoon(); + return; + } + + attempted.add(upstream.key); + + if (streamRequest) upstream.state.inFlight += 1; + let released = false; + const release = () => { + if (released) return; + released = true; + if (streamRequest) { + upstream.state.inFlight = Math.max(0, upstream.state.inFlight - 1); + } + }; + currentRelease = release; + + const pathname = rewritePath(creds, upstream); + const search = rewriteSearch(reqUrl, upstream); + const target = buildUpstreamUrl(upstream, pathname, search); + + const headers = filterHopByHop(req.headers); + delete headers.host; + delete headers['accept-encoding']; + headers.host = target.host; + headers['accept-encoding'] = 'identity'; + + const clientIp = req.socket.remoteAddress || ''; + const existingForwardedFor = req.headers['x-forwarded-for']; + headers['x-forwarded-for'] = existingForwardedFor + ? `${existingForwardedFor}, ${clientIp}` + : clientIp; + if (!headers['x-forwarded-proto']) { + headers['x-forwarded-proto'] = req.socket.encrypted ? 'https' : 'http'; + } + if (!headers['x-forwarded-host'] && req.headers.host) { + headers['x-forwarded-host'] = req.headers.host; + } + + const lib = target.protocol === 'https:' ? https : http; + let proxyReq; + let headersTimeout = null; + try { + proxyReq = lib.request( + { + protocol: target.protocol, + hostname: target.hostname, + port: target.port || undefined, + path: `${target.pathname}${target.search}`, + method: req.method, + headers, + rejectUnauthorized: settings.rejectUnauthorized, + }, + (proxyRes) => { + clearTimeout(headersTimeout); + + const proxyOrigin = getProxyOrigin(req); + const rewriting = shouldRewriteBody(req, proxyRes); + const responseHeaders = filterResponseHeaders( + proxyRes.headers, + rewriting + ); + + if (responseHeaders.location) { + responseHeaders.location = rewriteUrlValue( + responseHeaders.location, + upstream, + proxyOrigin + ); + } + + try { + res.writeHead(proxyRes.statusCode || 502, responseHeaders); + } catch { + release(); + try { + proxyRes.destroy(); + } catch {} + try { + res.destroy(); + } catch {} + return; + } + + proxyRes.on('close', release); + proxyRes.on('error', () => { + release(); + if (!res.headersSent) { + sendText(res, 502, 'Upstream response error'); + } else { + res.destroy(); + } + }); + + if (rewriting) { + const replacer = new ReplaceStream( + buildReplacements(upstream, proxyOrigin) + ); + replacer.on('error', () => { + try { + res.destroy(); + } catch {} + release(); + }); + proxyRes.pipe(replacer).pipe(res); + } else { + proxyRes.pipe(res); + } + } + ); + } catch (e) { + release(); + markUpstreamFailure(upstream, e); + if (canRetry(req) && attempted.size < upstreamCount) { + attempt(); + } else { + sendText(res, 502, 'Upstream request failed'); + } + return; + } + + headersTimeout = setTimeout(() => { + try { + proxyReq.destroy(new Error('upstream_timeout')); + } catch {} + }, settings.upstreamTimeoutMs); + + currentProxyReq = proxyReq; + + proxyReq.on('error', (err) => { + clearTimeout(headersTimeout); + if (currentProxyReq === proxyReq) currentProxyReq = null; + release(); + if (closed) return; + + markUpstreamFailure(upstream, err); + + if (!res.headersSent && canRetry(req) && attempted.size < upstreamCount) { + attempt(); + return; + } + + if (!res.headersSent) { + sendText(res, 502, 'Upstream request failed'); + } else { + res.destroy(); + } + }); + + req.pipe(proxyReq); + }; + + attempt(); +} + +module.exports = { handleProxy }; diff --git a/Dockers/xtream-proxy/src/rewrite.js b/Dockers/xtream-proxy/src/rewrite.js new file mode 100644 index 0000000..52fc867 --- /dev/null +++ b/Dockers/xtream-proxy/src/rewrite.js @@ -0,0 +1,273 @@ +'use strict'; + +const { Transform } = require('stream'); +const { settings } = require('./settings'); + +const HOP_BY_HOP = new Set([ + 'connection', + 'keep-alive', + 'proxy-authenticate', + 'proxy-authorization', + 'te', + 'trailers', + 'transfer-encoding', + 'upgrade', +]); + +const STREAM_PATH = /^\/(live|movie|series|timeshift|hls|stream|vod)\//i; +const STREAM_EXT = + /\.(ts|m3u8|mp4|mkv|avi|mov|mpg|mpeg|flv|mp3|aac|m4a|m4v)$/i; + +class ReplaceStream extends Transform { + constructor(replacements) { + super(); + this.replacements = replacements + .filter((r) => r.from && r.to !== undefined && r.from !== r.to) + .map((r) => ({ from: Buffer.from(r.from), to: Buffer.from(r.to) })); + this.maxLen = this.replacements.reduce( + (max, r) => Math.max(max, r.from.length), + 0 + ); + this.carry = Buffer.alloc(0); + } + + _transform(chunk, _encoding, callback) { + this._process(Buffer.concat([this.carry, chunk]), false, callback); + } + + _flush(callback) { + this._process(this.carry, true, callback); + } + + _process(buffer, isEnd, callback) { + const output = []; + let position = 0; + + while (position < buffer.length) { + let best = null; + for (const replacement of this.replacements) { + const index = buffer.indexOf(replacement.from, position); + if (index === -1) continue; + if (!best || index < best.index) best = { index, replacement }; + } + + if (!best) break; + const end = best.index + best.replacement.from.length; + if (!isEnd && end > buffer.length) break; + + if (best.index > position) { + output.push(buffer.subarray(position, best.index)); + } + output.push(best.replacement.to); + position = end; + } + + if (position < buffer.length) { + const keepFrom = isEnd + ? buffer.length + : Math.max(position, buffer.length - (this.maxLen - 1)); + if (keepFrom > position) { + output.push(buffer.subarray(position, keepFrom)); + } + this.carry = isEnd ? Buffer.alloc(0) : buffer.subarray(keepFrom); + } else { + this.carry = Buffer.alloc(0); + } + + if (output.length) this.push(Buffer.concat(output)); + callback(); + } +} + +function encodeQueryComponent(value) { + return encodeURIComponent(value).replace(/%20/g, '+'); +} + +function buildReplacements(upstream, proxyOrigin) { + const proxyHost = new URL(proxyOrigin).host; + const replacements = []; + const seen = new Set(); + + const add = (from, to) => { + if (!from || to === undefined || from === to || seen.has(from)) return; + seen.add(from); + replacements.push({ from, to }); + }; + + add(upstream.baseNoSlash, proxyOrigin); + add(upstream.base.origin, proxyOrigin); + + const bareHost = upstream.base.host; + add(`"url":"${bareHost}"`, `"url":"${proxyHost}"`); + add(`"url": "${bareHost}"`, `"url": "${proxyHost}"`); + + add(upstream.username, settings.proxyUsername); + add( + encodeURIComponent(upstream.username), + encodeURIComponent(settings.proxyUsername) + ); + add( + encodeQueryComponent(upstream.username), + encodeQueryComponent(settings.proxyUsername) + ); + + add(upstream.password, settings.proxyPassword); + add( + encodeURIComponent(upstream.password), + encodeURIComponent(settings.proxyPassword) + ); + add( + encodeQueryComponent(upstream.password), + encodeQueryComponent(settings.proxyPassword) + ); + + return replacements; +} + +function rewriteUrlValue(value, upstream, proxyOrigin) { + if (typeof value !== 'string') return value; + let result = value; + for (const { from, to } of buildReplacements(upstream, proxyOrigin)) { + result = result.split(from).join(to); + } + return result; +} + +function isRewritableContentType(contentType) { + if (!contentType) return false; + const type = contentType.split(';')[0].trim().toLowerCase(); + return ( + type.startsWith('text/') || + type === 'application/json' || + type === 'application/xml' || + type === 'application/javascript' || + type === 'application/x-mpegurl' || + type === 'application/vnd.apple.mpegurl' || + type === 'audio/mpegurl' || + type === 'audio/x-mpegurl' || + type === 'application/octet-stream' + ); +} + +function shouldRewriteBody(req, upstreamResponse) { + if (req.method === 'HEAD') return false; + if ( + upstreamResponse.statusCode === 204 || + upstreamResponse.statusCode === 304 + ) { + return false; + } + const encoding = upstreamResponse.headers['content-encoding']; + if (encoding && encoding.toLowerCase() !== 'identity') return false; + return isRewritableContentType(upstreamResponse.headers['content-type']); +} + +function filterHopByHop(headers) { + const result = {}; + if (!headers) return result; + for (const [key, value] of Object.entries(headers)) { + if (value === undefined) continue; + if (HOP_BY_HOP.has(key.toLowerCase())) continue; + result[key] = value; + } + return result; +} + +function filterResponseHeaders(headers, rewriting) { + const result = {}; + for (const [key, value] of Object.entries(headers)) { + if (value === undefined) continue; + const lower = key.toLowerCase(); + if (HOP_BY_HOP.has(lower)) continue; + if ( + rewriting && + (lower === 'content-length' || + lower === 'etag' || + lower === 'content-md5') + ) { + continue; + } + result[key] = value; + } + return result; +} + +function isStreamPath(pathname) { + return STREAM_PATH.test(pathname) || STREAM_EXT.test(pathname); +} + +function extractCreds(reqUrl) { + const queryUsername = reqUrl.searchParams.get('username'); + const queryPassword = reqUrl.searchParams.get('password'); + const hasQueryCreds = queryUsername !== null || queryPassword !== null; + + const rawSegments = reqUrl.pathname.split('/'); + const decodedSegments = rawSegments.map((segment) => { + try { + return decodeURIComponent(segment); + } catch { + return segment; + } + }); + + const pathUsername = decodedSegments.includes(settings.proxyUsername); + const pathPassword = decodedSegments.includes(settings.proxyPassword); + + return { + queryUsername, + queryPassword, + hasQueryCreds, + rawSegments, + hasPathCreds: pathUsername && pathPassword, + }; +} + +function isAuthenticated(creds) { + if (creds.hasQueryCreds) { + return ( + creds.queryUsername === settings.proxyUsername && + creds.queryPassword === settings.proxyPassword + ); + } + return creds.hasPathCreds; +} + +function rewritePath(creds, upstream) { + return creds.rawSegments + .map((segment) => { + let decoded = segment; + try { + decoded = decodeURIComponent(segment); + } catch {} + if (decoded === settings.proxyUsername) { + return encodeURIComponent(upstream.username); + } + if (decoded === settings.proxyPassword) { + return encodeURIComponent(upstream.password); + } + return segment; + }) + .join('/'); +} + +function rewriteSearch(reqUrl, upstream) { + const params = new URLSearchParams(reqUrl.searchParams); + if (params.has('username')) params.set('username', upstream.username); + if (params.has('password')) params.set('password', upstream.password); + const search = params.toString(); + return search ? `?${search}` : ''; +} + +module.exports = { + ReplaceStream, + buildReplacements, + rewriteUrlValue, + shouldRewriteBody, + filterHopByHop, + filterResponseHeaders, + isStreamPath, + extractCreds, + isAuthenticated, + rewritePath, + rewriteSearch, +}; diff --git a/Dockers/xtream-proxy/src/settings.js b/Dockers/xtream-proxy/src/settings.js new file mode 100644 index 0000000..dbc68f9 --- /dev/null +++ b/Dockers/xtream-proxy/src/settings.js @@ -0,0 +1,35 @@ +'use strict'; + +const settings = { + listenPort: Number(process.env.LISTEN_PORT || 8080), + configFile: process.env.CONFIG_FILE || '/config/upstreams.json', + proxyUsername: + process.env.PROXY_USERNAME || process.env.XTREAM_USERNAME || '', + proxyPassword: + process.env.PROXY_PASSWORD || process.env.XTREAM_PASSWORD || '', + probeIntervalSec: Math.max( + 5, + Number(process.env.PROBE_INTERVAL_SEC || 30) || 30 + ), + probeTimeoutMs: Math.max( + 1000, + Number(process.env.PROBE_TIMEOUT_MS || 8000) || 8000 + ), + upstreamTimeoutMs: Math.max( + 1000, + Number(process.env.UPSTREAM_TIMEOUT_MS || 15000) || 15000 + ), + rejectUnauthorized: process.env.PROXY_INSECURE_TLS !== '1', + allowBusyFallback: process.env.ALLOW_BUSY_FALLBACK !== '0', + userAgent: process.env.USER_AGENT || 'xtream-proxy/2.0', +}; + +function validate() { + if (!settings.proxyUsername || !settings.proxyPassword) { + throw new Error( + 'PROXY_USERNAME and PROXY_PASSWORD (or XTREAM_USERNAME / XTREAM_PASSWORD) are required' + ); + } +} + +module.exports = { settings, validate }; diff --git a/Dockers/xtream-proxy/src/upstream.js b/Dockers/xtream-proxy/src/upstream.js new file mode 100644 index 0000000..4667b7a --- /dev/null +++ b/Dockers/xtream-proxy/src/upstream.js @@ -0,0 +1,51 @@ +'use strict'; + +function nowIso() { + return new Date().toISOString(); +} + +function baseState() { + return { + healthy: false, + busy: false, + latencyMs: null, + activeCons: null, + maxCons: null, + status: null, + auth: null, + error: null, + lastChecked: nowIso(), + }; +} + +class Upstream { + constructor({ url, username, password }) { + const parsed = new URL(url); + parsed.hash = ''; + parsed.search = ''; + this.base = parsed; + this.basePath = parsed.pathname.replace(/\/+$/, ''); + this.username = username; + this.password = password; + this.key = `${parsed.origin}${this.basePath}|${username}|${password}`; + this.state = { ...baseState(), inFlight: 0 }; + } + + get label() { + return `${this.base.origin}${this.basePath}`; + } + + get baseNoSlash() { + return `${this.base.origin}${this.basePath}`; + } +} + +function buildUpstreamUrl(upstream, pathname, search) { + const p = pathname.startsWith('/') ? pathname : `/${pathname}`; + const target = new URL(upstream.base.origin); + target.pathname = `${upstream.basePath}${p}` || '/'; + target.search = search || ''; + return target; +} + +module.exports = { Upstream, baseState, nowIso, buildUpstreamUrl }; diff --git a/Dockers/xtream-proxy/src/upstreams.js b/Dockers/xtream-proxy/src/upstreams.js new file mode 100644 index 0000000..083ac26 --- /dev/null +++ b/Dockers/xtream-proxy/src/upstreams.js @@ -0,0 +1,163 @@ +'use strict'; + +const { settings } = require('./settings'); +const { reloadConfig, getUpstreams } = require('./config'); +const { probeUpstream } = require('./probe'); + +let lastProbeAt = null; +let probing = false; +let probeTimer = null; + +function nowIso() { + return new Date().toISOString(); +} + +function effectiveLoad(upstream) { + return Math.max( + upstream.state.activeCons || 0, + upstream.state.inFlight || 0 + ); +} + +function isBusy(upstream) { + const max = upstream.state.maxCons; + if (max === null || max <= 0) return false; + return effectiveLoad(upstream) >= max; +} + +function rankedUpstreams() { + return getUpstreams() + .filter((u) => u.state.healthy) + .map((u) => ({ upstream: u, busy: isBusy(u) })) + .sort((a, b) => { + if (a.busy !== b.busy) return a.busy ? 1 : -1; + const la = a.upstream.state.latencyMs ?? Infinity; + const lb = b.upstream.state.latencyMs ?? Infinity; + return la - lb; + }); +} + +function selectUpstream(exclude = new Set()) { + const candidates = rankedUpstreams().filter( + ({ upstream }) => !exclude.has(upstream.key) + ); + + const idle = candidates.find((c) => !c.busy); + if (idle) return idle.upstream; + + if (settings.allowBusyFallback) { + const fallback = candidates.find((c) => c.busy); + if (fallback) return fallback.upstream; + } + + return null; +} + +function describeUpstream(upstream) { + return { + url: upstream.label, + healthy: upstream.state.healthy, + busy: isBusy(upstream), + latencyMs: upstream.state.latencyMs, + activeCons: upstream.state.activeCons, + maxCons: upstream.state.maxCons, + inFlight: upstream.state.inFlight, + status: upstream.state.status, + error: upstream.state.error, + lastChecked: upstream.state.lastChecked, + }; +} + +function logProbeResults(snapshot) { + if (snapshot.length === 0) { + console.warn(`No upstreams configured in ${settings.configFile}`); + return; + } + + const ranked = rankedUpstreams(); + const lines = ranked.map(({ upstream, busy }, index) => { + const load = `${upstream.state.activeCons ?? '?'}/${upstream.state.maxCons ?? '?'}`; + return `${index + 1}. ${upstream.label} ${upstream.state.latencyMs ?? '?'}ms ${ + busy ? `busy(${load})` : 'idle' + }${upstream.state.inFlight ? ` inflight=${upstream.state.inFlight}` : ''}`; + }); + + const failed = snapshot.filter((u) => !u.state.healthy); + if (failed.length) { + lines.push( + ...failed.map((u) => `x. ${u.label} ${u.state.error || 'unhealthy'}`) + ); + } + console.log(`Probe results:\n ${lines.join('\n ')}`); +} + +async function probeCycle() { + if (probing) return; + probing = true; + + try { + reloadConfig(); + const snapshot = getUpstreams().slice(); + const results = await Promise.all( + snapshot.map(async (upstream) => ({ + upstream, + state: await probeUpstream(upstream), + })) + ); + + for (const { upstream, state } of results) { + upstream.state = { ...upstream.state, ...state }; + } + + lastProbeAt = nowIso(); + logProbeResults(snapshot); + } catch (e) { + console.error('Probe cycle failed:', e); + } finally { + probing = false; + } +} + +function scheduleProbe(delayMs) { + if (probeTimer) { + clearTimeout(probeTimer); + probeTimer = null; + } + probeTimer = setTimeout(async () => { + probeTimer = null; + await probeCycle(); + scheduleProbe(settings.probeIntervalSec * 1000); + }, delayMs); +} + +function startProbing() { + scheduleProbe(settings.probeIntervalSec * 1000); +} + +function stopProbing() { + if (probeTimer) { + clearTimeout(probeTimer); + probeTimer = null; + } +} + +function requestProbeSoon() { + if (probing) return; + scheduleProbe(1000); +} + +function getLastProbeAt() { + return lastProbeAt; +} + +module.exports = { + probeCycle, + startProbing, + stopProbing, + requestProbeSoon, + selectUpstream, + rankedUpstreams, + isBusy, + describeUpstream, + getLastProbeAt, +}; diff --git a/Dockers/xtream-proxy/upstreams.json.example b/Dockers/xtream-proxy/upstreams.json.example new file mode 100644 index 0000000..972080e --- /dev/null +++ b/Dockers/xtream-proxy/upstreams.json.example @@ -0,0 +1,19 @@ +# +# Every entry must point to an Xtream-compatible panel that serves the same +# content. The proxy probes each entry via /player_api.php and picks the +# fastest one that is not at its connection limit. +# +# The URL may include a path prefix, e.g. https://example.com/portal +# +[ + { + "url": "http://panel1.example.com:8080", + "username": "user1", + "password": "pass1" + }, + { + "url": "https://panel2.example.com", + "username": "user2", + "password": "pass2" + } +]