node-server-engine 2.0.2 → 2.1.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/README.md CHANGED
@@ -528,22 +528,24 @@ const server = new Server({
528
528
  });
529
529
  ```
530
530
 
531
- | Parameter | Type | Description | Default |
532
- | ----------------- | ------------------------------------------ | --------------------------------------------------------- | ------------ |
533
- | handlers | Array\<[MessageHandler](#message-handler)> | A list of message handlers to use | **required** |
534
- | authCallbacks | Function \| Array\<Function> | Callbacks called when a client successfully authenticates | [] |
535
- | initCallbacks | Function \| Array\<Function> | Callbacks called when the socket client is created | [] |
536
- | shutdownCallbacks | Function \| Array\<Function> | Callbacks called when the socket client is destroyed | [] |
531
+ | Parameter | Type | Description | Default |
532
+ | ----------------- | ------------------------------------------ | --------------------------------------------------------------------------------- | ------------ |
533
+ | handlers | Array\<[MessageHandler](#message-handler)> | A list of message handlers to use | **required** |
534
+ | authCallbacks | Function \| Array\<Function> | Callbacks called when a client successfully authenticates | [] |
535
+ | initCallbacks | Function \| Array\<Function> | Callbacks called when the socket client is created | [] |
536
+ | shutdownCallbacks | Function \| Array\<Function> | Callbacks called when the socket client is destroyed | [] |
537
+ | authTimeoutMs | Number | Close the socket with code 4401 if it has not authenticated within this time (ms) | never |
537
538
 
538
539
  #### Client Properties & Methods
539
540
 
540
- | Property/Method | Type | Description |
541
- | ----------------- | ----------------------------- | ----------------------------------------------------------------- |
542
- | id | String | Unique identifier for the connection |
543
- | establishedAt | Date | Timestamp when connection was established |
544
- | isAuthenticated() | () => Boolean | Check if client is authenticated |
545
- | getUser() | () => SocketUser \| undefined | Get authenticated user data (userId, deviceId, tokenId, audience) |
546
- | sendMessage() | (type, payload, options) | Send a message to the client |
541
+ | Property/Method | Type | Description |
542
+ | ----------------- | ----------------------------- | -------------------------------------------------------------------------------------------------------- |
543
+ | id | String | Unique identifier for the connection |
544
+ | establishedAt | Date | Timestamp when connection was established |
545
+ | isAuthenticated() | () => Boolean | Check if client is authenticated |
546
+ | getUser() | () => SocketUser \| undefined | Get authenticated user data (userId, deviceId, tokenId, audience, the token's `user` claim, `expiresAt`) |
547
+ | sendMessage() | (type, payload, options) | Send a message to the client |
548
+ | close() | (code?, reason?) | Close the connection, e.g. `close(4403, 'Not allowed')` from an `authCallbacks` check |
547
549
 
548
550
  #### Client Authentication
549
551
 
@@ -1055,14 +1057,16 @@ Sequelize.closeSequelize();
1055
1057
 
1056
1058
  It can be configured through environment variables
1057
1059
 
1058
- | env | description | default |
1059
- | ------------ | ------------------------------------------------- | -------- |
1060
- | SQL_HOST | Host to which connect to | |
1061
- | SQL_PORT | Port on which SQL is served | 5432 |
1062
- | SQL_PASSWORD | Password used to authenticate with the SQL server | |
1063
- | SQL_USER | User used to authenticate with the SQL server | |
1064
- | SQL_DB | Database to which connect to | |
1065
- | SQL_TYPE | SQL type which connect to | postgres |
1060
+ | env | description | default |
1061
+ | --------------------- | ------------------------------------------------------------------------------------------ | -------- |
1062
+ | SQL_HOST | Host to which connect to | |
1063
+ | SQL_PORT | Port on which SQL is served | 5432 |
1064
+ | SQL_PASSWORD | Password used to authenticate with the SQL server | |
1065
+ | SQL_USER | User used to authenticate with the SQL server | |
1066
+ | SQL_DB | Database to which connect to | |
1067
+ | SQL_TYPE | SQL type which connect to | postgres |
1068
+ | SQL_ENCRYPT | `mssql` only: set to `false` to disable TLS | true |
1069
+ | SQL_TRUST_SERVER_CERT | `mssql` only: `true` skips certificate verification (self-signed development servers only) | false |
1066
1070
 
1067
1071
  ---
1068
1072
 
@@ -45,14 +45,18 @@ const config = {
45
45
 
46
46
  // Additional configurations for MSSQL
47
47
  if (config.dialect === 'mssql') {
48
+ // tedious connection options live under dialectOptions.options
48
49
  config.dialectOptions = {
49
- requestTimeout: 30000,
50
- // Increase request timeout for MSSQL
51
- connectTimeout: 30000,
52
- // Increase connection timeout for MSSQL
53
- encrypt: true,
54
- // Use encryption for MSSQL (set to false if not needed)
55
- trustServerCertificate: true // Set to true if using self-signed certificates
50
+ options: {
51
+ requestTimeout: 30000,
52
+ // Increase request timeout for MSSQL
53
+ connectTimeout: 30000,
54
+ // Increase connection timeout for MSSQL
55
+ // Encrypted connections by default; SQL_ENCRYPT=false only for servers without TLS
56
+ encrypt: process.env.SQL_ENCRYPT !== 'false',
57
+ // The server certificate is verified unless SQL_TRUST_SERVER_CERT=true (self-signed development servers)
58
+ trustServerCertificate: process.env.SQL_TRUST_SERVER_CERT === 'true'
59
+ }
56
60
  };
57
61
  }
58
62
 
@@ -1 +1 @@
1
- {"version":3,"file":"Sequelize.config.js","names":["_Sequelize","require","validateSequelizeEnvironment","isUnixSocket","process","env","SQL_HOST","startsWith","config","username","SQL_USER","password","SQL_PASSWORD","database","SQL_DB","host","port","undefined","SQL_PORT","parseInt","dialect","SQL_TYPE","logging","SQL_LOGGING","console","log","define","freezeTableName","charset","collate","retry","max","NODE_ENV","dialectOptions","pool","min","acquire","idle","evict","requestTimeout","connectTimeout","encrypt","trustServerCertificate","timezone","ssl","PG_SSL","rejectUnauthorized","development","exports","staging","production","test","_default","default"],"sources":["../../../src/entities/Sequelize/Sequelize.config.ts"],"sourcesContent":["import { Options, Dialect } from 'sequelize';\nimport { validateSequelizeEnvironment } from './Sequelize.validate';\n\n// Check that environment variables are correctly set\nvalidateSequelizeEnvironment();\n\n// Check if SQL_HOST is a Unix socket path (Cloud SQL)\nconst isUnixSocket = process.env.SQL_HOST?.startsWith('/');\n\nconst config: Options = {\n username: process.env.SQL_USER,\n password: process.env.SQL_PASSWORD,\n database: process.env.SQL_DB,\n host: process.env.SQL_HOST,\n // Don't set port for Unix socket connections (Cloud SQL)\n port: isUnixSocket\n ? undefined\n : process.env.SQL_PORT\n ? parseInt(process.env.SQL_PORT)\n : 5432,\n dialect: (process.env.SQL_TYPE ?? 'postgres') as Dialect, // Dynamically set the dialect (postgres, mysql, mssql)\n logging: process.env.SQL_LOGGING === 'true' ? console.log : false, // Enable SQL logging with SQL_LOGGING=true\n define: {\n freezeTableName: false, // Prevent automatic pluralization of table names\n charset: 'utf8mb4', // Set character set for MySQL/MariaDB\n collate: 'utf8mb4_unicode_ci' // Set collation for MySQL/MariaDB\n },\n retry: {\n max: process.env.NODE_ENV === 'test' ? 0 : 3 // Disable retries in test environment to prevent unhandled rejections\n },\n dialectOptions: {},\n pool: {\n max: process.env.NODE_ENV === 'test' ? 1 : 5,\n min: 0,\n acquire: process.env.NODE_ENV === 'test' ? 1000 : 30000, // Reduce acquire timeout in test\n idle: process.env.NODE_ENV === 'test' ? 1000 : 10000, // Reduce idle time in test\n evict: process.env.NODE_ENV === 'test' ? 100 : 1000 // How often to check for idle connections\n }\n};\n\n// Additional configurations for MSSQL\nif (config.dialect === 'mssql') {\n config.dialectOptions = {\n requestTimeout: 30000, // Increase request timeout for MSSQL\n connectTimeout: 30000, // Increase connection timeout for MSSQL\n encrypt: true, // Use encryption for MSSQL (set to false if not needed)\n trustServerCertificate: true // Set to true if using self-signed certificates\n };\n}\n\n// Add specific dialect configurations if necessary for MySQL/PostgreSQL\nif (config.dialect === 'mysql') {\n config.dialectOptions = {\n timezone: 'Z' // Set timezone for MySQL\n };\n}\n\nif (config.dialect === 'postgres') {\n config.dialectOptions = {\n ssl: process.env.PG_SSL === 'true' ? { rejectUnauthorized: false } : false // SSL options for PostgreSQL (if required)\n };\n}\n\nexport const development = config;\nexport const staging = config;\nexport const production = config;\nexport const test = config;\nexport default config;\n"],"mappings":";;;;;;AACA,IAAAA,UAAA,GAAAC,OAAA;AAEA;AACA,IAAAC,uCAA4B,EAAC,CAAC;;AAE9B;AACA,MAAMC,YAAY,GAAGC,OAAO,CAACC,GAAG,CAACC,QAAQ,EAAEC,UAAU,CAAC,GAAG,CAAC;AAE1D,MAAMC,MAAe,GAAG;EACtBC,QAAQ,EAAEL,OAAO,CAACC,GAAG,CAACK,QAAQ;EAC9BC,QAAQ,EAAEP,OAAO,CAACC,GAAG,CAACO,YAAY;EAClCC,QAAQ,EAAET,OAAO,CAACC,GAAG,CAAC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AAK;IAAE;IACvBC,cAAc,EAAE,KAAK;IAAE;IACvBC,OAAO,EAAE,IAAI;IAAE;IACfC,sBAAsB,EAAE,IAAI,CAAC;EAC/B,CAAC;AACH;;AAEA;AACA,IAAIlC,MAAM,CAACY,OAAO,KAAK,OAAO,EAAE;EAC9BZ,MAAM,CAACyB,cAAc,GAAG;IACtBU,QAAQ,EAAE,GAAG,CAAC;EAChB,CAAC;AACH;AAEA,IAAInC,MAAM,CAACY,OAAO,KAAK,UAAU,EAAE;EACjCZ,MAAM,CAACyB,cAAc,GAAG;IACtBW,GAAG,EAAExC,OAAO,CAACC,GAAG,CAACwC,MAAM,KAAK,MAAM,GAAG;MAAEC,kBAAkB,EAAE;IAAM,CAAC,GAAG,KAAK,CAAC;EAC7E,CAAC;AACH;AAEO,MAAMC,WAAW,GAAAC,OAAA,CAAAD,WAAA,GAAGvC,MAAM;AAC1B,MAAMyC,OAAO,GAAAD,OAAA,CAAAC,OAAA,GAAGzC,MAAM;AACtB,MAAM0C,UAAU,GAAAF,OAAA,CAAAE,UAAA,GAAG1C,MAAM;AACzB,MAAM2C,IAAI,GAAAH,OAAA,CAAAG,IAAA,GAAG3C,MAAM;AAAC,IAAA4C,QAAA,GAAAJ,OAAA,CAAAK,OAAA,GACZ7C,MAAM","ignoreList":[]}
1
+ {"version":3,"file":"Sequelize.config.js","names":["_Sequelize","require","validateSequelizeEnvironment","isUnixSocket","process","env","SQL_HOST","startsWith","config","username","SQL_USER","password","SQL_PASSWORD","database","SQL_DB","host","port","undefined","SQL_PORT","parseInt","dialect","SQL_TYPE","logging","SQL_LOGGING","console","log","define","freezeTableName","charset","collate","retry","max","NODE_ENV","dialectOptions","pool","min","acquire","idle","evict","options","requestTimeout","connectTimeout","encrypt","SQL_ENCRYPT","trustServerCertificate","SQL_TRUST_SERVER_CERT","timezone","ssl","PG_SSL","rejectUnauthorized","development","exports","staging","production","test","_default","default"],"sources":["../../../src/entities/Sequelize/Sequelize.config.ts"],"sourcesContent":["import { Options, Dialect } from 'sequelize';\nimport { validateSequelizeEnvironment } from './Sequelize.validate';\n\n// Check that environment variables are correctly set\nvalidateSequelizeEnvironment();\n\n// Check if SQL_HOST is a Unix socket path (Cloud SQL)\nconst isUnixSocket = process.env.SQL_HOST?.startsWith('/');\n\nconst config: Options = {\n username: process.env.SQL_USER,\n password: process.env.SQL_PASSWORD,\n database: process.env.SQL_DB,\n host: process.env.SQL_HOST,\n // Don't set port for Unix socket connections (Cloud SQL)\n port: isUnixSocket\n ? undefined\n : process.env.SQL_PORT\n ? parseInt(process.env.SQL_PORT)\n : 5432,\n dialect: (process.env.SQL_TYPE ?? 'postgres') as Dialect, // Dynamically set the dialect (postgres, mysql, mssql)\n logging: process.env.SQL_LOGGING === 'true' ? console.log : false, // Enable SQL logging with SQL_LOGGING=true\n define: {\n freezeTableName: false, // Prevent automatic pluralization of table names\n charset: 'utf8mb4', // Set character set for MySQL/MariaDB\n collate: 'utf8mb4_unicode_ci' // Set collation for MySQL/MariaDB\n },\n retry: {\n max: process.env.NODE_ENV === 'test' ? 0 : 3 // Disable retries in test environment to prevent unhandled rejections\n },\n dialectOptions: {},\n pool: {\n max: process.env.NODE_ENV === 'test' ? 1 : 5,\n min: 0,\n acquire: process.env.NODE_ENV === 'test' ? 1000 : 30000, // Reduce acquire timeout in test\n idle: process.env.NODE_ENV === 'test' ? 1000 : 10000, // Reduce idle time in test\n evict: process.env.NODE_ENV === 'test' ? 100 : 1000 // How often to check for idle connections\n }\n};\n\n// Additional configurations for MSSQL\nif (config.dialect === 'mssql') {\n // tedious connection options live under dialectOptions.options\n config.dialectOptions = {\n options: {\n requestTimeout: 30000, // Increase request timeout for MSSQL\n connectTimeout: 30000, // Increase connection timeout for MSSQL\n // Encrypted connections by default; SQL_ENCRYPT=false only for servers without TLS\n encrypt: process.env.SQL_ENCRYPT !== 'false',\n // The server certificate is verified unless SQL_TRUST_SERVER_CERT=true (self-signed development servers)\n trustServerCertificate: process.env.SQL_TRUST_SERVER_CERT === 'true'\n }\n };\n}\n\n// Add specific dialect configurations if necessary for MySQL/PostgreSQL\nif (config.dialect === 'mysql') {\n config.dialectOptions = {\n timezone: 'Z' // Set timezone for MySQL\n };\n}\n\nif (config.dialect === 'postgres') {\n config.dialectOptions = {\n ssl: process.env.PG_SSL === 'true' ? { rejectUnauthorized: false } : false // SSL options for PostgreSQL (if required)\n };\n}\n\nexport const development = config;\nexport const staging = config;\nexport const production = config;\nexport const test = config;\nexport default config;\n"],"mappings":";;;;;;AACA,IAAAA,UAAA,GAAAC,OAAA;AAEA;AACA,IAAAC,uCAA4B,EAAC,CAAC;;AAE9B;AACA,MAAMC,YAAY,GAAGC,OAAO,CAACC,GAAG,CAACC,QAAQ,EAAEC,UAAU,CAAC,GAAG,CAAC;AAE1D,MAAMC,MAAe,GAAG;EACtBC,QAAQ,EAAEL,OAAO,CAACC,GAAG,CAACK,QAAQ;EAC9BC,QAAQ,EAAEP,OAAO,CAACC,GAAG,CAACO,YAAY;EAClCC,QAAQ,EAAET,OAAO,CAACC,GAAG,CAACS,MAAM;EAC5BC,IAAI,EAAEX,OAAO,CAACC,GAAG,CAACC,QAAQ;EAC1B;EACAU,IAAI,EAAEb,YAAY,GACdc,SAAS,GACTb,OAAO,CAACC,GAAG,CAACa,QAAQ,GAClBC,QAAQ,CAACf,OAAO,CAACC,GAAG,CAACa,QAAQ,CAAC,GAC9B,IAAI;EACVE,OAAO,EAAGhB,OAAO,CAACC,GAAG,CAACgB,QAAQ,IAAI,UAAsB;EAAE;EAC1DC,OAAO,EAAElB,OAAO,CAACC,GAAG,CAACkB,WAAW,KAAK,MAAM,GAAGC,OAAO,CAACC,GAAG,GAAG,KAAK;EAAE;EACnEC,MAAM,EAAE;IACNC,eAAe,EAAE,KAAK;IAAE;IACxBC,OAAO,EAAE,SAAS;IAAE;IACpBC,OAAO,EAAE,oBAAoB,CAAC;EAChC,CAAC;EACDC,KAAK,EAAE;IACLC,GAAG,EAAE3B,OAAO,CAACC,GAAG,CAAC2B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;AACH;AAEO,MAAMC,WAAW,GAAAC,OAAA,CAAAD,WAAA,GAAG1C,MAAM;AAC1B,MAAM4C,OAAO,GAAAD,OAAA,CAAAC,OAAA,GAAG5C,MAAM;AACtB,MAAM6C,UAAU,GAAAF,OAAA,CAAAE,UAAA,GAAG7C,MAAM;AACzB,MAAM8C,IAAI,GAAAH,OAAA,CAAAG,IAAA,GAAG9C,MAAM;AAAC,IAAA+C,QAAA,GAAAJ,OAAA,CAAAK,OAAA,GACZhD,MAAM","ignoreList":[]}
@@ -37,6 +37,12 @@ export declare class SocketClient {
37
37
  private audience;
38
38
  /** Status tracking variable used to check the liveness of connections */
39
39
  private isAlive;
40
+ /** The `user` claim of the token the client authenticated with */
41
+ private tokenUser;
42
+ /** Timestamp (ms) at which the current authentication expires */
43
+ private authExpiresAt;
44
+ /** Closes the connection if the client does not authenticate in time */
45
+ private authTimeout;
40
46
  /** Timer used to track interval between client pinging */
41
47
  private pingInterval;
42
48
  /**
@@ -54,6 +60,12 @@ export declare class SocketClient {
54
60
  * Send a message to the client
55
61
  */
56
62
  sendMessage(type: string, payload?: unknown, options?: SocketClientSendMessageOptions): void;
63
+ /**
64
+ * Close the connection
65
+ * @param code - WebSocket close code (4000-4999 are free for applications, e.g. 4401 / 4403)
66
+ * @param reason - Human readable reason, sent to the client
67
+ */
68
+ close(code?: number, reason?: string): void;
57
69
  /** Get the client authentication status */
58
70
  isAuthenticated(): boolean;
59
71
  /** Fetch data on the user if he is authenticated */
@@ -61,6 +61,12 @@ let SocketClient = exports.SocketClient = /*#__PURE__*/function () {
61
61
  (0, _defineProperty2.default)(this, "audience", void 0);
62
62
  /** Status tracking variable used to check the liveness of connections */
63
63
  (0, _defineProperty2.default)(this, "isAlive", true);
64
+ /** The `user` claim of the token the client authenticated with */
65
+ (0, _defineProperty2.default)(this, "tokenUser", void 0);
66
+ /** Timestamp (ms) at which the current authentication expires */
67
+ (0, _defineProperty2.default)(this, "authExpiresAt", void 0);
68
+ /** Closes the connection if the client does not authenticate in time */
69
+ (0, _defineProperty2.default)(this, "authTimeout", void 0);
64
70
  /** Timer used to track interval between client pinging */
65
71
  (0, _defineProperty2.default)(this, "pingInterval", void 0);
66
72
  this.id = (0, _crypto.randomUUID)();
@@ -91,9 +97,15 @@ let SocketClient = exports.SocketClient = /*#__PURE__*/function () {
91
97
  (0, _report.reportInfo)({
92
98
  message: `Client connected [${this.id}]`
93
99
  });
100
+ // Optionally close connections that do not authenticate in time
101
+ if (options.authTimeoutMs && options.authTimeoutMs > 0) {
102
+ this.authTimeout = setTimeout(() => {
103
+ if (!this.authenticated) this.close(4401, 'Authentication required');
104
+ }, options.authTimeoutMs);
105
+ }
94
106
  // On socket close, deregister from clients list
95
- this.ws.on('close', () => {
96
- this.handleClose.bind(this)().catch(error => {
107
+ this.ws.on('close', (code, reason) => {
108
+ this.handleClose.bind(this)(code, reason?.toString()).catch(error => {
97
109
  (0, _report.reportError)(error);
98
110
  });
99
111
  });
@@ -184,6 +196,19 @@ let SocketClient = exports.SocketClient = /*#__PURE__*/function () {
184
196
  }
185
197
  }
186
198
 
199
+ /**
200
+ * Close the connection
201
+ * @param code - WebSocket close code (4000-4999 are free for applications, e.g. 4401 / 4403)
202
+ * @param reason - Human readable reason, sent to the client
203
+ */
204
+ }, {
205
+ key: "close",
206
+ value: function close(code = 1000, reason) {
207
+ this.clearTimeouts();
208
+ if (this.authTimeout) clearTimeout(this.authTimeout);
209
+ this.ws.close(code, reason);
210
+ }
211
+
187
212
  /** Get the client authentication status */
188
213
  }, {
189
214
  key: "isAuthenticated",
@@ -199,7 +224,9 @@ let SocketClient = exports.SocketClient = /*#__PURE__*/function () {
199
224
  userId: this.userId,
200
225
  deviceId: this.deviceId,
201
226
  tokenId: this.tokenId,
202
- audience: this.audience
227
+ audience: this.audience,
228
+ user: this.tokenUser,
229
+ expiresAt: this.authExpiresAt
203
230
  };
204
231
  return undefined;
205
232
  }
@@ -258,6 +285,9 @@ let SocketClient = exports.SocketClient = /*#__PURE__*/function () {
258
285
  const payload = await (0, _jwt.jwtVerify)(token);
259
286
  this.setUserData(payload);
260
287
  this.authenticated = true;
288
+ this.tokenUser = payload.user;
289
+ this.authExpiresAt = payload.exp * 1000;
290
+ if (this.authTimeout) clearTimeout(this.authTimeout);
261
291
  // Time remaining before token expiration
262
292
  const authExpiration = payload.exp * 1000 - Date.now();
263
293
  // Clear previously created timers
@@ -365,6 +395,7 @@ let SocketClient = exports.SocketClient = /*#__PURE__*/function () {
365
395
  value: async function handleClose(code, reason) {
366
396
  delete SocketClient.socketClients[this.id];
367
397
  this.clearTimeouts();
398
+ if (this.authTimeout) clearTimeout(this.authTimeout);
368
399
  // Stop ping process
369
400
  if (this.pingInterval) clearInterval(this.pingInterval);
370
401
  // Run all the shutdown callbacks
@@ -1 +1 @@
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 * @param webSocket - The WebSocket instance\n * @param _request - The incoming HTTP request (reserved for future use)\n * @param options - Socket client configuration options\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,IA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C,IAAI,CAAC+E,aAAa,CAAC,CAAC;MACpB;MACA,IAAI,IAAI,CAAC1C,YAAY,EAAEsD,aAAa,CAAC,IAAI,CAACtD,YAAY,CAAC;MACvD;MACA,MAAMT,eAAe,GAAG,MAAMC,OAAO,CAACC,UAAU,CAC9C,IAAI,CAACpB,iBAAiB,CAACqB,GAAG,CAAEC,QAAQ,IAAKA,QAAQ,CAAC,IAAI,CAAC,CACzD,CAAC;MACDJ,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;AAlKD;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","authTimeoutMs","authTimeout","setTimeout","authenticated","close","on","code","reason","handleClose","bind","toString","catch","error","reportError","severity","LogSeverity","WARNING","data","handleMessage","callbackResults","Promise","allSettled","map","callback","forEach","result","status","pingInterval","setInterval","isAlive","terminate","ping","process","env","WS_PING_INTERVAL","parseInt","_createClass2","key","value","sendMessage","type","payload","send","noAuth","audience","includes","DEFAULT_MESSAGE_AUDIENCE","JSON","stringify","clearTimeouts","clearTimeout","isAuthenticated","getUser","userId","deviceId","tokenId","user","tokenUser","expiresAt","authExpiresAt","undefined","parseMessage","authenticate","handle","handleError","token","WebError","errorCode","jwtVerify","setUserData","exp","authExpiration","now","authRenewTimer","authExpireTimer","sub","dev","jti","aud","hint","ValidationError","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 /** The `user` claim of the token the client authenticated with */\n private tokenUser: undefined | Record<string, unknown>;\n /** Timestamp (ms) at which the current authentication expires */\n private authExpiresAt: undefined | number;\n /** Closes the connection if the client does not authenticate in time */\n private authTimeout: NodeJS.Timeout | undefined;\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 * @param webSocket - The WebSocket instance\n * @param _request - The incoming HTTP request (reserved for future use)\n * @param options - Socket client configuration options\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 // Optionally close connections that do not authenticate in time\n if (options.authTimeoutMs && options.authTimeoutMs > 0) {\n this.authTimeout = setTimeout(() => {\n if (!this.authenticated) this.close(4401, 'Authentication required');\n }, options.authTimeoutMs);\n }\n // On socket close, deregister from clients list\n this.ws.on('close', (code: number, reason: Buffer) => {\n this.handleClose\n .bind(this)(code, reason?.toString())\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 /**\n * Close the connection\n * @param code - WebSocket close code (4000-4999 are free for applications, e.g. 4401 / 4403)\n * @param reason - Human readable reason, sent to the client\n */\n public close(code = 1000, reason?: string): void {\n this.clearTimeouts();\n if (this.authTimeout) clearTimeout(this.authTimeout);\n this.ws.close(code, reason);\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 user: this.tokenUser,\n expiresAt: this.authExpiresAt\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 this.tokenUser = payload.user;\n this.authExpiresAt = payload.exp * 1000;\n if (this.authTimeout) clearTimeout(this.authTimeout);\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?: number, reason?: string): Promise<void> {\n delete SocketClient.socketClients[this.id];\n this.clearTimeouts();\n if (this.authTimeout) clearTimeout(this.authTimeout);\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,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AU,CAC9C,IAAI,CAAC5B,iBAAiB,CAAC6B,GAAG,CAAEC,QAAQ,IAAKA,QAAQ,CAAC,IAAI,CAAC,CACzD,CAAC;MACDJ,eAAe,CAACK,OAAO,CAAEC,MAAM,IAAK;QAClC,IAAIA,MAAM,CAACC,MAAM,KAAK,UAAU,EAAE,IAAAb,mBAAW,EAACY,MAAM,CAAClB,MAAM,CAAC;MAC9D,CAAC,CAAC;MACF,IAAAR,kBAAU,EAAC;QACTV,OAAO,EAAE,wBAAwB,IAAI,CAACN,EAAE,GAAG;QAC3CkC,IAAI,EAAE;UAAEX,IAAI;UAAEC;QAAO;MACvB,CAAC,CAAC;IACJ;EAAC;IAAA8B,GAAA;IAAAC,KAAA,EA/OD,SAAc4C,gBAAgBA,CAAA,EAAqB;MACjD,OAAO,IAAI,CAACpF,aAAa;IAC3B;;IAEA;EAAA;IAAAuC,GAAA;IAAAC,KAAA,EACA,SAAc6C,eAAeA,CAACpG,EAAU,EAA4B;MAClE,OAAO,IAAI,CAACe,aAAa,CAACf,EAAE,CAAC;IAC/B;EAAC;AAAA;AA9KD;AAAA,IAAAD,gBAAA,CAAAD,OAAA,EADWN,YAAY,mBAE0B,CAAC,CAAC","ignoreList":[]}
@@ -11,6 +11,8 @@ export interface SocketClientOptions {
11
11
  authCallbacks?: SocketClientCallback | Array<SocketClientCallback>;
12
12
  /** Callback function that are called when the client connection is terminated */
13
13
  shutdownCallbacks?: SocketClientCallback | Array<SocketClientCallback>;
14
+ /** Close the connection with code 4401 if the client has not authenticated after this many ms (default: never) */
15
+ authTimeoutMs?: number;
14
16
  }
15
17
  /** Socket Message abstract typing */
16
18
  export interface SocketMessage<T = unknown> {
@@ -50,4 +52,8 @@ export interface SocketUser {
50
52
  tokenId: string;
51
53
  /** Audience included in the token */
52
54
  audience: Array<string>;
55
+ /** The `user` claim of the authentication token (application data such as role or organisation) */
56
+ user?: Record<string, unknown>;
57
+ /** Timestamp (ms) at which the authentication expires */
58
+ expiresAt?: number;
53
59
  }
@@ -1 +1 @@
1
- {"version":3,"file":"SocketClient.types.js","names":[],"sources":["../../../src/entities/SocketClient/SocketClient.types.ts"],"sourcesContent":["import { SocketClient } from './SocketClient';\nimport { MessageHandler } from 'entities/MessageHandler';\n\nexport type SocketClientCallback = (\n client: SocketClient\n) => void | Promise<void>;\n\n/** SocketClient creation option */\nexport interface SocketClientOptions {\n /** List of message handlers that are registered with the client */\n handlers: Array<MessageHandler>;\n /** Callback function that are called when the client is created */\n initCallbacks?: SocketClientCallback | Array<SocketClientCallback>;\n /** Callback function that are called when the client successfully authenticates */\n authCallbacks?: SocketClientCallback | Array<SocketClientCallback>;\n /** Callback function that are called when the client connection is terminated */\n shutdownCallbacks?: SocketClientCallback | Array<SocketClientCallback>;\n}\n\n/** Socket Message abstract typing */\nexport interface SocketMessage<T = unknown> {\n /** A string that identifies the message type */\n type: string;\n /** Free-form data payload of the message */\n payload: T;\n}\n\n/** SocketMessage used by client for authentication */\nexport interface SocketAuthenticationMessage extends SocketMessage {\n /** Sting that identifies the message type */\n type: 'authenticate';\n /** Data payload of the message */\n payload: {\n /** Authentication token */\n token: string;\n };\n}\n\n/** Options for sending a message with the client */\nexport interface SocketClientSendMessageOptions {\n /** Send message event if the user is not authenticated */\n noAuth?: boolean;\n /** Audience that the authenticated user must have on his token to continue */\n audience?: string;\n}\n\n/** Map of socket clients connected to the server */\nexport interface SocketClientList {\n [id: string]: SocketClient;\n}\n\n/** User that authenticated though his socket */\nexport interface SocketUser {\n /** ID od the user */\n userId: string;\n /** ID of the device */\n deviceId: string;\n /** ID of the token used */\n tokenId: string;\n /** Audience included in the token */\n audience: Array<string>;\n}\n"],"mappings":"","ignoreList":[]}
1
+ {"version":3,"file":"SocketClient.types.js","names":[],"sources":["../../../src/entities/SocketClient/SocketClient.types.ts"],"sourcesContent":["import { SocketClient } from './SocketClient';\nimport { MessageHandler } from 'entities/MessageHandler';\n\nexport type SocketClientCallback = (\n client: SocketClient\n) => void | Promise<void>;\n\n/** SocketClient creation option */\nexport interface SocketClientOptions {\n /** List of message handlers that are registered with the client */\n handlers: Array<MessageHandler>;\n /** Callback function that are called when the client is created */\n initCallbacks?: SocketClientCallback | Array<SocketClientCallback>;\n /** Callback function that are called when the client successfully authenticates */\n authCallbacks?: SocketClientCallback | Array<SocketClientCallback>;\n /** Callback function that are called when the client connection is terminated */\n shutdownCallbacks?: SocketClientCallback | Array<SocketClientCallback>;\n /** Close the connection with code 4401 if the client has not authenticated after this many ms (default: never) */\n authTimeoutMs?: number;\n}\n\n/** Socket Message abstract typing */\nexport interface SocketMessage<T = unknown> {\n /** A string that identifies the message type */\n type: string;\n /** Free-form data payload of the message */\n payload: T;\n}\n\n/** SocketMessage used by client for authentication */\nexport interface SocketAuthenticationMessage extends SocketMessage {\n /** Sting that identifies the message type */\n type: 'authenticate';\n /** Data payload of the message */\n payload: {\n /** Authentication token */\n token: string;\n };\n}\n\n/** Options for sending a message with the client */\nexport interface SocketClientSendMessageOptions {\n /** Send message event if the user is not authenticated */\n noAuth?: boolean;\n /** Audience that the authenticated user must have on his token to continue */\n audience?: string;\n}\n\n/** Map of socket clients connected to the server */\nexport interface SocketClientList {\n [id: string]: SocketClient;\n}\n\n/** User that authenticated though his socket */\nexport interface SocketUser {\n /** ID od the user */\n userId: string;\n /** ID of the device */\n deviceId: string;\n /** ID of the token used */\n tokenId: string;\n /** Audience included in the token */\n audience: Array<string>;\n /** The `user` claim of the authentication token (application data such as role or organisation) */\n user?: Record<string, unknown>;\n /** Timestamp (ms) at which the authentication expires */\n expiresAt?: number;\n}\n"],"mappings":"","ignoreList":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-server-engine",
3
- "version": "2.0.2",
3
+ "version": "2.1.0",
4
4
  "description": "Framework used to develop backend services. This package ships with a lot of features to standardize the creation of services, letting you focus on the business logic.",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {