@homebridge/hap-nodejs 2.3.1-beta.1 → 2.3.1-beta.2

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 (252) hide show
  1. package/README.md +13 -4
  2. package/dist/accessories/types.d.ts +0 -1
  3. package/dist/hap.d.ts +1 -1
  4. package/dist/hap.js +6 -4
  5. package/dist/hap.js.map +1 -1
  6. package/dist/index.d.ts +4 -1
  7. package/dist/index.js +4 -0
  8. package/dist/index.js.map +1 -1
  9. package/dist/internal-types.d.ts +6 -7
  10. package/dist/internal-types.js +1 -5
  11. package/dist/internal-types.js.map +1 -1
  12. package/dist/lib/Accessory.d.ts +49 -25
  13. package/dist/lib/Accessory.js +275 -171
  14. package/dist/lib/Accessory.js.map +1 -1
  15. package/dist/lib/Advertiser.d.ts +37 -18
  16. package/dist/lib/Advertiser.js +143 -62
  17. package/dist/lib/Advertiser.js.map +1 -1
  18. package/dist/lib/Bridge.d.ts +1 -2
  19. package/dist/lib/Bridge.js +1 -1
  20. package/dist/lib/Characteristic.d.ts +19 -20
  21. package/dist/lib/Characteristic.js +187 -153
  22. package/dist/lib/Characteristic.js.map +1 -1
  23. package/dist/lib/HAPServer.d.ts +19 -13
  24. package/dist/lib/HAPServer.js +266 -220
  25. package/dist/lib/HAPServer.js.map +1 -1
  26. package/dist/lib/Service.d.ts +11 -11
  27. package/dist/lib/Service.js +54 -37
  28. package/dist/lib/Service.js.map +1 -1
  29. package/dist/lib/camera/RTPProxy.d.ts +5 -5
  30. package/dist/lib/camera/RTPProxy.js +48 -23
  31. package/dist/lib/camera/RTPProxy.js.map +1 -1
  32. package/dist/lib/camera/RTPStreamManagement.d.ts +18 -13
  33. package/dist/lib/camera/RTPStreamManagement.js +247 -216
  34. package/dist/lib/camera/RTPStreamManagement.js.map +1 -1
  35. package/dist/lib/camera/RecordingManagement.d.ts +13 -13
  36. package/dist/lib/camera/RecordingManagement.js +115 -110
  37. package/dist/lib/camera/RecordingManagement.js.map +1 -1
  38. package/dist/lib/camera/index.d.ts +0 -1
  39. package/dist/lib/controller/AdaptiveLightingController.d.ts +41 -36
  40. package/dist/lib/controller/AdaptiveLightingController.js +126 -113
  41. package/dist/lib/controller/AdaptiveLightingController.js.map +1 -1
  42. package/dist/lib/controller/CameraController.d.ts +17 -17
  43. package/dist/lib/controller/CameraController.js +30 -26
  44. package/dist/lib/controller/CameraController.js.map +1 -1
  45. package/dist/lib/controller/Controller.d.ts +15 -12
  46. package/dist/lib/controller/Controller.js +0 -1
  47. package/dist/lib/controller/Controller.js.map +1 -1
  48. package/dist/lib/controller/DoorbellController.d.ts +6 -6
  49. package/dist/lib/controller/DoorbellController.js +10 -3
  50. package/dist/lib/controller/DoorbellController.js.map +1 -1
  51. package/dist/lib/controller/RemoteController.d.ts +46 -27
  52. package/dist/lib/controller/RemoteController.js +268 -178
  53. package/dist/lib/controller/RemoteController.js.map +1 -1
  54. package/dist/lib/controller/index.d.ts +0 -1
  55. package/dist/lib/datastream/DataStreamManagement.d.ts +6 -6
  56. package/dist/lib/datastream/DataStreamManagement.js +30 -26
  57. package/dist/lib/datastream/DataStreamManagement.js.map +1 -1
  58. package/dist/lib/datastream/DataStreamParser.d.ts +25 -8
  59. package/dist/lib/datastream/DataStreamParser.js +124 -105
  60. package/dist/lib/datastream/DataStreamParser.js.map +1 -1
  61. package/dist/lib/datastream/DataStreamServer.d.ts +47 -23
  62. package/dist/lib/datastream/DataStreamServer.js +285 -143
  63. package/dist/lib/datastream/DataStreamServer.js.map +1 -1
  64. package/dist/lib/datastream/index.d.ts +0 -1
  65. package/dist/lib/definitions/CharacteristicDefinitions.d.ts +0 -1
  66. package/dist/lib/definitions/CharacteristicDefinitions.js +578 -578
  67. package/dist/lib/definitions/CharacteristicDefinitions.js.map +1 -1
  68. package/dist/lib/definitions/ServiceDefinitions.d.ts +0 -1
  69. package/dist/lib/definitions/index.d.ts +0 -1
  70. package/dist/lib/gen/HomeKit.d.ts +0 -1
  71. package/dist/lib/model/AccessoryInfo.d.ts +5 -6
  72. package/dist/lib/model/AccessoryInfo.js +23 -19
  73. package/dist/lib/model/AccessoryInfo.js.map +1 -1
  74. package/dist/lib/model/ControllerStorage.d.ts +11 -5
  75. package/dist/lib/model/ControllerStorage.js +34 -8
  76. package/dist/lib/model/ControllerStorage.js.map +1 -1
  77. package/dist/lib/model/HAPFileStorage.d.ts +20 -2
  78. package/dist/lib/model/HAPFileStorage.js +59 -10
  79. package/dist/lib/model/HAPFileStorage.js.map +1 -1
  80. package/dist/lib/model/HAPStorage.d.ts +0 -1
  81. package/dist/lib/model/HAPStorage.js +6 -3
  82. package/dist/lib/model/HAPStorage.js.map +1 -1
  83. package/dist/lib/model/IdentifierCache.d.ts +2 -3
  84. package/dist/lib/model/IdentifierCache.js +26 -13
  85. package/dist/lib/model/IdentifierCache.js.map +1 -1
  86. package/dist/lib/tv/AccessControlManagement.d.ts +6 -7
  87. package/dist/lib/tv/AccessControlManagement.js +13 -19
  88. package/dist/lib/tv/AccessControlManagement.js.map +1 -1
  89. package/dist/lib/util/checkName.d.ts +1 -2
  90. package/dist/lib/util/checkName.js.map +1 -1
  91. package/dist/lib/util/clone.d.ts +0 -1
  92. package/dist/lib/util/clone.js.map +1 -1
  93. package/dist/lib/util/color-utils.d.ts +1 -2
  94. package/dist/lib/util/color-utils.js +1 -1
  95. package/dist/lib/util/errors.d.ts +4 -0
  96. package/dist/lib/util/errors.js +15 -0
  97. package/dist/lib/util/errors.js.map +1 -0
  98. package/dist/lib/util/eventedhttp.d.ts +63 -19
  99. package/dist/lib/util/eventedhttp.js +170 -48
  100. package/dist/lib/util/eventedhttp.js.map +1 -1
  101. package/dist/lib/util/hapCrypto.d.ts +1 -2
  102. package/dist/lib/util/hapCrypto.js +6 -7
  103. package/dist/lib/util/hapCrypto.js.map +1 -1
  104. package/dist/lib/util/hapStatusError.d.ts +0 -1
  105. package/dist/lib/util/hapStatusError.js +1 -1
  106. package/dist/lib/util/hapStatusError.js.map +1 -1
  107. package/dist/lib/util/net-utils.d.ts +1 -2
  108. package/dist/lib/util/net-utils.js +6 -7
  109. package/dist/lib/util/net-utils.js.map +1 -1
  110. package/dist/lib/util/once.d.ts +0 -1
  111. package/dist/lib/util/promise-utils.d.ts +1 -2
  112. package/dist/lib/util/promise-utils.js +2 -1
  113. package/dist/lib/util/promise-utils.js.map +1 -1
  114. package/dist/lib/util/request-util.d.ts +4 -4
  115. package/dist/lib/util/request-util.js +29 -28
  116. package/dist/lib/util/request-util.js.map +1 -1
  117. package/dist/lib/util/time.d.ts +1 -2
  118. package/dist/lib/util/time.js.map +1 -1
  119. package/dist/lib/util/tlv.d.ts +4 -4
  120. package/dist/lib/util/tlv.js +16 -5
  121. package/dist/lib/util/tlv.js.map +1 -1
  122. package/dist/lib/util/uuid.d.ts +5 -2
  123. package/dist/lib/util/uuid.js +6 -0
  124. package/dist/lib/util/uuid.js.map +1 -1
  125. package/dist/types.d.ts +20 -17
  126. package/dist/types.js +0 -1
  127. package/dist/types.js.map +1 -1
  128. package/package.json +8 -14
  129. package/dist/accessories/AirConditioner_accessory.d.ts +0 -2
  130. package/dist/accessories/AirConditioner_accessory.d.ts.map +0 -1
  131. package/dist/accessories/AirConditioner_accessory.js +0 -126
  132. package/dist/accessories/AirConditioner_accessory.js.map +0 -1
  133. package/dist/accessories/AppleTVRemote_accessory.d.ts +0 -2
  134. package/dist/accessories/AppleTVRemote_accessory.d.ts.map +0 -1
  135. package/dist/accessories/AppleTVRemote_accessory.js +0 -146
  136. package/dist/accessories/AppleTVRemote_accessory.js.map +0 -1
  137. package/dist/accessories/Camera_accessory.d.ts +0 -2
  138. package/dist/accessories/Camera_accessory.d.ts.map +0 -1
  139. package/dist/accessories/Camera_accessory.js +0 -562
  140. package/dist/accessories/Camera_accessory.js.map +0 -1
  141. package/dist/accessories/Fan_accessory.d.ts +0 -2
  142. package/dist/accessories/Fan_accessory.d.ts.map +0 -1
  143. package/dist/accessories/Fan_accessory.js +0 -71
  144. package/dist/accessories/Fan_accessory.js.map +0 -1
  145. package/dist/accessories/GarageDoorOpener_accessory.d.ts +0 -2
  146. package/dist/accessories/GarageDoorOpener_accessory.d.ts.map +0 -1
  147. package/dist/accessories/GarageDoorOpener_accessory.js +0 -76
  148. package/dist/accessories/GarageDoorOpener_accessory.js.map +0 -1
  149. package/dist/accessories/Light-AdaptiveLighting_accessory.d.ts +0 -2
  150. package/dist/accessories/Light-AdaptiveLighting_accessory.d.ts.map +0 -1
  151. package/dist/accessories/Light-AdaptiveLighting_accessory.js +0 -103
  152. package/dist/accessories/Light-AdaptiveLighting_accessory.js.map +0 -1
  153. package/dist/accessories/Light_accessory.d.ts +0 -2
  154. package/dist/accessories/Light_accessory.d.ts.map +0 -1
  155. package/dist/accessories/Light_accessory.js +0 -143
  156. package/dist/accessories/Light_accessory.js.map +0 -1
  157. package/dist/accessories/Lock_accessory.d.ts +0 -2
  158. package/dist/accessories/Lock_accessory.d.ts.map +0 -1
  159. package/dist/accessories/Lock_accessory.js +0 -74
  160. package/dist/accessories/Lock_accessory.js.map +0 -1
  161. package/dist/accessories/MotionSensor_accessory.d.ts +0 -2
  162. package/dist/accessories/MotionSensor_accessory.d.ts.map +0 -1
  163. package/dist/accessories/MotionSensor_accessory.js +0 -43
  164. package/dist/accessories/MotionSensor_accessory.js.map +0 -1
  165. package/dist/accessories/Outlet_accessory.d.ts +0 -2
  166. package/dist/accessories/Outlet_accessory.d.ts.map +0 -1
  167. package/dist/accessories/Outlet_accessory.js +0 -77
  168. package/dist/accessories/Outlet_accessory.js.map +0 -1
  169. package/dist/accessories/SmartSpeaker_accessory.d.ts +0 -2
  170. package/dist/accessories/SmartSpeaker_accessory.d.ts.map +0 -1
  171. package/dist/accessories/SmartSpeaker_accessory.js +0 -42
  172. package/dist/accessories/SmartSpeaker_accessory.js.map +0 -1
  173. package/dist/accessories/Sprinkler_accessory.d.ts +0 -2
  174. package/dist/accessories/Sprinkler_accessory.d.ts.map +0 -1
  175. package/dist/accessories/Sprinkler_accessory.js +0 -126
  176. package/dist/accessories/Sprinkler_accessory.js.map +0 -1
  177. package/dist/accessories/TV_accessory.d.ts +0 -2
  178. package/dist/accessories/TV_accessory.d.ts.map +0 -1
  179. package/dist/accessories/TV_accessory.js +0 -99
  180. package/dist/accessories/TV_accessory.js.map +0 -1
  181. package/dist/accessories/TemperatureSensor_accessory.d.ts +0 -2
  182. package/dist/accessories/TemperatureSensor_accessory.d.ts.map +0 -1
  183. package/dist/accessories/TemperatureSensor_accessory.js +0 -42
  184. package/dist/accessories/TemperatureSensor_accessory.js.map +0 -1
  185. package/dist/accessories/Wi-FiRouter_accessory.d.ts +0 -3
  186. package/dist/accessories/Wi-FiRouter_accessory.d.ts.map +0 -1
  187. package/dist/accessories/Wi-FiRouter_accessory.js +0 -14
  188. package/dist/accessories/Wi-FiRouter_accessory.js.map +0 -1
  189. package/dist/accessories/Wi-FiSatellite_accessory.d.ts +0 -3
  190. package/dist/accessories/Wi-FiSatellite_accessory.d.ts.map +0 -1
  191. package/dist/accessories/Wi-FiSatellite_accessory.js +0 -16
  192. package/dist/accessories/Wi-FiSatellite_accessory.js.map +0 -1
  193. package/dist/accessories/gstreamer-audioProducer.d.ts +0 -25
  194. package/dist/accessories/gstreamer-audioProducer.d.ts.map +0 -1
  195. package/dist/accessories/gstreamer-audioProducer.js +0 -145
  196. package/dist/accessories/gstreamer-audioProducer.js.map +0 -1
  197. package/dist/accessories/types.d.ts.map +0 -1
  198. package/dist/hap.d.ts.map +0 -1
  199. package/dist/index.d.ts.map +0 -1
  200. package/dist/internal-types.d.ts.map +0 -1
  201. package/dist/lib/Accessory.d.ts.map +0 -1
  202. package/dist/lib/Advertiser.d.ts.map +0 -1
  203. package/dist/lib/Bridge.d.ts.map +0 -1
  204. package/dist/lib/Characteristic.d.ts.map +0 -1
  205. package/dist/lib/HAPServer.d.ts.map +0 -1
  206. package/dist/lib/Service.d.ts.map +0 -1
  207. package/dist/lib/camera/RTPProxy.d.ts.map +0 -1
  208. package/dist/lib/camera/RTPStreamManagement.d.ts.map +0 -1
  209. package/dist/lib/camera/RecordingManagement.d.ts.map +0 -1
  210. package/dist/lib/camera/index.d.ts.map +0 -1
  211. package/dist/lib/controller/AdaptiveLightingController.d.ts.map +0 -1
  212. package/dist/lib/controller/CameraController.d.ts.map +0 -1
  213. package/dist/lib/controller/Controller.d.ts.map +0 -1
  214. package/dist/lib/controller/DoorbellController.d.ts.map +0 -1
  215. package/dist/lib/controller/RemoteController.d.ts.map +0 -1
  216. package/dist/lib/controller/index.d.ts.map +0 -1
  217. package/dist/lib/datastream/DataStreamManagement.d.ts.map +0 -1
  218. package/dist/lib/datastream/DataStreamParser.d.ts.map +0 -1
  219. package/dist/lib/datastream/DataStreamServer.d.ts.map +0 -1
  220. package/dist/lib/datastream/index.d.ts.map +0 -1
  221. package/dist/lib/definitions/CharacteristicDefinitions.d.ts.map +0 -1
  222. package/dist/lib/definitions/ServiceDefinitions.d.ts.map +0 -1
  223. package/dist/lib/definitions/generate-definitions.d.ts +0 -34
  224. package/dist/lib/definitions/generate-definitions.d.ts.map +0 -1
  225. package/dist/lib/definitions/generate-definitions.js +0 -624
  226. package/dist/lib/definitions/generate-definitions.js.map +0 -1
  227. package/dist/lib/definitions/generator-configuration.d.ts +0 -22
  228. package/dist/lib/definitions/generator-configuration.d.ts.map +0 -1
  229. package/dist/lib/definitions/generator-configuration.js +0 -674
  230. package/dist/lib/definitions/generator-configuration.js.map +0 -1
  231. package/dist/lib/definitions/index.d.ts.map +0 -1
  232. package/dist/lib/gen/HomeKit.d.ts.map +0 -1
  233. package/dist/lib/model/AccessoryInfo.d.ts.map +0 -1
  234. package/dist/lib/model/ControllerStorage.d.ts.map +0 -1
  235. package/dist/lib/model/HAPFileStorage.d.ts.map +0 -1
  236. package/dist/lib/model/HAPStorage.d.ts.map +0 -1
  237. package/dist/lib/model/IdentifierCache.d.ts.map +0 -1
  238. package/dist/lib/tv/AccessControlManagement.d.ts.map +0 -1
  239. package/dist/lib/util/checkName.d.ts.map +0 -1
  240. package/dist/lib/util/clone.d.ts.map +0 -1
  241. package/dist/lib/util/color-utils.d.ts.map +0 -1
  242. package/dist/lib/util/eventedhttp.d.ts.map +0 -1
  243. package/dist/lib/util/hapCrypto.d.ts.map +0 -1
  244. package/dist/lib/util/hapStatusError.d.ts.map +0 -1
  245. package/dist/lib/util/net-utils.d.ts.map +0 -1
  246. package/dist/lib/util/once.d.ts.map +0 -1
  247. package/dist/lib/util/promise-utils.d.ts.map +0 -1
  248. package/dist/lib/util/request-util.d.ts.map +0 -1
  249. package/dist/lib/util/time.d.ts.map +0 -1
  250. package/dist/lib/util/tlv.d.ts.map +0 -1
  251. package/dist/lib/util/uuid.d.ts.map +0 -1
  252. package/dist/types.d.ts.map +0 -1
@@ -2,16 +2,23 @@
2
2
  import assert from 'node:assert';
3
3
  import { Buffer } from 'node:buffer';
4
4
  import crypto from 'node:crypto';
5
- import { EventEmitter, EventEmitter as NodeEventEmitter } from 'node:events';
5
+ import { EventEmitter } from 'node:events';
6
6
  import net from 'node:net';
7
7
  import createDebug from 'debug';
8
+ import { errorMessage, errorStack } from '../util/errors.js';
9
+ import { HAPConnectionEvent } from '../util/eventedhttp.js';
8
10
  import * as hapCrypto from '../util/hapCrypto.js';
9
11
  import { DataStreamParser, DataStreamReader, DataStreamWriter, Int64 } from './DataStreamParser.js';
10
12
  const debug = createDebug('HAP-NodeJS:DataStream:Server');
13
+ /**
14
+ * Tells whether a decoded value is a dictionary, which is the shape of the header and of the body of a message.
15
+ */
16
+ function isHDSMessage(value) {
17
+ return typeof value === 'object' && value !== null && !Array.isArray(value) && !Buffer.isBuffer(value);
18
+ }
11
19
  /**
12
20
  * @group HomeKit Data Streams (HDS)
13
21
  */
14
- // eslint-disable-next-line no-restricted-syntax
15
22
  export var Protocols;
16
23
  (function (Protocols) {
17
24
  Protocols["CONTROL"] = "control";
@@ -21,7 +28,6 @@ export var Protocols;
21
28
  /**
22
29
  * @group HomeKit Data Streams (HDS)
23
30
  */
24
- // eslint-disable-next-line no-restricted-syntax
25
31
  export var Topics;
26
32
  (function (Topics) {
27
33
  // control
@@ -83,7 +89,6 @@ export class HDSProtocolError extends Error {
83
89
  this.reason = reason;
84
90
  }
85
91
  }
86
- // eslint-disable-next-line no-restricted-syntax
87
92
  var ServerState;
88
93
  (function (ServerState) {
89
94
  ServerState[ServerState["UNINITIALIZED"] = 0] = "UNINITIALIZED";
@@ -91,7 +96,6 @@ var ServerState;
91
96
  ServerState[ServerState["LISTENING"] = 2] = "LISTENING";
92
97
  ServerState[ServerState["CLOSING"] = 3] = "CLOSING";
93
98
  })(ServerState || (ServerState = {}));
94
- // eslint-disable-next-line no-restricted-syntax
95
99
  var ConnectionState;
96
100
  (function (ConnectionState) {
97
101
  ConnectionState[ConnectionState["UNIDENTIFIED"] = 0] = "UNIDENTIFIED";
@@ -103,17 +107,63 @@ var ConnectionState;
103
107
  /**
104
108
  * @group HomeKit Data Streams (HDS)
105
109
  */
106
- // eslint-disable-next-line no-restricted-syntax
107
110
  export var MessageType;
108
111
  (function (MessageType) {
109
112
  MessageType[MessageType["EVENT"] = 1] = "EVENT";
110
113
  MessageType[MessageType["REQUEST"] = 2] = "REQUEST";
111
114
  MessageType[MessageType["RESPONSE"] = 3] = "RESPONSE";
112
115
  })(MessageType || (MessageType = {}));
116
+ /**
117
+ * Reads the fields of the header of a message.
118
+ *
119
+ * @returns undefined for a header which is neither an event, a request nor a response, or which has a field of the wrong type.
120
+ */
121
+ function parseHeader(header) {
122
+ const protocol = header.protocol;
123
+ const id = header.id;
124
+ const status = header.status;
125
+ if (typeof protocol !== 'string') {
126
+ return undefined;
127
+ }
128
+ if (header.event !== undefined) {
129
+ return typeof header.event === 'string'
130
+ ? {
131
+ type: MessageType.EVENT,
132
+ protocol,
133
+ topic: header.event,
134
+ id: undefined,
135
+ status: undefined,
136
+ }
137
+ : undefined;
138
+ }
139
+ else if (header.request !== undefined) {
140
+ return typeof header.request === 'string' && typeof id === 'number'
141
+ ? {
142
+ type: MessageType.REQUEST,
143
+ protocol,
144
+ topic: header.request,
145
+ id,
146
+ status: undefined,
147
+ }
148
+ : undefined;
149
+ }
150
+ else if (header.response !== undefined) {
151
+ // a response without a status is passed on like before
152
+ return typeof header.response === 'string' && typeof id === 'number' && (status === undefined || typeof status === 'number')
153
+ ? {
154
+ type: MessageType.RESPONSE,
155
+ protocol,
156
+ topic: header.response,
157
+ id,
158
+ status,
159
+ }
160
+ : undefined;
161
+ }
162
+ return undefined;
163
+ }
113
164
  /**
114
165
  * @group HomeKit Data Streams (HDS)
115
166
  */
116
- // eslint-disable-next-line no-restricted-syntax
117
167
  export var DataStreamServerEvent;
118
168
  (function (DataStreamServerEvent) {
119
169
  /**
@@ -130,24 +180,27 @@ export var DataStreamServerEvent;
130
180
  * DataStreamServer which listens for incoming tcp connections and handles identification of new connections
131
181
  * @group HomeKit Data Streams (HDS)
132
182
  */
133
- // eslint-disable-next-line ts/no-unsafe-declaration-merging
134
183
  export class DataStreamServer extends EventEmitter {
135
184
  static version = '1.0';
136
- state = 0 /* ServerState.UNINITIALIZED */;
185
+ state = ServerState.UNINITIALIZED;
137
186
  static accessoryToControllerInfo = Buffer.from('HDS-Read-Encryption-Key');
138
187
  static controllerToAccessoryInfo = Buffer.from('HDS-Write-Encryption-Key');
139
188
  tcpServer;
140
189
  tcpPort;
190
+ /**
191
+ * The prepared sessions which wait for the TCP server to start listening.
192
+ */
193
+ pendingBinds = [];
141
194
  preparedSessions = [];
142
195
  connections = [];
143
196
  removeListenersOnceClosed = false;
144
- internalEventEmitter = new NodeEventEmitter(); // used for message event and message request handlers
197
+ internalEventEmitter = new EventEmitter(); // used for message event and message request handlers
145
198
  constructor() {
146
199
  super();
147
200
  }
148
201
  /**
149
202
  * Registers a new event handler to handle incoming event messages.
150
- * The handler is only called for a connection if for the give protocol no ProtocolHandler
203
+ * The handler is only called for a connection if for the given protocol no ProtocolHandler
151
204
  * was registered on the connection level.
152
205
  *
153
206
  * @param protocol - name of the protocol to register the handler for
@@ -171,7 +224,7 @@ export class DataStreamServer extends EventEmitter {
171
224
  }
172
225
  /**
173
226
  * Registers a new request handler to handle incoming request messages.
174
- * The handler is only called for a connection if for the give protocol no ProtocolHandler
227
+ * The handler is only called for a connection if for the given protocol no ProtocolHandler
175
228
  * was registered on the connection level.
176
229
  *
177
230
  * @param protocol - name of the protocol to register the handler for
@@ -204,9 +257,8 @@ export class DataStreamServer extends EventEmitter {
204
257
  accessoryToControllerEncryptionKey,
205
258
  controllerToAccessoryEncryptionKey,
206
259
  accessoryKeySalt,
207
- connectTimeout: setTimeout(() => this.timeoutPreparedSession(preparedSession), 10000),
260
+ connectTimeout: setTimeout(() => this.timeoutPreparedSession(preparedSession), 10000).unref(),
208
261
  };
209
- preparedSession.connectTimeout.unref();
210
262
  this.preparedSessions.push(preparedSession);
211
263
  this.checkTCPServerEstablished(preparedSession, (error) => {
212
264
  if (error) {
@@ -218,7 +270,7 @@ export class DataStreamServer extends EventEmitter {
218
270
  });
219
271
  }
220
272
  timeoutPreparedSession(preparedSession) {
221
- debug('Prepared HDS session timed out out since no connection was opened for 10 seconds (%s)', preparedSession.connection.sessionID);
273
+ debug('Prepared HDS session timed out since no connection was opened for 10 seconds (%s)', preparedSession.connection.sessionID);
222
274
  const index = this.preparedSessions.indexOf(preparedSession);
223
275
  if (index >= 0) {
224
276
  this.preparedSessions.splice(index, 1);
@@ -227,49 +279,85 @@ export class DataStreamServer extends EventEmitter {
227
279
  }
228
280
  checkTCPServerEstablished(preparedSession, callback) {
229
281
  switch (this.state) {
230
- case 0 /* ServerState.UNINITIALIZED */:
282
+ case ServerState.UNINITIALIZED:
231
283
  debug('Starting up TCP server.');
232
284
  this.tcpServer = net.createServer();
233
- this.tcpServer.once('listening', this.listening.bind(this, preparedSession, callback));
285
+ this.tcpServer.once('listening', this.listening.bind(this));
234
286
  this.tcpServer.on('connection', this.onConnection.bind(this));
235
287
  this.tcpServer.on('close', this.closed.bind(this));
288
+ this.tcpServer.on('error', this.onServerError.bind(this, this.tcpServer));
289
+ this.pendingBinds.push({ preparedSession, callback });
236
290
  this.tcpServer.listen();
237
- this.state = 1 /* ServerState.BINDING */;
291
+ this.state = ServerState.BINDING;
238
292
  break;
239
- case 1 /* ServerState.BINDING */:
293
+ case ServerState.BINDING:
240
294
  debug('TCP server already running. Waiting for it to bind.');
241
- this.tcpServer.once('listening', this.listening.bind(this, preparedSession, callback));
295
+ this.pendingBinds.push({ preparedSession, callback });
242
296
  break;
243
- case 2 /* ServerState.LISTENING */:
297
+ case ServerState.LISTENING:
244
298
  debug('Instructing client to connect to already running TCP server');
245
299
  preparedSession.port = this.tcpPort;
246
300
  callback();
247
301
  break;
248
- case 3 /* ServerState.CLOSING */:
302
+ case ServerState.CLOSING:
249
303
  debug('TCP socket is currently closing. Trying again when server is fully closed and opening a new one then.');
250
304
  this.tcpServer.once('close', () => setTimeout(() => this.checkTCPServerEstablished(preparedSession, callback), 10));
251
305
  break;
252
306
  }
253
307
  }
254
- listening(preparedSession, callback) {
255
- this.state = 2 /* ServerState.LISTENING */;
308
+ listening() {
309
+ this.state = ServerState.LISTENING;
256
310
  const address = this.tcpServer.address();
257
311
  if (address && typeof address !== 'string') { // address is only typeof string when listening to a pipe or unix socket
258
312
  this.tcpPort = address.port;
259
- preparedSession.port = address.port;
260
313
  debug('TCP server is now listening for new data stream connections on port %s', address.port);
261
- callback();
314
+ for (const { preparedSession, callback } of this.pendingBinds.splice(0)) {
315
+ preparedSession.port = address.port;
316
+ callback();
317
+ }
318
+ }
319
+ }
320
+ /**
321
+ * Without a listener, an `error` event of the TCP server (it can't listen, or it can't accept a connection,
322
+ * e.g. because the process ran out of file descriptors) is an uncaught exception.
323
+ */
324
+ onServerError(server, error) {
325
+ console.warn(`The HomeKit Data Stream server reported an error: ${error.message}`);
326
+ if (this.state !== ServerState.BINDING || server !== this.tcpServer) {
327
+ return;
328
+ }
329
+ // The server never started to listen, so neither `listening` nor `close` will follow.
330
+ // Answer everybody who waits for it and start with a new server on the next attempt.
331
+ server.removeAllListeners();
332
+ server.on('error', () => undefined);
333
+ server.close();
334
+ this.tcpServer = undefined;
335
+ this.tcpPort = undefined;
336
+ this.state = ServerState.UNINITIALIZED;
337
+ this.failPendingBinds(error);
338
+ }
339
+ /**
340
+ * Answers everybody who waits for the TCP server to start listening with the given error, each of them once.
341
+ */
342
+ failPendingBinds(error) {
343
+ for (const { preparedSession, callback } of this.pendingBinds.splice(0)) {
344
+ clearTimeout(preparedSession.connectTimeout);
345
+ const index = this.preparedSessions.indexOf(preparedSession);
346
+ if (index >= 0) {
347
+ this.preparedSessions.splice(index, 1);
348
+ }
349
+ callback(error);
262
350
  }
263
351
  }
264
352
  onConnection(socket) {
265
353
  debug('[%s] New DataStream connection was established', socket.remoteAddress);
266
354
  // eslint-disable-next-line ts/no-use-before-define
267
355
  const connection = new DataStreamConnection(socket);
268
- connection.on("identification" /* DataStreamConnectionEvent.IDENTIFICATION */, this.handleSessionIdentification.bind(this, connection));
269
- connection.on("handle-message-globally" /* DataStreamConnectionEvent.HANDLE_MESSAGE_GLOBALLY */, this.handleMessageGlobally.bind(this, connection));
270
- connection.on("closed" /* DataStreamConnectionEvent.CLOSED */, this.connectionClosed.bind(this, connection));
356
+ connection.on(DataStreamConnectionEvent.IDENTIFICATION, this.handleSessionIdentification.bind(this, connection));
357
+ connection.on(DataStreamConnectionEvent.HANDLE_MESSAGE_GLOBALLY, this.handleMessageGlobally.bind(this, connection));
358
+ connection.on(DataStreamConnectionEvent.CLOSED, this.connectionClosed.bind(this, connection));
271
359
  this.connections.push(connection);
272
- this.emit("connection-opened" /* DataStreamServerEvent.CONNECTION_OPENED */, connection);
360
+ this.emit(DataStreamServerEvent.CONNECTION_OPENED, connection);
273
361
  }
274
362
  handleSessionIdentification(connection, firstFrame, callback) {
275
363
  let identifiedSession;
@@ -294,19 +382,19 @@ export class DataStreamServer extends EventEmitter {
294
382
  // by their hap sessionId in order to clear out old but still open connections when the controller opens a new one
295
383
  // on the other hand the keepAlive should handle that also :thinking:
296
384
  }
297
- else { // we looped through all session and didn't find anything
385
+ else { // we looped through all sessions and didn't find anything
298
386
  debug('[%s] Could not identify connection. Terminating.', connection.remoteAddress);
299
387
  connection.close(); // disconnecting since first message was not a valid hello
300
388
  }
301
389
  }
302
390
  handleMessageGlobally(connection, message) {
303
- assert.notStrictEqual(message.type, 3 /* MessageType.RESPONSE */); // responses can't physically get here
391
+ assert.notStrictEqual(message.type, MessageType.RESPONSE); // responses can't physically get here
304
392
  let separator = '';
305
393
  const args = [];
306
- if (message.type === 1 /* MessageType.EVENT */) {
394
+ if (message.type === MessageType.EVENT) {
307
395
  separator = '-e-';
308
396
  }
309
- else if (message.type === 2 /* MessageType.REQUEST */) {
397
+ else if (message.type === MessageType.REQUEST) {
310
398
  separator = '-r-';
311
399
  args.push(message.id);
312
400
  }
@@ -318,7 +406,7 @@ export class DataStreamServer extends EventEmitter {
318
406
  catch (error) {
319
407
  hadListeners = true;
320
408
  debug('[%s] Error occurred while dispatching handler for HDS message: %o', connection.remoteAddress, message);
321
- debug(error.stack);
409
+ debug(errorStack(error) ?? errorMessage(error));
322
410
  }
323
411
  if (!hadListeners) {
324
412
  debug('[%s] WARNING no handler was found for message: %o', connection.remoteAddress, message);
@@ -328,16 +416,17 @@ export class DataStreamServer extends EventEmitter {
328
416
  connectionClosed(connection) {
329
417
  debug('[%s] DataStream connection closed', connection.remoteAddress);
330
418
  this.connections.splice(this.connections.indexOf(connection), 1);
331
- this.emit("connection-closed" /* DataStreamServerEvent.CONNECTION_CLOSED */, connection);
419
+ this.emit(DataStreamServerEvent.CONNECTION_CLOSED, connection);
332
420
  this.checkCloseable();
333
- if (this.state === 3 /* ServerState.CLOSING */ && this.removeListenersOnceClosed && this.connections.length === 0) {
421
+ if (this.state === ServerState.CLOSING && this.removeListenersOnceClosed && this.connections.length === 0) {
334
422
  this.removeAllListeners(); // see this.destroy()
335
423
  }
336
424
  }
337
425
  checkCloseable() {
338
- if (this.connections.length === 0 && this.preparedSessions.length === 0 && this.state < 3 /* ServerState.CLOSING */) {
426
+ // without a TCP server (it never started, or failed to listen) there is nothing to close
427
+ if (this.tcpServer && this.connections.length === 0 && this.preparedSessions.length === 0 && this.state < ServerState.CLOSING) {
339
428
  debug('Last connection disconnected. Closing the server now.');
340
- this.state = 3 /* ServerState.CLOSING */;
429
+ this.state = ServerState.CLOSING;
341
430
  this.tcpServer.close();
342
431
  }
343
432
  }
@@ -345,26 +434,35 @@ export class DataStreamServer extends EventEmitter {
345
434
  * This method will fully stop the DataStreamServer
346
435
  */
347
436
  destroy() {
348
- if (this.state > 0 /* ServerState.UNINITIALIZED */ && this.state < 3 /* ServerState.CLOSING */) {
437
+ if (this.tcpServer && this.state < ServerState.CLOSING) {
438
+ // Only a TCP server reports `close`, which is what leaves the closing state again.
439
+ // A server which never started would stay in it for ever, and could not prepare a session anymore.
440
+ this.state = ServerState.CLOSING;
349
441
  this.tcpServer.close();
350
442
  for (const connection of this.connections) {
351
443
  connection.close();
352
444
  }
445
+ // A server which is closed before it listens never reports `listening`,
446
+ // so nobody would answer those who still wait for its port.
447
+ this.failPendingBinds(new Error('The HomeKit Data Stream server was destroyed before it started to listen'));
448
+ }
449
+ if (this.connections.length > 0) {
450
+ this.removeListenersOnceClosed = true; // the connections still have to report that they closed
451
+ }
452
+ else {
453
+ this.removeAllListeners();
353
454
  }
354
- this.state = 3 /* ServerState.CLOSING */;
355
- this.removeListenersOnceClosed = true;
356
455
  this.internalEventEmitter.removeAllListeners();
357
456
  }
358
457
  closed() {
359
458
  this.tcpServer = undefined;
360
459
  this.tcpPort = undefined;
361
- this.state = 0 /* ServerState.UNINITIALIZED */;
460
+ this.state = ServerState.UNINITIALIZED;
362
461
  }
363
462
  }
364
463
  /**
365
464
  * @group HomeKit Data Streams (HDS)
366
465
  */
367
- // eslint-disable-next-line no-restricted-syntax
368
466
  export var DataStreamConnectionEvent;
369
467
  (function (DataStreamConnectionEvent) {
370
468
  /**
@@ -386,7 +484,6 @@ export var DataStreamConnectionEvent;
386
484
  /**
387
485
  * @group HomeKit Data Streams (HDS)
388
486
  */
389
- // eslint-disable-next-line no-restricted-syntax
390
487
  export var HDSConnectionErrorType;
391
488
  (function (HDSConnectionErrorType) {
392
489
  HDSConnectionErrorType[HDSConnectionErrorType["ILLEGAL_STATE"] = 1] = "ILLEGAL_STATE";
@@ -409,7 +506,6 @@ export class HDSConnectionError extends Error {
409
506
  *
410
507
  * @group HomeKit Data Streams (HDS)
411
508
  */
412
- // eslint-disable-next-line ts/no-unsafe-declaration-merging
413
509
  export class DataStreamConnection extends EventEmitter {
414
510
  static MAX_PAYLOAD_LENGTH = 0b11111111111111111111;
415
511
  // time we give the remote to close its side of the socket after we called `end()`, before we destroy the socket
@@ -423,14 +519,20 @@ export class DataStreamConnection extends EventEmitter {
423
519
  Thus, we find the correct PreparedDataStreamSession object by testing the encryption keys of all available
424
520
  prepared sessions. Then we can reference this hds connection with the correct hap connection and mark it as identified.
425
521
  */
426
- state = 0 /* ConnectionState.UNIDENTIFIED */;
522
+ state = ConnectionState.UNIDENTIFIED;
427
523
  accessoryToControllerEncryptionKey;
428
524
  controllerToAccessoryEncryptionKey;
429
525
  accessoryToControllerNonce;
430
526
  accessoryToControllerNonceBuffer;
431
527
  controllerToAccessoryNonce;
432
528
  controllerToAccessoryNonceBuffer;
433
- frameBuffer; // used to store incomplete HDS frames
529
+ // The received bytes of an HDS frame which is not complete yet, at the start of incompleteFrame. It grows by doubling: joining
530
+ // every chunk with what is there already would copy a large frame which arrives in small chunks over and over again, and a
531
+ // list of the chunks costs an object for every chunk, which a sender of tiny chunks turns into hundreds of bytes per byte.
532
+ // This way every byte is copied a few times at most, and it never holds more than twice what arrived
533
+ incompleteFrame = Buffer.alloc(0);
534
+ incompleteFrameLength = 0;
535
+ incompleteFrameNeeded = 0; // the total length the bytes need before there is something new to decode
434
536
  hapConnectionClosedListener;
435
537
  protocolHandlers = {}; // used to store protocolHandlers identified by their protocol name
436
538
  responseHandlers = {}; // used to store responseHandlers indexed by their respective requestId
@@ -448,9 +550,9 @@ export class DataStreamConnection extends EventEmitter {
448
550
  this.controllerToAccessoryNonce = 0;
449
551
  this.controllerToAccessoryNonceBuffer = Buffer.alloc(8);
450
552
  this.hapConnectionClosedListener = this.onHAPSessionClosed.bind(this);
451
- this.addProtocolHandler("control" /* Protocols.CONTROL */, {
553
+ this.addProtocolHandler(Protocols.CONTROL, {
452
554
  requestHandler: {
453
- ["hello" /* Topics.HELLO */]: this.handleHello.bind(this),
555
+ [Topics.HELLO]: this.handleHello.bind(this),
454
556
  },
455
557
  });
456
558
  this.helloTimer = setTimeout(() => {
@@ -463,8 +565,8 @@ export class DataStreamConnection extends EventEmitter {
463
565
  // this is to mitigate the event emitter "memory leak warning".
464
566
  // e.g. with HSV there might be multiple cameras subscribing to the CLOSE event. one subscription for
465
567
  // every active recording stream on a camera. The default limit of 10 might be easily reached.
466
- // Setting a high limit isn't the prefect solution, but will avoid false positives but ensures that
467
- // a warning is still be printed if running long enough.
568
+ // Setting a high limit isn't the perfect solution, but it will avoid false positives and ensures that
569
+ // a warning is still printed if running long enough.
468
570
  this.setMaxListeners(100);
469
571
  }
470
572
  handleHello(id, message) {
@@ -472,8 +574,8 @@ export class DataStreamConnection extends EventEmitter {
472
574
  debug('[%s] Received hello message from client: %o', this.remoteAddress, message);
473
575
  clearTimeout(this.helloTimer);
474
576
  this.helloTimer = undefined;
475
- this.state = 2 /* ConnectionState.READY */;
476
- this.sendResponse("control" /* Protocols.CONTROL */, "hello" /* Topics.HELLO */, id);
577
+ this.state = ConnectionState.READY;
578
+ this.sendResponse(Protocols.CONTROL, Topics.HELLO, id);
477
579
  }
478
580
  /**
479
581
  * Registers a new protocol handler to handle incoming messages.
@@ -512,23 +614,30 @@ export class DataStreamConnection extends EventEmitter {
512
614
  const header = {};
513
615
  header.protocol = protocol;
514
616
  header.event = event;
515
- if (this.state === 2 /* ConnectionState.READY */) {
617
+ if (this.state === ConnectionState.READY) {
516
618
  this.sendHDSFrame(header, message);
517
619
  }
518
620
  }
519
621
  /**
520
622
  * Sends a new request message to the connected client.
521
623
  *
624
+ * Throws an {@link HDSConnectionError} when the connection is closing or closed, is not identified yet, or the message is
625
+ * too large. The callback is not called for such a request.
626
+ *
522
627
  * @param protocol - name of the protocol
523
628
  * @param request - name of the request (also referred to as topic. See {@link Topics} for some known ones)
524
629
  * @param message - message dictionary which gets sent along the request
525
- * @param callback - handler which gets supplied with an error object if the response didn't
526
- * arrive in time or the status and the message dictionary from the response
630
+ * @param callback - handler which gets supplied with the status and the message dictionary of the response, or with an
631
+ * error when the response did not arrive within 10 seconds or the connection closed before it arrived
527
632
  */
528
633
  sendRequest(protocol, request, message = {}, callback) {
634
+ if (this.state >= ConnectionState.CLOSING) {
635
+ // before anything is registered: the caller gets this error, and must not get a timeout for the same request later
636
+ throw new HDSConnectionError('Cannot send message on closing/closed socket!', HDSConnectionErrorType.CLOSED_SOCKET);
637
+ }
529
638
  let requestId;
530
639
  do { // generate unused requestId
531
- // currently writing int64 to data stream is not really supported, so 32-bit int will be the max
640
+ // 32 bits are plenty for the requests waiting at one time (the writer could encode up to 64 bits)
532
641
  requestId = Math.floor(Math.random() * 4294967295);
533
642
  } while (this.responseHandlers[requestId] !== undefined);
534
643
  this.responseHandlers[requestId] = callback;
@@ -538,14 +647,29 @@ export class DataStreamConnection extends EventEmitter {
538
647
  const handler = this.responseHandlers[requestId];
539
648
  delete this.responseHandlers[requestId];
540
649
  delete this.responseTimers[requestId];
541
- // handler should be able to clean up their stuff
542
- handler(new Error('timeout'), undefined, {});
650
+ // handlers should be able to clean up their stuff. Thrown inside a timer, an error would end the process
651
+ try {
652
+ handler(new Error('timeout'), undefined, {});
653
+ }
654
+ catch (error) {
655
+ debug('[%s] Error occurred while dispatching the timeout of request %d to its response handler', this.remoteAddress, requestId);
656
+ debug(errorStack(error) ?? errorMessage(error));
657
+ }
543
658
  }, 10000); // 10s timer
544
659
  const header = {};
545
660
  header.protocol = protocol;
546
661
  header.request = request;
547
662
  header.id = new Int64(requestId);
548
- this.sendHDSFrame(header, message);
663
+ try {
664
+ this.sendHDSFrame(header, message);
665
+ }
666
+ catch (error) {
667
+ // the request never left (e.g. it is too large): the caller gets the error, so the handler is not needed
668
+ clearTimeout(this.responseTimers[requestId]);
669
+ delete this.responseHandlers[requestId];
670
+ delete this.responseTimers[requestId];
671
+ throw error;
672
+ }
549
673
  }
550
674
  /**
551
675
  * Send a new response message to a received request message to the client.
@@ -565,7 +689,7 @@ export class DataStreamConnection extends EventEmitter {
565
689
  this.sendHDSFrame(header, message);
566
690
  }
567
691
  onSocketData(data) {
568
- if (this.state >= 3 /* ConnectionState.CLOSING */) {
692
+ if (this.state >= ConnectionState.CLOSING) {
569
693
  return;
570
694
  }
571
695
  let frameIndex = 0;
@@ -573,24 +697,24 @@ export class DataStreamConnection extends EventEmitter {
573
697
  if (frames.length === 0) { // not enough data
574
698
  return;
575
699
  }
576
- if (this.state === 0 /* ConnectionState.UNIDENTIFIED */) {
700
+ if (this.state === ConnectionState.UNIDENTIFIED) {
577
701
  // at the beginning we are only interested in trying to decrypt the first frame in order to test decryption keys
578
702
  const firstFrame = frames[frameIndex++];
579
- this.emit("identification" /* DataStreamConnectionEvent.IDENTIFICATION */, firstFrame, (identifiedSession) => {
703
+ this.emit(DataStreamConnectionEvent.IDENTIFICATION, firstFrame, (identifiedSession) => {
580
704
  if (identifiedSession) {
581
- // horray, we found our connection
705
+ // hooray, we found our connection
582
706
  this.connection = identifiedSession.connection;
583
707
  this.accessoryToControllerEncryptionKey = identifiedSession.accessoryToControllerEncryptionKey;
584
708
  this.controllerToAccessoryEncryptionKey = identifiedSession.controllerToAccessoryEncryptionKey;
585
- this.state = 1 /* ConnectionState.EXPECTING_HELLO */;
709
+ this.state = ConnectionState.EXPECTING_HELLO;
586
710
  // below listener is removed in .close()
587
711
  this.connection.setMaxListeners(this.connection.getMaxListeners() + 1);
588
- this.connection.on("closed" /* HAPConnectionEvent.CLOSED */, this.hapConnectionClosedListener); // register close listener
589
- debug('[%s] Registering CLOSED handler to HAP connection. Connection currently has %d close handlers!', this.remoteAddress, this.connection.listeners("closed" /* HAPConnectionEvent.CLOSED */).length);
712
+ this.connection.on(HAPConnectionEvent.CLOSED, this.hapConnectionClosedListener); // register close listener
713
+ debug('[%s] Registering CLOSED handler to HAP connection. Connection currently has %d close handlers!', this.remoteAddress, this.connection.listenerCount(HAPConnectionEvent.CLOSED));
590
714
  }
591
715
  });
592
716
  // the cast is needed as typescript doesn't know that the callback above changes the state
593
- if (this.state !== 1 /* ConnectionState.EXPECTING_HELLO */) {
717
+ if (this.state !== ConnectionState.EXPECTING_HELLO) {
594
718
  // did not find a prepared connection, server already closed this connection (state is CLOSING); nothing to do here
595
719
  return;
596
720
  }
@@ -603,9 +727,9 @@ export class DataStreamConnection extends EventEmitter {
603
727
  }
604
728
  }
605
729
  const messages = this.decodePayloads(frames); // decode contents of payload
606
- if (this.state === 1 /* ConnectionState.EXPECTING_HELLO */) {
730
+ if (this.state === ConnectionState.EXPECTING_HELLO) {
607
731
  const firstMessage = messages[0];
608
- if (!firstMessage || firstMessage.protocol !== "control" /* Protocols.CONTROL */ || firstMessage.type !== 2 /* MessageType.REQUEST */ || firstMessage.topic !== "hello" /* Topics.HELLO */) {
732
+ if (!firstMessage || firstMessage.protocol !== Protocols.CONTROL || firstMessage.type !== MessageType.REQUEST || firstMessage.topic !== Topics.HELLO) {
609
733
  // first message is not the expected hello request
610
734
  debug('[%s] First message received was not the expected hello message. Instead got: %o', this.remoteAddress, firstMessage);
611
735
  this.close();
@@ -613,7 +737,10 @@ export class DataStreamConnection extends EventEmitter {
613
737
  }
614
738
  }
615
739
  messages.forEach((message) => {
616
- if (message.type === 3 /* MessageType.RESPONSE */) {
740
+ if (this.state >= ConnectionState.CLOSING) {
741
+ return; // a handler of an earlier message in this chunk closed the connection: the rest is not for anybody anymore
742
+ }
743
+ if (message.type === MessageType.RESPONSE) {
617
744
  // protocol and topic are currently not tested here; just assumed they are correct;
618
745
  // probably they are as the requestId is unique per connection no matter what protocol is used
619
746
  const responseHandler = this.responseHandlers[message.id];
@@ -632,21 +759,25 @@ export class DataStreamConnection extends EventEmitter {
632
759
  }
633
760
  catch (error) {
634
761
  debug('[%s] Error occurred while dispatching response handler for HDS message: %o', this.remoteAddress, message);
635
- debug(error.stack);
762
+ debug(errorStack(error) ?? errorMessage(error));
636
763
  }
637
764
  delete this.responseHandlers[message.id];
638
765
  }
639
766
  else {
640
- const handler = this.protocolHandlers[message.protocol];
767
+ // Object.hasOwn(): the protocol and the topic are picked by the controller, and a name like "toString"
768
+ // or "constructor" must not find what every object inherits
769
+ const handler = Object.hasOwn(this.protocolHandlers, message.protocol)
770
+ ? this.protocolHandlers[message.protocol]
771
+ : undefined;
641
772
  if (handler === undefined) {
642
773
  // send message to the server to check if there are some global handlers for it
643
- this.emit("handle-message-globally" /* DataStreamConnectionEvent.HANDLE_MESSAGE_GLOBALLY */, message);
774
+ this.emit(DataStreamConnectionEvent.HANDLE_MESSAGE_GLOBALLY, message);
644
775
  return;
645
776
  }
646
- if (message.type === 1 /* MessageType.EVENT */) {
777
+ if (message.type === MessageType.EVENT) {
647
778
  let eventHandler;
648
779
  // eslint-disable-next-line no-cond-assign
649
- if (!handler.eventHandler || !(eventHandler = handler.eventHandler[message.topic])) {
780
+ if (!handler.eventHandler || !Object.hasOwn(handler.eventHandler, message.topic) || !(eventHandler = handler.eventHandler[message.topic])) {
650
781
  debug('[%s] WARNING no event handler was found for message: %o', this.remoteAddress, message);
651
782
  return;
652
783
  }
@@ -655,13 +786,13 @@ export class DataStreamConnection extends EventEmitter {
655
786
  }
656
787
  catch (error) {
657
788
  debug('[%s] Error occurred while dispatching event handler for HDS message: %o', this.remoteAddress, message);
658
- debug(error.stack);
789
+ debug(errorStack(error) ?? errorMessage(error));
659
790
  }
660
791
  }
661
- else if (message.type === 2 /* MessageType.REQUEST */) {
792
+ else if (message.type === MessageType.REQUEST) {
662
793
  let requestHandler;
663
794
  // eslint-disable-next-line no-cond-assign
664
- if (!handler.requestHandler || !(requestHandler = handler.requestHandler[message.topic])) {
795
+ if (!handler.requestHandler || !Object.hasOwn(handler.requestHandler, message.topic) || !(requestHandler = handler.requestHandler[message.topic])) {
665
796
  debug('[%s] WARNING no request handler was found for message: %o', this.remoteAddress, message);
666
797
  this.respondToUnhandledRequest(message);
667
798
  return;
@@ -671,7 +802,7 @@ export class DataStreamConnection extends EventEmitter {
671
802
  }
672
803
  catch (error) {
673
804
  debug('[%s] Error occurred while dispatching request handler for HDS message: %o', this.remoteAddress, message);
674
- debug(error.stack);
805
+ debug(errorStack(error) ?? errorMessage(error));
675
806
  }
676
807
  }
677
808
  else {
@@ -681,22 +812,34 @@ export class DataStreamConnection extends EventEmitter {
681
812
  });
682
813
  }
683
814
  decodeHDSFrames(data) {
684
- if (this.frameBuffer !== undefined) {
685
- data = Buffer.concat([this.frameBuffer, data]);
686
- this.frameBuffer = undefined;
815
+ if (this.incompleteFrameLength > 0) {
816
+ const length = this.incompleteFrameLength + data.length;
817
+ if (length > this.incompleteFrame.length) {
818
+ const grown = Buffer.allocUnsafe(Math.max(length, 2 * this.incompleteFrame.length));
819
+ this.incompleteFrame.copy(grown, 0, 0, this.incompleteFrameLength);
820
+ this.incompleteFrame = grown;
821
+ }
822
+ data.copy(this.incompleteFrame, this.incompleteFrameLength);
823
+ this.incompleteFrameLength = length;
824
+ if (length < this.incompleteFrameNeeded) {
825
+ return []; // still not enough data for the frame header, or for the frame
826
+ }
827
+ data = this.incompleteFrame.subarray(0, length);
828
+ this.incompleteFrame = Buffer.alloc(0);
829
+ this.incompleteFrameLength = 0;
687
830
  }
688
831
  const totalBufferLength = data.length;
689
832
  const frames = [];
690
833
  for (let frameBegin = 0; frameBegin < totalBufferLength;) {
691
834
  if (frameBegin + 4 > totalBufferLength) {
692
835
  // we don't have enough data in the buffer for the next header
693
- this.frameBuffer = data.subarray(frameBegin);
836
+ this.keepIncompleteFrame(data.subarray(frameBegin), 4);
694
837
  break;
695
838
  }
696
839
  const payloadType = data.readUInt8(frameBegin); // type defining structure of payload; 8-bit; currently expected to be 1
697
840
  const payloadLength = data.readUIntBE(frameBegin + 1, 3); // read 24-bit big-endian uint length field
698
841
  if (payloadLength > DataStreamConnection.MAX_PAYLOAD_LENGTH) {
699
- debug('[%s] Connection send payload with size bigger than the maximum allow for data stream', this.remoteAddress);
842
+ debug('[%s] Connection sent payload with size bigger than the maximum allowed for data stream', this.remoteAddress);
700
843
  this.close();
701
844
  return [];
702
845
  }
@@ -704,7 +847,7 @@ export class DataStreamConnection extends EventEmitter {
704
847
  // check if the data from this frame is already there (payload + 16-byte authTag)
705
848
  if (payloadLength + 16 > remainingBufferLength) {
706
849
  // Frame is fragmented, so we wait until we receive more
707
- this.frameBuffer = data.subarray(frameBegin);
850
+ this.keepIncompleteFrame(data.subarray(frameBegin), 4 + payloadLength + 16);
708
851
  break;
709
852
  }
710
853
  const payloadBegin = frameBegin + 4;
@@ -727,20 +870,25 @@ export class DataStreamConnection extends EventEmitter {
727
870
  }
728
871
  return frames;
729
872
  }
873
+ keepIncompleteFrame(data, neededLength) {
874
+ this.incompleteFrame = data; // kept as it is: it is only copied once more data arrives
875
+ this.incompleteFrameLength = data.length;
876
+ this.incompleteFrameNeeded = neededLength;
877
+ }
730
878
  /**
731
879
  * Answers a request which no handler took care of, so the controller doesn't wait for a response which never comes.
732
880
  *
733
881
  * @private
734
882
  */
735
883
  respondToUnhandledRequest(message) {
736
- if (message.type !== 2 /* MessageType.REQUEST */ || typeof message.id !== 'number' || this.isConsideredClosed()) {
884
+ if (message.type !== MessageType.REQUEST || typeof message.id !== 'number' || this.isConsideredClosed()) {
737
885
  return;
738
886
  }
739
887
  try {
740
888
  this.sendResponse(message.protocol, message.topic, message.id, HDSStatus.MISSING_PROTOCOL);
741
889
  }
742
890
  catch (error) {
743
- debug('[%s] Failed to answer the unhandled request: %s', this.remoteAddress, error.message);
891
+ debug('[%s] Failed to answer the unhandled request: %s', this.remoteAddress, errorMessage(error));
744
892
  }
745
893
  }
746
894
  /**
@@ -751,7 +899,7 @@ export class DataStreamConnection extends EventEmitter {
751
899
  const key = keyOverwrite || this.controllerToAccessoryEncryptionKey;
752
900
  try {
753
901
  frame.plaintextPayload = hapCrypto.chacha20_poly1305_decryptAndVerify(key, this.controllerToAccessoryNonceBuffer, frame.header, frame.cipheredPayload, frame.authTag);
754
- this.controllerToAccessoryNonce++; // we had a successful encryption, increment the nonce
902
+ this.controllerToAccessoryNonce++; // we had a successful decryption, increment the nonce
755
903
  return true;
756
904
  }
757
905
  catch (error) {
@@ -764,7 +912,7 @@ export class DataStreamConnection extends EventEmitter {
764
912
  frames.forEach((frame) => {
765
913
  const payload = frame.plaintextPayload;
766
914
  if (!payload) {
767
- throw new HDSConnectionError('Reached illegal state. Encountered HDSFrame with wasn\'t decrypted yet!', 1 /* HDSConnectionErrorType.ILLEGAL_STATE */);
915
+ throw new HDSConnectionError('Reached illegal state. Encountered HDSFrame which wasn\'t decrypted yet!', HDSConnectionErrorType.ILLEGAL_STATE);
768
916
  }
769
917
  if (payload.length < 1 || payload.readUInt8(0) > payload.length - 1) {
770
918
  debug('[%s] Encountered HDS payload with a missing or too long header (payload: %s)', this.remoteAddress, payload.toString('hex'));
@@ -783,7 +931,7 @@ export class DataStreamConnection extends EventEmitter {
783
931
  headerPayload.finished();
784
932
  }
785
933
  catch (error) {
786
- debug('[%s] Failed to decode header payload: %s', this.remoteAddress, error.message);
934
+ debug('[%s] Failed to decode header payload: %s', this.remoteAddress, errorMessage(error));
787
935
  return;
788
936
  }
789
937
  try {
@@ -791,52 +939,38 @@ export class DataStreamConnection extends EventEmitter {
791
939
  messagePayload.finished();
792
940
  }
793
941
  catch (error) {
794
- debug('[%s] Failed to decode message payload: %s (header: %o)', this.remoteAddress, error.message, headerDictionary);
942
+ debug('[%s] Failed to decode message payload: %s (header: %o)', this.remoteAddress, errorMessage(error), headerDictionary);
795
943
  return;
796
944
  }
797
- if (headerDictionary === null || typeof headerDictionary !== 'object') {
945
+ if (!isHDSMessage(headerDictionary)) {
798
946
  debug('[%s] Encountered payload header which is not a dictionary: %o', this.remoteAddress, headerDictionary);
799
947
  return;
800
948
  }
801
- let type;
802
- const protocol = headerDictionary.protocol;
803
- let topic;
804
- let id;
805
- let status;
806
- if (headerDictionary.event !== undefined) {
807
- type = 1 /* MessageType.EVENT */;
808
- topic = headerDictionary.event;
809
- }
810
- else if (headerDictionary.request !== undefined) {
811
- type = 2 /* MessageType.REQUEST */;
812
- topic = headerDictionary.request;
813
- id = headerDictionary.id;
814
- }
815
- else if (headerDictionary.response !== undefined) {
816
- type = 3 /* MessageType.RESPONSE */;
817
- topic = headerDictionary.response;
818
- id = headerDictionary.id;
819
- status = headerDictionary.status;
820
- }
821
- else {
949
+ // the payload is sent by the controller, so nothing is known about its shape before it is checked.
950
+ // a message which is not of the expected shape is dropped, so that no handler is called with something it cannot read
951
+ const header = parseHeader(headerDictionary);
952
+ if (!header) {
822
953
  debug('[%s] Encountered unknown payload header format: %o (message: %o)', this.remoteAddress, headerDictionary, messageDictionary);
823
954
  return;
824
955
  }
825
- const message = {
826
- type,
827
- protocol,
828
- topic,
829
- id,
830
- status,
956
+ if (!isHDSMessage(messageDictionary)) {
957
+ debug('[%s] Encountered message which is not a dictionary: %o (header: %o)', this.remoteAddress, messageDictionary, headerDictionary);
958
+ return;
959
+ }
960
+ messages.push({
961
+ ...header,
831
962
  message: messageDictionary,
832
- };
833
- messages.push(message);
963
+ });
834
964
  });
835
965
  return messages;
836
966
  }
837
967
  sendHDSFrame(header, message) {
838
- if (this.state >= 3 /* ConnectionState.CLOSING */) {
839
- throw new HDSConnectionError('Cannot send message on closing/closed socket!', 2 /* HDSConnectionErrorType.CLOSED_SOCKET */);
968
+ if (this.state >= ConnectionState.CLOSING) {
969
+ throw new HDSConnectionError('Cannot send message on closing/closed socket!', HDSConnectionErrorType.CLOSED_SOCKET);
970
+ }
971
+ if (!this.accessoryToControllerEncryptionKey) {
972
+ // the keys are only known once the hello message identified the connection
973
+ throw new HDSConnectionError('Cannot send message on a connection which was not identified yet!', HDSConnectionErrorType.ILLEGAL_STATE);
840
974
  }
841
975
  const headerWriter = new DataStreamWriter();
842
976
  const messageWriter = new DataStreamWriter();
@@ -850,7 +984,7 @@ export class DataStreamConnection extends EventEmitter {
850
984
  messageWriter.getData(),
851
985
  ]);
852
986
  if (payloadBuffer.length > DataStreamConnection.MAX_PAYLOAD_LENGTH) {
853
- throw new HDSConnectionError('Tried sending payload with length larger than the maximum allowed for data stream', 3 /* HDSConnectionErrorType.MAX_PAYLOAD_LENGTH */);
987
+ throw new HDSConnectionError('Tried sending payload with length larger than the maximum allowed for data stream', HDSConnectionErrorType.MAX_PAYLOAD_LENGTH);
854
988
  }
855
989
  const frameTypeBuffer = Buffer.alloc(1);
856
990
  frameTypeBuffer.writeUInt8(1, 0);
@@ -861,23 +995,12 @@ export class DataStreamConnection extends EventEmitter {
861
995
  hapCrypto.writeUInt64LE(this.accessoryToControllerNonce++, this.accessoryToControllerNonceBuffer);
862
996
  const encrypted = hapCrypto.chacha20_poly1305_encryptAndSeal(this.accessoryToControllerEncryptionKey, this.accessoryToControllerNonceBuffer, frameHeader, payloadBuffer);
863
997
  this.socket.write(Buffer.concat([frameHeader, encrypted.ciphertext, encrypted.authTag]));
864
- /* Useful for debugging outgoing packages and detecting encoding errors
865
- console.log("SENT DATA: " + payloadBuffer.toString("hex"));
866
- const frame: HDSFrame = {
867
- header: frameHeader,
868
- plaintextPayload: payloadBuffer,
869
- cipheredPayload: cipheredPayload,
870
- authTag: authTag,
871
- };
872
- const sentMessage = this.decodePayloads([frame])[0];
873
- console.log("Sent message: " + JSON.stringify(sentMessage, null, 4));
874
- // */
875
998
  }
876
999
  close() {
877
- if (this.state >= 3 /* ConnectionState.CLOSING */) {
1000
+ if (this.state >= ConnectionState.CLOSING) {
878
1001
  return; // connection is already closing/closed
879
1002
  }
880
- this.state = 3 /* ConnectionState.CLOSING */;
1003
+ this.state = ConnectionState.CLOSING;
881
1004
  this.socket.end();
882
1005
  // a remote which never closes its side would otherwise keep the half-closed socket (and this connection) around forever
883
1006
  this.socketEndTimer = setTimeout(() => {
@@ -887,7 +1010,7 @@ export class DataStreamConnection extends EventEmitter {
887
1010
  this.socketEndTimer.unref();
888
1011
  }
889
1012
  isConsideredClosed() {
890
- return this.state >= 3 /* ConnectionState.CLOSING */;
1013
+ return this.state >= ConnectionState.CLOSING;
891
1014
  }
892
1015
  onHAPSessionClosed() {
893
1016
  // If the hap connection is closed it is probably also a good idea to close the data stream connection
@@ -900,13 +1023,32 @@ export class DataStreamConnection extends EventEmitter {
900
1023
  }
901
1024
  onSocketClose() {
902
1025
  // this instance is now considered completely dead
903
- this.state = 4 /* ConnectionState.CLOSED */;
1026
+ this.state = ConnectionState.CLOSED;
904
1027
  if (this.socketEndTimer) {
905
1028
  clearTimeout(this.socketEndTimer);
906
1029
  this.socketEndTimer = undefined;
907
1030
  }
908
- this.emit("closed" /* DataStreamConnectionEvent.CLOSED */);
909
- this.connection?.removeListener("closed" /* HAPConnectionEvent.CLOSED */, this.hapConnectionClosedListener);
1031
+ if (this.helloTimer) {
1032
+ clearTimeout(this.helloTimer);
1033
+ this.helloTimer = undefined;
1034
+ }
1035
+ // no response will arrive anymore: answer the waiting requests now instead of when their timeout runs out
1036
+ const pendingHandlers = Object.values(this.responseHandlers);
1037
+ for (const timer of Object.values(this.responseTimers)) {
1038
+ clearTimeout(timer);
1039
+ }
1040
+ this.responseHandlers = {};
1041
+ this.responseTimers = {};
1042
+ for (const handler of pendingHandlers) {
1043
+ try {
1044
+ handler(new HDSConnectionError('The connection was closed', HDSConnectionErrorType.CLOSED_SOCKET), undefined, {});
1045
+ }
1046
+ catch (error) {
1047
+ debug('[%s] Response handler failed for a request which was cancelled as the connection closed: %s', this.remoteAddress, error);
1048
+ }
1049
+ }
1050
+ this.emit(DataStreamConnectionEvent.CLOSED);
1051
+ this.connection?.removeListener(HAPConnectionEvent.CLOSED, this.hapConnectionClosedListener);
910
1052
  this.connection?.setMaxListeners(this.connection.getMaxListeners() - 1);
911
1053
  this.removeAllListeners();
912
1054
  }