@azure/web-pubsub-express 1.0.6-alpha.20250224.1 → 1.0.6

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.
Files changed (86) hide show
  1. package/README.md +53 -46
  2. package/dist/browser/cloudEventsDispatcher.d.ts +15 -0
  3. package/dist/browser/cloudEventsDispatcher.d.ts.map +1 -0
  4. package/dist/browser/cloudEventsDispatcher.js +411 -0
  5. package/dist/browser/cloudEventsDispatcher.js.map +1 -0
  6. package/dist/browser/cloudEventsProtocols.d.ts +411 -0
  7. package/dist/browser/cloudEventsProtocols.d.ts.map +1 -0
  8. package/dist/browser/cloudEventsProtocols.js +4 -0
  9. package/dist/browser/cloudEventsProtocols.js.map +1 -0
  10. package/dist/browser/enum/MqttErrorCodes/mqttDisconnectReasonCode.d.ts +180 -0
  11. package/dist/browser/enum/MqttErrorCodes/mqttDisconnectReasonCode.d.ts.map +1 -0
  12. package/dist/browser/enum/MqttErrorCodes/mqttDisconnectReasonCode.js +183 -0
  13. package/dist/browser/enum/MqttErrorCodes/mqttDisconnectReasonCode.js.map +1 -0
  14. package/dist/browser/enum/MqttErrorCodes/mqttV311ConnectReturnCode.d.ts +31 -0
  15. package/dist/browser/enum/MqttErrorCodes/mqttV311ConnectReturnCode.d.ts.map +1 -0
  16. package/dist/browser/enum/MqttErrorCodes/mqttV311ConnectReturnCode.js +34 -0
  17. package/dist/browser/enum/MqttErrorCodes/mqttV311ConnectReturnCode.js.map +1 -0
  18. package/dist/browser/enum/MqttErrorCodes/mqttV500ConnectReasonCode.d.ts +112 -0
  19. package/dist/browser/enum/MqttErrorCodes/mqttV500ConnectReasonCode.d.ts.map +1 -0
  20. package/dist/browser/enum/MqttErrorCodes/mqttV500ConnectReasonCode.js +115 -0
  21. package/dist/browser/enum/MqttErrorCodes/mqttV500ConnectReasonCode.js.map +1 -0
  22. package/dist/browser/index.d.ts +6 -0
  23. package/dist/browser/index.d.ts.map +1 -0
  24. package/dist/browser/index.js +8 -0
  25. package/dist/browser/index.js.map +1 -0
  26. package/dist/browser/logger.d.ts +7 -0
  27. package/dist/browser/logger.d.ts.map +1 -0
  28. package/dist/browser/logger.js +10 -0
  29. package/dist/browser/logger.js.map +1 -0
  30. package/dist/browser/package.json +3 -0
  31. package/dist/browser/utils.d.ts +6 -0
  32. package/dist/browser/utils.d.ts.map +1 -0
  33. package/dist/browser/utils.js +53 -0
  34. package/dist/browser/utils.js.map +1 -0
  35. package/dist/browser/webPubSubEventHandler.d.ts +46 -0
  36. package/dist/browser/webPubSubEventHandler.d.ts.map +1 -0
  37. package/dist/browser/webPubSubEventHandler.js +73 -0
  38. package/dist/browser/webPubSubEventHandler.js.map +1 -0
  39. package/dist/commonjs/index.js +14 -880
  40. package/dist/commonjs/index.js.map +1 -1
  41. package/dist/commonjs/webPubSubEventHandler.d.ts +7 -8
  42. package/dist/commonjs/webPubSubEventHandler.d.ts.map +1 -1
  43. package/dist/commonjs/webPubSubEventHandler.js +7 -8
  44. package/dist/commonjs/webPubSubEventHandler.js.map +1 -1
  45. package/dist/esm/webPubSubEventHandler.d.ts +7 -8
  46. package/dist/esm/webPubSubEventHandler.d.ts.map +1 -1
  47. package/dist/esm/webPubSubEventHandler.js +7 -8
  48. package/dist/esm/webPubSubEventHandler.js.map +1 -1
  49. package/dist/react-native/cloudEventsDispatcher.d.ts +15 -0
  50. package/dist/react-native/cloudEventsDispatcher.d.ts.map +1 -0
  51. package/dist/react-native/cloudEventsDispatcher.js +411 -0
  52. package/dist/react-native/cloudEventsDispatcher.js.map +1 -0
  53. package/dist/react-native/cloudEventsProtocols.d.ts +411 -0
  54. package/dist/react-native/cloudEventsProtocols.d.ts.map +1 -0
  55. package/dist/react-native/cloudEventsProtocols.js +4 -0
  56. package/dist/react-native/cloudEventsProtocols.js.map +1 -0
  57. package/dist/react-native/enum/MqttErrorCodes/mqttDisconnectReasonCode.d.ts +180 -0
  58. package/dist/react-native/enum/MqttErrorCodes/mqttDisconnectReasonCode.d.ts.map +1 -0
  59. package/dist/react-native/enum/MqttErrorCodes/mqttDisconnectReasonCode.js +183 -0
  60. package/dist/react-native/enum/MqttErrorCodes/mqttDisconnectReasonCode.js.map +1 -0
  61. package/dist/react-native/enum/MqttErrorCodes/mqttV311ConnectReturnCode.d.ts +31 -0
  62. package/dist/react-native/enum/MqttErrorCodes/mqttV311ConnectReturnCode.d.ts.map +1 -0
  63. package/dist/react-native/enum/MqttErrorCodes/mqttV311ConnectReturnCode.js +34 -0
  64. package/dist/react-native/enum/MqttErrorCodes/mqttV311ConnectReturnCode.js.map +1 -0
  65. package/dist/react-native/enum/MqttErrorCodes/mqttV500ConnectReasonCode.d.ts +112 -0
  66. package/dist/react-native/enum/MqttErrorCodes/mqttV500ConnectReasonCode.d.ts.map +1 -0
  67. package/dist/react-native/enum/MqttErrorCodes/mqttV500ConnectReasonCode.js +115 -0
  68. package/dist/react-native/enum/MqttErrorCodes/mqttV500ConnectReasonCode.js.map +1 -0
  69. package/dist/react-native/index.d.ts +6 -0
  70. package/dist/react-native/index.d.ts.map +1 -0
  71. package/dist/react-native/index.js +8 -0
  72. package/dist/react-native/index.js.map +1 -0
  73. package/dist/react-native/logger.d.ts +7 -0
  74. package/dist/react-native/logger.d.ts.map +1 -0
  75. package/dist/react-native/logger.js +10 -0
  76. package/dist/react-native/logger.js.map +1 -0
  77. package/dist/react-native/package.json +3 -0
  78. package/dist/react-native/utils.d.ts +6 -0
  79. package/dist/react-native/utils.d.ts.map +1 -0
  80. package/dist/react-native/utils.js +53 -0
  81. package/dist/react-native/utils.js.map +1 -0
  82. package/dist/react-native/webPubSubEventHandler.d.ts +46 -0
  83. package/dist/react-native/webPubSubEventHandler.d.ts.map +1 -0
  84. package/dist/react-native/webPubSubEventHandler.js +73 -0
  85. package/dist/react-native/webPubSubEventHandler.js.map +1 -0
  86. package/package.json +33 -17
@@ -1,882 +1,16 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var node_url = require('node:url');
6
- var logger$1 = require('@azure/logger');
7
-
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MqttDisconnectReasonCode = exports.MqttV500ConnectReasonCode = exports.MqttV311ConnectReturnCode = exports.WebPubSubEventHandler = void 0;
4
+ const tslib_1 = require("tslib");
8
5
  // Copyright (c) Microsoft Corporation.
9
6
  // Licensed under the MIT License.
10
- function isJsonObject(obj) {
11
- return obj && typeof obj === "object" && !Array.isArray(obj);
12
- }
13
- function toBase64JsonString(obj) {
14
- return Buffer.from(JSON.stringify(obj)).toString("base64");
15
- }
16
- function fromBase64JsonString(base64String) {
17
- if (base64String === undefined) {
18
- return {};
19
- }
20
- try {
21
- const buf = Buffer.from(base64String, "base64").toString();
22
- const parsed = JSON.parse(buf);
23
- return isJsonObject(parsed) ? parsed : {};
24
- }
25
- catch (e) {
26
- console.warn("Unexpected state format:" + e);
27
- return {};
28
- }
29
- }
30
- function getHttpHeader(req, key) {
31
- if (!key)
32
- return undefined;
33
- // According to https://nodejs.org/api/http.html#http_class_http_incomingmessage, header names are always lower-cased
34
- const value = req.headers[key.toLowerCase()];
35
- if (value === undefined) {
36
- return undefined;
37
- }
38
- if (typeof value === "string") {
39
- return value;
40
- }
41
- return value[0];
42
- }
43
- function readRequestBody(req) {
44
- return new Promise(function (resolve, reject) {
45
- const chunks = [];
46
- req.on("data", function (chunk) {
47
- chunks.push(chunk);
48
- });
49
- req.on("end", function () {
50
- const buffer = Buffer.concat(chunks);
51
- resolve(buffer);
52
- });
53
- // reject on request error
54
- req.on("error", function (err) {
55
- // This is not a "Second reject", just a different sort of failure
56
- reject(err);
57
- });
58
- });
59
- }
60
-
61
- // Copyright (c) Microsoft Corporation.
62
- // Licensed under the MIT License.
63
- /**
64
- * The \@azure/logger configuration for this package.
65
- *
66
- * @internal
67
- */
68
- const logger = logger$1.createClientLogger("web-pubsub-express");
69
-
70
- // Copyright (c) Microsoft Corporation.
71
- // Licensed under the MIT License.
72
- /**
73
- * MQTT 3.1.1 Connect Return Codes.
74
- */
75
- exports.MqttV311ConnectReturnCode = void 0;
76
- (function (MqttV311ConnectReturnCode) {
77
- /**
78
- * 0x01: Connection refused, unacceptable protocol version
79
- * The Server does not support the level of the MQTT protocol requested by the Client.
80
- */
81
- MqttV311ConnectReturnCode[MqttV311ConnectReturnCode["UnacceptableProtocolVersion"] = 1] = "UnacceptableProtocolVersion";
82
- /**
83
- * 0x02: Connection refused, identifier rejected
84
- * The Client identifier is correct UTF-8 but not allowed by the Server.
85
- */
86
- MqttV311ConnectReturnCode[MqttV311ConnectReturnCode["IdentifierRejected"] = 2] = "IdentifierRejected";
87
- /**
88
- * 0x03: Connection refused, server unavailable
89
- * The Network Connection has been made but the MQTT service is unavailable.
90
- */
91
- MqttV311ConnectReturnCode[MqttV311ConnectReturnCode["ServerUnavailable"] = 3] = "ServerUnavailable";
92
- /**
93
- * 0x04: Connection refused, bad user name or password
94
- * The data in the user name or password is malformed.
95
- */
96
- MqttV311ConnectReturnCode[MqttV311ConnectReturnCode["BadUsernameOrPassword"] = 4] = "BadUsernameOrPassword";
97
- /**
98
- * 0x05: Connection refused, not authorized
99
- * The Client is not authorized to connect.
100
- */
101
- MqttV311ConnectReturnCode[MqttV311ConnectReturnCode["NotAuthorized"] = 5] = "NotAuthorized";
102
- })(exports.MqttV311ConnectReturnCode || (exports.MqttV311ConnectReturnCode = {}));
103
-
104
- // Copyright (c) Microsoft Corporation.
105
- // Licensed under the MIT License.
106
- /**
107
- * MQTT Connect Reason Codes
108
- * These codes represent the reasons for the outcome of an MQTT CONNECT packet as per MQTT 5.0 specification.
109
- */
110
- exports.MqttV500ConnectReasonCode = void 0;
111
- (function (MqttV500ConnectReasonCode) {
112
- /**
113
- * 0x80 - Unspecified error
114
- * Description: The Server does not wish to reveal the reason for the failure, or none of the other Reason Codes apply.
115
- */
116
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["UnspecifiedError"] = 128] = "UnspecifiedError";
117
- /**
118
- * 0x81 - Malformed Packet
119
- * Description: Data within the CONNECT packet could not be correctly parsed.
120
- */
121
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["MalformedPacket"] = 129] = "MalformedPacket";
122
- /**
123
- * 0x82 - Protocol Error
124
- * Description: Data in the CONNECT packet does not conform to this specification.
125
- */
126
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["ProtocolError"] = 130] = "ProtocolError";
127
- /**
128
- * 0x83 - Implementation specific error
129
- * Description: The CONNECT is valid but is not accepted by this Server.
130
- */
131
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["ImplementationSpecificError"] = 131] = "ImplementationSpecificError";
132
- /**
133
- * 0x84 - Unsupported Protocol Version
134
- * Description: The Server does not support the version of the MQTT protocol requested by the Client.
135
- */
136
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["UnsupportedProtocolVersion"] = 132] = "UnsupportedProtocolVersion";
137
- /**
138
- * 0x85 - Client Identifier not valid
139
- * Description: The Client Identifier is a valid string but is not allowed by the Server.
140
- */
141
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["ClientIdentifierNotValid"] = 133] = "ClientIdentifierNotValid";
142
- /**
143
- * 0x86 - Bad User Name or Password
144
- * Description: The Server does not accept the User Name or Password specified by the Client.
145
- */
146
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["BadUserNameOrPassword"] = 134] = "BadUserNameOrPassword";
147
- /**
148
- * 0x87 - Not authorized
149
- * Description: The Client is not authorized to connect.
150
- */
151
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["NotAuthorized"] = 135] = "NotAuthorized";
152
- /**
153
- * 0x88 - Server unavailable
154
- * Description: The MQTT Server is not available.
155
- */
156
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["ServerUnavailable"] = 136] = "ServerUnavailable";
157
- /**
158
- * 0x89 - Server busy
159
- * Description: The Server is busy. Try again later.
160
- */
161
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["ServerBusy"] = 137] = "ServerBusy";
162
- /**
163
- * 0x8A - Banned
164
- * Description: This Client has been banned by administrative action. Contact the server administrator.
165
- */
166
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["Banned"] = 138] = "Banned";
167
- /**
168
- * 0x8C - Bad authentication method
169
- * Description: The authentication method is not supported or does not match the authentication method currently in use.
170
- */
171
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["BadAuthenticationMethod"] = 140] = "BadAuthenticationMethod";
172
- /**
173
- * 0x90 - Topic Name invalid
174
- * Description: The Will Topic Name is not malformed, but is not accepted by this Server.
175
- */
176
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["TopicNameInvalid"] = 144] = "TopicNameInvalid";
177
- /**
178
- * 0x95 - Packet too large
179
- * Description: The CONNECT packet exceeded the maximum permissible size.
180
- */
181
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["PacketTooLarge"] = 149] = "PacketTooLarge";
182
- /**
183
- * 0x97 - Quota exceeded
184
- * Description: An implementation or administrative imposed limit has been exceeded.
185
- */
186
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["QuotaExceeded"] = 151] = "QuotaExceeded";
187
- /**
188
- * 0x99 - Payload format invalid
189
- * Description: The Will Payload does not match the specified Payload Format Indicator.
190
- */
191
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["PayloadFormatInvalid"] = 153] = "PayloadFormatInvalid";
192
- /**
193
- * 0x9A - Retain not supported
194
- * Description: The Server does not support retained messages, and Will Retain was set to 1.
195
- */
196
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["RetainNotSupported"] = 154] = "RetainNotSupported";
197
- /**
198
- * 0x9B - QoS not supported
199
- * Description: The Server does not support the QoS set in Will QoS.
200
- */
201
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["QosNotSupported"] = 155] = "QosNotSupported";
202
- /**
203
- * 0x9C - Use another server
204
- * Description: The Client should temporarily use another server.
205
- */
206
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["UseAnotherServer"] = 156] = "UseAnotherServer";
207
- /**
208
- * 0x9D - Server moved
209
- * Description: The Client should permanently use another server.
210
- */
211
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["ServerMoved"] = 157] = "ServerMoved";
212
- /**
213
- * 0x9F - Connection rate exceeded
214
- * Description: The connection rate limit has been exceeded.
215
- */
216
- MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["ConnectionRateExceeded"] = 159] = "ConnectionRateExceeded";
217
- })(exports.MqttV500ConnectReasonCode || (exports.MqttV500ConnectReasonCode = {}));
218
-
219
- // Copyright (c) Microsoft Corporation.
220
- // Licensed under the MIT License.
221
- var EventType;
222
- (function (EventType) {
223
- EventType[EventType["Connect"] = 0] = "Connect";
224
- EventType[EventType["Connected"] = 1] = "Connected";
225
- EventType[EventType["Disconnected"] = 2] = "Disconnected";
226
- EventType[EventType["UserEvent"] = 3] = "UserEvent";
227
- })(EventType || (EventType = {}));
228
- function getConnectResponseHandler(connectRequest, response) {
229
- const states = connectRequest.context.states;
230
- let modified = false;
231
- const handler = {
232
- setState(name, value) {
233
- states[name] = value;
234
- modified = true;
235
- },
236
- success(res) {
237
- if (modified) {
238
- response.setHeader("ce-connectionState", toBase64JsonString(states));
239
- }
240
- if (res === undefined) {
241
- response.statusCode = 204;
242
- response.end();
243
- }
244
- else {
245
- response.statusCode = 200;
246
- response.setHeader("Content-Type", "application/json; charset=utf-8");
247
- response.end(JSON.stringify(res));
248
- }
249
- },
250
- fail(code, detail) {
251
- handleConnectErrorResponse(connectRequest, response, code, detail);
252
- },
253
- failWith(res) {
254
- if ("mqtt" in res) {
255
- response.statusCode = getStatusCodeFromMqttConnectCode(res.mqtt.code);
256
- response.setHeader("Content-Type", "application/json; charset=utf-8");
257
- response.end(JSON.stringify(res));
258
- }
259
- else {
260
- handleConnectErrorResponse(connectRequest, response, res.code, res.detail);
261
- }
262
- },
263
- };
264
- return handler;
265
- }
266
- function getUserEventResponseHandler(userRequest, response) {
267
- const states = userRequest.context.states;
268
- let modified = false;
269
- const handler = {
270
- setState(name, value) {
271
- modified = true;
272
- states[name] = value;
273
- },
274
- success(data, dataType) {
275
- response.statusCode = 200;
276
- if (modified) {
277
- response.setHeader("ce-connectionState", toBase64JsonString(states));
278
- }
279
- switch (dataType) {
280
- case "json":
281
- response.setHeader("Content-Type", "application/json; charset=utf-8");
282
- break;
283
- case "text":
284
- response.setHeader("Content-Type", "text/plain; charset=utf-8");
285
- break;
286
- default:
287
- response.setHeader("Content-Type", "application/octet-stream");
288
- break;
289
- }
290
- response.end(data !== null && data !== void 0 ? data : "");
291
- },
292
- fail(code, detail) {
293
- response.statusCode = code;
294
- response.end(detail !== null && detail !== void 0 ? detail : "");
295
- },
296
- };
297
- return handler;
298
- }
299
- function getContext(request, origin) {
300
- const baseContext = {
301
- signature: getHttpHeader(request, "ce-signature"),
302
- userId: getHttpHeader(request, "ce-userid"),
303
- hub: getHttpHeader(request, "ce-hub"),
304
- connectionId: getHttpHeader(request, "ce-connectionid"),
305
- eventName: getHttpHeader(request, "ce-eventname"),
306
- origin: origin,
307
- states: fromBase64JsonString(getHttpHeader(request, "ce-connectionstate")),
308
- clientProtocol: "default",
309
- };
310
- if (isMqttRequest(request)) {
311
- const mqttProperties = {
312
- physicalConnectionId: getHttpHeader(request, "ce-physicalConnectionId"),
313
- sessionId: getHttpHeader(request, "ce-sessionId"),
314
- };
315
- return Object.assign(Object.assign({}, baseContext), { clientProtocol: "mqtt", mqtt: mqttProperties });
316
- }
317
- else {
318
- return baseContext;
319
- }
320
- }
321
- function tryGetWebPubSubEvent(req) {
322
- // check ce-type to see if it is a valid WebPubSub CloudEvent request
323
- const prefix = "azure.webpubsub.";
324
- const connect = "azure.webpubsub.sys.connect";
325
- const connected = "azure.webpubsub.sys.connected";
326
- const disconnectd = "azure.webpubsub.sys.disconnected";
327
- const userPrefix = "azure.webpubsub.user.";
328
- const type = getHttpHeader(req, "ce-type");
329
- if (!(type === null || type === void 0 ? void 0 : type.startsWith(prefix))) {
330
- return undefined;
331
- }
332
- if (type.startsWith(userPrefix)) {
333
- return EventType.UserEvent;
334
- }
335
- switch (type) {
336
- case connect:
337
- return EventType.Connect;
338
- case connected:
339
- return EventType.Connected;
340
- case disconnectd:
341
- return EventType.Disconnected;
342
- default:
343
- return undefined;
344
- }
345
- }
346
- function getStatusCodeFromMqttConnectCode(mqttConnectCode) {
347
- if (mqttConnectCode < 0x80) {
348
- switch (mqttConnectCode) {
349
- case exports.MqttV311ConnectReturnCode.UnacceptableProtocolVersion:
350
- case exports.MqttV311ConnectReturnCode.IdentifierRejected:
351
- return 400; // BadRequest
352
- case exports.MqttV311ConnectReturnCode.ServerUnavailable:
353
- return 503; // ServiceUnavailable
354
- case exports.MqttV311ConnectReturnCode.BadUsernameOrPassword:
355
- case exports.MqttV311ConnectReturnCode.NotAuthorized:
356
- return 401; // Unauthorized
357
- default:
358
- logger.warning(`Invalid MQTT connect return code: ${mqttConnectCode}.`);
359
- return 500; // InternalServerError
360
- }
361
- }
362
- else {
363
- switch (mqttConnectCode) {
364
- case exports.MqttV500ConnectReasonCode.NotAuthorized:
365
- case exports.MqttV500ConnectReasonCode.BadUserNameOrPassword:
366
- return 401; // Unauthorized
367
- case exports.MqttV500ConnectReasonCode.ClientIdentifierNotValid:
368
- case exports.MqttV500ConnectReasonCode.MalformedPacket:
369
- case exports.MqttV500ConnectReasonCode.UnsupportedProtocolVersion:
370
- case exports.MqttV500ConnectReasonCode.BadAuthenticationMethod:
371
- case exports.MqttV500ConnectReasonCode.TopicNameInvalid:
372
- case exports.MqttV500ConnectReasonCode.PayloadFormatInvalid:
373
- case exports.MqttV500ConnectReasonCode.ImplementationSpecificError:
374
- case exports.MqttV500ConnectReasonCode.PacketTooLarge:
375
- case exports.MqttV500ConnectReasonCode.RetainNotSupported:
376
- case exports.MqttV500ConnectReasonCode.QosNotSupported:
377
- return 400; // BadRequest
378
- case exports.MqttV500ConnectReasonCode.QuotaExceeded:
379
- case exports.MqttV500ConnectReasonCode.ConnectionRateExceeded:
380
- return 429; // TooManyRequests
381
- case exports.MqttV500ConnectReasonCode.Banned:
382
- return 403; // Forbidden
383
- case exports.MqttV500ConnectReasonCode.UseAnotherServer:
384
- case exports.MqttV500ConnectReasonCode.ServerMoved:
385
- case exports.MqttV500ConnectReasonCode.ServerUnavailable:
386
- case exports.MqttV500ConnectReasonCode.ServerBusy:
387
- case exports.MqttV500ConnectReasonCode.UnspecifiedError:
388
- return 500; // InternalServerError
389
- default:
390
- logger.warning(`Invalid MQTT connect return code: ${mqttConnectCode}.`);
391
- return 500; // InternalServerError
392
- }
393
- }
394
- }
395
- function getMqttConnectCodeFromStatusCode(statusCode, protocolVersion) {
396
- if (protocolVersion === 4) {
397
- switch (statusCode) {
398
- case 400:
399
- return exports.MqttV311ConnectReturnCode.BadUsernameOrPassword;
400
- case 401:
401
- return exports.MqttV311ConnectReturnCode.NotAuthorized;
402
- case 500:
403
- return exports.MqttV311ConnectReturnCode.ServerUnavailable;
404
- default:
405
- logger.warning(`Unsupported HTTP Status Code: ${statusCode}.`);
406
- return exports.MqttV311ConnectReturnCode.ServerUnavailable;
407
- }
408
- }
409
- else if (protocolVersion === 5) {
410
- switch (statusCode) {
411
- case 400:
412
- return exports.MqttV500ConnectReasonCode.BadUserNameOrPassword;
413
- case 401:
414
- return exports.MqttV500ConnectReasonCode.NotAuthorized;
415
- case 500:
416
- return exports.MqttV500ConnectReasonCode.UnspecifiedError;
417
- default:
418
- logger.warning(`Unsupported HTTP Status Code: ${statusCode}.`);
419
- return exports.MqttV500ConnectReasonCode.UnspecifiedError;
420
- }
421
- }
422
- else {
423
- logger.warning(`Invalid MQTT protocol version: ${protocolVersion}.`);
424
- return exports.MqttV311ConnectReturnCode.UnacceptableProtocolVersion;
425
- }
426
- }
427
- function handleConnectErrorResponse(connectRequest, response, code, detail) {
428
- const isMqttReq = connectRequest.context.clientProtocol === "mqtt";
429
- if (isMqttReq) {
430
- const protocolVersion = connectRequest.mqtt.protocolVersion;
431
- const mqttErrorResponse = {
432
- mqtt: {
433
- code: getMqttConnectCodeFromStatusCode(code, protocolVersion),
434
- reason: detail,
435
- },
436
- };
437
- response.statusCode = code;
438
- response.setHeader("Content-Type", "application/json; charset=utf-8");
439
- response.end(JSON.stringify(mqttErrorResponse));
440
- }
441
- else {
442
- response.statusCode = code;
443
- response.end(detail !== null && detail !== void 0 ? detail : "");
444
- }
445
- }
446
- function isWebPubSubRequest(req) {
447
- return getHttpHeader(req, "ce-awpsversion") !== undefined;
448
- }
449
- function isMqttRequest(req) {
450
- const subprotocol = getHttpHeader(req, "ce-subprotocol");
451
- const physicalConnectionId = getHttpHeader(req, "ce-physicalConnectionId");
452
- return (subprotocol !== undefined &&
453
- subprotocol.toLowerCase().includes("mqtt") &&
454
- physicalConnectionId !== undefined);
455
- }
456
- async function readUserEventRequest(request, origin) {
457
- const contentTypeheader = getHttpHeader(request, "content-type");
458
- if (contentTypeheader === undefined) {
459
- return undefined;
460
- }
461
- const contentType = contentTypeheader.split(";")[0].trim();
462
- switch (contentType) {
463
- case "application/octet-stream":
464
- return {
465
- context: getContext(request, origin),
466
- data: await readRequestBody(request),
467
- dataType: "binary",
468
- };
469
- case "application/json":
470
- return {
471
- context: getContext(request, origin),
472
- data: JSON.parse((await readRequestBody(request)).toString()),
473
- dataType: "json",
474
- };
475
- case "text/plain":
476
- return {
477
- context: getContext(request, origin),
478
- data: (await readRequestBody(request)).toString(),
479
- dataType: "text",
480
- };
481
- default:
482
- return undefined;
483
- }
484
- }
485
- async function readSystemEventRequest(request, origin) {
486
- const body = (await readRequestBody(request)).toString();
487
- const parsedRequest = JSON.parse(body);
488
- parsedRequest.context = getContext(request, origin);
489
- return parsedRequest;
490
- }
491
- /**
492
- * @internal
493
- */
494
- class CloudEventsDispatcher {
495
- constructor(hub, eventHandler) {
496
- this.hub = hub;
497
- this.eventHandler = eventHandler;
498
- this._allowAll = true;
499
- this._allowedOrigins = [];
500
- if (Array.isArray(eventHandler)) {
501
- throw new Error("Unexpected WebPubSubEventHandlerOptions");
502
- }
503
- if ((eventHandler === null || eventHandler === void 0 ? void 0 : eventHandler.allowedEndpoints) !== undefined) {
504
- this._allowedOrigins = eventHandler.allowedEndpoints.map((endpoint) => new node_url.URL(endpoint).host.toLowerCase());
505
- this._allowAll = false;
506
- }
507
- }
508
- handlePreflight(req, res) {
509
- if (!isWebPubSubRequest(req)) {
510
- return false;
511
- }
512
- const origin = getHttpHeader(req, "webhook-request-origin");
513
- if (origin === undefined) {
514
- logger.warning("Expecting webhook-request-origin header.");
515
- res.statusCode = 400;
516
- }
517
- else if (this._allowAll) {
518
- res.setHeader("WebHook-Allowed-Origin", "*");
519
- }
520
- else {
521
- // service to do the check
522
- res.setHeader("WebHook-Allowed-Origin", this._allowedOrigins);
523
- }
524
- res.end();
525
- return true;
526
- }
527
- async handleRequest(request, response) {
528
- var _a, _b, _c, _d;
529
- if (!isWebPubSubRequest(request)) {
530
- return false;
531
- }
532
- // check if it is a valid WebPubSub cloud events
533
- const origin = getHttpHeader(request, "webhook-request-origin");
534
- if (origin === undefined) {
535
- return false;
536
- }
537
- const eventType = tryGetWebPubSubEvent(request);
538
- if (eventType === undefined) {
539
- return false;
540
- }
541
- // check if hub matches
542
- const hub = getHttpHeader(request, "ce-hub");
543
- if ((hub === null || hub === void 0 ? void 0 : hub.toUpperCase()) !== this.hub.toUpperCase()) {
544
- return false;
545
- }
546
- const isMqtt = isMqttRequest(request);
547
- // No need to read body if handler is not specified
548
- switch (eventType) {
549
- case EventType.Connect:
550
- if (!((_a = this.eventHandler) === null || _a === void 0 ? void 0 : _a.handleConnect)) {
551
- if (isMqtt)
552
- response.statusCode = 204;
553
- response.end();
554
- return true;
555
- }
556
- break;
557
- case EventType.Connected:
558
- if (!((_b = this.eventHandler) === null || _b === void 0 ? void 0 : _b.onConnected)) {
559
- response.end();
560
- return true;
561
- }
562
- break;
563
- case EventType.Disconnected:
564
- if (!((_c = this.eventHandler) === null || _c === void 0 ? void 0 : _c.onDisconnected)) {
565
- response.end();
566
- return true;
567
- }
568
- break;
569
- case EventType.UserEvent:
570
- if (!((_d = this.eventHandler) === null || _d === void 0 ? void 0 : _d.handleUserEvent)) {
571
- response.end();
572
- return true;
573
- }
574
- break;
575
- default:
576
- logger.warning(`Unknown EventType ${eventType}`);
577
- return false;
578
- }
579
- switch (eventType) {
580
- case EventType.Connect: {
581
- const connectRequest = isMqtt
582
- ? await readSystemEventRequest(request, origin)
583
- : await readSystemEventRequest(request, origin);
584
- // service passes out query property, assign it to queries
585
- connectRequest.queries = connectRequest.query;
586
- logger.verbose(connectRequest);
587
- this.eventHandler.handleConnect(connectRequest, getConnectResponseHandler(connectRequest, response));
588
- return true;
589
- }
590
- case EventType.Connected: {
591
- // for unblocking events, we responds to the service as early as possible
592
- response.end();
593
- const connectedRequest = await readSystemEventRequest(request, origin);
594
- logger.verbose(connectedRequest);
595
- this.eventHandler.onConnected(connectedRequest);
596
- return true;
597
- }
598
- case EventType.Disconnected: {
599
- // for unblocking events, we responds to the service as early as possible
600
- response.end();
601
- const disconnectedRequest = isMqtt
602
- ? await readSystemEventRequest(request, origin)
603
- : await readSystemEventRequest(request, origin);
604
- logger.verbose(disconnectedRequest);
605
- this.eventHandler.onDisconnected(disconnectedRequest);
606
- return true;
607
- }
608
- case EventType.UserEvent: {
609
- const userRequest = await readUserEventRequest(request, origin);
610
- if (userRequest === undefined) {
611
- logger.warning(`Unsupported content type ${getHttpHeader(request, "content-type")}`);
612
- return false;
613
- }
614
- logger.verbose(userRequest);
615
- this.eventHandler.handleUserEvent(userRequest, getUserEventResponseHandler(userRequest, response));
616
- return true;
617
- }
618
- default:
619
- logger.warning(`Unknown EventType ${eventType}`);
620
- return false;
621
- }
622
- }
623
- }
624
-
625
- // Copyright (c) Microsoft Corporation.
626
- // Licensed under the MIT License.
627
- /**
628
- * The handler to handle incoming CloudEvents messages
629
- */
630
- class WebPubSubEventHandler {
631
- /**
632
- * Creates an instance of a WebPubSubEventHandler for handling incoming CloudEvents messages.
633
- *
634
- * Example usage:
635
- * ```ts
636
- * import express from "express";
637
- * import { WebPubSubEventHandler } from "@azure/web-pubsub-express";
638
- * const endpoint = "https://xxxx.webpubsubdev.azure.com"
639
- * const handler = new WebPubSubEventHandler('chat', {
640
- * handleConnect: (req, res) => {
641
- * console.log(JSON.stringify(req));
642
- * return {};
643
- * },
644
- * onConnected: req => {
645
- * console.log(JSON.stringify(req));
646
- * },
647
- * handleUserEvent: (req, res) => {
648
- * console.log(JSON.stringify(req));
649
- * res.success("Hey " + req.data, req.dataType);
650
- * };
651
- * allowedEndpoints: [ endpoint ]
652
- * },
653
- * });
654
- * ```
655
- *
656
- * @param hub - The name of the hub to listen to
657
- * @param options - Options to configure the event handler
658
- */
659
- constructor(hub, options) {
660
- var _a;
661
- this.hub = hub;
662
- const path = ((_a = options === null || options === void 0 ? void 0 : options.path) !== null && _a !== void 0 ? _a : `/api/webpubsub/hubs/${hub}/`).toLowerCase();
663
- this.path = path.endsWith("/") ? path : path + "/";
664
- this._cloudEventsHandler = new CloudEventsDispatcher(this.hub, options);
665
- }
666
- /**
667
- * Get the middleware to process the CloudEvents requests
668
- */
669
- getMiddleware() {
670
- return async (req, res, next) => {
671
- // Request originalUrl can contain query while baseUrl + path not
672
- let requestUrl = (req.baseUrl + req.path).toLowerCase();
673
- // normalize the Url
674
- requestUrl = requestUrl.endsWith("/") ? requestUrl : requestUrl + "/";
675
- if (requestUrl.startsWith(this.path)) {
676
- if (req.method === "OPTIONS") {
677
- if (this._cloudEventsHandler.handlePreflight(req, res)) {
678
- return;
679
- }
680
- }
681
- else if (req.method === "POST") {
682
- try {
683
- if (await this._cloudEventsHandler.handleRequest(req, res)) {
684
- return;
685
- }
686
- }
687
- catch (err) {
688
- next(err);
689
- return;
690
- }
691
- }
692
- }
693
- next();
694
- };
695
- }
696
- }
697
-
698
- // Copyright (c) Microsoft Corporation.
699
- // Licensed under the MIT License.
700
- /**
701
- * MQTT 5.0 Disconnect Reason Codes.
702
- */
703
- exports.MqttDisconnectReasonCode = void 0;
704
- (function (MqttDisconnectReasonCode) {
705
- /**
706
- * 0x00 - Normal disconnection
707
- * Sent by: Client or Server
708
- * Description: Close the connection normally. Do not send the Will Message.
709
- */
710
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["NormalDisconnection"] = 0] = "NormalDisconnection";
711
- /**
712
- * 0x04 - Disconnect with Will Message
713
- * Sent by: Client
714
- * Description: The Client wishes to disconnect but requires that the Server also publishes its Will Message.
715
- */
716
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["DisconnectWithWillMessage"] = 4] = "DisconnectWithWillMessage";
717
- /**
718
- * 0x80 - Unspecified error
719
- * Sent by: Client or Server
720
- * Description: The Connection is closed but the sender either does not wish to reveal the reason, or none of the other Reason Codes apply.
721
- */
722
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["UnspecifiedError"] = 128] = "UnspecifiedError";
723
- /**
724
- * 0x81 - Malformed Packet
725
- * Sent by: Client or Server
726
- * Description: The received packet does not conform to this specification.
727
- */
728
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["MalformedPacket"] = 129] = "MalformedPacket";
729
- /**
730
- * 0x82 - Protocol Error
731
- * Sent by: Client or Server
732
- * Description: An unexpected or out of order packet was received.
733
- */
734
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["ProtocolError"] = 130] = "ProtocolError";
735
- /**
736
- * 0x83 - Implementation specific error
737
- * Sent by: Client or Server
738
- * Description: The packet received is valid but cannot be processed by this implementation.
739
- */
740
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["ImplementationSpecificError"] = 131] = "ImplementationSpecificError";
741
- /**
742
- * 0x87 - Not authorized
743
- * Sent by: Server
744
- * Description: The request is not authorized.
745
- */
746
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["NotAuthorized"] = 135] = "NotAuthorized";
747
- /**
748
- * 0x89 - Server busy
749
- * Sent by: Server
750
- * Description: The Server is busy and cannot continue processing requests from this Client.
751
- */
752
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["ServerBusy"] = 137] = "ServerBusy";
753
- /**
754
- * 0x8B - Server shutting down
755
- * Sent by: Server
756
- * Description: The Server is shutting down.
757
- */
758
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["ServerShuttingDown"] = 139] = "ServerShuttingDown";
759
- /**
760
- * 0x8D - Keep Alive timeout
761
- * Sent by: Server
762
- * Description: The Connection is closed because no packet has been received for 1.5 times the Keepalive time.
763
- */
764
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["KeepAliveTimeout"] = 141] = "KeepAliveTimeout";
765
- /**
766
- * 0x8E - Session taken over
767
- * Sent by: Server
768
- * Description: Another Connection using the same ClientID has connected causing this Connection to be closed.
769
- */
770
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["SessionTakenOver"] = 142] = "SessionTakenOver";
771
- /**
772
- * 0x8F - Topic Filter invalid
773
- * Sent by: Server
774
- * Description: The Topic Filter is correctly formed, but is not accepted by this Server.
775
- */
776
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["TopicFilterInvalid"] = 143] = "TopicFilterInvalid";
777
- /**
778
- * 0x90 - Topic Name invalid
779
- * Sent by: Client or Server
780
- * Description: The Topic Name is correctly formed, but is not accepted by this Client or Server.
781
- */
782
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["TopicNameInvalid"] = 144] = "TopicNameInvalid";
783
- /**
784
- * 0x93 - Receive Maximum exceeded
785
- * Sent by: Client or Server
786
- * Description: The Client or Server has received more than Receive Maximum publication for which it has not sent PUBACK or PUBCOMP.
787
- */
788
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["ReceiveMaximumExceeded"] = 147] = "ReceiveMaximumExceeded";
789
- /**
790
- * 0x94 - Topic Alias invalid
791
- * Sent by: Client or Server
792
- * Description: The Client or Server has received a PUBLISH packet containing a Topic Alias which is greater than the Maximum Topic Alias it sent in the CONNECT or CONNACK packet.
793
- */
794
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["TopicAliasInvalid"] = 148] = "TopicAliasInvalid";
795
- /**
796
- * 0x95 - Packet too large
797
- * Sent by: Client or Server
798
- * Description: The packet size is greater than Maximum Packet Size for this Client or Server.
799
- */
800
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["PacketTooLarge"] = 149] = "PacketTooLarge";
801
- /**
802
- * 0x96 - Message rate too high
803
- * Sent by: Client or Server
804
- * Description: The received data rate is too high.
805
- */
806
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["MessageRateTooHigh"] = 150] = "MessageRateTooHigh";
807
- /**
808
- * 0x97 - Quota exceeded
809
- * Sent by: Client or Server
810
- * Description: An implementation or administrative imposed limit has been exceeded.
811
- */
812
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["QuotaExceeded"] = 151] = "QuotaExceeded";
813
- /**
814
- * 0x98 - Administrative action
815
- * Sent by: Client or Server
816
- * Description: The Connection is closed due to an administrative action.
817
- */
818
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["AdministrativeAction"] = 152] = "AdministrativeAction";
819
- /**
820
- * 0x99 - Payload format invalid
821
- * Sent by: Client or Server
822
- * Description: The payload format does not match the one specified by the Payload Format Indicator.
823
- */
824
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["PayloadFormatInvalid"] = 153] = "PayloadFormatInvalid";
825
- /**
826
- * 0x9A - Retain not supported
827
- * Sent by: Server
828
- * Description: The Server does not support retained messages.
829
- */
830
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["RetainNotSupported"] = 154] = "RetainNotSupported";
831
- /**
832
- * 0x9B - QoS not supported
833
- * Sent by: Server
834
- * Description: The Client specified a QoS greater than the QoS specified in a Maximum QoS in the CONNACK.
835
- */
836
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["QosNotSupported"] = 155] = "QosNotSupported";
837
- /**
838
- * 0x9C - Use another server
839
- * Sent by: Server
840
- * Description: The Client should temporarily change its Server.
841
- */
842
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["UseAnotherServer"] = 156] = "UseAnotherServer";
843
- /**
844
- * 0x9D - Server moved
845
- * Sent by: Server
846
- * Description: The Server is moved and the Client should permanently change its server location.
847
- */
848
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["ServerMoved"] = 157] = "ServerMoved";
849
- /**
850
- * 0x9E - Shared Subscriptions not supported
851
- * Sent by: Server
852
- * Description: The Server does not support Shared Subscriptions.
853
- */
854
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["SharedSubscriptionsNotSupported"] = 158] = "SharedSubscriptionsNotSupported";
855
- /**
856
- * 0x9F - Connection rate exceeded
857
- * Sent by: Server
858
- * Description: This connection is closed because the connection rate is too high.
859
- */
860
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["ConnectionRateExceeded"] = 159] = "ConnectionRateExceeded";
861
- /**
862
- * 0xA0 - Maximum connect time
863
- * Sent by: Server
864
- * Description: The maximum connection time authorized for this connection has been exceeded.
865
- */
866
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["MaximumConnectTime"] = 160] = "MaximumConnectTime";
867
- /**
868
- * 0xA1 - Subscription Identifiers not supported
869
- * Sent by: Server
870
- * Description: The Server does not support Subscription Identifiers; the subscription is not accepted.
871
- */
872
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["SubscriptionIdentifiersNotSupported"] = 161] = "SubscriptionIdentifiersNotSupported";
873
- /**
874
- * 0xA2 - Wildcard Subscriptions not supported
875
- * Sent by: Server
876
- * Description: The Server does not support Wildcard Subscriptions; the subscription is not accepted.
877
- */
878
- MqttDisconnectReasonCode[MqttDisconnectReasonCode["WildcardSubscriptionsNotSupported"] = 162] = "WildcardSubscriptionsNotSupported";
879
- })(exports.MqttDisconnectReasonCode || (exports.MqttDisconnectReasonCode = {}));
880
-
881
- exports.WebPubSubEventHandler = WebPubSubEventHandler;
882
- //# sourceMappingURL=index.js.map
7
+ var webPubSubEventHandler_js_1 = require("./webPubSubEventHandler.js");
8
+ Object.defineProperty(exports, "WebPubSubEventHandler", { enumerable: true, get: function () { return webPubSubEventHandler_js_1.WebPubSubEventHandler; } });
9
+ tslib_1.__exportStar(require("./cloudEventsProtocols.js"), exports);
10
+ var mqttV311ConnectReturnCode_js_1 = require("./enum/MqttErrorCodes/mqttV311ConnectReturnCode.js");
11
+ Object.defineProperty(exports, "MqttV311ConnectReturnCode", { enumerable: true, get: function () { return mqttV311ConnectReturnCode_js_1.MqttV311ConnectReturnCode; } });
12
+ var mqttV500ConnectReasonCode_js_1 = require("./enum/MqttErrorCodes/mqttV500ConnectReasonCode.js");
13
+ Object.defineProperty(exports, "MqttV500ConnectReasonCode", { enumerable: true, get: function () { return mqttV500ConnectReasonCode_js_1.MqttV500ConnectReasonCode; } });
14
+ var mqttDisconnectReasonCode_js_1 = require("./enum/MqttErrorCodes/mqttDisconnectReasonCode.js");
15
+ Object.defineProperty(exports, "MqttDisconnectReasonCode", { enumerable: true, get: function () { return mqttDisconnectReasonCode_js_1.MqttDisconnectReasonCode; } });
16
+ //# sourceMappingURL=index.js.map