diff --git a/README.md b/README.md new file mode 100644 index 0000000..e5601e8 --- /dev/null +++ b/README.md @@ -0,0 +1,44 @@ +# File Manager API Server + +## Kuvaus +ApiServer tarjoaa turvallisen rajapinnan tiedostonhallinnan toimintoihin. Kaikki kutsut vaativat API-avaimen. + +## Käynnistys +```bash +cd ApiServer +npm install +npm run dev +``` + +## Ympäristömuuttujat (.env) +- `PORT`: Palvelimen portti (oletus: 3001) +- `API_KEY`: API-avain, jota vaaditaan kaikissa kutsuissa +- `NODE_ENV`: Ympäristö (development/production) + +## Autentikointi +Kaikki API-kutsut vaativat Authorization-headerin: +``` +Authorization: Bearer YOUR_API_KEY +``` + +## Endpointit + +### GET /api/v1/health +Terveystarkistus - palauttaa palvelimen tilan. + +### GET /api/v1/server-info +Palauttaa palvelimen tiedot ja ominaisuudet. + +### GET /api/v1/servers +Palauttaa listan hallinnoiduista palvelimista. + +### GET /api/v1/servers/:id +Palauttaa tietyn palvelimen tiedot. + +### POST /api/v1/servers/:id/test +Testaa yhteyden tiettyyn palvelimeen. + +## Tietoturva +- Kaikki kutsut vaativat kelvollisen API-avaimen +- Virheelliset API-avaimet palauttavat 401 Unauthorized +- Kaikki kutsut lokitetaan \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..2678c9d --- /dev/null +++ b/package-lock.json @@ -0,0 +1,876 @@ +{ + "name": "file-manager-api-server", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "file-manager-api-server", + "version": "1.0.0", + "dependencies": { + "cors": "^2.8.5", + "crypto": "^1.0.1", + "dotenv": "^16.3.1", + "express": "^4.18.2" + } + }, + "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.3", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", + "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "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.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.13.0", + "raw-body": "2.5.2", + "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.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz", + "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==", + "license": "MIT" + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/crypto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/crypto/-/crypto-1.0.1.tgz", + "integrity": "sha512-VxBKmeNcqQdiUQUW2Tzq0t377b54N2bMtXO/qiLa+6eRRmmC4qT3D4OnTGoT/U6O9aklQ/jTwbOtRMTTY8G0Ig==", + "deprecated": "This package is no longer supported. It's now a built-in Node module. If you've depended on crypto, you should switch to the one that's built-in.", + "license": "ISC" + }, + "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/dotenv": { + "version": "16.5.0", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.5.0.tgz", + "integrity": "sha512-m/C+AwOAr9/W1UOIZUo232ejMNnJAJtYQjUbHoNTBNTJSvqzzDh7vnrei3o3r3m9blf6ZoDkvcw0VmozNRFJxg==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "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.21.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz", + "integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==", + "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.13.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.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", + "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "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.1", + "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.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "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-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "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.12", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", + "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==", + "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.13.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.0.6" + }, + "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.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "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.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz", + "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "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.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", + "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.19.0" + }, + "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.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "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.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "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" + } + } + } +} diff --git a/server.js b/server.js new file mode 100644 index 0000000..1828018 --- /dev/null +++ b/server.js @@ -0,0 +1,1117 @@ +import express from 'express'; +import cors from 'cors'; +import dotenv from 'dotenv'; +import crypto from 'crypto'; +import fs from 'fs/promises'; +import path from 'path'; + +dotenv.config(); + +const app = express(); +const CONFIG_FILE = path.join(process.cwd(), 'config.json'); + +// Load configuration +let config = {}; + +async function loadConfig() { + try { + const configData = await fs.readFile(CONFIG_FILE, 'utf8'); + const newConfig = JSON.parse(configData); + + // Check if root directory changed + const oldRootDirectory = config.server?.rootDirectory; + const newRootDirectory = newConfig.server?.rootDirectory; + + config = newConfig; + console.log('✅ API Server: Configuration loaded successfully'); + + // If root directory changed, refresh file system cache + if (oldRootDirectory && newRootDirectory && oldRootDirectory !== newRootDirectory) { + console.log(`📁 API Server: Root directory changed from ${oldRootDirectory} to ${newRootDirectory}`); + console.log('🔄 API Server: Refreshing file system cache...'); + await refreshFileSystemCache(); + } + + return config; + } catch (error) { + console.error('❌ API Server: Error loading config:', error.message); + // Create default config if file doesn't exist + config = { + server: { + name: "File Manager API Server", + port: 3001, + rootDirectory: "/home/project", + logLevel: "info", + environment: "development", + capabilities: [ + "file-transfer", + "server-management", + "health-monitoring", + "filesystem-browsing" + ] + }, + filesystem: { + maxDepth: 10, + cacheSettings: { + ttl: 60000, + refreshInterval: 300000 + }, + watchEnabled: true, + maxFileSize: 104857600 + }, + transfer: { + maxConcurrentTransfers: 5, + uploadTimeout: 300000, + maxRequestSize: 104857600 + }, + security: { + corsOrigins: [ + "http://localhost:3000", + "http://localhost:5173" + ], + requestTimeout: 30000, + rateLimiting: { + windowMs: 900000, + maxRequests: 1000 + } + }, + logging: { + requests: true, + errors: true, + filePath: "./logs/api-server.log" + }, + health: { + checkEnabled: true, + checkInterval: 60000 + } + }; + await saveConfig(); + return config; + } +} + +async function saveConfig() { + try { + await fs.writeFile(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf8'); + console.log('✅ API Server: Configuration saved successfully'); + return true; + } catch (error) { + console.error('❌ API Server: Error saving config:', error.message); + return false; + } +} + +// Watch config file for changes +async function watchConfigFile() { + try { + const { watch } = await import('fs'); + + console.log('👁️ API Server: Starting config file watcher...'); + + const watcher = watch(CONFIG_FILE, { persistent: false }, async (eventType, filename) => { + if (eventType === 'change' && filename === 'config.json') { + console.log('📝 API Server: Config file changed, reloading...'); + + // Add a small delay to ensure file write is complete + setTimeout(async () => { + try { + await loadConfig(); + console.log('✅ API Server: Configuration reloaded successfully'); + } catch (error) { + console.error('❌ API Server: Error reloading configuration:', error.message); + } + }, 100); + } + }); + + watcher.on('error', (error) => { + console.error('❌ API Server: Config file watcher error:', error.message); + }); + + console.log('✅ API Server: Config file watcher started'); + return watcher; + } catch (error) { + console.error('❌ API Server: Failed to start config file watcher:', error.message); + return null; + } +} + +// Get current configuration +function getConfig() { + return config; +} + +const API_KEY = process.env.API_KEY; +const PORT = process.env.PORT || config.server?.port || 3001; + +// Middleware +app.use(cors({ + origin: config.security?.corsOrigins || ["http://localhost:3000", "http://localhost:5173"], + credentials: true +})); +app.use(express.json()); + +// API Key validation middleware +const validateApiKey = (req, res, next) => { + const authHeader = req.headers.authorization; + + if (!authHeader) { + return res.status(401).json({ + success: false, + error: 'Authorization header missing' + }); + } + + const token = authHeader.replace('Bearer ', ''); + + if (token !== API_KEY) { + return res.status(401).json({ + success: false, + error: 'Invalid API key' + }); + } + + next(); +}; + +// Request logging middleware +app.use((req, res, next) => { + if (config.logging?.requests) { + const timestamp = new Date().toISOString(); + console.log(`[${timestamp}] API Server: ${req.method} ${req.path} - ${req.ip}`); + } + next(); +}); + +// File system cache +let fileSystemCache = { + data: null, + lastUpdate: null, + ttl: config.filesystem?.cacheSettings?.ttl || 60000 +}; + +// Helper function to resolve file path correctly +function resolveFilePath(relativePath) { + const rootDir = config.server.rootDirectory; + + // If relativePath is already absolute and starts with rootDir, use it as is + if (path.isAbsolute(relativePath) && relativePath.startsWith(rootDir)) { + return relativePath; + } + + // If relativePath is absolute but doesn't start with rootDir, + // treat it as relative to rootDir + if (path.isAbsolute(relativePath)) { + // Remove leading slash and join with rootDir + const cleanPath = relativePath.startsWith('/') ? relativePath.slice(1) : relativePath; + return path.join(rootDir, cleanPath); + } + + // If relativePath is relative, join with rootDir + return path.join(rootDir, relativePath); +} + +// Helper function to get relative path from absolute path +function getRelativePath(absolutePath) { + const rootDir = config.server.rootDirectory; + + // If path starts with rootDir, remove it to get relative path + if (absolutePath.startsWith(rootDir)) { + const relativePath = absolutePath.slice(rootDir.length); + return relativePath.startsWith('/') ? relativePath : '/' + relativePath; + } + + // If path doesn't start with rootDir, return as is + return absolutePath; +} + +// Dangerous directories to skip when scanning from root +const DANGEROUS_DIRECTORIES = new Set([ + '/proc', + '/sys', + '/dev', + '/run', + '/tmp', + '/var/run', + '/var/lock', + '/var/tmp', + '/boot', + '/lost+found' +]); + +// Helper function to check if directory should be skipped +function shouldSkipDirectory(dirPath) { + // Skip dangerous system directories + if (DANGEROUS_DIRECTORIES.has(dirPath)) { + return true; + } + + // Skip any subdirectories of dangerous directories + for (const dangerousDir of DANGEROUS_DIRECTORIES) { + if (dirPath.startsWith(dangerousDir + '/')) { + return true; + } + } + + // Skip hidden directories when scanning from root + const rootDir = config.server.rootDirectory; + if (rootDir === '/' && path.basename(dirPath).startsWith('.')) { + return true; + } + + return false; +} + +// Helper function to get file stats safely +async function getFileStats(filePath) { + try { + const stats = await fs.stat(filePath); + return { + isDirectory: stats.isDirectory(), + isFile: stats.isFile(), + size: stats.size, + lastModified: stats.mtime, + created: stats.birthtime, + permissions: stats.mode + }; + } catch (error) { + return null; + } +} + +// Helper function to scan directory recursively with safety limits +async function scanDirectory(dirPath, currentDepth = 0, maxDepth = 10) { + if (currentDepth >= maxDepth) { + console.log(`⚠️ API Server: Max depth ${maxDepth} reached for ${dirPath}`); + return []; + } + + // Check if directory should be skipped for safety + if (shouldSkipDirectory(dirPath)) { + console.log(`⚠️ API Server: Skipping dangerous directory: ${dirPath}`); + return []; + } + + try { + const entries = await fs.readdir(dirPath); + const files = []; + let processedCount = 0; + const maxEntriesPerDirectory = 1000; // Limit entries per directory + + for (const entry of entries) { + // Limit number of entries processed per directory + if (processedCount >= maxEntriesPerDirectory) { + console.log(`⚠️ API Server: Directory ${dirPath} has too many entries, limiting to ${maxEntriesPerDirectory}`); + break; + } + + const fullPath = path.join(dirPath, entry); + + // Skip dangerous directories + if (shouldSkipDirectory(fullPath)) { + continue; + } + + const stats = await getFileStats(fullPath); + + if (!stats) continue; + + const relativePath = getRelativePath(fullPath); + + const fileItem = { + id: crypto.randomUUID(), + name: entry, + path: relativePath, + type: stats.isDirectory ? 'folder' : 'file', + size: stats.isFile ? stats.size : undefined, + lastModified: stats.lastModified, + created: stats.created, + permissions: stats.permissions + }; + + if (stats.isDirectory && currentDepth < maxDepth - 1) { + try { + fileItem.children = await scanDirectory(fullPath, currentDepth + 1, maxDepth); + } catch (error) { + console.warn(`⚠️ API Server: Cannot read directory ${fullPath}: ${error.message}`); + fileItem.children = []; + } + } + + files.push(fileItem); + processedCount++; + } + + return files.sort((a, b) => { + // Folders first, then files, both alphabetically + if (a.type !== b.type) { + return a.type === 'folder' ? -1 : 1; + } + return a.name.localeCompare(b.name); + }); + } catch (error) { + console.error(`❌ API Server: Error scanning directory ${dirPath}: ${error.message}`); + return []; + } +} + +// Helper function to refresh file system cache with safety limits +async function refreshFileSystemCache() { + try { + const rootDir = config.server.rootDirectory; + console.log(`🔍 API Server: Scanning file system from root: ${rootDir}`); + + // Special handling for root directory + if (rootDir === '/') { + console.log(`⚠️ API Server: Root directory is '/', applying safety limits`); + } + + const startTime = Date.now(); + + // Use reduced max depth for root directory scanning + const maxDepth = rootDir === '/' ? 3 : (config.filesystem?.maxDepth || 10); + console.log(`📊 API Server: Using max depth: ${maxDepth}`); + + const files = await scanDirectory(rootDir, 0, maxDepth); + + fileSystemCache = { + data: files, + lastUpdate: new Date().toISOString(), + ttl: config.filesystem?.cacheSettings?.ttl || 60000, + scanTime: Date.now() - startTime, + totalFiles: countFiles(files), + rootDirectory: rootDir, + maxDepth: maxDepth + }; + + console.log(`✅ API Server: File system scan completed in ${fileSystemCache.scanTime}ms, found ${fileSystemCache.totalFiles} items`); + return true; + } catch (error) { + console.error('❌ API Server: Error refreshing file system cache:', error); + return false; + } +} + +// Helper function to count files recursively +function countFiles(files) { + let count = 0; + for (const file of files) { + count++; + if (file.children) { + count += countFiles(file.children); + } + } + return count; +} + +// Check if cache is valid +function isCacheValid() { + if (!fileSystemCache.data || !fileSystemCache.lastUpdate) { + return false; + } + + const now = Date.now(); + const lastUpdate = new Date(fileSystemCache.lastUpdate).getTime(); + return (now - lastUpdate) < fileSystemCache.ttl; +} + +// Mock data for servers (keeping existing functionality) +const mockServers = [ + { + id: 'server1', + name: 'Production Server', + address: '192.168.1.100', + port: 22, + type: 'sftp', + status: 'online', + lastSeen: new Date().toISOString() + }, + { + id: 'server2', + name: 'Development Server', + address: '192.168.1.101', + port: 22, + type: 'sftp', + status: 'offline', + lastSeen: new Date(Date.now() - 3600000).toISOString() + } +]; + +// Routes + +// Get configuration +app.get('/api/v1/config', validateApiKey, (req, res) => { + res.json({ + success: true, + data: config + }); +}); + +// Update configuration +app.post('/api/v1/config', validateApiKey, async (req, res) => { + try { + const updates = req.body; + + // Deep merge configuration + function deepMerge(target, source) { + for (const key in source) { + if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) { + if (!target[key]) target[key] = {}; + deepMerge(target[key], source[key]); + } else { + target[key] = source[key]; + } + } + } + + const oldRootDirectory = config.server?.rootDirectory; + deepMerge(config, updates); + + const saved = await saveConfig(); + if (saved) { + // Refresh file system if root directory changed + const newRootDirectory = config.server?.rootDirectory; + if (oldRootDirectory !== newRootDirectory) { + console.log(`📁 API Server: Root directory updated from ${oldRootDirectory} to ${newRootDirectory}`); + await refreshFileSystemCache(); + } + + res.json({ + success: true, + message: 'Configuration updated successfully', + data: config + }); + } else { + res.status(500).json({ + success: false, + error: 'Failed to save configuration' + }); + } + } catch (error) { + res.status(500).json({ + success: false, + error: 'Failed to update configuration', + details: error.message + }); + } +}); + +// Update root directory +app.post('/api/v1/config/root-directory', validateApiKey, async (req, res) => { + try { + const { rootDirectory } = req.body; + + console.log(`📡 API Server: Received root directory update request`); + console.log(`📡 API Server: Request body:`, req.body); + console.log(`📡 API Server: Headers:`, req.headers); + + if (!rootDirectory) { + console.log(`❌ API Server: Root directory is missing from request`); + return res.status(400).json({ + success: false, + error: 'Root directory is required' + }); + } + + const oldRootDirectory = config.server.rootDirectory; + console.log(`📁 API Server: Updating root directory from "${oldRootDirectory}" to "${rootDirectory}"`); + + // Validate root directory + if (rootDirectory === '/') { + console.log(`⚠️ API Server: Warning - Setting root directory to '/' will apply safety limits`); + } + + // Update the configuration + config.server.rootDirectory = rootDirectory; + + // Save the configuration to file + console.log(`💾 API Server: Saving configuration to ${CONFIG_FILE}`); + const saved = await saveConfig(); + + if (saved) { + console.log(`✅ API Server: Root directory updated successfully to "${rootDirectory}"`); + console.log(`🔄 API Server: Refreshing file system cache...`); + + // Refresh file system cache with new root directory + const refreshed = await refreshFileSystemCache(); + + console.log(`✅ API Server: File system cache refresh ${refreshed ? 'successful' : 'failed'}`); + + res.json({ + success: true, + message: 'Root directory updated successfully', + data: { + rootDirectory, + previousDirectory: oldRootDirectory, + configSaved: true, + cacheRefreshed: refreshed, + safetyLimitsApplied: rootDirectory === '/' + } + }); + } else { + console.error(`❌ API Server: Failed to save configuration`); + res.status(500).json({ + success: false, + error: 'Failed to save configuration' + }); + } + } catch (error) { + console.error(`❌ API Server: Error updating root directory:`, error); + res.status(500).json({ + success: false, + error: 'Failed to update root directory', + details: error.message + }); + } +}); + +// Health check endpoint +app.get('/api/v1/health', validateApiKey, (req, res) => { + const uptime = process.uptime(); + const timestamp = new Date().toISOString(); + + res.json({ + success: true, + data: { + status: 'healthy', + timestamp, + uptime: Math.floor(uptime), + version: '1.0.0', + environment: config.server?.environment || 'development', + rootDirectory: config.server.rootDirectory, + fileSystemCache: { + lastUpdate: fileSystemCache.lastUpdate, + isValid: isCacheValid(), + totalFiles: fileSystemCache.totalFiles || 0, + maxDepth: fileSystemCache.maxDepth, + safetyLimitsActive: config.server.rootDirectory === '/' + } + } + }); +}); + +// Get server information +app.get('/api/v1/server-info', validateApiKey, (req, res) => { + res.json({ + success: true, + data: { + name: config.server.name, + version: '1.0.0', + rootDirectory: config.server.rootDirectory, + capabilities: config.server.capabilities, + limits: { + maxFileSize: `${Math.round(config.filesystem.maxFileSize / 1024 / 1024)}MB`, + maxConcurrentTransfers: config.transfer.maxConcurrentTransfers, + maxScanDepth: config.filesystem.maxDepth, + safetyLimitsActive: config.server.rootDirectory === '/' + } + } + }); +}); + +// Get file system structure +app.get('/api/v1/filesystem', validateApiKey, async (req, res) => { + try { + // Check if cache is valid, refresh if needed + if (!isCacheValid()) { + const refreshed = await refreshFileSystemCache(); + if (!refreshed) { + return res.status(500).json({ + success: false, + error: 'Failed to scan file system' + }); + } + } + + res.json({ + success: true, + data: { + files: fileSystemCache.data || [], + rootDirectory: config.server.rootDirectory, + lastUpdate: fileSystemCache.lastUpdate, + scanTime: fileSystemCache.scanTime, + totalFiles: fileSystemCache.totalFiles, + maxDepth: fileSystemCache.maxDepth, + safetyLimitsActive: config.server.rootDirectory === '/', + cached: true + } + }); + } catch (error) { + console.error('❌ API Server: Error getting file system:', error); + res.status(500).json({ + success: false, + error: 'Failed to get file system structure', + details: error.message + }); + } +}); + +// Refresh file system cache manually +app.post('/api/v1/filesystem/refresh', validateApiKey, async (req, res) => { + try { + const refreshed = await refreshFileSystemCache(); + + if (refreshed) { + res.json({ + success: true, + data: { + message: 'File system cache refreshed successfully', + lastUpdate: fileSystemCache.lastUpdate, + scanTime: fileSystemCache.scanTime, + totalFiles: fileSystemCache.totalFiles, + maxDepth: fileSystemCache.maxDepth, + safetyLimitsActive: config.server.rootDirectory === '/' + } + }); + } else { + res.status(500).json({ + success: false, + error: 'Failed to refresh file system cache' + }); + } + } catch (error) { + console.error('❌ API Server: Error refreshing file system:', error); + res.status(500).json({ + success: false, + error: 'Failed to refresh file system cache', + details: error.message + }); + } +}); + +// Get specific directory contents +app.get('/api/v1/filesystem/directory', validateApiKey, async (req, res) => { + const { path: dirPath = '/' } = req.query; + + try { + const fullPath = resolveFilePath(dirPath); + console.log(`📁 API Server: Getting directory contents for: ${dirPath} -> ${fullPath}`); + + const files = await scanDirectory(fullPath, 0, 2); // Limit depth for directory listing + + res.json({ + success: true, + data: { + path: dirPath, + files, + timestamp: new Date().toISOString() + } + }); + } catch (error) { + console.error('❌ API Server: Error getting directory contents:', error); + res.status(500).json({ + success: false, + error: 'Failed to get directory contents', + details: error.message + }); + } +}); + +// Read file content +app.get('/api/v1/filesystem/file-content', validateApiKey, async (req, res) => { + try { + const { path: filePath } = req.query; + + if (!filePath) { + return res.status(400).json({ + success: false, + error: 'File path is required' + }); + } + + const fullPath = resolveFilePath(filePath); + console.log(`📄 API Server: Reading file content from: ${filePath} -> ${fullPath}`); + + // Check if file exists and is a file + const stats = await getFileStats(fullPath); + if (!stats) { + return res.status(404).json({ + success: false, + error: 'File not found' + }); + } + + if (!stats.isFile) { + return res.status(400).json({ + success: false, + error: 'Path is not a file' + }); + } + + // Check file size limit (100MB default) + const maxFileSize = config.filesystem?.maxFileSize || 104857600; + if (stats.size > maxFileSize) { + return res.status(413).json({ + success: false, + error: `File too large. Maximum size: ${Math.round(maxFileSize / 1024 / 1024)}MB` + }); + } + + const content = await fs.readFile(fullPath, 'utf8'); + + console.log(`✅ API Server: File content read successfully, size: ${content.length} characters`); + + res.json({ + success: true, + data: { + content, + path: filePath, + size: stats.size, + lastModified: stats.lastModified, + encoding: 'utf8' + } + }); + } catch (error) { + console.error('❌ API Server: Error reading file content:', error); + + if (error.code === 'ENOENT') { + res.status(404).json({ + success: false, + error: 'File not found' + }); + } else if (error.code === 'EACCES') { + res.status(403).json({ + success: false, + error: 'Permission denied' + }); + } else if (error.code === 'EISDIR') { + res.status(400).json({ + success: false, + error: 'Path is a directory, not a file' + }); + } else { + res.status(500).json({ + success: false, + error: 'Failed to read file content', + details: error.message + }); + } + } +}); + +// Write file content +app.post('/api/v1/filesystem/file-content', validateApiKey, async (req, res) => { + try { + const { path: filePath, content } = req.body; + + if (!filePath) { + return res.status(400).json({ + success: false, + error: 'File path is required' + }); + } + + if (content === undefined || content === null) { + return res.status(400).json({ + success: false, + error: 'File content is required' + }); + } + + const fullPath = resolveFilePath(filePath); + console.log(`📄 API Server: Writing file content to: ${filePath} -> ${fullPath}`); + console.log(`📄 API Server: Content length: ${content.length} characters`); + + // Ensure parent directory exists + const parentDir = path.dirname(fullPath); + await fs.mkdir(parentDir, { recursive: true }); + + // Write file content + await fs.writeFile(fullPath, content, 'utf8'); + + // Get file stats after writing + const stats = await getFileStats(fullPath); + + // Refresh file system cache + await refreshFileSystemCache(); + + console.log(`✅ API Server: File content written successfully`); + + res.json({ + success: true, + message: 'File content written successfully', + data: { + path: filePath, + size: stats?.size || content.length, + lastModified: stats?.lastModified || new Date(), + encoding: 'utf8' + } + }); + } catch (error) { + console.error('❌ API Server: Error writing file content:', error); + + if (error.code === 'EACCES') { + res.status(403).json({ + success: false, + error: 'Permission denied' + }); + } else if (error.code === 'ENOSPC') { + res.status(507).json({ + success: false, + error: 'Insufficient storage space' + }); + } else { + res.status(500).json({ + success: false, + error: 'Failed to write file content', + details: error.message + }); + } + } +}); + +// Create folder +app.post('/api/v1/filesystem/folder', validateApiKey, async (req, res) => { + try { + const { parentPath, name } = req.body; + + if (!parentPath || !name) { + return res.status(400).json({ + success: false, + error: 'Parent path and name are required' + }); + } + + const fullParentPath = resolveFilePath(parentPath); + const newFolderPath = path.join(fullParentPath, name); + + console.log(`📁 API Server: Creating folder: ${parentPath}/${name} -> ${newFolderPath}`); + + await fs.mkdir(newFolderPath, { recursive: true }); + await refreshFileSystemCache(); + + console.log(`✅ API Server: Folder created successfully: ${newFolderPath}`); + + res.json({ + success: true, + message: 'Folder created successfully', + data: { path: newFolderPath } + }); + } catch (error) { + console.error('❌ API Server: Error creating folder:', error); + res.status(500).json({ + success: false, + error: 'Failed to create folder', + details: error.message + }); + } +}); + +// Create file +app.post('/api/v1/filesystem/file', validateApiKey, async (req, res) => { + try { + const { parentPath, name } = req.body; + + if (!parentPath || !name) { + return res.status(400).json({ + success: false, + error: 'Parent path and name are required' + }); + } + + const fullParentPath = resolveFilePath(parentPath); + const newFilePath = path.join(fullParentPath, name); + + console.log(`📄 API Server: Creating file: ${parentPath}/${name} -> ${newFilePath}`); + + await fs.writeFile(newFilePath, '', 'utf8'); + await refreshFileSystemCache(); + + console.log(`✅ API Server: File created successfully: ${newFilePath}`); + + res.json({ + success: true, + message: 'File created successfully', + data: { path: newFilePath } + }); + } catch (error) { + console.error('❌ API Server: Error creating file:', error); + res.status(500).json({ + success: false, + error: 'Failed to create file', + details: error.message + }); + } +}); + +// Delete item - Updated to read path from query parameter +app.delete('/api/v1/filesystem/item', validateApiKey, async (req, res) => { + try { + const itemPath = req.query.path; + + if (!itemPath) { + return res.status(400).json({ + success: false, + error: 'Item path is required' + }); + } + + const fullPath = resolveFilePath(itemPath); + console.log(`🗑️ API Server: Attempting to delete item: ${itemPath} -> ${fullPath}`); + + const stats = await getFileStats(fullPath); + + if (!stats) { + console.log(`❌ API Server: Item not found: ${fullPath}`); + return res.status(404).json({ + success: false, + error: 'Item not found' + }); + } + + if (stats.isDirectory) { + console.log(`📁 API Server: Deleting directory: ${fullPath}`); + await fs.rm(fullPath, { recursive: true, force: true }); + } else { + console.log(`📄 API Server: Deleting file: ${fullPath}`); + await fs.unlink(fullPath); + } + + await refreshFileSystemCache(); + + console.log(`✅ API Server: Item deleted successfully: ${fullPath}`); + + res.json({ + success: true, + message: 'Item deleted successfully' + }); + } catch (error) { + console.error('❌ API Server: Error deleting item:', error); + res.status(500).json({ + success: false, + error: 'Failed to delete item', + details: error.message + }); + } +}); + +// Get servers list (existing functionality) +app.get('/api/v1/servers', validateApiKey, (req, res) => { + res.json({ + success: true, + data: { + servers: mockServers, + total: mockServers.length + } + }); +}); + +// Get specific server (existing functionality) +app.get('/api/v1/servers/:serverId', validateApiKey, (req, res) => { + const { serverId } = req.params; + const server = mockServers.find(s => s.id === serverId); + + if (!server) { + return res.status(404).json({ + success: false, + error: 'Server not found' + }); + } + + res.json({ + success: true, + data: server + }); +}); + +// Test server connection (existing functionality) +app.post('/api/v1/servers/:serverId/test', validateApiKey, (req, res) => { + const { serverId } = req.params; + const server = mockServers.find(s => s.id === serverId); + + if (!server) { + return res.status(404).json({ + success: false, + error: 'Server not found' + }); + } + + const isOnline = Math.random() > 0.3; + + setTimeout(() => { + res.json({ + success: true, + data: { + serverId, + connected: isOnline, + responseTime: Math.floor(Math.random() * 200) + 50, + timestamp: new Date().toISOString() + } + }); + }, 1000 + Math.random() * 2000); +}); + +// Error handling middleware +app.use((error, req, res, next) => { + if (config.logging?.errors) { + console.error('❌ API Server Error:', error); + } + res.status(500).json({ + success: false, + error: 'Internal server error', + details: process.env.NODE_ENV === 'development' ? error.message : undefined + }); +}); + +// 404 handler +app.use('*', (req, res) => { + res.status(404).json({ + success: false, + error: 'Endpoint not found' + }); +}); + +// Initialize file system cache on startup +async function initializeServer() { + console.log(`🔧 API Server starting...`); + + // Load configuration first + await loadConfig(); + + console.log(`📁 API Server: Root directory: ${config.server.rootDirectory}`); + console.log(`🔍 API Server: Max scan depth: ${config.filesystem.maxDepth}`); + + if (config.server.rootDirectory === '/') { + console.log(`⚠️ API Server: WARNING - Root directory is '/', safety limits will be applied`); + } + + // Start config file watcher + await watchConfigFile(); + + // Initial file system scan + await refreshFileSystemCache(); + + // Set up periodic cache refresh + const refreshInterval = config.filesystem?.cacheSettings?.refreshInterval || 300000; // 5 minutes default + setInterval(async () => { + console.log('🔄 API Server: Performing scheduled file system cache refresh...'); + await refreshFileSystemCache(); + }, refreshInterval); +} + +// Start server +app.listen(PORT, async () => { + await initializeServer(); + + console.log(`🔧 API Server running on port ${PORT}`); + console.log(`🔑 API Server: API Key: ${API_KEY ? 'Configured' : 'Missing'}`); + console.log(`🌍 API Server: Environment: ${config.server?.environment || 'development'}`); + console.log(`👁️ API Server: Config file watching: Enabled`); + console.log(`📋 API Server: Available endpoints:`); + console.log(` GET /api/v1/config`); + console.log(` POST /api/v1/config`); + console.log(` POST /api/v1/config/root-directory`); + console.log(` GET /api/v1/health`); + console.log(` GET /api/v1/server-info`); + console.log(` GET /api/v1/filesystem`); + console.log(` POST /api/v1/filesystem/refresh`); + console.log(` GET /api/v1/filesystem/directory`); + console.log(` GET /api/v1/filesystem/file-content`); + console.log(` POST /api/v1/filesystem/file-content`); + console.log(` POST /api/v1/filesystem/folder`); + console.log(` POST /api/v1/filesystem/file`); + console.log(` DELETE /api/v1/filesystem/item`); + console.log(` GET /api/v1/servers`); + console.log(` GET /api/v1/servers/:id`); + console.log(` POST /api/v1/servers/:id/test`); +}); \ No newline at end of file