node-server-engine 1.4.9 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.commitlintrc.js +27 -0
- package/.releaserc.js +56 -0
- package/README.md +154 -2
- package/dist/const/tokenIssuer.js +1 -0
- package/dist/const/tokenIssuer.js.map +1 -1
- package/dist/db/models/SequelizeMeta.js +3 -1
- package/dist/db/models/SequelizeMeta.js.map +1 -1
- package/dist/entities/ElasticSearch/ElasticSearch.js +1 -2
- package/dist/entities/ElasticSearch/ElasticSearch.js.map +1 -1
- package/dist/entities/SocketClient/SocketClient.js +1 -0
- package/dist/entities/SocketClient/SocketClient.js.map +1 -1
- package/dist/index.js +1 -2
- package/dist/index.js.map +1 -1
- package/dist/middleware/checkPermission/checkPermission.d.ts +1 -1
- package/dist/middleware/checkPermission/checkPermission.js +4 -2
- package/dist/middleware/checkPermission/checkPermission.js.map +1 -1
- package/dist/utils/jwt/jwt.js +1 -1
- package/dist/utils/jwt/jwt.js.map +1 -1
- package/dist/utils/semverCompare/semverCompare.js +1 -5
- package/dist/utils/semverCompare/semverCompare.js.map +1 -1
- package/package.json +30 -19
- package/.env.example +0 -186
- package/.github/workflows/publish.yml +0 -41
- package/.prettierrc +0 -7
- package/Dockerfile +0 -31
- package/babel.config.json +0 -34
- package/eslint.config.mjs +0 -11
- package/src/const/DebeziumEvent.ts +0 -6
- package/src/const/LogSeverity.ts +0 -7
- package/src/const/index.ts +0 -5
- package/src/const/metrics.ts +0 -6
- package/src/const/mime.ts +0 -37
- package/src/const/tokenIssuer.ts +0 -7
- package/src/db/migrations/20241030121500-create-sequelize-meta-table.ts +0 -29
- package/src/db/models/SequelizeMeta.ts +0 -16
- package/src/db/models/index.ts +0 -2
- package/src/entities/ElasticSearch/ElasticSearch.ts +0 -103
- package/src/entities/ElasticSearch/ElasticSearch.types.ts +0 -7
- package/src/entities/ElasticSearch/index.ts +0 -2
- package/src/entities/Endpoint/Endpoint.test.ts +0 -248
- package/src/entities/Endpoint/Endpoint.ts +0 -221
- package/src/entities/Endpoint/Endpoint.types.ts +0 -181
- package/src/entities/Endpoint/index.ts +0 -2
- package/src/entities/EngineError/EngineError.ts +0 -28
- package/src/entities/EngineError/EngineError.types.ts +0 -15
- package/src/entities/EngineError/index.ts +0 -2
- package/src/entities/KeySet/KeySet.test.ts +0 -126
- package/src/entities/KeySet/KeySet.ts +0 -172
- package/src/entities/KeySet/KeySet.types.ts +0 -28
- package/src/entities/KeySet/index.ts +0 -2
- package/src/entities/LifecycleController/LifecycleController.test.ts +0 -48
- package/src/entities/LifecycleController/LifecycleController.ts +0 -24
- package/src/entities/LifecycleController/LifecycleController.types.ts +0 -5
- package/src/entities/LifecycleController/index.ts +0 -2
- package/src/entities/Localizator/Localizator.ts +0 -139
- package/src/entities/Localizator/Localizator.types.ts +0 -52
- package/src/entities/Localizator/guessNamingConvention/guessNamingConvention.test.ts +0 -165
- package/src/entities/Localizator/guessNamingConvention/guessNamingConvention.ts +0 -58
- package/src/entities/Localizator/guessNamingConvention/index.ts +0 -1
- package/src/entities/Localizator/index.ts +0 -2
- package/src/entities/MessageHandler/MessageHandler.test.ts +0 -130
- package/src/entities/MessageHandler/MessageHandler.ts +0 -72
- package/src/entities/MessageHandler/MessageHandler.types.ts +0 -15
- package/src/entities/MessageHandler/index.ts +0 -2
- package/src/entities/PubSub/PubSub.test.ts +0 -297
- package/src/entities/PubSub/PubSub.ts +0 -202
- package/src/entities/PubSub/PubSub.types.ts +0 -76
- package/src/entities/PubSub/handleMessage/handleMessage.test.ts +0 -102
- package/src/entities/PubSub/handleMessage/handleMessage.ts +0 -65
- package/src/entities/PubSub/handleMessage/index.ts +0 -1
- package/src/entities/PubSub/index.ts +0 -2
- package/src/entities/PushNotification/PushNotification.test.ts +0 -35
- package/src/entities/PushNotification/PushNotification.ts +0 -44
- package/src/entities/PushNotification/PushNotification.types.ts +0 -25
- package/src/entities/PushNotification/index.ts +0 -2
- package/src/entities/Redis/Redis.ts +0 -71
- package/src/entities/Redis/Redis.types.ts +0 -19
- package/src/entities/Redis/Redis.validate.ts +0 -17
- package/src/entities/Redis/index.ts +0 -2
- package/src/entities/Sequelize/Sequelize.config.ts +0 -59
- package/src/entities/Sequelize/Sequelize.test.ts +0 -21
- package/src/entities/Sequelize/Sequelize.ts +0 -75
- package/src/entities/Sequelize/Sequelize.types.ts +0 -10
- package/src/entities/Sequelize/Sequelize.validate.ts +0 -15
- package/src/entities/Sequelize/index.ts +0 -2
- package/src/entities/Server/Server.const.ts +0 -56
- package/src/entities/Server/Server.test.ts +0 -272
- package/src/entities/Server/Server.ts +0 -471
- package/src/entities/Server/Server.types.ts +0 -88
- package/src/entities/Server/index.ts +0 -2
- package/src/entities/SocketClient/SocketClient.test.ts +0 -392
- package/src/entities/SocketClient/SocketClient.ts +0 -401
- package/src/entities/SocketClient/SocketClient.types.ts +0 -62
- package/src/entities/SocketClient/index.ts +0 -2
- package/src/entities/SocketClient/parseMessage/index.ts +0 -1
- package/src/entities/SocketClient/parseMessage/parseMessage.test.ts +0 -20
- package/src/entities/SocketClient/parseMessage/parseMessage.ts +0 -26
- package/src/entities/Storage/Storage.test.ts +0 -58
- package/src/entities/Storage/Storage.ts +0 -219
- package/src/entities/Storage/Storage.types.ts +0 -57
- package/src/entities/Storage/index.ts +0 -2
- package/src/entities/ValidationError/ValidationError.ts +0 -34
- package/src/entities/ValidationError/index.ts +0 -1
- package/src/entities/WebError/WebError.test.ts +0 -18
- package/src/entities/WebError/WebError.ts +0 -23
- package/src/entities/WebError/WebError.types.ts +0 -9
- package/src/entities/WebError/index.ts +0 -2
- package/src/entities/index.ts +0 -16
- package/src/index.ts +0 -6
- package/src/metrics/debug.ts +0 -10
- package/src/metrics/index.ts +0 -2
- package/src/metrics/request.ts +0 -17
- package/src/middleware/authHmac/authHmac.test.ts +0 -86
- package/src/middleware/authHmac/authHmac.ts +0 -56
- package/src/middleware/authHmac/authHmac.types.ts +0 -7
- package/src/middleware/authHmac/index.ts +0 -2
- package/src/middleware/authJwt/authJwt.test.ts +0 -54
- package/src/middleware/authJwt/authJwt.ts +0 -55
- package/src/middleware/authJwt/authJwt.types.ts +0 -14
- package/src/middleware/authJwt/index.ts +0 -2
- package/src/middleware/authStatic/authStatic.test.ts +0 -36
- package/src/middleware/authStatic/authStatic.ts +0 -45
- package/src/middleware/authStatic/index.ts +0 -1
- package/src/middleware/authTls/authTls.test.ts +0 -138
- package/src/middleware/authTls/authTls.ts +0 -119
- package/src/middleware/authTls/authTls.types.ts +0 -13
- package/src/middleware/authTls/index.ts +0 -2
- package/src/middleware/checkPermission/checkPermission.ts +0 -33
- package/src/middleware/checkPermission/index.ts +0 -1
- package/src/middleware/error/error.test.ts +0 -60
- package/src/middleware/error/error.ts +0 -25
- package/src/middleware/error/index.ts +0 -1
- package/src/middleware/fileUploader/fileUploader.ts +0 -154
- package/src/middleware/fileUploader/fileUploader.types.ts +0 -35
- package/src/middleware/fileUploader/index.ts +0 -2
- package/src/middleware/fileUploader/isMultiPart/index.ts +0 -1
- package/src/middleware/fileUploader/isMultiPart/isMultipart.ts +0 -9
- package/src/middleware/fileUploader/validate/index.ts +0 -1
- package/src/middleware/fileUploader/validate/validate.ts +0 -27
- package/src/middleware/fourOhFour/fourOhFour.test.ts +0 -14
- package/src/middleware/fourOhFour/fourOhFour.ts +0 -13
- package/src/middleware/fourOhFour/index.ts +0 -1
- package/src/middleware/geminiFileUploader/geminiFileUploader.ts +0 -68
- package/src/middleware/geminiFileUploader/index.ts +0 -1
- package/src/middleware/healthCheck/healthCheck.test.ts +0 -12
- package/src/middleware/healthCheck/healthCheck.ts +0 -14
- package/src/middleware/healthCheck/index.ts +0 -1
- package/src/middleware/index.ts +0 -17
- package/src/middleware/metrics/index.ts +0 -1
- package/src/middleware/metrics/metrics.test.ts +0 -46
- package/src/middleware/metrics/metrics.ts +0 -24
- package/src/middleware/multiPartFileUploader/index.ts +0 -2
- package/src/middleware/multiPartFileUploader/multiPartFileUploader.ts +0 -249
- package/src/middleware/multiPartFileUploader/multiPartFileUploader.types.ts +0 -23
- package/src/middleware/multiPartFileUploader/validate/index.ts +0 -1
- package/src/middleware/multiPartFileUploader/validate/validate.ts +0 -27
- package/src/middleware/requestMetrics/index.ts +0 -1
- package/src/middleware/requestMetrics/requestMetrics.test.ts +0 -77
- package/src/middleware/requestMetrics/requestMetrics.ts +0 -20
- package/src/middleware/swaggerDocs/index.ts +0 -2
- package/src/middleware/swaggerDocs/swaggerDocs.ts +0 -114
- package/src/middleware/swaggerDocs/swaggerDocs.types.ts +0 -41
- package/src/middleware/userResolver/index.ts +0 -1
- package/src/middleware/userResolver/userResolver.ts +0 -53
- package/src/middleware/validate/index.ts +0 -1
- package/src/middleware/validate/validate.test.ts +0 -43
- package/src/middleware/validate/validate.ts +0 -25
- package/src/middleware/version/index.ts +0 -1
- package/src/middleware/version/version.test.ts +0 -23
- package/src/middleware/version/version.ts +0 -12
- package/src/utils/checkEnvironment/index.ts +0 -49
- package/src/utils/createHttpServer/createHttpServer.test.ts +0 -24
- package/src/utils/createHttpServer/createHttpServer.ts +0 -34
- package/src/utils/createHttpServer/createHttpServer.validate.ts +0 -17
- package/src/utils/createHttpServer/index.ts +0 -1
- package/src/utils/createSortedObject/createSortedObject.ts +0 -20
- package/src/utils/createSortedObject/createSortedObjet.test.ts +0 -47
- package/src/utils/createSortedObject/index.ts +0 -1
- package/src/utils/dbMigration/dbMigration.test.ts +0 -209
- package/src/utils/dbMigration/dbMigration.ts +0 -199
- package/src/utils/dbMigration/dbMigration.types.ts +0 -11
- package/src/utils/dbMigration/index.ts +0 -2
- package/src/utils/dbMigration/migrateMetadataTable/index.ts +0 -1
- package/src/utils/dbMigration/migrateMetadataTable/migrateMetadataTable.test.ts +0 -59
- package/src/utils/dbMigration/migrateMetadataTable/migrateMetadataTable.ts +0 -102
- package/src/utils/envAssert/envAssert.ts +0 -31
- package/src/utils/envAssert/index.ts +0 -1
- package/src/utils/envAssert/validators/hostList.ts +0 -17
- package/src/utils/envAssert/validators/index.ts +0 -5
- package/src/utils/envAssert/validators/ipList.ts +0 -13
- package/src/utils/envAssert/validators/path.ts +0 -13
- package/src/utils/envAssert/validators/string.ts +0 -9
- package/src/utils/envAssert/validators/stringList.ts +0 -13
- package/src/utils/filter/filter.ts +0 -17
- package/src/utils/filter/index.ts +0 -1
- package/src/utils/geminiFileUpload/geminiFileUpload.ts +0 -93
- package/src/utils/geminiFileUpload/index.ts +0 -1
- package/src/utils/hmac/checkEnv/checkEnv.test.ts +0 -18
- package/src/utils/hmac/checkEnv/checkEnv.ts +0 -9
- package/src/utils/hmac/checkEnv/index.ts +0 -1
- package/src/utils/hmac/createHmac/createHmac.ts +0 -33
- package/src/utils/hmac/createHmac/index.ts +0 -1
- package/src/utils/hmac/index.ts +0 -4
- package/src/utils/hmac/index.types.ts +0 -13
- package/src/utils/hmac/signPayload/index.ts +0 -1
- package/src/utils/hmac/signPayload/signPayload.ts +0 -16
- package/src/utils/hmac/verifySignature/index.ts +0 -1
- package/src/utils/hmac/verifySignature/verifySignature.ts +0 -24
- package/src/utils/index.ts +0 -29
- package/src/utils/jwt/index.ts +0 -2
- package/src/utils/jwt/jwt.test.ts +0 -28
- package/src/utils/jwt/jwt.ts +0 -182
- package/src/utils/jwt/jwt.types.ts +0 -21
- package/src/utils/report/index.ts +0 -3
- package/src/utils/report/output.ts +0 -45
- package/src/utils/report/output.types.ts +0 -70
- package/src/utils/report/report.test.ts +0 -133
- package/src/utils/report/report.ts +0 -133
- package/src/utils/report/report.types.ts +0 -13
- package/src/utils/request/index.ts +0 -1
- package/src/utils/request/request.test.ts +0 -26
- package/src/utils/request/request.ts +0 -48
- package/src/utils/secretManager/index.ts +0 -2
- package/src/utils/secretManager/secretLoader.ts +0 -62
- package/src/utils/secretManager/secretResolver.ts +0 -35
- package/src/utils/semverCompare/index.ts +0 -1
- package/src/utils/semverCompare/semverCompare.test.ts +0 -49
- package/src/utils/semverCompare/semverCompare.ts +0 -60
- package/src/utils/sendEmail/index.ts +0 -2
- package/src/utils/sendEmail/sendEmail.ts +0 -61
- package/src/utils/sendEmail/sendEmail.types.ts +0 -61
- package/src/utils/sendPush/index.ts +0 -2
- package/src/utils/sendPush/sendPush.ts +0 -20
- package/src/utils/sendPush/sendPush.types.ts +0 -25
- package/src/utils/tlsConfig/index.ts +0 -2
- package/src/utils/tlsConfig/tlsConfig.test.ts +0 -32
- package/src/utils/tlsConfig/tlsConfig.ts +0 -47
- package/src/utils/tlsConfig/tlsConfig.types.ts +0 -11
- package/src/utils/tlsConfig/tlsConfig.validate.ts +0 -25
- package/src/utils/tlsRequest/index.ts +0 -1
- package/src/utils/tlsRequest/tlsRequest.test.ts +0 -63
- package/src/utils/tlsRequest/tlsRequest.ts +0 -12
- package/src/utils/trimPathSlash/index.ts +0 -1
- package/src/utils/trimPathSlash/trimPathSlash.test.ts +0 -26
- package/src/utils/trimPathSlash/trimPathSlash.ts +0 -8
- package/test/env.ts +0 -53
- package/test/factory/index.ts +0 -8
- package/test/factory/sequelizeMeta.ts +0 -12
- package/test/hooks.ts +0 -35
- package/test/index.ts +0 -3
- package/test/stub/index.ts +0 -3
- package/test/stub/stubLocales.ts +0 -68
- package/test/stub/stubPubSub.ts +0 -7
- package/test/stub/stubStorage.ts +0 -77
- package/test/stub/stubStorage.types.ts +0 -11
- package/test/utils/app.ts +0 -31
- package/test/utils/index.ts +0 -1
- package/tsconfig.build.json +0 -5
- package/tsconfig.json +0 -32
package/.commitlintrc.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
module.exports = {
|
|
2
|
+
extends: ['@commitlint/config-conventional'],
|
|
3
|
+
rules: {
|
|
4
|
+
'type-enum': [
|
|
5
|
+
2,
|
|
6
|
+
'always',
|
|
7
|
+
[
|
|
8
|
+
'feat', // New feature
|
|
9
|
+
'fix', // Bug fix
|
|
10
|
+
'docs', // Documentation only changes
|
|
11
|
+
'style', // Changes that don't affect the code meaning
|
|
12
|
+
'refactor', // Code change that neither fixes a bug nor adds a feature
|
|
13
|
+
'perf', // Performance improvement
|
|
14
|
+
'test', // Adding missing tests or correcting existing tests
|
|
15
|
+
'build', // Changes that affect the build system or dependencies
|
|
16
|
+
'ci', // Changes to CI configuration files and scripts
|
|
17
|
+
'chore', // Other changes that don't modify src or test files
|
|
18
|
+
'revert' // Reverts a previous commit
|
|
19
|
+
]
|
|
20
|
+
],
|
|
21
|
+
'subject-case': [0],
|
|
22
|
+
'subject-empty': [2, 'never'],
|
|
23
|
+
'subject-full-stop': [2, 'never', '.'],
|
|
24
|
+
'type-case': [2, 'always', 'lower-case'],
|
|
25
|
+
'type-empty': [2, 'never']
|
|
26
|
+
}
|
|
27
|
+
};
|
package/.releaserc.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
module.exports = {
|
|
2
|
+
branches: ['main', 'master'],
|
|
3
|
+
plugins: [
|
|
4
|
+
[
|
|
5
|
+
'@semantic-release/commit-analyzer',
|
|
6
|
+
{
|
|
7
|
+
preset: 'conventionalcommits',
|
|
8
|
+
releaseRules: [
|
|
9
|
+
{ type: 'feat', release: 'minor' },
|
|
10
|
+
{ type: 'fix', release: 'patch' },
|
|
11
|
+
{ type: 'perf', release: 'patch' },
|
|
12
|
+
{ type: 'revert', release: 'patch' },
|
|
13
|
+
{ type: 'docs', release: 'patch' },
|
|
14
|
+
{ type: 'style', release: 'patch' },
|
|
15
|
+
{ type: 'refactor', release: 'patch' },
|
|
16
|
+
{ type: 'test', release: 'patch' },
|
|
17
|
+
{ type: 'build', release: 'patch' },
|
|
18
|
+
{ type: 'ci', release: 'patch' },
|
|
19
|
+
{ type: 'chore', release: false },
|
|
20
|
+
{ breaking: true, release: 'major' }
|
|
21
|
+
]
|
|
22
|
+
}
|
|
23
|
+
],
|
|
24
|
+
[
|
|
25
|
+
'@semantic-release/release-notes-generator',
|
|
26
|
+
{
|
|
27
|
+
preset: 'conventionalcommits',
|
|
28
|
+
presetConfig: {
|
|
29
|
+
types: [
|
|
30
|
+
{ type: 'feat', section: '✨ Features' },
|
|
31
|
+
{ type: 'fix', section: '🐛 Bug Fixes' },
|
|
32
|
+
{ type: 'perf', section: '⚡ Performance' },
|
|
33
|
+
{ type: 'revert', section: '⏪ Reverts' },
|
|
34
|
+
{ type: 'docs', section: '📚 Documentation' },
|
|
35
|
+
{ type: 'style', section: '💄 Styles' },
|
|
36
|
+
{ type: 'refactor', section: '♻️ Code Refactoring' },
|
|
37
|
+
{ type: 'test', section: '✅ Tests' },
|
|
38
|
+
{ type: 'build', section: '🏗️ Build System' },
|
|
39
|
+
{ type: 'ci', section: '👷 CI/CD' },
|
|
40
|
+
{ type: 'chore', section: '🔧 Chores', hidden: true }
|
|
41
|
+
]
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
],
|
|
45
|
+
'@semantic-release/changelog',
|
|
46
|
+
'@semantic-release/npm',
|
|
47
|
+
[
|
|
48
|
+
'@semantic-release/git',
|
|
49
|
+
{
|
|
50
|
+
assets: ['package.json', 'package-lock.json', 'CHANGELOG.md'],
|
|
51
|
+
message: 'chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}'
|
|
52
|
+
}
|
|
53
|
+
],
|
|
54
|
+
'@semantic-release/github'
|
|
55
|
+
]
|
|
56
|
+
};
|
package/README.md
CHANGED
|
@@ -2,7 +2,34 @@
|
|
|
2
2
|
|
|
3
3
|
Framework used to develop Node backend services. This package ships with a lot of features to standardize the creation of services, letting you focus on the business logic.
|
|
4
4
|
|
|
5
|
+
[](https://www.npmjs.com/package/node-server-engine)
|
|
6
|
+
[](https://opensource.org/licenses/ISC)
|
|
7
|
+
[](https://github.com/semantic-release/semantic-release)
|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
- 🚀 **Express-based** - Built on the popular Express.js framework
|
|
12
|
+
- 🔒 **Multiple Auth Methods** - JWT, mTLS, HMAC, and Static token authentication
|
|
13
|
+
- 🔌 **WebSocket Support** - Built-in WebSocket server with message handling
|
|
14
|
+
- 📊 **Database Integration** - Sequelize ORM with migrations support
|
|
15
|
+
- 📡 **Pub/Sub** - Google Cloud Pub/Sub integration
|
|
16
|
+
- 🔔 **Push Notifications** - Built-in push notification support
|
|
17
|
+
- 🌐 **i18n** - Internationalization with translation management
|
|
18
|
+
- 🔍 **ElasticSearch** - Full-text search integration
|
|
19
|
+
- 📝 **API Documentation** - Swagger/OpenAPI documentation support
|
|
20
|
+
- 📤 **File Uploads** - Single and chunked file upload middleware
|
|
21
|
+
- 🧪 **TypeScript** - Written in TypeScript with full type definitions
|
|
22
|
+
- ✅ **Modern Tooling** - ESLint, Prettier, and automated versioning
|
|
23
|
+
|
|
24
|
+
## Requirements
|
|
25
|
+
|
|
26
|
+
- **Node.js** 18.x or higher
|
|
27
|
+
- **npm** 9.x or higher
|
|
28
|
+
- **TypeScript** 5.x (if contributing)
|
|
29
|
+
|
|
5
30
|
- [Node Server Engine](#node-server-engine)
|
|
31
|
+
- [Features](#features)
|
|
32
|
+
- [Requirements](#requirements)
|
|
6
33
|
- [Install](#install)
|
|
7
34
|
- [Entities](#entities)
|
|
8
35
|
- [Server](#server)
|
|
@@ -71,12 +98,18 @@ Framework used to develop Node backend services. This package ships with a lot o
|
|
|
71
98
|
|
|
72
99
|
## Install
|
|
73
100
|
|
|
74
|
-
To start a new service, it is **highly
|
|
101
|
+
To start a new service, it is **highly recommended** that you clone it from [our template](https://github.com/prakashmahendran/node-server-template). It will already include all the necessary tools and boilerplate.
|
|
75
102
|
|
|
76
103
|
If you need to install it manually:
|
|
77
104
|
|
|
78
105
|
```bash
|
|
79
|
-
npm
|
|
106
|
+
npm install node-server-engine
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
For development dependencies:
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
npm install --save-dev backend-test-tools
|
|
80
113
|
```
|
|
81
114
|
|
|
82
115
|
## Entities
|
|
@@ -1238,3 +1271,122 @@ await wait(600);
|
|
|
1238
1271
|
```
|
|
1239
1272
|
|
|
1240
1273
|
<!-- markdownlint-enable MD033 -->
|
|
1274
|
+
|
|
1275
|
+
## Development
|
|
1276
|
+
|
|
1277
|
+
### Prerequisites
|
|
1278
|
+
|
|
1279
|
+
- Node.js 18.x or higher
|
|
1280
|
+
- npm 9.x or higher
|
|
1281
|
+
- Git
|
|
1282
|
+
|
|
1283
|
+
### Setup
|
|
1284
|
+
|
|
1285
|
+
```bash
|
|
1286
|
+
# Clone the repository
|
|
1287
|
+
git clone https://github.com/prakashmahendran/node-server-engine.git
|
|
1288
|
+
cd node-server-engine
|
|
1289
|
+
|
|
1290
|
+
# Install dependencies
|
|
1291
|
+
npm install
|
|
1292
|
+
|
|
1293
|
+
# Build the project
|
|
1294
|
+
npm run build
|
|
1295
|
+
|
|
1296
|
+
# Run tests
|
|
1297
|
+
npm test
|
|
1298
|
+
|
|
1299
|
+
# Run tests with coverage
|
|
1300
|
+
npm run coverage
|
|
1301
|
+
```
|
|
1302
|
+
|
|
1303
|
+
### Scripts
|
|
1304
|
+
|
|
1305
|
+
| Script | Description |
|
|
1306
|
+
|--------|-------------|
|
|
1307
|
+
| `npm run build` | Compile TypeScript and generate distribution files |
|
|
1308
|
+
| `npm run lint` | Check code for linting errors |
|
|
1309
|
+
| `npm run lint:fix` | Automatically fix linting errors |
|
|
1310
|
+
| `npm run format` | Format code with Prettier |
|
|
1311
|
+
| `npm run format:check` | Check code formatting without modifying files |
|
|
1312
|
+
| `npm test` | Run all tests with coverage |
|
|
1313
|
+
| `npm run test:file` | Run a specific test file |
|
|
1314
|
+
| `npm run coverage` | Generate HTML coverage report |
|
|
1315
|
+
| `npm run coverage:ci` | Generate coverage summary for CI |
|
|
1316
|
+
|
|
1317
|
+
### Commit Convention
|
|
1318
|
+
|
|
1319
|
+
This project uses [Conventional Commits](https://www.conventionalcommits.org/) for automated versioning and changelog generation.
|
|
1320
|
+
|
|
1321
|
+
**Format:** `type(scope): subject`
|
|
1322
|
+
|
|
1323
|
+
**Types:**
|
|
1324
|
+
- `feat`: New feature (triggers minor version bump)
|
|
1325
|
+
- `fix`: Bug fix (triggers patch version bump)
|
|
1326
|
+
- `docs`: Documentation changes
|
|
1327
|
+
- `style`: Code style changes (formatting, semicolons, etc.)
|
|
1328
|
+
- `refactor`: Code refactoring without feature changes
|
|
1329
|
+
- `perf`: Performance improvements
|
|
1330
|
+
- `test`: Adding or updating tests
|
|
1331
|
+
- `chore`: Maintenance tasks
|
|
1332
|
+
- `ci`: CI/CD changes
|
|
1333
|
+
|
|
1334
|
+
**Examples:**
|
|
1335
|
+
```bash
|
|
1336
|
+
git commit -m "feat(endpoints): add support for GraphQL endpoints"
|
|
1337
|
+
git commit -m "fix(auth): resolve JWT token validation issue"
|
|
1338
|
+
git commit -m "docs(readme): update installation instructions"
|
|
1339
|
+
```
|
|
1340
|
+
|
|
1341
|
+
**Breaking Changes:** Add `BREAKING CHANGE:` in the commit body to trigger a major version bump:
|
|
1342
|
+
```bash
|
|
1343
|
+
git commit -m "feat(api): redesign authentication flow" -m "BREAKING CHANGE: AuthType enum values changed"
|
|
1344
|
+
```
|
|
1345
|
+
|
|
1346
|
+
### Automated Versioning
|
|
1347
|
+
|
|
1348
|
+
This project uses [semantic-release](https://github.com/semantic-release/semantic-release) for automated version management and package publishing.
|
|
1349
|
+
|
|
1350
|
+
**How it works:**
|
|
1351
|
+
1. Commits are analyzed based on conventional commit format
|
|
1352
|
+
2. Version number is automatically determined (major.minor.patch)
|
|
1353
|
+
3. Changelog is generated from commit messages
|
|
1354
|
+
4. Git tag is created
|
|
1355
|
+
5. Package is published to npm
|
|
1356
|
+
6. GitHub release is created
|
|
1357
|
+
|
|
1358
|
+
**When releases happen:**
|
|
1359
|
+
- Automatically on every push to `main` branch
|
|
1360
|
+
- Only if there are release-worthy commits (feat, fix, perf, BREAKING CHANGE)
|
|
1361
|
+
- Releases are skipped for commits with `[skip ci]` in the message
|
|
1362
|
+
|
|
1363
|
+
## Contributing
|
|
1364
|
+
|
|
1365
|
+
We welcome contributions! Please follow these guidelines:
|
|
1366
|
+
|
|
1367
|
+
1. **Fork the repository** and create your branch from `main`
|
|
1368
|
+
2. **Follow the commit convention** described above
|
|
1369
|
+
3. **Write or update tests** for your changes
|
|
1370
|
+
4. **Ensure all tests pass** before submitting
|
|
1371
|
+
5. **Update documentation** if needed
|
|
1372
|
+
6. **Submit a pull request** with a clear description
|
|
1373
|
+
|
|
1374
|
+
### Code Style
|
|
1375
|
+
|
|
1376
|
+
- This project uses ESLint and Prettier for code consistency
|
|
1377
|
+
- Run `npm run lint:fix` and `npm run format` before committing
|
|
1378
|
+
- Husky pre-commit hooks will automatically check your code
|
|
1379
|
+
|
|
1380
|
+
## License
|
|
1381
|
+
|
|
1382
|
+
ISC © Ram
|
|
1383
|
+
|
|
1384
|
+
## Support
|
|
1385
|
+
|
|
1386
|
+
- 📫 **Issues:** [GitHub Issues](https://github.com/prakashmahendran/node-server-engine/issues)
|
|
1387
|
+
- 📖 **Documentation:** [README](https://github.com/prakashmahendran/node-server-engine#readme)
|
|
1388
|
+
- 💬 **Discussions:** [GitHub Discussions](https://github.com/prakashmahendran/node-server-engine/discussions)
|
|
1389
|
+
|
|
1390
|
+
---
|
|
1391
|
+
|
|
1392
|
+
**Made with ❤️ for the Node.js community**
|
|
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
6
6
|
exports.TokenIssuer = exports.TOKEN_ISSUERS = void 0;
|
|
7
7
|
/** Enum to identify access tokens JWT issuers */
|
|
8
8
|
let TokenIssuer = exports.TokenIssuer = /*#__PURE__*/function (TokenIssuer) {
|
|
9
|
+
/** For tokens issued by the auth service */
|
|
9
10
|
TokenIssuer[TokenIssuer["AUTH_SERVICE"] = 0] = "AUTH_SERVICE";
|
|
10
11
|
return TokenIssuer;
|
|
11
12
|
}({});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tokenIssuer.js","names":["TokenIssuer","exports","TOKEN_ISSUERS","Object","values"],"sources":["../../src/const/tokenIssuer.ts"],"sourcesContent":["/** Enum to identify access tokens JWT issuers */\nexport enum TokenIssuer {\n /** For tokens issued by the auth service */\n AUTH_SERVICE\n}\n\nexport const TOKEN_ISSUERS = Object.values(TokenIssuer);\n"],"mappings":";;;;;;AAAA;AAAA,IACYA,WAAW,GAAAC,OAAA,CAAAD,WAAA,0BAAXA,WAAW;
|
|
1
|
+
{"version":3,"file":"tokenIssuer.js","names":["TokenIssuer","exports","TOKEN_ISSUERS","Object","values"],"sources":["../../src/const/tokenIssuer.ts"],"sourcesContent":["/** Enum to identify access tokens JWT issuers */\nexport enum TokenIssuer {\n /** For tokens issued by the auth service */\n AUTH_SERVICE\n}\n\nexport const TOKEN_ISSUERS = Object.values(TokenIssuer);\n"],"mappings":";;;;;;AAAA;AAAA,IACYA,WAAW,GAAAC,OAAA,CAAAD,WAAA,0BAAXA,WAAW;EACrB;EADUA,WAAW,CAAXA,WAAW;EAAA,OAAXA,WAAW;AAAA;AAKhB,MAAME,aAAa,GAAAD,OAAA,CAAAC,aAAA,GAAGC,MAAM,CAACC,MAAM,CAACJ,WAAW,CAAC","ignoreList":[]}
|
|
@@ -44,6 +44,8 @@ let SequelizeMeta = exports.SequelizeMeta = (_dec = (0, _sequelizeTypescript.Col
|
|
|
44
44
|
configurable: true,
|
|
45
45
|
enumerable: true,
|
|
46
46
|
writable: true,
|
|
47
|
-
initializer:
|
|
47
|
+
initializer: function () {
|
|
48
|
+
return '';
|
|
49
|
+
}
|
|
48
50
|
}), _class2)) || _class);
|
|
49
51
|
//# sourceMappingURL=SequelizeMeta.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SequelizeMeta.js","names":["_sequelizeTypescript","require","_dec","_dec2","_class","_class2","_descriptor","_descriptor2","_callSuper","t","o","e","_getPrototypeOf2","default","_possibleConstructorReturn2","_isNativeReflectConstruct","Reflect","construct","constructor","apply","Boolean","prototype","valueOf","call","SequelizeMeta","exports","Column","type","DataType","STRING","allowNull","Table","_Model","args","_this","_classCallCheck2","_initializerDefineProperty2","_inherits2","_createClass2","Model","_applyDecoratedDescriptor2","configurable","enumerable","writable","initializer"],"sources":["../../../src/db/models/SequelizeMeta.ts"],"sourcesContent":["import { Table, Column, Model, DataType } from 'sequelize-typescript';\n\n@Table\nexport class SequelizeMeta extends Model {\n @Column({\n type: DataType.STRING,\n allowNull: false\n })\n name!: string;\n\n @Column({\n type: DataType.STRING,\n allowNull: false\n })\n version
|
|
1
|
+
{"version":3,"file":"SequelizeMeta.js","names":["_sequelizeTypescript","require","_dec","_dec2","_class","_class2","_descriptor","_descriptor2","_callSuper","t","o","e","_getPrototypeOf2","default","_possibleConstructorReturn2","_isNativeReflectConstruct","Reflect","construct","constructor","apply","Boolean","prototype","valueOf","call","SequelizeMeta","exports","Column","type","DataType","STRING","allowNull","Table","_Model","args","_this","_classCallCheck2","_initializerDefineProperty2","_inherits2","_createClass2","Model","_applyDecoratedDescriptor2","configurable","enumerable","writable","initializer"],"sources":["../../../src/db/models/SequelizeMeta.ts"],"sourcesContent":["import { Table, Column, Model, DataType } from 'sequelize-typescript';\n\n@Table\nexport class SequelizeMeta extends Model {\n @Column({\n type: DataType.STRING,\n allowNull: false\n })\n name!: string;\n\n @Column({\n type: DataType.STRING,\n allowNull: false\n })\n version: string = '';\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,IAAAA,oBAAA,GAAAC,OAAA;AAAsE,IAAAC,IAAA,EAAAC,KAAA,EAAAC,MAAA,EAAAC,OAAA,EAAAC,WAAA,EAAAC,YAAA;AAAA,SAAAC,WAAAC,CAAA,EAAAC,CAAA,EAAAC,CAAA,WAAAD,CAAA,OAAAE,gBAAA,CAAAC,OAAA,EAAAH,CAAA,OAAAI,2BAAA,CAAAD,OAAA,EAAAJ,CAAA,EAAAM,yBAAA,KAAAC,OAAA,CAAAC,SAAA,CAAAP,CAAA,EAAAC,CAAA,YAAAC,gBAAA,CAAAC,OAAA,EAAAJ,CAAA,EAAAS,WAAA,IAAAR,CAAA,CAAAS,KA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AAA,cAAAlB,KAAA;EAAAsC,YAAA;EAAAC,UAAA;EAAAC,QAAA;EAAAC,WAAA,WAAAA,CAAA;IAAA,OAWpB,EAAE;EAAA;AAAA,IAAAvC,OAAA,MAAAD,MAAA","ignoreList":[]}
|
|
@@ -12,8 +12,7 @@ var _EngineError = require("../EngineError");
|
|
|
12
12
|
var _LifecycleController = require("../LifecycleController");
|
|
13
13
|
var _utils = require("../../utils");
|
|
14
14
|
var _checkEnvironment = require("../../utils/checkEnvironment");
|
|
15
|
-
function
|
|
16
|
-
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
|
|
15
|
+
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
|
|
17
16
|
/** Elastic search client */
|
|
18
17
|
let client;
|
|
19
18
|
const ElasticSearch = exports.ElasticSearch = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ElasticSearch.js","names":["_fs","require","_path","_interopRequireDefault","_elasticsearch","_EngineError","_LifecycleController","_utils","_checkEnvironment","
|
|
1
|
+
{"version":3,"file":"ElasticSearch.js","names":["_fs","require","_path","_interopRequireDefault","_elasticsearch","_EngineError","_LifecycleController","_utils","_checkEnvironment","_interopRequireWildcard","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","client","ElasticSearch","exports","init","checkEnvironment","ELASTIC_SEARCH_HOST","envAssert","isString","ELASTIC_SEARCH_USERNAME","ELASTIC_SEARCH_PASSWORD","ELASTIC_SEARCH_MIGRATION_PATH","process","env","EngineError","message","Client","node","auth","username","password","NODE_ENV","indices","delete","index","migrate","LifecycleController","register","migrationPath","path","resolve","files","readdirSync","indexExists","exists","ran","file","hits","total","search","body","query","match","tot","value","push","migration","specifier","Promise","then","s","error","reportError","exit","create","id","ranAt","Date","reportInfo","length","data","shutdown","close"],"sources":["../../../src/entities/ElasticSearch/ElasticSearch.ts"],"sourcesContent":["import { readdirSync } from 'fs';\nimport path from 'path';\nimport { Client } from '@elastic/elasticsearch';\nimport { ElasticSearchMigration } from './ElasticSearch.types';\nimport { EngineError } from 'entities/EngineError';\nimport { LifecycleController } from 'entities/LifecycleController';\nimport { envAssert, reportError, reportInfo } from 'utils';\nimport { checkEnvironment } from 'utils/checkEnvironment';\n\n/** Elastic search client */\nlet client: undefined | Client;\n\nexport const ElasticSearch = {\n /**\n * Init function that should be called on server startup to establish the connection\n */\n async init(): Promise<void> {\n checkEnvironment({\n ELASTIC_SEARCH_HOST: envAssert.isString(),\n ELASTIC_SEARCH_USERNAME: envAssert.isString(),\n ELASTIC_SEARCH_PASSWORD: envAssert.isString(),\n ELASTIC_SEARCH_MIGRATION_PATH: envAssert.isString()\n });\n\n if (!process.env.ELASTIC_SEARCH_HOST)\n throw new EngineError({\n message: 'ElasticSearch Hosts not set in environment'\n });\n\n client = new Client({\n node: process.env.ELASTIC_SEARCH_HOST,\n auth: {\n username: process.env.ELASTIC_SEARCH_USERNAME as string,\n password: process.env.ELASTIC_SEARCH_PASSWORD as string\n }\n });\n // In test environment flush the database before running migrations\n if (process.env.NODE_ENV === 'test')\n await client.indices.delete({ index: '*' });\n await this.migrate();\n LifecycleController.register(this);\n },\n\n /**\n * Migration function called during the init process\n * Manages the database structure\n */\n async migrate(): Promise<void> {\n if (!client) throw new EngineError('ElasticSearch was not initialized');\n const migrationPath = path.resolve(\n process.env.ELASTIC_SEARCH_MIGRATION_PATH as string\n );\n const files = readdirSync(`${migrationPath}`);\n const indexExists = await client.indices.exists({\n index: 'migrations'\n });\n const ran = [];\n for (const file of files) {\n if (indexExists) {\n const {\n hits: { total }\n } = await client.search({\n index: 'migrations',\n body: { query: { match: { file } } }\n });\n let tot = 0;\n if (typeof total === 'number') {\n tot = total;\n } else {\n tot = total?.value ?? 0;\n }\n if (tot > 0) continue;\n }\n ran.push(file);\n const migration = (await import(\n `${migrationPath}/${file}`\n )) as ElasticSearchMigration;\n try {\n await migration.migrate(client);\n } catch (error) {\n reportError(error);\n process.exit(1);\n }\n\n await client.create({\n index: 'migrations',\n id: file,\n body: { file, ranAt: new Date() }\n });\n }\n reportInfo({\n message: `ElasticSearch: ran ${ran.length} migrations`,\n data: { files: ran }\n });\n },\n\n /**\n * Shutdown function that should be called on server stop to close the connection\n */\n async shutdown(): Promise<void> {\n if (client) await client.close();\n }\n};\n"],"mappings":";;;;;;;AAAA,IAAAA,GAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAC,sBAAA,CAAAF,OAAA;AACA,IAAAG,cAAA,GAAAH,OAAA;AAEA,IAAAI,YAAA,GAAAJ,OAAA;AACA,IAAAK,oBAAA,GAAAL,OAAA;AACA,IAAAM,MAAA,GAAAN,OAAA;AACA,IAAAO,iBAAA,GAAAP,OAAA;AAA0D,SAAAQ,wBAAAC,CAAA,EAAAC,CAAA,6BAAAC,OAAA,MAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAH,uBAAA,YAAAA,CAAAC,CAAA,EAAAC,CAAA,SAAAA,CAA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SocketClient.js","names":["_crypto","require","_parseMessage","_const","_EngineError","_MessageHandler","_ValidationError","_WebError","_jwt","_report","namespace","SocketClient","exports","webSocket","request","options","_classCallCheck2","default","_defineProperty2","id","randomUUID","ws","establishedAt","Date","reportDebug","message","initCallbacks","Array","authCallbacks","shutdownCallbacks","handlers","handler","MessageHandler","EngineError","socketClients","reportInfo","on","handleClose","bind","catch","error","reportError","severity","LogSeverity","WARNING","data","handleMessage","callbackResults","Promise","allSettled","map","callback","forEach","result","status","reason","pingInterval","setInterval","isAlive","terminate","ping","process","env","WS_PING_INTERVAL","parseInt","_createClass2","key","value","sendMessage","type","payload","send","noAuth","authenticated","audience","includes","DEFAULT_MESSAGE_AUDIENCE","JSON","stringify","isAuthenticated","getUser","userId","deviceId","tokenId","parseMessage","toString","authenticate","handle","handleError","token","WebError","errorCode","jwtVerify","setUserData","authExpiration","exp","now","clearTimeouts","authRenewTimer","setTimeout","authExpireTimer","clearTimeout","sub","dev","jti","aud","hint","ValidationError","code","clearInterval","getSocketClients","getSocketClient"],"sources":["../../../src/entities/SocketClient/SocketClient.ts"],"sourcesContent":["import { randomUUID } from 'crypto';\nimport { IncomingMessage } from 'http';\nimport WS, { RawData } from 'ws';\nimport { parseMessage } from './parseMessage';\nimport {\n SocketClientOptions,\n SocketClientSendMessageOptions,\n SocketAuthenticationMessage,\n SocketClientCallback,\n SocketClientList,\n SocketUser\n} from './SocketClient.types';\nimport { LogSeverity } from 'const';\nimport { EngineError } from 'entities/EngineError';\nimport { MessageHandler } from 'entities/MessageHandler';\nimport { ValidationError } from 'entities/ValidationError';\nimport { WebError } from 'entities/WebError';\nimport { jwtVerify, UserTokenPayload } from 'utils/jwt';\nimport { reportInfo, reportError, reportDebug } from 'utils/report';\n\nconst namespace = 'SocketClient';\n\n/**\n * Class where each instance represents a client connected through web-sockets\n */\nexport class SocketClient {\n /** Mapping of all the connected socket clients */\n private static socketClients: SocketClientList = {};\n /** Unique identifier of the client */\n public readonly id: string;\n /** Date at which the client connection was established */\n public readonly establishedAt: Date;\n /** WS instance of the client connection */\n private ws: WS;\n /** List of message handlers that are registered with the client */\n private handlers: Array<MessageHandler>;\n /** Callback function that are called when the client is created */\n private initCallbacks: Array<SocketClientCallback> = [];\n /** Callback function that are called when the client successfully authenticates */\n private authCallbacks: Array<SocketClientCallback> = [];\n /** Callback function that are called when the client connection is terminated */\n private shutdownCallbacks: Array<SocketClientCallback> = [];\n /** Authentication status of the client */\n private authenticated = false;\n /** Timer used to track when to send authentication renewal reminder to the client */\n private authRenewTimer: NodeJS.Timeout | string | number | undefined;\n /** Timers used to track the time at which a user losses authentication */\n private authExpireTimer: NodeJS.Timeout | string | number | undefined;\n /** ID of the user that is authenticated */\n private userId: undefined | string;\n /** ID of the device with which the client authenticated */\n private deviceId: undefined | string;\n /** Id of the token with which the client authenticated */\n private tokenId: undefined | string;\n /** Audience claims that were in the latest authentication token used by the client */\n private audience: undefined | Array<string>;\n /** Status tracking variable used to check the liveness of connections */\n private isAlive = true;\n /** Timer used to track interval between client pinging */\n private pingInterval: NodeJS.Timeout | string | number | undefined;\n\n /**\n * Create a WS client\n */\n public constructor(\n webSocket: WS,\n request: IncomingMessage,\n options: SocketClientOptions\n ) {\n this.id = randomUUID();\n this.ws = webSocket;\n this.establishedAt = new Date();\n\n reportDebug({ namespace, message: `Creating socket client [${this.id}]` });\n\n // Make sure that callbacks are made as lists of functions\n // Init\n if (typeof options.initCallbacks === 'function')\n this.initCallbacks = [options.initCallbacks];\n else if (options.initCallbacks instanceof Array)\n this.initCallbacks = options.initCallbacks;\n // Auth\n if (typeof options.authCallbacks === 'function')\n this.authCallbacks = [options.authCallbacks];\n else if (options.authCallbacks instanceof Array)\n this.authCallbacks = options.authCallbacks;\n // Shutdown\n if (typeof options.shutdownCallbacks === 'function')\n this.shutdownCallbacks = [options.shutdownCallbacks];\n else if (options.shutdownCallbacks instanceof Array)\n this.shutdownCallbacks = options.shutdownCallbacks;\n\n // Check that all handlers are valid\n this.handlers = options.handlers;\n for (const handler of this.handlers) {\n if (!(handler instanceof MessageHandler))\n throw new EngineError({\n message: 'Handler is not an instance of MessageHandler'\n });\n }\n // Register in clients list\n SocketClient.socketClients[this.id] = this;\n\n reportInfo({ message: `Client connected [${this.id}]` });\n // On socket close, deregister from clients list\n this.ws.on('close', () => {\n this.handleClose\n .bind(this)()\n .catch((error) => {\n reportError(error);\n });\n });\n // On socket error, log the error\n this.ws.on('error', (error) => {\n reportError(\n new EngineError({\n severity: LogSeverity.WARNING,\n message: `Error [${this.id}]`\n })\n );\n reportError(error);\n });\n // When receiving a message, call message handler\n this.ws.on('message', (data) => {\n this.handleMessage\n .bind(this)(data)\n .catch((error) => {\n reportError(error);\n });\n });\n\n // Run all the init callbacks\n // For proper error handling of potential asynchronous callbacks, we wrap the execution in an auto-executing async function\n (async (): Promise<void> => {\n const callbackResults = await Promise.allSettled(\n this.initCallbacks.map((callback) => callback(this))\n );\n callbackResults.forEach((result) => {\n if (result.status === 'rejected') reportError(result.reason);\n });\n })().catch((error) => {\n reportError(error);\n });\n\n // Server -> client ping mechanism using WS standard ping control frames\n // We terminate the connection if we did not get a reply in the previous interval\n this.pingInterval = setInterval(\n () => {\n if (!this.isAlive) {\n reportError(\n new EngineError({\n severity: LogSeverity.WARNING,\n message: `Terminating socket connection, ping timeout [${this.id}]`\n })\n );\n this.ws.terminate();\n return;\n }\n this.isAlive = false;\n this.ws.ping();\n reportDebug({ namespace, message: `Ping sent to client [${this.id}]` });\n },\n process.env.WS_PING_INTERVAL\n ? parseInt(process.env.WS_PING_INTERVAL) * 1000\n : 30000\n );\n\n // Track the connection as alive as we get a pong back\n this.ws.on('pong', () => {\n reportDebug({\n namespace,\n message: `Client responded to ping [${this.id}]`\n });\n this.isAlive = true;\n });\n }\n\n /** Get the list of all connected clients indexed by ID */\n public static getSocketClients(): SocketClientList {\n return this.socketClients;\n }\n\n /** Get a client by his ID */\n public static getSocketClient(id: string): SocketClient | undefined {\n return this.socketClients[id];\n }\n\n /**\n * Send a message to the client\n */\n public sendMessage(\n type: string,\n payload: unknown = {},\n options: SocketClientSendMessageOptions = {}\n ): void {\n reportDebug({\n namespace,\n message: `Received request to send message to client of type \"${type}\" [${this.id}]`,\n data: { options }\n });\n let send = false;\n // If the message is sent to unauthenticated user skip auth check\n if (options.noAuth) send = true;\n // If the message is authenticated and with the correct audience, it gets sent\n else if (\n this.authenticated &&\n (this.audience as Array<string>).includes(\n options.audience ?? (process.env.DEFAULT_MESSAGE_AUDIENCE as string)\n )\n )\n send = true;\n\n if (send) {\n reportDebug({\n namespace,\n message: `Sending message to client of type \"${type ?? 'unknown'}\" [${this.id}]`\n });\n this.ws.send(JSON.stringify({ type, payload }));\n }\n }\n\n /** Get the client authentication status */\n public isAuthenticated(): boolean {\n return this.authenticated;\n }\n\n /** Fetch data on the user if he is authenticated */\n public getUser(): SocketUser | undefined {\n if (this.authenticated)\n return {\n userId: this.userId as string,\n deviceId: this.deviceId as string,\n tokenId: this.tokenId as string,\n audience: this.audience as Array<string>\n };\n }\n\n /** Process an incoming message */\n private async handleMessage(data: RawData): Promise<void> {\n try {\n const message = parseMessage(data.toString('utf-8'));\n reportInfo({\n message: `Received message of type \"${message?.type ?? 'unknown'}\" [${this.id}]`\n });\n switch (message.type) {\n case 'authenticate':\n await this.authenticate(message as SocketAuthenticationMessage);\n break;\n // As not all client libraries allow sending pings through WS control frames,\n // we add a higher level ping mechanism\n case 'ping':\n reportDebug({\n namespace,\n message: `Received ping from client [${this.id}]`\n });\n this.sendMessage('pong', {}, { noAuth: true });\n break;\n default:\n for (const handler of this.handlers) {\n await handler.handle(message, this);\n }\n }\n } catch (error) {\n this.handleError(error);\n }\n }\n\n /**\n * Process an authentication request\n * @param {String} message - Authentication message\n */\n private async authenticate(\n message: SocketAuthenticationMessage\n ): Promise<void> {\n const token = message.payload?.token;\n if (!token) {\n throw new WebError({\n errorCode: 'no-token',\n message: 'No token was given',\n data: { message }\n });\n }\n const payload = await jwtVerify(token);\n this.setUserData(payload);\n\n this.authenticated = true;\n // Time remaining before token expiration\n const authExpiration = payload.exp * 1000 - Date.now();\n // Clear previously created timers\n this.clearTimeouts();\n // Send a refresh request to the client 1 minute before expiration\n this.authRenewTimer = setTimeout(\n () => {\n this.sendMessage('renewAuthentication');\n },\n authExpiration - 60 * 1000\n );\n // Expire client authentication\n this.authExpireTimer = setTimeout(() => {\n this.authenticated = false;\n }, authExpiration);\n\n // Run all the post-authentication callbacks\n const callbackResults = await Promise.allSettled(\n this.authCallbacks.map((callback) => callback(this))\n );\n callbackResults.forEach((result) => {\n if (result.status === 'rejected') reportError(result.reason);\n });\n }\n\n // Clear all the pending timers\n /** */\n private clearTimeouts(): void {\n if (this.authRenewTimer) clearTimeout(this.authRenewTimer);\n if (this.authExpireTimer) clearTimeout(this.authExpireTimer);\n }\n\n /**\n * Fetch the user's data and attach it to the connection for new connections. For existing connections, it checks that the authentication is done on the same user.\n */\n private setUserData({ sub, dev, jti, aud }: UserTokenPayload): void {\n // Check if the user is already authenticated\n if (this.userId) {\n // Check that the token is for the same connection as before\n if (this.userId && this.userId !== sub)\n throw new WebError({\n errorCode: 'wrong-user-token',\n message:\n 'A user tried to authenticate with a token that is not for him [userId]'\n });\n } else {\n // Set the user's ID\n this.userId = sub;\n // Set the user's Device Id\n this.deviceId = dev;\n // Set the token ID\n this.tokenId = jti;\n // Set the aud\n this.audience = aud instanceof Array ? aud : [aud];\n\n reportDebug({\n namespace,\n message: `Successfully authenticated client [${this.id}]`,\n data: {\n userId: this.userId,\n deviceId: this.deviceId,\n tokenId: this.tokenId,\n audience: this.audience\n }\n });\n }\n }\n\n /**\n * Properly return errors to clients\n */\n private handleError(error: unknown): void {\n reportError(error);\n if (error instanceof WebError) {\n this.sendMessage(\n 'error',\n { errorCode: error.errorCode, hint: error.hint },\n { noAuth: true }\n );\n } else if (error instanceof ValidationError) {\n this.sendMessage(\n 'error',\n { errorCode: 'validation-error', hint: error.data },\n { noAuth: true }\n );\n } else {\n this.sendMessage(\n 'error',\n { errorCode: 'server-error' },\n { noAuth: true }\n );\n }\n }\n\n /**\n * Process a socket close event\n */\n private async handleClose(code?: string, reason?: string): Promise<void> {\n delete SocketClient.socketClients[this.id];\n this.clearTimeouts();\n // Stop ping process\n if (this.pingInterval) clearInterval(this.pingInterval);\n // Run all the shutdown callbacks\n const callbackResults = await Promise.allSettled(\n this.shutdownCallbacks.map((callback) => callback(this))\n );\n callbackResults.forEach((result) => {\n if (result.status === 'rejected') reportError(result.reason);\n });\n reportInfo({\n message: `Client disconnected [${this.id}]`,\n data: { code, reason }\n });\n }\n}\n"],"mappings":";;;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAGA,IAAAC,aAAA,GAAAD,OAAA;AASA,IAAAE,MAAA,GAAAF,OAAA;AACA,IAAAG,YAAA,GAAAH,OAAA;AACA,IAAAI,eAAA,GAAAJ,OAAA;AACA,IAAAK,gBAAA,GAAAL,OAAA;AACA,IAAAM,SAAA,GAAAN,OAAA;AACA,IAAAO,IAAA,GAAAP,OAAA;AACA,IAAAQ,OAAA,GAAAR,OAAA;AAEA,MAAMS,SAAS,GAAG,cAAc;;AAEhC;AACA;AACA;AAFA,IAGaC,YAAY,GAAAC,OAAA,CAAAD,YAAA;EAoCvB;AACF;AACA;EACE,SAAAA,aACEE,SAAa,EACbC,OAAwB,EACxBC,OAA4B,EAC5B;IAAA,IAAAC,gBAAA,CAAAC,OAAA,QAAAN,YAAA;IAxCF;IAAA,IAAAO,gBAAA,CAAAD,OAAA;IAEA;IAAA,IAAAC,gBAAA,CAAAD,OAAA;IAEA;IAAA,IAAAC,gBAAA,CAAAD,OAAA;IAEA;IAAA,IAAAC,gBAAA,CAAAD,OAAA;IAEA;IAAA,IAAAC,gBAAA,CAAAD,OAAA,yBACqD,EAAE;IACvD;IAAA,IAAAC,gBAAA,CAAAD,OAAA,yBACqD,EAAE;IACvD;IAAA,IAAAC,gBAAA,CAAAD,OAAA,6BACyD,EAAE;IAC3D;IAAA,IAAAC,gBAAA,CA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BA,CAAA,EAAqB;MACjD,OAAO,IAAI,CAAC5E,aAAa;IAC3B;;IAEA;EAAA;IAAAgC,GAAA;IAAAC,KAAA,EACA,SAAc4C,eAAeA,CAAC5F,EAAU,EAA4B;MAClE,OAAO,IAAI,CAACe,aAAa,CAACf,EAAE,CAAC;IAC/B;EAAC;AAAA;AA/JD;AAAA,IAAAD,gBAAA,CAAAD,OAAA,EADWN,YAAY,mBAE0B,CAAC,CAAC","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"SocketClient.js","names":["_crypto","require","_parseMessage","_const","_EngineError","_MessageHandler","_ValidationError","_WebError","_jwt","_report","namespace","SocketClient","exports","webSocket","request","options","_classCallCheck2","default","_defineProperty2","id","randomUUID","ws","establishedAt","Date","reportDebug","message","initCallbacks","Array","authCallbacks","shutdownCallbacks","handlers","handler","MessageHandler","EngineError","socketClients","reportInfo","on","handleClose","bind","catch","error","reportError","severity","LogSeverity","WARNING","data","handleMessage","callbackResults","Promise","allSettled","map","callback","forEach","result","status","reason","pingInterval","setInterval","isAlive","terminate","ping","process","env","WS_PING_INTERVAL","parseInt","_createClass2","key","value","sendMessage","type","payload","send","noAuth","authenticated","audience","includes","DEFAULT_MESSAGE_AUDIENCE","JSON","stringify","isAuthenticated","getUser","userId","deviceId","tokenId","undefined","parseMessage","toString","authenticate","handle","handleError","token","WebError","errorCode","jwtVerify","setUserData","authExpiration","exp","now","clearTimeouts","authRenewTimer","setTimeout","authExpireTimer","clearTimeout","sub","dev","jti","aud","hint","ValidationError","code","clearInterval","getSocketClients","getSocketClient"],"sources":["../../../src/entities/SocketClient/SocketClient.ts"],"sourcesContent":["import { randomUUID } from 'crypto';\nimport { IncomingMessage } from 'http';\nimport WS, { RawData } from 'ws';\nimport { parseMessage } from './parseMessage';\nimport {\n SocketClientOptions,\n SocketClientSendMessageOptions,\n SocketAuthenticationMessage,\n SocketClientCallback,\n SocketClientList,\n SocketUser\n} from './SocketClient.types';\nimport { LogSeverity } from 'const';\nimport { EngineError } from 'entities/EngineError';\nimport { MessageHandler } from 'entities/MessageHandler';\nimport { ValidationError } from 'entities/ValidationError';\nimport { WebError } from 'entities/WebError';\nimport { jwtVerify, UserTokenPayload } from 'utils/jwt';\nimport { reportInfo, reportError, reportDebug } from 'utils/report';\n\nconst namespace = 'SocketClient';\n\n/**\n * Class where each instance represents a client connected through web-sockets\n */\nexport class SocketClient {\n /** Mapping of all the connected socket clients */\n private static socketClients: SocketClientList = {};\n /** Unique identifier of the client */\n public readonly id: string;\n /** Date at which the client connection was established */\n public readonly establishedAt: Date;\n /** WS instance of the client connection */\n private ws: WS;\n /** List of message handlers that are registered with the client */\n private handlers: Array<MessageHandler>;\n /** Callback function that are called when the client is created */\n private initCallbacks: Array<SocketClientCallback> = [];\n /** Callback function that are called when the client successfully authenticates */\n private authCallbacks: Array<SocketClientCallback> = [];\n /** Callback function that are called when the client connection is terminated */\n private shutdownCallbacks: Array<SocketClientCallback> = [];\n /** Authentication status of the client */\n private authenticated = false;\n /** Timer used to track when to send authentication renewal reminder to the client */\n private authRenewTimer: NodeJS.Timeout | string | number | undefined;\n /** Timers used to track the time at which a user losses authentication */\n private authExpireTimer: NodeJS.Timeout | string | number | undefined;\n /** ID of the user that is authenticated */\n private userId: undefined | string;\n /** ID of the device with which the client authenticated */\n private deviceId: undefined | string;\n /** Id of the token with which the client authenticated */\n private tokenId: undefined | string;\n /** Audience claims that were in the latest authentication token used by the client */\n private audience: undefined | Array<string>;\n /** Status tracking variable used to check the liveness of connections */\n private isAlive = true;\n /** Timer used to track interval between client pinging */\n private pingInterval: NodeJS.Timeout | string | number | undefined;\n\n /**\n * Create a WS client\n */\n public constructor(\n webSocket: WS,\n request: IncomingMessage,\n options: SocketClientOptions\n ) {\n this.id = randomUUID();\n this.ws = webSocket;\n this.establishedAt = new Date();\n\n reportDebug({ namespace, message: `Creating socket client [${this.id}]` });\n\n // Make sure that callbacks are made as lists of functions\n // Init\n if (typeof options.initCallbacks === 'function')\n this.initCallbacks = [options.initCallbacks];\n else if (options.initCallbacks instanceof Array)\n this.initCallbacks = options.initCallbacks;\n // Auth\n if (typeof options.authCallbacks === 'function')\n this.authCallbacks = [options.authCallbacks];\n else if (options.authCallbacks instanceof Array)\n this.authCallbacks = options.authCallbacks;\n // Shutdown\n if (typeof options.shutdownCallbacks === 'function')\n this.shutdownCallbacks = [options.shutdownCallbacks];\n else if (options.shutdownCallbacks instanceof Array)\n this.shutdownCallbacks = options.shutdownCallbacks;\n\n // Check that all handlers are valid\n this.handlers = options.handlers;\n for (const handler of this.handlers) {\n if (!(handler instanceof MessageHandler))\n throw new EngineError({\n message: 'Handler is not an instance of MessageHandler'\n });\n }\n // Register in clients list\n SocketClient.socketClients[this.id] = this;\n\n reportInfo({ message: `Client connected [${this.id}]` });\n // On socket close, deregister from clients list\n this.ws.on('close', () => {\n this.handleClose\n .bind(this)()\n .catch((error) => {\n reportError(error);\n });\n });\n // On socket error, log the error\n this.ws.on('error', (error) => {\n reportError(\n new EngineError({\n severity: LogSeverity.WARNING,\n message: `Error [${this.id}]`\n })\n );\n reportError(error);\n });\n // When receiving a message, call message handler\n this.ws.on('message', (data) => {\n this.handleMessage\n .bind(this)(data)\n .catch((error) => {\n reportError(error);\n });\n });\n\n // Run all the init callbacks\n // For proper error handling of potential asynchronous callbacks, we wrap the execution in an auto-executing async function\n (async (): Promise<void> => {\n const callbackResults = await Promise.allSettled(\n this.initCallbacks.map((callback) => callback(this))\n );\n callbackResults.forEach((result) => {\n if (result.status === 'rejected') reportError(result.reason);\n });\n })().catch((error) => {\n reportError(error);\n });\n\n // Server -> client ping mechanism using WS standard ping control frames\n // We terminate the connection if we did not get a reply in the previous interval\n this.pingInterval = setInterval(\n () => {\n if (!this.isAlive) {\n reportError(\n new EngineError({\n severity: LogSeverity.WARNING,\n message: `Terminating socket connection, ping timeout [${this.id}]`\n })\n );\n this.ws.terminate();\n return;\n }\n this.isAlive = false;\n this.ws.ping();\n reportDebug({ namespace, message: `Ping sent to client [${this.id}]` });\n },\n process.env.WS_PING_INTERVAL\n ? parseInt(process.env.WS_PING_INTERVAL) * 1000\n : 30000\n );\n\n // Track the connection as alive as we get a pong back\n this.ws.on('pong', () => {\n reportDebug({\n namespace,\n message: `Client responded to ping [${this.id}]`\n });\n this.isAlive = true;\n });\n }\n\n /** Get the list of all connected clients indexed by ID */\n public static getSocketClients(): SocketClientList {\n return this.socketClients;\n }\n\n /** Get a client by his ID */\n public static getSocketClient(id: string): SocketClient | undefined {\n return this.socketClients[id];\n }\n\n /**\n * Send a message to the client\n */\n public sendMessage(\n type: string,\n payload: unknown = {},\n options: SocketClientSendMessageOptions = {}\n ): void {\n reportDebug({\n namespace,\n message: `Received request to send message to client of type \"${type}\" [${this.id}]`,\n data: { options }\n });\n let send = false;\n // If the message is sent to unauthenticated user skip auth check\n if (options.noAuth) send = true;\n // If the message is authenticated and with the correct audience, it gets sent\n else if (\n this.authenticated &&\n (this.audience as Array<string>).includes(\n options.audience ?? (process.env.DEFAULT_MESSAGE_AUDIENCE as string)\n )\n )\n send = true;\n\n if (send) {\n reportDebug({\n namespace,\n message: `Sending message to client of type \"${type ?? 'unknown'}\" [${this.id}]`\n });\n this.ws.send(JSON.stringify({ type, payload }));\n }\n }\n\n /** Get the client authentication status */\n public isAuthenticated(): boolean {\n return this.authenticated;\n }\n\n /** Fetch data on the user if he is authenticated */\n public getUser(): SocketUser | undefined {\n if (this.authenticated)\n return {\n userId: this.userId as string,\n deviceId: this.deviceId as string,\n tokenId: this.tokenId as string,\n audience: this.audience as Array<string>\n };\n return undefined;\n }\n\n /** Process an incoming message */\n private async handleMessage(data: RawData): Promise<void> {\n try {\n const message = parseMessage(data.toString('utf-8'));\n reportInfo({\n message: `Received message of type \"${message?.type ?? 'unknown'}\" [${this.id}]`\n });\n switch (message.type) {\n case 'authenticate':\n await this.authenticate(message as SocketAuthenticationMessage);\n break;\n // As not all client libraries allow sending pings through WS control frames,\n // we add a higher level ping mechanism\n case 'ping':\n reportDebug({\n namespace,\n message: `Received ping from client [${this.id}]`\n });\n this.sendMessage('pong', {}, { noAuth: true });\n break;\n default:\n for (const handler of this.handlers) {\n await handler.handle(message, this);\n }\n }\n } catch (error) {\n this.handleError(error);\n }\n }\n\n /**\n * Process an authentication request\n * @param {String} message - Authentication message\n */\n private async authenticate(\n message: SocketAuthenticationMessage\n ): Promise<void> {\n const token = message.payload?.token;\n if (!token) {\n throw new WebError({\n errorCode: 'no-token',\n message: 'No token was given',\n data: { message }\n });\n }\n const payload = await jwtVerify(token);\n this.setUserData(payload);\n\n this.authenticated = true;\n // Time remaining before token expiration\n const authExpiration = payload.exp * 1000 - Date.now();\n // Clear previously created timers\n this.clearTimeouts();\n // Send a refresh request to the client 1 minute before expiration\n this.authRenewTimer = setTimeout(\n () => {\n this.sendMessage('renewAuthentication');\n },\n authExpiration - 60 * 1000\n );\n // Expire client authentication\n this.authExpireTimer = setTimeout(() => {\n this.authenticated = false;\n }, authExpiration);\n\n // Run all the post-authentication callbacks\n const callbackResults = await Promise.allSettled(\n this.authCallbacks.map((callback) => callback(this))\n );\n callbackResults.forEach((result) => {\n if (result.status === 'rejected') reportError(result.reason);\n });\n }\n\n // Clear all the pending timers\n /** */\n private clearTimeouts(): void {\n if (this.authRenewTimer) clearTimeout(this.authRenewTimer);\n if (this.authExpireTimer) clearTimeout(this.authExpireTimer);\n }\n\n /**\n * Fetch the user's data and attach it to the connection for new connections. For existing connections, it checks that the authentication is done on the same user.\n */\n private setUserData({ sub, dev, jti, aud }: UserTokenPayload): void {\n // Check if the user is already authenticated\n if (this.userId) {\n // Check that the token is for the same connection as before\n if (this.userId && this.userId !== sub)\n throw new WebError({\n errorCode: 'wrong-user-token',\n message:\n 'A user tried to authenticate with a token that is not for him [userId]'\n });\n } else {\n // Set the user's ID\n this.userId = sub;\n // Set the user's Device Id\n this.deviceId = dev;\n // Set the token ID\n this.tokenId = jti;\n // Set the aud\n this.audience = aud instanceof Array ? aud : [aud];\n\n reportDebug({\n namespace,\n message: `Successfully authenticated client [${this.id}]`,\n data: {\n userId: this.userId,\n deviceId: this.deviceId,\n tokenId: this.tokenId,\n audience: this.audience\n }\n });\n }\n }\n\n /**\n * Properly return errors to clients\n */\n private handleError(error: unknown): void {\n reportError(error);\n if (error instanceof WebError) {\n this.sendMessage(\n 'error',\n { errorCode: error.errorCode, hint: error.hint },\n { noAuth: true }\n );\n } else if (error instanceof ValidationError) {\n this.sendMessage(\n 'error',\n { errorCode: 'validation-error', hint: error.data },\n { noAuth: true }\n );\n } else {\n this.sendMessage(\n 'error',\n { errorCode: 'server-error' },\n { noAuth: true }\n );\n }\n }\n\n /**\n * Process a socket close event\n */\n private async handleClose(code?: string, reason?: string): Promise<void> {\n delete SocketClient.socketClients[this.id];\n this.clearTimeouts();\n // Stop ping process\n if (this.pingInterval) clearInterval(this.pingInterval);\n // Run all the shutdown callbacks\n const callbackResults = await Promise.allSettled(\n this.shutdownCallbacks.map((callback) => callback(this))\n );\n callbackResults.forEach((result) => {\n if (result.status === 'rejected') reportError(result.reason);\n });\n reportInfo({\n message: `Client disconnected [${this.id}]`,\n data: { code, reason }\n });\n }\n}\n"],"mappings":";;;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAGA,IAAAC,aAAA,GAAAD,OAAA;AASA,IAAAE,MAAA,GAAAF,OAAA;AACA,IAAAG,YAAA,GAAAH,OAAA;AACA,IAAAI,eAAA,GAAAJ,OAAA;AACA,IAAAK,gBAAA,GAAAL,OAAA;AACA,IAAAM,SAAA,GAAAN,OAAA;AACA,IAAAO,IAAA,GAAAP,OAAA;AACA,IAAAQ,OAAA,GAAAR,OAAA;AAEA,MAAMS,SAAS,GAAG,cAAc;;AAEhC;AACA;AACA;AAFA,IAGaC,YAAY,GAAAC,OAAA,CAAAD,YAAA;EAoCvB;AACF;AACA;EACE,SAAAA,aACEE,SAAa,EACbC,OAAwB,EACxBC,OAA4B,EAC5B;IAAA,IAAAC,gBAAA,CAAAC,OAAA,QAAAN,YAAA;IAxCF;IAAA,IAAAO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J,eAAe,CAACK,OAAO,CAAEC,MAAM,IAAK;QAClC,IAAIA,MAAM,CAACC,MAAM,KAAK,UAAU,EAAE,IAAAb,mBAAW,EAACY,MAAM,CAACE,MAAM,CAAC;MAC9D,CAAC,CAAC;MACF,IAAApB,kBAAU,EAAC;QACTV,OAAO,EAAE,wBAAwB,IAAI,CAACN,EAAE,GAAG;QAC3C0B,IAAI,EAAE;UAAEgE,IAAI;UAAEtD;QAAO;MACvB,CAAC,CAAC;IACJ;EAAC;IAAAW,GAAA;IAAAC,KAAA,EA9ND,SAAc4C,gBAAgBA,CAAA,EAAqB;MACjD,OAAO,IAAI,CAAC7E,aAAa;IAC3B;;IAEA;EAAA;IAAAgC,GAAA;IAAAC,KAAA,EACA,SAAc6C,eAAeA,CAAC7F,EAAU,EAA4B;MAClE,OAAO,IAAI,CAACe,aAAa,CAACf,EAAE,CAAC;IAC/B;EAAC;AAAA;AA/JD;AAAA,IAAAD,gBAAA,CAAAD,OAAA,EADWN,YAAY,mBAE0B,CAAC,CAAC","ignoreList":[]}
|
package/dist/index.js
CHANGED
|
@@ -57,6 +57,5 @@ Object.keys(_tlsRequest).forEach(function (key) {
|
|
|
57
57
|
});
|
|
58
58
|
var _middleware = _interopRequireWildcard(require("./middleware"));
|
|
59
59
|
exports.middleware = _middleware;
|
|
60
|
-
function
|
|
61
|
-
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
|
|
60
|
+
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
|
|
62
61
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_const","require","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_entities","_utils","_tlsRequest","_middleware","_interopRequireWildcard","middleware","
|
|
1
|
+
{"version":3,"file":"index.js","names":["_const","require","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_entities","_utils","_tlsRequest","_middleware","_interopRequireWildcard","middleware","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","set","getOwnPropertyDescriptor"],"sources":["../src/index.ts"],"sourcesContent":["// src/index.ts\nexport * from './const';\nexport * from './entities';\nexport * from './utils';\nexport * from './utils/tlsRequest';\nexport * as middleware from './middleware';\n"],"mappings":";;;;;;;;;AACA,IAAAA,MAAA,GAAAC,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAH,MAAA,EAAAI,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAL,MAAA,CAAAK,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MA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
|
|
|
1
1
|
import { Request, Response, NextFunction } from 'express';
|
|
2
2
|
/** Middleware to check if the user has at least one of the required permissions (case-insensitive). */
|
|
3
|
-
declare function checkPermission(requiredActions: string | string[]): (req: Request, res: Response, next: NextFunction) =>
|
|
3
|
+
declare function checkPermission(requiredActions: string | string[]): (req: Request, res: Response, next: NextFunction) => void;
|
|
4
4
|
export { checkPermission };
|
|
@@ -9,9 +9,10 @@ function checkPermission(requiredActions) {
|
|
|
9
9
|
return function (req, res, next) {
|
|
10
10
|
const user = req.user;
|
|
11
11
|
if (!user || !user.permissions) {
|
|
12
|
-
|
|
12
|
+
res.status(403).json({
|
|
13
13
|
message: 'User does not have permissions'
|
|
14
14
|
});
|
|
15
|
+
return;
|
|
15
16
|
}
|
|
16
17
|
|
|
17
18
|
// Normalize input to an array of strings
|
|
@@ -23,9 +24,10 @@ function checkPermission(requiredActions) {
|
|
|
23
24
|
// Check if the user has any of the required permissions (case-insensitive)
|
|
24
25
|
const hasPermission = user.permissions.some(permission => requiredActionsLower.includes(permission.toLowerCase()));
|
|
25
26
|
if (!hasPermission) {
|
|
26
|
-
|
|
27
|
+
res.status(403).json({
|
|
27
28
|
message: 'Permission denied'
|
|
28
29
|
});
|
|
30
|
+
return;
|
|
29
31
|
}
|
|
30
32
|
next();
|
|
31
33
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkPermission.js","names":["checkPermission","requiredActions","req","res","next","user","permissions","status","json","message","requiredActionsArray","Array","isArray","requiredActionsLower","map","action","toLowerCase","hasPermission","some","permission","includes"],"sources":["../../../src/middleware/checkPermission/checkPermission.ts"],"sourcesContent":["import { Request, Response, NextFunction } from 'express';\n\n/** Middleware to check if the user has at least one of the required permissions (case-insensitive). */\nfunction checkPermission(requiredActions: string | string[]) {\n return function (req: Request, res: Response, next: NextFunction) {\n const user = req.user;\n\n if (!user || !user.permissions) {\n
|
|
1
|
+
{"version":3,"file":"checkPermission.js","names":["checkPermission","requiredActions","req","res","next","user","permissions","status","json","message","requiredActionsArray","Array","isArray","requiredActionsLower","map","action","toLowerCase","hasPermission","some","permission","includes"],"sources":["../../../src/middleware/checkPermission/checkPermission.ts"],"sourcesContent":["import { Request, Response, NextFunction } from 'express';\n\n/** Middleware to check if the user has at least one of the required permissions (case-insensitive). */\nfunction checkPermission(requiredActions: string | string[]) {\n return function (req: Request, res: Response, next: NextFunction) {\n const user = req.user;\n\n if (!user || !user.permissions) {\n res.status(403).json({ message: 'User does not have permissions' });\n return;\n }\n\n // Normalize input to an array of strings\n const requiredActionsArray = Array.isArray(requiredActions)\n ? requiredActions\n : [requiredActions];\n\n // Normalize required actions to lowercase\n const requiredActionsLower = requiredActionsArray.map(action => action.toLowerCase());\n\n // Check if the user has any of the required permissions (case-insensitive)\n const hasPermission = user.permissions.some((permission: string) =>\n requiredActionsLower.includes(permission.toLowerCase())\n );\n\n if (!hasPermission) {\n res.status(403).json({ message: 'Permission denied' });\n return;\n }\n\n next();\n };\n}\n\nexport { checkPermission };"],"mappings":";;;;;;AAEA;AACA,SAASA,eAAeA,CAACC,eAAkC,EAAE;EAC3D,OAAO,UAAUC,GAAY,EAAEC,GAAa,EAAEC,IAAkB,EAAE;IAChE,MAAMC,IAAI,GAAGH,GAAG,CAACG,IAAI;IAErB,IAAI,CAACA,IAAI,IAAI,CAACA,IAAI,CAACC,WAAW,EAAE;MAC9BH,GAAG,CAACI,MAAM,CAAC,GAAG,CAAC,CAACC,IAAI,CAAC;QAAEC,OAAO,EAAE;MAAiC,CAAC,CAAC;MACnE;IACF;;IAEA;IACA,MAAMC,oBAAoB,GAAGC,KAAK,CAACC,OAAO,CAACX,eAAe,CAAC,GACvDA,eAAe,GACf,CAACA,eAAe,CAAC;;IAErB;IACA,MAAMY,oBAAoB,GAAGH,oBAAoB,CAACI,GAAG,CAACC,MAAM,IAAIA,MAAM,CAACC,WAAW,CAAC,CAAC,CAAC;;IAErF;IACA,MAAMC,aAAa,GAAGZ,IAAI,CAACC,WAAW,CAACY,IAAI,CAAEC,UAAkB,IAC7DN,oBAAoB,CAACO,QAAQ,CAACD,UAAU,CAACH,WAAW,CAAC,CAAC,CACxD,CAAC;IAED,IAAI,CAACC,aAAa,EAAE;MAClBd,GAAG,CAACI,MAAM,CAAC,GAAG,CAAC,CAACC,IAAI,CAAC;QAAEC,OAAO,EAAE;MAAoB,CAAC,CAAC;MACtD;IACF;IAEAL,IAAI,CAAC,CAAC;EACR,CAAC;AACH","ignoreList":[]}
|
package/dist/utils/jwt/jwt.js
CHANGED
|
@@ -160,7 +160,7 @@ function generateJwtToken(user) {
|
|
|
160
160
|
const signOptions = {
|
|
161
161
|
algorithm: 'ES256',
|
|
162
162
|
// or 'ES256' as Algorithm
|
|
163
|
-
expiresIn: process.env.ACCESS_TOKEN_EXPIRATION_TIME ? parseInt(process.env.ACCESS_TOKEN_EXPIRATION_TIME, 10) :
|
|
163
|
+
expiresIn: process.env.ACCESS_TOKEN_EXPIRATION_TIME ? parseInt(process.env.ACCESS_TOKEN_EXPIRATION_TIME, 10) : 3600,
|
|
164
164
|
issuer: process.env.ACCESS_TOKEN_ISSUER,
|
|
165
165
|
audience: process.env.ACCESS_TOKEN_AUDIENCE,
|
|
166
166
|
keyid: Object.keys(keySet?.getKeys() ?? {})[0]
|