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
|
@@ -1,401 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from 'crypto';
|
|
2
|
-
import { IncomingMessage } from 'http';
|
|
3
|
-
import WS, { RawData } from 'ws';
|
|
4
|
-
import { parseMessage } from './parseMessage';
|
|
5
|
-
import {
|
|
6
|
-
SocketClientOptions,
|
|
7
|
-
SocketClientSendMessageOptions,
|
|
8
|
-
SocketAuthenticationMessage,
|
|
9
|
-
SocketClientCallback,
|
|
10
|
-
SocketClientList,
|
|
11
|
-
SocketUser
|
|
12
|
-
} from './SocketClient.types';
|
|
13
|
-
import { LogSeverity } from 'const';
|
|
14
|
-
import { EngineError } from 'entities/EngineError';
|
|
15
|
-
import { MessageHandler } from 'entities/MessageHandler';
|
|
16
|
-
import { ValidationError } from 'entities/ValidationError';
|
|
17
|
-
import { WebError } from 'entities/WebError';
|
|
18
|
-
import { jwtVerify, UserTokenPayload } from 'utils/jwt';
|
|
19
|
-
import { reportInfo, reportError, reportDebug } from 'utils/report';
|
|
20
|
-
|
|
21
|
-
const namespace = 'SocketClient';
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Class where each instance represents a client connected through web-sockets
|
|
25
|
-
*/
|
|
26
|
-
export class SocketClient {
|
|
27
|
-
/** Mapping of all the connected socket clients */
|
|
28
|
-
private static socketClients: SocketClientList = {};
|
|
29
|
-
/** Unique identifier of the client */
|
|
30
|
-
public readonly id: string;
|
|
31
|
-
/** Date at which the client connection was established */
|
|
32
|
-
public readonly establishedAt: Date;
|
|
33
|
-
/** WS instance of the client connection */
|
|
34
|
-
private ws: WS;
|
|
35
|
-
/** List of message handlers that are registered with the client */
|
|
36
|
-
private handlers: Array<MessageHandler>;
|
|
37
|
-
/** Callback function that are called when the client is created */
|
|
38
|
-
private initCallbacks: Array<SocketClientCallback> = [];
|
|
39
|
-
/** Callback function that are called when the client successfully authenticates */
|
|
40
|
-
private authCallbacks: Array<SocketClientCallback> = [];
|
|
41
|
-
/** Callback function that are called when the client connection is terminated */
|
|
42
|
-
private shutdownCallbacks: Array<SocketClientCallback> = [];
|
|
43
|
-
/** Authentication status of the client */
|
|
44
|
-
private authenticated = false;
|
|
45
|
-
/** Timer used to track when to send authentication renewal reminder to the client */
|
|
46
|
-
private authRenewTimer: NodeJS.Timeout | string | number | undefined;
|
|
47
|
-
/** Timers used to track the time at which a user losses authentication */
|
|
48
|
-
private authExpireTimer: NodeJS.Timeout | string | number | undefined;
|
|
49
|
-
/** ID of the user that is authenticated */
|
|
50
|
-
private userId: undefined | string;
|
|
51
|
-
/** ID of the device with which the client authenticated */
|
|
52
|
-
private deviceId: undefined | string;
|
|
53
|
-
/** Id of the token with which the client authenticated */
|
|
54
|
-
private tokenId: undefined | string;
|
|
55
|
-
/** Audience claims that were in the latest authentication token used by the client */
|
|
56
|
-
private audience: undefined | Array<string>;
|
|
57
|
-
/** Status tracking variable used to check the liveness of connections */
|
|
58
|
-
private isAlive = true;
|
|
59
|
-
/** Timer used to track interval between client pinging */
|
|
60
|
-
private pingInterval: NodeJS.Timeout | string | number | undefined;
|
|
61
|
-
|
|
62
|
-
/**
|
|
63
|
-
* Create a WS client
|
|
64
|
-
*/
|
|
65
|
-
public constructor(
|
|
66
|
-
webSocket: WS,
|
|
67
|
-
request: IncomingMessage,
|
|
68
|
-
options: SocketClientOptions
|
|
69
|
-
) {
|
|
70
|
-
this.id = randomUUID();
|
|
71
|
-
this.ws = webSocket;
|
|
72
|
-
this.establishedAt = new Date();
|
|
73
|
-
|
|
74
|
-
reportDebug({ namespace, message: `Creating socket client [${this.id}]` });
|
|
75
|
-
|
|
76
|
-
// Make sure that callbacks are made as lists of functions
|
|
77
|
-
// Init
|
|
78
|
-
if (typeof options.initCallbacks === 'function')
|
|
79
|
-
this.initCallbacks = [options.initCallbacks];
|
|
80
|
-
else if (options.initCallbacks instanceof Array)
|
|
81
|
-
this.initCallbacks = options.initCallbacks;
|
|
82
|
-
// Auth
|
|
83
|
-
if (typeof options.authCallbacks === 'function')
|
|
84
|
-
this.authCallbacks = [options.authCallbacks];
|
|
85
|
-
else if (options.authCallbacks instanceof Array)
|
|
86
|
-
this.authCallbacks = options.authCallbacks;
|
|
87
|
-
// Shutdown
|
|
88
|
-
if (typeof options.shutdownCallbacks === 'function')
|
|
89
|
-
this.shutdownCallbacks = [options.shutdownCallbacks];
|
|
90
|
-
else if (options.shutdownCallbacks instanceof Array)
|
|
91
|
-
this.shutdownCallbacks = options.shutdownCallbacks;
|
|
92
|
-
|
|
93
|
-
// Check that all handlers are valid
|
|
94
|
-
this.handlers = options.handlers;
|
|
95
|
-
for (const handler of this.handlers) {
|
|
96
|
-
if (!(handler instanceof MessageHandler))
|
|
97
|
-
throw new EngineError({
|
|
98
|
-
message: 'Handler is not an instance of MessageHandler'
|
|
99
|
-
});
|
|
100
|
-
}
|
|
101
|
-
// Register in clients list
|
|
102
|
-
SocketClient.socketClients[this.id] = this;
|
|
103
|
-
|
|
104
|
-
reportInfo({ message: `Client connected [${this.id}]` });
|
|
105
|
-
// On socket close, deregister from clients list
|
|
106
|
-
this.ws.on('close', () => {
|
|
107
|
-
this.handleClose
|
|
108
|
-
.bind(this)()
|
|
109
|
-
.catch((error) => {
|
|
110
|
-
reportError(error);
|
|
111
|
-
});
|
|
112
|
-
});
|
|
113
|
-
// On socket error, log the error
|
|
114
|
-
this.ws.on('error', (error) => {
|
|
115
|
-
reportError(
|
|
116
|
-
new EngineError({
|
|
117
|
-
severity: LogSeverity.WARNING,
|
|
118
|
-
message: `Error [${this.id}]`
|
|
119
|
-
})
|
|
120
|
-
);
|
|
121
|
-
reportError(error);
|
|
122
|
-
});
|
|
123
|
-
// When receiving a message, call message handler
|
|
124
|
-
this.ws.on('message', (data) => {
|
|
125
|
-
this.handleMessage
|
|
126
|
-
.bind(this)(data)
|
|
127
|
-
.catch((error) => {
|
|
128
|
-
reportError(error);
|
|
129
|
-
});
|
|
130
|
-
});
|
|
131
|
-
|
|
132
|
-
// Run all the init callbacks
|
|
133
|
-
// For proper error handling of potential asynchronous callbacks, we wrap the execution in an auto-executing async function
|
|
134
|
-
(async (): Promise<void> => {
|
|
135
|
-
const callbackResults = await Promise.allSettled(
|
|
136
|
-
this.initCallbacks.map((callback) => callback(this))
|
|
137
|
-
);
|
|
138
|
-
callbackResults.forEach((result) => {
|
|
139
|
-
if (result.status === 'rejected') reportError(result.reason);
|
|
140
|
-
});
|
|
141
|
-
})().catch((error) => {
|
|
142
|
-
reportError(error);
|
|
143
|
-
});
|
|
144
|
-
|
|
145
|
-
// Server -> client ping mechanism using WS standard ping control frames
|
|
146
|
-
// We terminate the connection if we did not get a reply in the previous interval
|
|
147
|
-
this.pingInterval = setInterval(
|
|
148
|
-
() => {
|
|
149
|
-
if (!this.isAlive) {
|
|
150
|
-
reportError(
|
|
151
|
-
new EngineError({
|
|
152
|
-
severity: LogSeverity.WARNING,
|
|
153
|
-
message: `Terminating socket connection, ping timeout [${this.id}]`
|
|
154
|
-
})
|
|
155
|
-
);
|
|
156
|
-
this.ws.terminate();
|
|
157
|
-
return;
|
|
158
|
-
}
|
|
159
|
-
this.isAlive = false;
|
|
160
|
-
this.ws.ping();
|
|
161
|
-
reportDebug({ namespace, message: `Ping sent to client [${this.id}]` });
|
|
162
|
-
},
|
|
163
|
-
process.env.WS_PING_INTERVAL
|
|
164
|
-
? parseInt(process.env.WS_PING_INTERVAL) * 1000
|
|
165
|
-
: 30000
|
|
166
|
-
);
|
|
167
|
-
|
|
168
|
-
// Track the connection as alive as we get a pong back
|
|
169
|
-
this.ws.on('pong', () => {
|
|
170
|
-
reportDebug({
|
|
171
|
-
namespace,
|
|
172
|
-
message: `Client responded to ping [${this.id}]`
|
|
173
|
-
});
|
|
174
|
-
this.isAlive = true;
|
|
175
|
-
});
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
/** Get the list of all connected clients indexed by ID */
|
|
179
|
-
public static getSocketClients(): SocketClientList {
|
|
180
|
-
return this.socketClients;
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
/** Get a client by his ID */
|
|
184
|
-
public static getSocketClient(id: string): SocketClient | undefined {
|
|
185
|
-
return this.socketClients[id];
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
/**
|
|
189
|
-
* Send a message to the client
|
|
190
|
-
*/
|
|
191
|
-
public sendMessage(
|
|
192
|
-
type: string,
|
|
193
|
-
payload: unknown = {},
|
|
194
|
-
options: SocketClientSendMessageOptions = {}
|
|
195
|
-
): void {
|
|
196
|
-
reportDebug({
|
|
197
|
-
namespace,
|
|
198
|
-
message: `Received request to send message to client of type "${type}" [${this.id}]`,
|
|
199
|
-
data: { options }
|
|
200
|
-
});
|
|
201
|
-
let send = false;
|
|
202
|
-
// If the message is sent to unauthenticated user skip auth check
|
|
203
|
-
if (options.noAuth) send = true;
|
|
204
|
-
// If the message is authenticated and with the correct audience, it gets sent
|
|
205
|
-
else if (
|
|
206
|
-
this.authenticated &&
|
|
207
|
-
(this.audience as Array<string>).includes(
|
|
208
|
-
options.audience ?? (process.env.DEFAULT_MESSAGE_AUDIENCE as string)
|
|
209
|
-
)
|
|
210
|
-
)
|
|
211
|
-
send = true;
|
|
212
|
-
|
|
213
|
-
if (send) {
|
|
214
|
-
reportDebug({
|
|
215
|
-
namespace,
|
|
216
|
-
message: `Sending message to client of type "${type ?? 'unknown'}" [${this.id}]`
|
|
217
|
-
});
|
|
218
|
-
this.ws.send(JSON.stringify({ type, payload }));
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
/** Get the client authentication status */
|
|
223
|
-
public isAuthenticated(): boolean {
|
|
224
|
-
return this.authenticated;
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
/** Fetch data on the user if he is authenticated */
|
|
228
|
-
public getUser(): SocketUser | undefined {
|
|
229
|
-
if (this.authenticated)
|
|
230
|
-
return {
|
|
231
|
-
userId: this.userId as string,
|
|
232
|
-
deviceId: this.deviceId as string,
|
|
233
|
-
tokenId: this.tokenId as string,
|
|
234
|
-
audience: this.audience as Array<string>
|
|
235
|
-
};
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
/** Process an incoming message */
|
|
239
|
-
private async handleMessage(data: RawData): Promise<void> {
|
|
240
|
-
try {
|
|
241
|
-
const message = parseMessage(data.toString('utf-8'));
|
|
242
|
-
reportInfo({
|
|
243
|
-
message: `Received message of type "${message?.type ?? 'unknown'}" [${this.id}]`
|
|
244
|
-
});
|
|
245
|
-
switch (message.type) {
|
|
246
|
-
case 'authenticate':
|
|
247
|
-
await this.authenticate(message as SocketAuthenticationMessage);
|
|
248
|
-
break;
|
|
249
|
-
// As not all client libraries allow sending pings through WS control frames,
|
|
250
|
-
// we add a higher level ping mechanism
|
|
251
|
-
case 'ping':
|
|
252
|
-
reportDebug({
|
|
253
|
-
namespace,
|
|
254
|
-
message: `Received ping from client [${this.id}]`
|
|
255
|
-
});
|
|
256
|
-
this.sendMessage('pong', {}, { noAuth: true });
|
|
257
|
-
break;
|
|
258
|
-
default:
|
|
259
|
-
for (const handler of this.handlers) {
|
|
260
|
-
await handler.handle(message, this);
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
} catch (error) {
|
|
264
|
-
this.handleError(error);
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
/**
|
|
269
|
-
* Process an authentication request
|
|
270
|
-
* @param {String} message - Authentication message
|
|
271
|
-
*/
|
|
272
|
-
private async authenticate(
|
|
273
|
-
message: SocketAuthenticationMessage
|
|
274
|
-
): Promise<void> {
|
|
275
|
-
const token = message.payload?.token;
|
|
276
|
-
if (!token) {
|
|
277
|
-
throw new WebError({
|
|
278
|
-
errorCode: 'no-token',
|
|
279
|
-
message: 'No token was given',
|
|
280
|
-
data: { message }
|
|
281
|
-
});
|
|
282
|
-
}
|
|
283
|
-
const payload = await jwtVerify(token);
|
|
284
|
-
this.setUserData(payload);
|
|
285
|
-
|
|
286
|
-
this.authenticated = true;
|
|
287
|
-
// Time remaining before token expiration
|
|
288
|
-
const authExpiration = payload.exp * 1000 - Date.now();
|
|
289
|
-
// Clear previously created timers
|
|
290
|
-
this.clearTimeouts();
|
|
291
|
-
// Send a refresh request to the client 1 minute before expiration
|
|
292
|
-
this.authRenewTimer = setTimeout(
|
|
293
|
-
() => {
|
|
294
|
-
this.sendMessage('renewAuthentication');
|
|
295
|
-
},
|
|
296
|
-
authExpiration - 60 * 1000
|
|
297
|
-
);
|
|
298
|
-
// Expire client authentication
|
|
299
|
-
this.authExpireTimer = setTimeout(() => {
|
|
300
|
-
this.authenticated = false;
|
|
301
|
-
}, authExpiration);
|
|
302
|
-
|
|
303
|
-
// Run all the post-authentication callbacks
|
|
304
|
-
const callbackResults = await Promise.allSettled(
|
|
305
|
-
this.authCallbacks.map((callback) => callback(this))
|
|
306
|
-
);
|
|
307
|
-
callbackResults.forEach((result) => {
|
|
308
|
-
if (result.status === 'rejected') reportError(result.reason);
|
|
309
|
-
});
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
// Clear all the pending timers
|
|
313
|
-
/** */
|
|
314
|
-
private clearTimeouts(): void {
|
|
315
|
-
if (this.authRenewTimer) clearTimeout(this.authRenewTimer);
|
|
316
|
-
if (this.authExpireTimer) clearTimeout(this.authExpireTimer);
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
/**
|
|
320
|
-
* 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.
|
|
321
|
-
*/
|
|
322
|
-
private setUserData({ sub, dev, jti, aud }: UserTokenPayload): void {
|
|
323
|
-
// Check if the user is already authenticated
|
|
324
|
-
if (this.userId) {
|
|
325
|
-
// Check that the token is for the same connection as before
|
|
326
|
-
if (this.userId && this.userId !== sub)
|
|
327
|
-
throw new WebError({
|
|
328
|
-
errorCode: 'wrong-user-token',
|
|
329
|
-
message:
|
|
330
|
-
'A user tried to authenticate with a token that is not for him [userId]'
|
|
331
|
-
});
|
|
332
|
-
} else {
|
|
333
|
-
// Set the user's ID
|
|
334
|
-
this.userId = sub;
|
|
335
|
-
// Set the user's Device Id
|
|
336
|
-
this.deviceId = dev;
|
|
337
|
-
// Set the token ID
|
|
338
|
-
this.tokenId = jti;
|
|
339
|
-
// Set the aud
|
|
340
|
-
this.audience = aud instanceof Array ? aud : [aud];
|
|
341
|
-
|
|
342
|
-
reportDebug({
|
|
343
|
-
namespace,
|
|
344
|
-
message: `Successfully authenticated client [${this.id}]`,
|
|
345
|
-
data: {
|
|
346
|
-
userId: this.userId,
|
|
347
|
-
deviceId: this.deviceId,
|
|
348
|
-
tokenId: this.tokenId,
|
|
349
|
-
audience: this.audience
|
|
350
|
-
}
|
|
351
|
-
});
|
|
352
|
-
}
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
/**
|
|
356
|
-
* Properly return errors to clients
|
|
357
|
-
*/
|
|
358
|
-
private handleError(error: unknown): void {
|
|
359
|
-
reportError(error);
|
|
360
|
-
if (error instanceof WebError) {
|
|
361
|
-
this.sendMessage(
|
|
362
|
-
'error',
|
|
363
|
-
{ errorCode: error.errorCode, hint: error.hint },
|
|
364
|
-
{ noAuth: true }
|
|
365
|
-
);
|
|
366
|
-
} else if (error instanceof ValidationError) {
|
|
367
|
-
this.sendMessage(
|
|
368
|
-
'error',
|
|
369
|
-
{ errorCode: 'validation-error', hint: error.data },
|
|
370
|
-
{ noAuth: true }
|
|
371
|
-
);
|
|
372
|
-
} else {
|
|
373
|
-
this.sendMessage(
|
|
374
|
-
'error',
|
|
375
|
-
{ errorCode: 'server-error' },
|
|
376
|
-
{ noAuth: true }
|
|
377
|
-
);
|
|
378
|
-
}
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
/**
|
|
382
|
-
* Process a socket close event
|
|
383
|
-
*/
|
|
384
|
-
private async handleClose(code?: string, reason?: string): Promise<void> {
|
|
385
|
-
delete SocketClient.socketClients[this.id];
|
|
386
|
-
this.clearTimeouts();
|
|
387
|
-
// Stop ping process
|
|
388
|
-
if (this.pingInterval) clearInterval(this.pingInterval);
|
|
389
|
-
// Run all the shutdown callbacks
|
|
390
|
-
const callbackResults = await Promise.allSettled(
|
|
391
|
-
this.shutdownCallbacks.map((callback) => callback(this))
|
|
392
|
-
);
|
|
393
|
-
callbackResults.forEach((result) => {
|
|
394
|
-
if (result.status === 'rejected') reportError(result.reason);
|
|
395
|
-
});
|
|
396
|
-
reportInfo({
|
|
397
|
-
message: `Client disconnected [${this.id}]`,
|
|
398
|
-
data: { code, reason }
|
|
399
|
-
});
|
|
400
|
-
}
|
|
401
|
-
}
|
|
@@ -1,62 +0,0 @@
|
|
|
1
|
-
import { SocketClient } from './SocketClient';
|
|
2
|
-
import { MessageHandler } from 'entities/MessageHandler';
|
|
3
|
-
|
|
4
|
-
export type SocketClientCallback = (
|
|
5
|
-
client: SocketClient
|
|
6
|
-
) => void | Promise<void>;
|
|
7
|
-
|
|
8
|
-
/** SocketClient creation option */
|
|
9
|
-
export interface SocketClientOptions {
|
|
10
|
-
/** List of message handlers that are registered with the client */
|
|
11
|
-
handlers: Array<MessageHandler>;
|
|
12
|
-
/** Callback function that are called when the client is created */
|
|
13
|
-
initCallbacks?: SocketClientCallback | Array<SocketClientCallback>;
|
|
14
|
-
/** Callback function that are called when the client successfully authenticates */
|
|
15
|
-
authCallbacks?: SocketClientCallback | Array<SocketClientCallback>;
|
|
16
|
-
/** Callback function that are called when the client connection is terminated */
|
|
17
|
-
shutdownCallbacks?: SocketClientCallback | Array<SocketClientCallback>;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
/** Socket Message abstract typing */
|
|
21
|
-
export interface SocketMessage<T = unknown> {
|
|
22
|
-
/** A string that identifies the message type */
|
|
23
|
-
type: string;
|
|
24
|
-
/** Free-form data payload of the message */
|
|
25
|
-
payload: T;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
/** SocketMessage used by client for authentication */
|
|
29
|
-
export interface SocketAuthenticationMessage extends SocketMessage {
|
|
30
|
-
/** Sting that identifies the message type */
|
|
31
|
-
type: 'authenticate';
|
|
32
|
-
/** Data payload of the message */
|
|
33
|
-
payload: {
|
|
34
|
-
/** Authentication token */
|
|
35
|
-
token: string;
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/** Options for sending a message with the client */
|
|
40
|
-
export interface SocketClientSendMessageOptions {
|
|
41
|
-
/** Send message event if the user is not authenticated */
|
|
42
|
-
noAuth?: boolean;
|
|
43
|
-
/** Audience that the authenticated user must have on his token to continue */
|
|
44
|
-
audience?: string;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/** Map of socket clients connected to the server */
|
|
48
|
-
export interface SocketClientList {
|
|
49
|
-
[id: string]: SocketClient;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/** User that authenticated though his socket */
|
|
53
|
-
export interface SocketUser {
|
|
54
|
-
/** ID od the user */
|
|
55
|
-
userId: string;
|
|
56
|
-
/** ID of the device */
|
|
57
|
-
deviceId: string;
|
|
58
|
-
/** ID of the token used */
|
|
59
|
-
tokenId: string;
|
|
60
|
-
/** Audience included in the token */
|
|
61
|
-
audience: Array<string>;
|
|
62
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './parseMessage';
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import { expect } from 'chai';
|
|
2
|
-
import { faker } from '@faker-js/faker';
|
|
3
|
-
import { parseMessage } from './parseMessage';
|
|
4
|
-
|
|
5
|
-
describe('Entities - Socket Client - Utils - Parse Message', () => {
|
|
6
|
-
it('should transform a JSON string into an object', () => {
|
|
7
|
-
const object = { [faker.lorem.word()]: faker.lorem.word() };
|
|
8
|
-
const result = parseMessage(JSON.stringify(object));
|
|
9
|
-
expect(result).to.deep.equal(object);
|
|
10
|
-
});
|
|
11
|
-
|
|
12
|
-
it('should throw an error if the input is not parsable', () => {
|
|
13
|
-
const object = faker.lorem.word();
|
|
14
|
-
expect(() => parseMessage(JSON.stringify(object))).to.throw;
|
|
15
|
-
});
|
|
16
|
-
|
|
17
|
-
it('should throw an error if the input is not an object when parsed', () => {
|
|
18
|
-
expect(() => parseMessage(JSON.stringify([faker.lorem.word()]))).to.throw;
|
|
19
|
-
});
|
|
20
|
-
});
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import { SocketMessage } from '../SocketClient.types';
|
|
2
|
-
import { WebError } from 'entities/WebError';
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Parse an incoming message into a JSON object
|
|
6
|
-
*/
|
|
7
|
-
export function parseMessage(data: string): SocketMessage {
|
|
8
|
-
try {
|
|
9
|
-
const message = JSON.parse(data) as SocketMessage;
|
|
10
|
-
if (message.constructor.name !== 'Object')
|
|
11
|
-
throw new WebError({
|
|
12
|
-
statusCode: 400,
|
|
13
|
-
errorCode: 'non-json',
|
|
14
|
-
message: 'Received message is not an object',
|
|
15
|
-
data: { data }
|
|
16
|
-
});
|
|
17
|
-
return message;
|
|
18
|
-
} catch {
|
|
19
|
-
throw new WebError({
|
|
20
|
-
statusCode: 400,
|
|
21
|
-
errorCode: 'non-json',
|
|
22
|
-
message: 'Received message is not valid JSON',
|
|
23
|
-
data: { data }
|
|
24
|
-
});
|
|
25
|
-
}
|
|
26
|
-
}
|
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
import { expect } from 'chai';
|
|
2
|
-
import { faker } from '@faker-js/faker';
|
|
3
|
-
import validator from 'validator';
|
|
4
|
-
import { Storage } from './Storage';
|
|
5
|
-
|
|
6
|
-
describe('Storage', function () {
|
|
7
|
-
it('should generate path info for a regular file', function () {
|
|
8
|
-
const path = Storage.generateFileDestination();
|
|
9
|
-
// eslint-disable-next-line import/no-named-as-default-member
|
|
10
|
-
expect(validator.isUUID(path)).to.be.true;
|
|
11
|
-
});
|
|
12
|
-
|
|
13
|
-
it('should add a path to a file', function () {
|
|
14
|
-
const directory = `${faker.lorem.word()}`;
|
|
15
|
-
const path = Storage.generateFileDestination({
|
|
16
|
-
directory
|
|
17
|
-
});
|
|
18
|
-
|
|
19
|
-
expect(path.startsWith(directory)).to.be.true;
|
|
20
|
-
});
|
|
21
|
-
|
|
22
|
-
it('should add a path to a file but remove appended slash', function () {
|
|
23
|
-
const directory = `${faker.lorem.word()}`;
|
|
24
|
-
const path = Storage.generateFileDestination({
|
|
25
|
-
directory: '/' + directory
|
|
26
|
-
});
|
|
27
|
-
expect(path.startsWith(directory)).to.be.true;
|
|
28
|
-
});
|
|
29
|
-
|
|
30
|
-
it('should not append an extension if specified', function () {
|
|
31
|
-
const directory = `${faker.lorem.word()}`;
|
|
32
|
-
const mimeType = 'image/png';
|
|
33
|
-
const path = Storage.generateFileDestination({
|
|
34
|
-
directory,
|
|
35
|
-
mime: mimeType,
|
|
36
|
-
noExtension: true
|
|
37
|
-
});
|
|
38
|
-
|
|
39
|
-
const resultExt = path.split('.')[1];
|
|
40
|
-
|
|
41
|
-
expect(path.startsWith(directory)).to.be.true;
|
|
42
|
-
expect(resultExt).to.be.undefined;
|
|
43
|
-
});
|
|
44
|
-
|
|
45
|
-
it('should append an extension if specified', function () {
|
|
46
|
-
const directory = `${faker.lorem.word()}`;
|
|
47
|
-
const mimeType = 'image/png';
|
|
48
|
-
const path = Storage.generateFileDestination({
|
|
49
|
-
directory,
|
|
50
|
-
mime: mimeType
|
|
51
|
-
});
|
|
52
|
-
|
|
53
|
-
const resultExt = path.split('.')[1];
|
|
54
|
-
|
|
55
|
-
expect(path.startsWith(directory)).to.be.true;
|
|
56
|
-
expect(resultExt).to.equal('png');
|
|
57
|
-
});
|
|
58
|
-
});
|