@homebridge/hap-nodejs 2.3.1-beta.0 → 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 (254) 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 +40 -21
  21. package/dist/lib/Characteristic.js +207 -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 +16 -12
  27. package/dist/lib/Service.js +58 -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 +35 -1
  66. package/dist/lib/definitions/CharacteristicDefinitions.js +649 -568
  67. package/dist/lib/definitions/CharacteristicDefinitions.js.map +1 -1
  68. package/dist/lib/definitions/ServiceDefinitions.d.ts +7 -1
  69. package/dist/lib/definitions/ServiceDefinitions.js +16 -1
  70. package/dist/lib/definitions/ServiceDefinitions.js.map +1 -1
  71. package/dist/lib/definitions/index.d.ts +0 -1
  72. package/dist/lib/gen/HomeKit.d.ts +0 -1
  73. package/dist/lib/model/AccessoryInfo.d.ts +5 -6
  74. package/dist/lib/model/AccessoryInfo.js +23 -19
  75. package/dist/lib/model/AccessoryInfo.js.map +1 -1
  76. package/dist/lib/model/ControllerStorage.d.ts +11 -5
  77. package/dist/lib/model/ControllerStorage.js +34 -8
  78. package/dist/lib/model/ControllerStorage.js.map +1 -1
  79. package/dist/lib/model/HAPFileStorage.d.ts +20 -2
  80. package/dist/lib/model/HAPFileStorage.js +59 -10
  81. package/dist/lib/model/HAPFileStorage.js.map +1 -1
  82. package/dist/lib/model/HAPStorage.d.ts +0 -1
  83. package/dist/lib/model/HAPStorage.js +6 -3
  84. package/dist/lib/model/HAPStorage.js.map +1 -1
  85. package/dist/lib/model/IdentifierCache.d.ts +2 -3
  86. package/dist/lib/model/IdentifierCache.js +26 -13
  87. package/dist/lib/model/IdentifierCache.js.map +1 -1
  88. package/dist/lib/tv/AccessControlManagement.d.ts +6 -7
  89. package/dist/lib/tv/AccessControlManagement.js +13 -19
  90. package/dist/lib/tv/AccessControlManagement.js.map +1 -1
  91. package/dist/lib/util/checkName.d.ts +1 -2
  92. package/dist/lib/util/checkName.js.map +1 -1
  93. package/dist/lib/util/clone.d.ts +0 -1
  94. package/dist/lib/util/clone.js.map +1 -1
  95. package/dist/lib/util/color-utils.d.ts +1 -2
  96. package/dist/lib/util/color-utils.js +1 -1
  97. package/dist/lib/util/errors.d.ts +4 -0
  98. package/dist/lib/util/errors.js +15 -0
  99. package/dist/lib/util/errors.js.map +1 -0
  100. package/dist/lib/util/eventedhttp.d.ts +63 -19
  101. package/dist/lib/util/eventedhttp.js +170 -48
  102. package/dist/lib/util/eventedhttp.js.map +1 -1
  103. package/dist/lib/util/hapCrypto.d.ts +1 -2
  104. package/dist/lib/util/hapCrypto.js +6 -7
  105. package/dist/lib/util/hapCrypto.js.map +1 -1
  106. package/dist/lib/util/hapStatusError.d.ts +0 -1
  107. package/dist/lib/util/hapStatusError.js +1 -1
  108. package/dist/lib/util/hapStatusError.js.map +1 -1
  109. package/dist/lib/util/net-utils.d.ts +1 -2
  110. package/dist/lib/util/net-utils.js +6 -7
  111. package/dist/lib/util/net-utils.js.map +1 -1
  112. package/dist/lib/util/once.d.ts +0 -1
  113. package/dist/lib/util/promise-utils.d.ts +1 -2
  114. package/dist/lib/util/promise-utils.js +2 -1
  115. package/dist/lib/util/promise-utils.js.map +1 -1
  116. package/dist/lib/util/request-util.d.ts +4 -4
  117. package/dist/lib/util/request-util.js +29 -28
  118. package/dist/lib/util/request-util.js.map +1 -1
  119. package/dist/lib/util/time.d.ts +1 -2
  120. package/dist/lib/util/time.js.map +1 -1
  121. package/dist/lib/util/tlv.d.ts +4 -4
  122. package/dist/lib/util/tlv.js +16 -5
  123. package/dist/lib/util/tlv.js.map +1 -1
  124. package/dist/lib/util/uuid.d.ts +5 -2
  125. package/dist/lib/util/uuid.js +6 -0
  126. package/dist/lib/util/uuid.js.map +1 -1
  127. package/dist/types.d.ts +20 -17
  128. package/dist/types.js +0 -1
  129. package/dist/types.js.map +1 -1
  130. package/package.json +8 -14
  131. package/dist/accessories/AirConditioner_accessory.d.ts +0 -2
  132. package/dist/accessories/AirConditioner_accessory.d.ts.map +0 -1
  133. package/dist/accessories/AirConditioner_accessory.js +0 -126
  134. package/dist/accessories/AirConditioner_accessory.js.map +0 -1
  135. package/dist/accessories/AppleTVRemote_accessory.d.ts +0 -2
  136. package/dist/accessories/AppleTVRemote_accessory.d.ts.map +0 -1
  137. package/dist/accessories/AppleTVRemote_accessory.js +0 -146
  138. package/dist/accessories/AppleTVRemote_accessory.js.map +0 -1
  139. package/dist/accessories/Camera_accessory.d.ts +0 -2
  140. package/dist/accessories/Camera_accessory.d.ts.map +0 -1
  141. package/dist/accessories/Camera_accessory.js +0 -562
  142. package/dist/accessories/Camera_accessory.js.map +0 -1
  143. package/dist/accessories/Fan_accessory.d.ts +0 -2
  144. package/dist/accessories/Fan_accessory.d.ts.map +0 -1
  145. package/dist/accessories/Fan_accessory.js +0 -71
  146. package/dist/accessories/Fan_accessory.js.map +0 -1
  147. package/dist/accessories/GarageDoorOpener_accessory.d.ts +0 -2
  148. package/dist/accessories/GarageDoorOpener_accessory.d.ts.map +0 -1
  149. package/dist/accessories/GarageDoorOpener_accessory.js +0 -76
  150. package/dist/accessories/GarageDoorOpener_accessory.js.map +0 -1
  151. package/dist/accessories/Light-AdaptiveLighting_accessory.d.ts +0 -2
  152. package/dist/accessories/Light-AdaptiveLighting_accessory.d.ts.map +0 -1
  153. package/dist/accessories/Light-AdaptiveLighting_accessory.js +0 -103
  154. package/dist/accessories/Light-AdaptiveLighting_accessory.js.map +0 -1
  155. package/dist/accessories/Light_accessory.d.ts +0 -2
  156. package/dist/accessories/Light_accessory.d.ts.map +0 -1
  157. package/dist/accessories/Light_accessory.js +0 -143
  158. package/dist/accessories/Light_accessory.js.map +0 -1
  159. package/dist/accessories/Lock_accessory.d.ts +0 -2
  160. package/dist/accessories/Lock_accessory.d.ts.map +0 -1
  161. package/dist/accessories/Lock_accessory.js +0 -74
  162. package/dist/accessories/Lock_accessory.js.map +0 -1
  163. package/dist/accessories/MotionSensor_accessory.d.ts +0 -2
  164. package/dist/accessories/MotionSensor_accessory.d.ts.map +0 -1
  165. package/dist/accessories/MotionSensor_accessory.js +0 -43
  166. package/dist/accessories/MotionSensor_accessory.js.map +0 -1
  167. package/dist/accessories/Outlet_accessory.d.ts +0 -2
  168. package/dist/accessories/Outlet_accessory.d.ts.map +0 -1
  169. package/dist/accessories/Outlet_accessory.js +0 -77
  170. package/dist/accessories/Outlet_accessory.js.map +0 -1
  171. package/dist/accessories/SmartSpeaker_accessory.d.ts +0 -2
  172. package/dist/accessories/SmartSpeaker_accessory.d.ts.map +0 -1
  173. package/dist/accessories/SmartSpeaker_accessory.js +0 -42
  174. package/dist/accessories/SmartSpeaker_accessory.js.map +0 -1
  175. package/dist/accessories/Sprinkler_accessory.d.ts +0 -2
  176. package/dist/accessories/Sprinkler_accessory.d.ts.map +0 -1
  177. package/dist/accessories/Sprinkler_accessory.js +0 -126
  178. package/dist/accessories/Sprinkler_accessory.js.map +0 -1
  179. package/dist/accessories/TV_accessory.d.ts +0 -2
  180. package/dist/accessories/TV_accessory.d.ts.map +0 -1
  181. package/dist/accessories/TV_accessory.js +0 -99
  182. package/dist/accessories/TV_accessory.js.map +0 -1
  183. package/dist/accessories/TemperatureSensor_accessory.d.ts +0 -2
  184. package/dist/accessories/TemperatureSensor_accessory.d.ts.map +0 -1
  185. package/dist/accessories/TemperatureSensor_accessory.js +0 -42
  186. package/dist/accessories/TemperatureSensor_accessory.js.map +0 -1
  187. package/dist/accessories/Wi-FiRouter_accessory.d.ts +0 -3
  188. package/dist/accessories/Wi-FiRouter_accessory.d.ts.map +0 -1
  189. package/dist/accessories/Wi-FiRouter_accessory.js +0 -14
  190. package/dist/accessories/Wi-FiRouter_accessory.js.map +0 -1
  191. package/dist/accessories/Wi-FiSatellite_accessory.d.ts +0 -3
  192. package/dist/accessories/Wi-FiSatellite_accessory.d.ts.map +0 -1
  193. package/dist/accessories/Wi-FiSatellite_accessory.js +0 -16
  194. package/dist/accessories/Wi-FiSatellite_accessory.js.map +0 -1
  195. package/dist/accessories/gstreamer-audioProducer.d.ts +0 -25
  196. package/dist/accessories/gstreamer-audioProducer.d.ts.map +0 -1
  197. package/dist/accessories/gstreamer-audioProducer.js +0 -145
  198. package/dist/accessories/gstreamer-audioProducer.js.map +0 -1
  199. package/dist/accessories/types.d.ts.map +0 -1
  200. package/dist/hap.d.ts.map +0 -1
  201. package/dist/index.d.ts.map +0 -1
  202. package/dist/internal-types.d.ts.map +0 -1
  203. package/dist/lib/Accessory.d.ts.map +0 -1
  204. package/dist/lib/Advertiser.d.ts.map +0 -1
  205. package/dist/lib/Bridge.d.ts.map +0 -1
  206. package/dist/lib/Characteristic.d.ts.map +0 -1
  207. package/dist/lib/HAPServer.d.ts.map +0 -1
  208. package/dist/lib/Service.d.ts.map +0 -1
  209. package/dist/lib/camera/RTPProxy.d.ts.map +0 -1
  210. package/dist/lib/camera/RTPStreamManagement.d.ts.map +0 -1
  211. package/dist/lib/camera/RecordingManagement.d.ts.map +0 -1
  212. package/dist/lib/camera/index.d.ts.map +0 -1
  213. package/dist/lib/controller/AdaptiveLightingController.d.ts.map +0 -1
  214. package/dist/lib/controller/CameraController.d.ts.map +0 -1
  215. package/dist/lib/controller/Controller.d.ts.map +0 -1
  216. package/dist/lib/controller/DoorbellController.d.ts.map +0 -1
  217. package/dist/lib/controller/RemoteController.d.ts.map +0 -1
  218. package/dist/lib/controller/index.d.ts.map +0 -1
  219. package/dist/lib/datastream/DataStreamManagement.d.ts.map +0 -1
  220. package/dist/lib/datastream/DataStreamParser.d.ts.map +0 -1
  221. package/dist/lib/datastream/DataStreamServer.d.ts.map +0 -1
  222. package/dist/lib/datastream/index.d.ts.map +0 -1
  223. package/dist/lib/definitions/CharacteristicDefinitions.d.ts.map +0 -1
  224. package/dist/lib/definitions/ServiceDefinitions.d.ts.map +0 -1
  225. package/dist/lib/definitions/generate-definitions.d.ts +0 -34
  226. package/dist/lib/definitions/generate-definitions.d.ts.map +0 -1
  227. package/dist/lib/definitions/generate-definitions.js +0 -624
  228. package/dist/lib/definitions/generate-definitions.js.map +0 -1
  229. package/dist/lib/definitions/generator-configuration.d.ts +0 -22
  230. package/dist/lib/definitions/generator-configuration.d.ts.map +0 -1
  231. package/dist/lib/definitions/generator-configuration.js +0 -674
  232. package/dist/lib/definitions/generator-configuration.js.map +0 -1
  233. package/dist/lib/definitions/index.d.ts.map +0 -1
  234. package/dist/lib/gen/HomeKit.d.ts.map +0 -1
  235. package/dist/lib/model/AccessoryInfo.d.ts.map +0 -1
  236. package/dist/lib/model/ControllerStorage.d.ts.map +0 -1
  237. package/dist/lib/model/HAPFileStorage.d.ts.map +0 -1
  238. package/dist/lib/model/HAPStorage.d.ts.map +0 -1
  239. package/dist/lib/model/IdentifierCache.d.ts.map +0 -1
  240. package/dist/lib/tv/AccessControlManagement.d.ts.map +0 -1
  241. package/dist/lib/util/checkName.d.ts.map +0 -1
  242. package/dist/lib/util/clone.d.ts.map +0 -1
  243. package/dist/lib/util/color-utils.d.ts.map +0 -1
  244. package/dist/lib/util/eventedhttp.d.ts.map +0 -1
  245. package/dist/lib/util/hapCrypto.d.ts.map +0 -1
  246. package/dist/lib/util/hapStatusError.d.ts.map +0 -1
  247. package/dist/lib/util/net-utils.d.ts.map +0 -1
  248. package/dist/lib/util/once.d.ts.map +0 -1
  249. package/dist/lib/util/promise-utils.d.ts.map +0 -1
  250. package/dist/lib/util/request-util.d.ts.map +0 -1
  251. package/dist/lib/util/time.d.ts.map +0 -1
  252. package/dist/lib/util/tlv.d.ts.map +0 -1
  253. package/dist/lib/util/uuid.d.ts.map +0 -1
  254. package/dist/types.d.ts.map +0 -1
@@ -4,8 +4,9 @@ import { EventEmitter } from 'node:events';
4
4
  import { URL } from 'node:url';
5
5
  import createDebug from 'debug';
6
6
  import { SRP, SrpServer } from 'fast-srp-hap';
7
- import { consideredTrue } from '../internal-types.js';
8
- import { EventedHTTPServer, HAPEncryption } from './util/eventedhttp.js';
7
+ import { consideredTrue, HAPMimeTypes, PairingStates, PairMethods, TLVValues } from '../internal-types.js';
8
+ import { errorMessage, errorStack } from './util/errors.js';
9
+ import { EventedHTTPServer, EventedHTTPServerEvent, HAPEncryption } from './util/eventedhttp.js';
9
10
  import * as hapCrypto from './util/hapCrypto.js';
10
11
  import { once } from './util/once.js';
11
12
  import * as tlv from './util/tlv.js';
@@ -15,7 +16,6 @@ const debug = createDebug('HAP-NodeJS:HAPServer');
15
16
  *
16
17
  * @group HAP Accessory Server
17
18
  */
18
- // eslint-disable-next-line no-restricted-syntax
19
19
  export var TLVErrorCode;
20
20
  (function (TLVErrorCode) {
21
21
  // noinspection JSUnusedGlobalSymbols
@@ -102,7 +102,7 @@ export function IsKnownHAPStatusError(status) {
102
102
  && status <= HAPStatus.INSUFFICIENT_PRIVILEGES);
103
103
  }
104
104
  /**
105
- * Those status codes are the one listed as appropriate for the HAP spec!
105
+ * Those status codes are the ones listed as appropriate for the HAP spec!
106
106
  *
107
107
  * When the response is a client error 4xx or server error 5xx, the response
108
108
  * must include a status {@link HAPStatus} property.
@@ -111,7 +111,6 @@ export function IsKnownHAPStatusError(status) {
111
111
  *
112
112
  * @group HAP Accessory Server
113
113
  */
114
- // eslint-disable-next-line no-restricted-syntax
115
114
  export var HAPHTTPCode;
116
115
  (function (HAPHTTPCode) {
117
116
  // noinspection JSUnusedGlobalSymbols
@@ -132,7 +131,6 @@ export var HAPHTTPCode;
132
131
  *
133
132
  * @group HAP Accessory Server
134
133
  */
135
- // eslint-disable-next-line no-restricted-syntax
136
134
  export var HAPPairingHTTPCode;
137
135
  (function (HAPPairingHTTPCode) {
138
136
  // noinspection JSUnusedGlobalSymbols
@@ -146,7 +144,6 @@ export var HAPPairingHTTPCode;
146
144
  /**
147
145
  * @group HAP Accessory Server
148
146
  */
149
- // eslint-disable-next-line no-restricted-syntax
150
147
  export var HAPServerEventTypes;
151
148
  (function (HAPServerEventTypes) {
152
149
  /**
@@ -212,7 +209,6 @@ export var HAPServerEventTypes;
212
209
  *
213
210
  * @group HAP Accessory Server
214
211
  */
215
- // eslint-disable-next-line ts/no-unsafe-declaration-merging
216
212
  export class HAPServer extends EventEmitter {
217
213
  accessoryInfo;
218
214
  httpServer;
@@ -226,17 +222,17 @@ export class HAPServer extends EventEmitter {
226
222
  * The longest delay a Node.js timer supports. Above it, the timer fires after 1 ms and the timed write would expire at once.
227
223
  */
228
224
  static MAX_TIMED_WRITE_TTL = 0x7FFFFFFF;
229
- unsuccessfulPairAttempts = 0; // after 100 unsuccessful attempts the server won't accept any further attempts. Will currently be reset on a reboot
225
+ unsuccessfulPairAttempts = 0; // after more than 100 unsuccessful attempts the server won't accept any further attempts. Will currently be reset on a reboot
230
226
  allowInsecureRequest;
231
227
  constructor(accessoryInfo) {
232
228
  super();
233
229
  this.accessoryInfo = accessoryInfo;
234
230
  this.allowInsecureRequest = false;
235
231
  // internal server that does all the actual communication
236
- this.httpServer = new EventedHTTPServer();
237
- this.httpServer.on("listening" /* EventedHTTPServerEvent.LISTENING */, this.onListening.bind(this));
238
- this.httpServer.on("request" /* EventedHTTPServerEvent.REQUEST */, this.handleRequestOnHAPConnection.bind(this));
239
- this.httpServer.on("connection-closed" /* EventedHTTPServerEvent.CONNECTION_CLOSED */, this.handleConnectionClosed.bind(this));
232
+ this.httpServer = new EventedHTTPServer(() => `${accessoryInfo.displayName} ${accessoryInfo.username}`.trim());
233
+ this.httpServer.on(EventedHTTPServerEvent.LISTENING, this.onListening.bind(this));
234
+ this.httpServer.on(EventedHTTPServerEvent.REQUEST, this.handleRequestOnHAPConnection.bind(this));
235
+ this.httpServer.on(EventedHTTPServerEvent.CONNECTION_CLOSED, this.handleConnectionClosed.bind(this));
240
236
  }
241
237
  listen(port = 0, host) {
242
238
  if (host === '::') {
@@ -263,14 +259,23 @@ export class HAPServer extends EventEmitter {
263
259
  return this.httpServer.disableEventNotificationsForAccessory(aid);
264
260
  }
265
261
  /**
266
- * Send an even notification for given characteristic and changed value to all connected clients.
262
+ * Removes the event registrations every connected client holds for a characteristic which does not exist anymore.
263
+ *
264
+ * @param exists - Tells if the characteristic with the given ids still exists.
265
+ * @returns the removed registrations as `<aid>.<iid>`, once for every connection that held one.
266
+ */
267
+ disableStaleEventNotifications(exists) {
268
+ return this.httpServer.disableStaleEventNotifications(exists);
269
+ }
270
+ /**
271
+ * Send an event notification for the given characteristic and changed value to all connected clients.
267
272
  * If `originator` is specified, the given {@link HAPConnection} will be excluded from the broadcast.
268
273
  *
269
274
  * @param aid - The accessory id of the updated characteristic.
270
275
  * @param iid - The instance id of the updated characteristic.
271
276
  * @param value - The newly set value of the characteristic.
272
277
  * @param originator - If specified, the connection will not get an event message.
273
- * @param immediateDelivery - The HAP spec requires some characteristics to be delivery immediately.
278
+ * @param immediateDelivery - The HAP spec requires some characteristics to be delivered immediately.
274
279
  * Namely, for the {@link Characteristic.ButtonEvent} and the {@link Characteristic.ProgrammableSwitchEvent} characteristics.
275
280
  */
276
281
  sendEventNotifications(aid, iid, value, originator, immediateDelivery) {
@@ -278,11 +283,11 @@ export class HAPServer extends EventEmitter {
278
283
  this.httpServer.broadcastEvent(aid, iid, value, originator, immediateDelivery);
279
284
  }
280
285
  catch (error) {
281
- console.warn(`[${this.accessoryInfo.username}] Error when sending event notifications: ${error.message}`);
286
+ console.warn(`[${this.accessoryInfo.username}] Error when sending event notifications: ${errorMessage(error)}`);
282
287
  }
283
288
  }
284
289
  onListening(port, hostname) {
285
- this.emit("listening" /* HAPServerEventTypes.LISTENING */, port, hostname);
290
+ this.emit(HAPServerEventTypes.LISTENING, port, hostname);
286
291
  }
287
292
  // Called when an HTTP request was detected.
288
293
  handleRequestOnHAPConnection(connection, request, response) {
@@ -303,7 +308,7 @@ export class HAPServer extends EventEmitter {
303
308
  buffers.length = 0;
304
309
  debug('[%s] Rejecting request %s as its body exceeds %d bytes', this.accessoryInfo.username, request.url, maxBodySize);
305
310
  // closing the connection stops the client from sending the rest of the body
306
- response.writeHead(400 /* HAPHTTPCode.BAD_REQUEST */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */, 'Connection': 'close' });
311
+ response.writeHead(HAPHTTPCode.BAD_REQUEST, { 'Content-Type': HAPMimeTypes.HAP_JSON, 'Connection': 'close' });
307
312
  response.end(JSON.stringify({ status: HAPStatus.OUT_OF_RESOURCE }));
308
313
  return;
309
314
  }
@@ -320,14 +325,14 @@ export class HAPServer extends EventEmitter {
320
325
  catch {
321
326
  // e.g. "//[" parses as an invalid host. this runs in an event listener, so a throw here would crash the process
322
327
  debug('[%s] Received request with an invalid url: %s', this.accessoryInfo.username, request.url);
323
- response.writeHead(400 /* HAPHTTPCode.BAD_REQUEST */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
328
+ response.writeHead(HAPHTTPCode.BAD_REQUEST, { 'Content-Type': HAPMimeTypes.HAP_JSON });
324
329
  response.end(JSON.stringify({ status: HAPStatus.INVALID_VALUE_IN_REQUEST }));
325
330
  return;
326
331
  }
327
332
  const handler = this.getHandler(url);
328
333
  if (!handler) {
329
334
  debug('[%s] WARNING: Handler for %s not implemented', this.accessoryInfo.username, request.url);
330
- response.writeHead(404 /* HAPHTTPCode.NOT_FOUND */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
335
+ response.writeHead(HAPHTTPCode.NOT_FOUND, { 'Content-Type': HAPMimeTypes.HAP_JSON });
331
336
  response.end(JSON.stringify({ status: HAPStatus.RESOURCE_DOES_NOT_EXIST }));
332
337
  }
333
338
  else {
@@ -336,15 +341,15 @@ export class HAPServer extends EventEmitter {
336
341
  handler(connection, url, request, data, response);
337
342
  }
338
343
  catch (error) {
339
- debug('[%s] Error executing route handler: %s', this.accessoryInfo.username, error.stack);
340
- response.writeHead(500 /* HAPHTTPCode.INTERNAL_SERVER_ERROR */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
344
+ debug('[%s] Error executing route handler: %s', this.accessoryInfo.username, errorStack(error) ?? errorMessage(error));
345
+ response.writeHead(HAPHTTPCode.INTERNAL_SERVER_ERROR, { 'Content-Type': HAPMimeTypes.HAP_JSON });
341
346
  response.end(JSON.stringify({ status: HAPStatus.RESOURCE_BUSY })); // resource busy try again, does somehow fit?
342
347
  }
343
348
  }
344
349
  });
345
350
  }
346
351
  handleConnectionClosed(connection) {
347
- this.emit("connection-closed" /* HAPServerEventTypes.CONNECTION_CLOSED */, connection);
352
+ this.emit(HAPServerEventTypes.CONNECTION_CLOSED, connection);
348
353
  }
349
354
  getHandler(url) {
350
355
  switch (url.pathname.toLowerCase()) {
@@ -371,37 +376,37 @@ export class HAPServer extends EventEmitter {
371
376
  /**
372
377
  * UNPAIRED Accessory identification.
373
378
  */
374
- handleIdentifyRequest(connection, url, request, data, response) {
379
+ handleIdentifyRequest(_connection, _url, _request, _data, response) {
375
380
  // POST body is empty
376
381
  if (this.accessoryInfo.paired() && !this.allowInsecureRequest) {
377
- response.writeHead(400 /* HAPHTTPCode.BAD_REQUEST */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
382
+ response.writeHead(HAPHTTPCode.BAD_REQUEST, { 'Content-Type': HAPMimeTypes.HAP_JSON });
378
383
  response.end(JSON.stringify({ status: HAPStatus.INSUFFICIENT_PRIVILEGES }));
379
384
  return;
380
385
  }
381
- this.emit("identify" /* HAPServerEventTypes.IDENTIFY */, once((err) => {
386
+ this.emit(HAPServerEventTypes.IDENTIFY, once((err) => {
382
387
  if (!err) {
383
388
  debug('[%s] Identification success', this.accessoryInfo.username);
384
- response.writeHead(204 /* HAPHTTPCode.NO_CONTENT */);
389
+ response.writeHead(HAPHTTPCode.NO_CONTENT);
385
390
  response.end();
386
391
  }
387
392
  else {
388
393
  debug('[%s] Identification error: %s', this.accessoryInfo.username, err.message);
389
- response.writeHead(500 /* HAPHTTPCode.INTERNAL_SERVER_ERROR */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
394
+ response.writeHead(HAPHTTPCode.INTERNAL_SERVER_ERROR, { 'Content-Type': HAPMimeTypes.HAP_JSON });
390
395
  response.end(JSON.stringify({ status: HAPStatus.RESOURCE_BUSY }));
391
396
  }
392
397
  }));
393
398
  }
394
- handlePairSetup(connection, url, request, data, response) {
399
+ handlePairSetup(connection, _url, _request, data, response) {
395
400
  // Can only be directly paired with one iOS device
396
401
  if (!this.allowInsecureRequest && this.accessoryInfo.paired()) {
397
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
398
- response.end(tlv.encode(6 /* TLVValues.STATE */, 2 /* PairingStates.M2 */, 7 /* TLVValues.ERROR_CODE */, 6 /* TLVErrorCode.UNAVAILABLE */));
402
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
403
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M2, TLVValues.ERROR_CODE, TLVErrorCode.UNAVAILABLE));
399
404
  return;
400
405
  }
401
406
  if (this.unsuccessfulPairAttempts > 100) {
402
407
  debug('[%s] Reached maximum amount of unsuccessful pair attempts!', this.accessoryInfo.username);
403
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
404
- response.end(tlv.encode(6 /* TLVValues.STATE */, 2 /* PairingStates.M2 */, 7 /* TLVValues.ERROR_CODE */, 5 /* TLVErrorCode.MAX_TRIES */));
408
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
409
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M2, TLVValues.ERROR_CODE, TLVErrorCode.MAX_TRIES));
405
410
  return;
406
411
  }
407
412
  let tlvData;
@@ -409,33 +414,33 @@ export class HAPServer extends EventEmitter {
409
414
  tlvData = tlv.decode(data);
410
415
  }
411
416
  catch (error) {
412
- debug('[%s] Pair-Setup: failed to decode TLV request: %s', this.accessoryInfo.username, error.message);
413
- response.writeHead(400 /* HAPPairingHTTPCode.BAD_REQUEST */, { 'Content-Type': 'application/pairing+tlv8' });
414
- response.end(tlv.encode(6 /* TLVValues.STATE */, 2 /* PairingStates.M2 */, 7 /* TLVValues.ERROR_CODE */, 1 /* TLVErrorCode.UNKNOWN */));
417
+ debug('[%s] Pair-Setup: failed to decode TLV request: %s', this.accessoryInfo.username, errorMessage(error));
418
+ response.writeHead(HAPPairingHTTPCode.BAD_REQUEST, { 'Content-Type': 'application/pairing+tlv8' });
419
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M2, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
415
420
  return;
416
421
  }
417
- if (!tlvData[6 /* TLVValues.SEQUENCE_NUM */]) {
418
- response.writeHead(400 /* HAPPairingHTTPCode.BAD_REQUEST */, { 'Content-Type': 'application/pairing+tlv8' });
419
- response.end(tlv.encode(6 /* TLVValues.STATE */, 2 /* PairingStates.M2 */, 7 /* TLVValues.ERROR_CODE */, 1 /* TLVErrorCode.UNKNOWN */));
422
+ if (!tlvData[TLVValues.SEQUENCE_NUM]) {
423
+ response.writeHead(HAPPairingHTTPCode.BAD_REQUEST, { 'Content-Type': 'application/pairing+tlv8' });
424
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M2, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
420
425
  return;
421
426
  }
422
- const sequence = tlvData[6 /* TLVValues.SEQUENCE_NUM */][0]; // value is single byte with sequence number
423
- if (sequence === 1 /* PairingStates.M1 */ && !connection._pairSetupState) {
424
- this.handlePairSetupM1(connection, request, response);
427
+ const sequence = tlvData[TLVValues.SEQUENCE_NUM][0]; // value is single byte with sequence number
428
+ if (sequence === PairingStates.M1 && !connection._pairSetupState) {
429
+ this.handlePairSetupM1(connection, response);
425
430
  }
426
- else if (sequence === 3 /* PairingStates.M3 */ && connection._pairSetupState === 2 /* PairingStates.M2 */) {
427
- this.handlePairSetupM3(connection, request, response, tlvData);
431
+ else if (sequence === PairingStates.M3 && connection._pairSetupState === PairingStates.M2) {
432
+ this.handlePairSetupM3(connection, response, tlvData);
428
433
  }
429
- else if (sequence === 5 /* PairingStates.M5 */ && connection._pairSetupState === 4 /* PairingStates.M4 */) {
430
- this.handlePairSetupM5(connection, request, response, tlvData);
434
+ else if (sequence === PairingStates.M5 && connection._pairSetupState === PairingStates.M4) {
435
+ this.handlePairSetupM5(connection, response, tlvData);
431
436
  }
432
437
  else {
433
438
  // Invalid state/sequence number
434
- response.writeHead(400 /* HAPPairingHTTPCode.BAD_REQUEST */, { 'Content-Type': 'application/pairing+tlv8' });
435
- response.end(tlv.encode(6 /* TLVValues.STATE */, sequence + 1, 7 /* TLVValues.ERROR_CODE */, 1 /* TLVErrorCode.UNKNOWN */));
439
+ response.writeHead(HAPPairingHTTPCode.BAD_REQUEST, { 'Content-Type': 'application/pairing+tlv8' });
440
+ response.end(tlv.encode(TLVValues.STATE, sequence + 1, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
436
441
  }
437
442
  }
438
- handlePairSetupM1(connection, request, response) {
443
+ handlePairSetupM1(connection, response) {
439
444
  debug('[%s] Pair step 1/5', this.accessoryInfo.username);
440
445
  const salt = crypto.randomBytes(16);
441
446
  const srpParams = SRP.params.hap;
@@ -445,49 +450,61 @@ export class HAPServer extends EventEmitter {
445
450
  const srpB = srpServer.computeB();
446
451
  // attach it to the current TCP session
447
452
  connection.srpServer = srpServer;
448
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
449
- response.end(tlv.encode(6 /* TLVValues.SEQUENCE_NUM */, 2 /* PairingStates.M2 */, 2 /* TLVValues.SALT */, salt, 3 /* TLVValues.PUBLIC_KEY */, srpB));
450
- connection._pairSetupState = 2 /* PairingStates.M2 */;
453
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
454
+ response.end(tlv.encode(TLVValues.SEQUENCE_NUM, PairingStates.M2, TLVValues.SALT, salt, TLVValues.PUBLIC_KEY, srpB));
455
+ connection._pairSetupState = PairingStates.M2;
451
456
  }).catch((error) => {
452
457
  debug('[%s] Error occurred when generating srp key: %s', this.accessoryInfo.username, error.message);
453
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
454
- response.end(tlv.encode(6 /* TLVValues.STATE */, 2 /* PairingStates.M2 */, 7 /* TLVValues.ERROR_CODE */, 1 /* TLVErrorCode.UNKNOWN */));
458
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
459
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M2, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
455
460
  });
456
461
  }
457
- handlePairSetupM3(connection, request, response, tlvData) {
462
+ handlePairSetupM3(connection, response, tlvData) {
458
463
  debug('[%s] Pair step 2/5', this.accessoryInfo.username);
459
- const A = tlvData[3 /* TLVValues.PUBLIC_KEY */]; // "A is a public key that exists only for a single login session."
460
- const M1 = tlvData[4 /* TLVValues.PASSWORD_PROOF */]; // "M1 is the proof that you actually know your own password."
461
- // pull the SRP server we created in stepOne out of the current session
464
+ const A = tlvData[TLVValues.PUBLIC_KEY]; // "A is a public key that exists only for a single login session."
465
+ const M1 = tlvData[TLVValues.PASSWORD_PROOF]; // "M1 is the proof that you actually know your own password."
466
+ // pull the SRP server we created in handlePairSetupM1 out of the current session
462
467
  const srpServer = connection.srpServer;
463
- srpServer.setA(A);
468
+ try {
469
+ if (!A || !M1) {
470
+ throw new Error('the public key or the proof is missing');
471
+ }
472
+ srpServer.setA(A); // throws for a key the SRP exchange cannot use, like one of only zero bytes
473
+ }
474
+ catch (err) {
475
+ debug('[%s] M3: Invalid request: %s', this.accessoryInfo.username, errorMessage(err));
476
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
477
+ response.end(tlv.encode(TLVValues.SEQUENCE_NUM, PairingStates.M4, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
478
+ connection._pairSetupState = undefined;
479
+ return;
480
+ }
464
481
  try {
465
482
  srpServer.checkM1(M1);
466
483
  }
467
484
  catch (err) {
468
485
  // most likely the client supplied an incorrect pincode.
469
486
  this.unsuccessfulPairAttempts++;
470
- debug('[%s] Error while checking pincode: %s', this.accessoryInfo.username, err.message);
471
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
472
- response.end(tlv.encode(6 /* TLVValues.SEQUENCE_NUM */, 4 /* PairingStates.M4 */, 7 /* TLVValues.ERROR_CODE */, 2 /* TLVErrorCode.AUTHENTICATION */));
487
+ debug('[%s] Error while checking pincode: %s', this.accessoryInfo.username, errorMessage(err));
488
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
489
+ response.end(tlv.encode(TLVValues.SEQUENCE_NUM, PairingStates.M4, TLVValues.ERROR_CODE, TLVErrorCode.AUTHENTICATION));
473
490
  connection._pairSetupState = undefined;
474
491
  return;
475
492
  }
476
493
  // "M2 is the proof that the server actually knows your password."
477
494
  const M2 = srpServer.computeM2();
478
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
479
- response.end(tlv.encode(6 /* TLVValues.SEQUENCE_NUM */, 4 /* PairingStates.M4 */, 4 /* TLVValues.PASSWORD_PROOF */, M2));
480
- connection._pairSetupState = 4 /* PairingStates.M4 */;
495
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
496
+ response.end(tlv.encode(TLVValues.SEQUENCE_NUM, PairingStates.M4, TLVValues.PASSWORD_PROOF, M2));
497
+ connection._pairSetupState = PairingStates.M4;
481
498
  }
482
- handlePairSetupM5(connection, request, response, tlvData) {
499
+ handlePairSetupM5(connection, response, tlvData) {
483
500
  debug('[%s] Pair step 3/5', this.accessoryInfo.username);
484
- // pull the SRP server we created in stepOne out of the current session
501
+ // pull the SRP server we created in handlePairSetupM1 out of the current session
485
502
  const srpServer = connection.srpServer;
486
- const encryptedData = tlvData[5 /* TLVValues.ENCRYPTED_DATA */];
503
+ const encryptedData = tlvData[TLVValues.ENCRYPTED_DATA];
487
504
  if (!encryptedData || encryptedData.length < 16) {
488
505
  debug('[%s] M5: Encrypted data missing or too short', this.accessoryInfo.username);
489
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
490
- response.end(tlv.encode(6 /* TLVValues.SEQUENCE_NUM */, 4 /* PairingStates.M4 */, 7 /* TLVValues.ERROR_CODE */, 2 /* TLVErrorCode.AUTHENTICATION */));
506
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
507
+ response.end(tlv.encode(TLVValues.SEQUENCE_NUM, PairingStates.M6, TLVValues.ERROR_CODE, TLVErrorCode.AUTHENTICATION));
491
508
  connection._pairSetupState = undefined;
492
509
  return;
493
510
  }
@@ -505,8 +522,8 @@ export class HAPServer extends EventEmitter {
505
522
  }
506
523
  catch (error) {
507
524
  debug('[%s] Error while decrypting and verifying M5 subTlv: %s', this.accessoryInfo.username, error);
508
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
509
- response.end(tlv.encode(6 /* TLVValues.SEQUENCE_NUM */, 4 /* PairingStates.M4 */, 7 /* TLVValues.ERROR_CODE */, 2 /* TLVErrorCode.AUTHENTICATION */));
525
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
526
+ response.end(tlv.encode(TLVValues.SEQUENCE_NUM, PairingStates.M6, TLVValues.ERROR_CODE, TLVErrorCode.AUTHENTICATION));
510
527
  connection._pairSetupState = undefined;
511
528
  return;
512
529
  }
@@ -516,26 +533,26 @@ export class HAPServer extends EventEmitter {
516
533
  M5Packet = tlv.decode(plaintext);
517
534
  }
518
535
  catch (error) {
519
- debug('[%s] M5: Failed to decode decrypted TLV payload: %s', this.accessoryInfo.username, error.message);
520
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
521
- response.end(tlv.encode(6 /* TLVValues.SEQUENCE_NUM */, 4 /* PairingStates.M4 */, 7 /* TLVValues.ERROR_CODE */, 1 /* TLVErrorCode.UNKNOWN */));
536
+ debug('[%s] M5: Failed to decode decrypted TLV payload: %s', this.accessoryInfo.username, errorMessage(error));
537
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
538
+ response.end(tlv.encode(TLVValues.SEQUENCE_NUM, PairingStates.M6, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
522
539
  connection._pairSetupState = undefined;
523
540
  return;
524
541
  }
525
- const clientUsername = M5Packet[1 /* TLVValues.USERNAME */];
526
- const clientLTPK = M5Packet[3 /* TLVValues.PUBLIC_KEY */];
527
- const clientProof = M5Packet[10 /* TLVValues.PROOF */];
542
+ const clientUsername = M5Packet[TLVValues.USERNAME];
543
+ const clientLTPK = M5Packet[TLVValues.PUBLIC_KEY];
544
+ const clientProof = M5Packet[TLVValues.PROOF];
528
545
  if (!clientUsername || !clientLTPK || !clientProof) {
529
546
  debug('[%s] M5: Missing required TLV fields in decrypted payload', this.accessoryInfo.username);
530
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
531
- response.end(tlv.encode(6 /* TLVValues.SEQUENCE_NUM */, 4 /* PairingStates.M4 */, 7 /* TLVValues.ERROR_CODE */, 1 /* TLVErrorCode.UNKNOWN */));
547
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
548
+ response.end(tlv.encode(TLVValues.SEQUENCE_NUM, PairingStates.M6, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
532
549
  connection._pairSetupState = undefined;
533
550
  return;
534
551
  }
535
- this.handlePairSetupM5_2(connection, request, response, clientUsername, clientLTPK, clientProof, outputKey);
552
+ this.handlePairSetupM5_2(connection, response, clientUsername, clientLTPK, clientProof, outputKey);
536
553
  }
537
554
  // M5-2
538
- handlePairSetupM5_2(connection, request, response, clientUsername, clientLTPK, clientProof, hkdfEncKey) {
555
+ handlePairSetupM5_2(connection, response, clientUsername, clientLTPK, clientProof, hkdfEncKey) {
539
556
  debug('[%s] Pair step 4/5', this.accessoryInfo.username);
540
557
  const S_private = connection.srpServer.computeK();
541
558
  const controllerSalt = Buffer.from('Pair-Setup-Controller-Sign-Salt');
@@ -544,15 +561,15 @@ export class HAPServer extends EventEmitter {
544
561
  const completeData = Buffer.concat([outputKey, clientUsername, clientLTPK]);
545
562
  if (!hapCrypto.ed25519Verify(completeData, clientProof, clientLTPK)) {
546
563
  debug('[%s] Invalid signature', this.accessoryInfo.username);
547
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
548
- response.end(tlv.encode(6 /* TLVValues.SEQUENCE_NUM */, 6 /* PairingStates.M6 */, 7 /* TLVValues.ERROR_CODE */, 2 /* TLVErrorCode.AUTHENTICATION */));
564
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
565
+ response.end(tlv.encode(TLVValues.SEQUENCE_NUM, PairingStates.M6, TLVValues.ERROR_CODE, TLVErrorCode.AUTHENTICATION));
549
566
  connection._pairSetupState = undefined;
550
567
  return;
551
568
  }
552
- this.handlePairSetupM5_3(connection, request, response, clientUsername, clientLTPK, hkdfEncKey);
569
+ this.handlePairSetupM5_3(connection, response, clientUsername, clientLTPK, hkdfEncKey);
553
570
  }
554
571
  // M5 - F + M6
555
- handlePairSetupM5_3(connection, request, response, clientUsername, clientLTPK, hkdfEncKey) {
572
+ handlePairSetupM5_3(connection, response, clientUsername, clientLTPK, hkdfEncKey) {
556
573
  debug('[%s] Pair step 5/5', this.accessoryInfo.username);
557
574
  const S_private = connection.srpServer.computeK();
558
575
  const accessorySalt = Buffer.from('Pair-Setup-Accessory-Sign-Salt');
@@ -563,63 +580,70 @@ export class HAPServer extends EventEmitter {
563
580
  const material = Buffer.concat([outputKey, usernameData, serverLTPK]);
564
581
  const privateKey = Buffer.from(this.accessoryInfo.signSk);
565
582
  const serverProof = hapCrypto.ed25519Sign(material, privateKey);
566
- const message = tlv.encode(1 /* TLVValues.USERNAME */, usernameData, 3 /* TLVValues.PUBLIC_KEY */, serverLTPK, 10 /* TLVValues.PROOF */, serverProof);
583
+ const message = tlv.encode(TLVValues.USERNAME, usernameData, TLVValues.PUBLIC_KEY, serverLTPK, TLVValues.PROOF, serverProof);
567
584
  const encrypted = hapCrypto.chacha20_poly1305_encryptAndSeal(hkdfEncKey, Buffer.from('PS-Msg06'), null, message);
568
585
  // finally, notify listeners that we have been paired with a client
569
- this.emit("pair" /* HAPServerEventTypes.PAIR */, clientUsername.toString(), clientLTPK, once((err) => {
586
+ this.emit(HAPServerEventTypes.PAIR, clientUsername.toString(), clientLTPK, once((err) => {
570
587
  if (err) {
571
588
  debug('[%s] Error adding pairing info: %s', this.accessoryInfo.username, err.message);
572
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
573
- response.end(tlv.encode(6 /* TLVValues.SEQUENCE_NUM */, 6 /* PairingStates.M6 */, 7 /* TLVValues.ERROR_CODE */, 1 /* TLVErrorCode.UNKNOWN */));
589
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
590
+ response.end(tlv.encode(TLVValues.SEQUENCE_NUM, PairingStates.M6, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
574
591
  connection._pairSetupState = undefined;
575
592
  return;
576
593
  }
577
594
  // send final pairing response to client
578
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
579
- response.end(tlv.encode(6 /* TLVValues.SEQUENCE_NUM */, 6 /* PairingStates.M6 */, 5 /* TLVValues.ENCRYPTED_DATA */, Buffer.concat([encrypted.ciphertext, encrypted.authTag])));
595
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
596
+ response.end(tlv.encode(TLVValues.SEQUENCE_NUM, PairingStates.M6, TLVValues.ENCRYPTED_DATA, Buffer.concat([encrypted.ciphertext, encrypted.authTag])));
580
597
  connection._pairSetupState = undefined;
581
598
  }));
582
599
  }
583
- handlePairVerify(connection, url, request, data, response) {
600
+ handlePairVerify(connection, _url, _request, data, response) {
584
601
  let tlvData;
585
602
  try {
586
603
  tlvData = tlv.decode(data);
587
604
  }
588
605
  catch (error) {
589
- debug('[%s] Pair-Verify: failed to decode TLV request: %s', this.accessoryInfo.username, error.message);
590
- response.writeHead(400 /* HAPPairingHTTPCode.BAD_REQUEST */, { 'Content-Type': 'application/pairing+tlv8' });
591
- response.end(tlv.encode(6 /* TLVValues.STATE */, 2 /* PairingStates.M2 */, 7 /* TLVValues.ERROR_CODE */, 1 /* TLVErrorCode.UNKNOWN */));
606
+ debug('[%s] Pair-Verify: failed to decode TLV request: %s', this.accessoryInfo.username, errorMessage(error));
607
+ response.writeHead(HAPPairingHTTPCode.BAD_REQUEST, { 'Content-Type': 'application/pairing+tlv8' });
608
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M2, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
592
609
  return;
593
610
  }
594
- if (!tlvData[6 /* TLVValues.SEQUENCE_NUM */]) {
595
- response.writeHead(400 /* HAPPairingHTTPCode.BAD_REQUEST */, { 'Content-Type': 'application/pairing+tlv8' });
596
- response.end(tlv.encode(6 /* TLVValues.STATE */, 2 /* PairingStates.M2 */, 7 /* TLVValues.ERROR_CODE */, 1 /* TLVErrorCode.UNKNOWN */));
611
+ if (!tlvData[TLVValues.SEQUENCE_NUM]) {
612
+ response.writeHead(HAPPairingHTTPCode.BAD_REQUEST, { 'Content-Type': 'application/pairing+tlv8' });
613
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M2, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
597
614
  return;
598
615
  }
599
- const sequence = tlvData[6 /* TLVValues.SEQUENCE_NUM */][0]; // value is single byte with sequence number
616
+ const sequence = tlvData[TLVValues.SEQUENCE_NUM][0]; // value is single byte with sequence number
600
617
  if (connection.isAuthenticated()) {
601
618
  // M1 would replace the session keys of this connection with empty ones: it would keep counting as
602
619
  // authenticated while accepting and sending plaintext
603
620
  debug('[%s] Pair-Verify: rejecting pair-verify on an already verified connection', this.accessoryInfo.username);
604
- response.writeHead(400 /* HAPPairingHTTPCode.BAD_REQUEST */, { 'Content-Type': 'application/pairing+tlv8' });
605
- response.end(tlv.encode(6 /* TLVValues.STATE */, sequence + 1, 7 /* TLVValues.ERROR_CODE */, 1 /* TLVErrorCode.UNKNOWN */));
621
+ response.writeHead(HAPPairingHTTPCode.BAD_REQUEST, { 'Content-Type': 'application/pairing+tlv8' });
622
+ response.end(tlv.encode(TLVValues.STATE, sequence + 1, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
606
623
  return;
607
624
  }
608
- if (sequence === 1 /* PairingStates.M1 */) {
609
- this.handlePairVerifyM1(connection, request, response, tlvData);
625
+ if (sequence === PairingStates.M1) {
626
+ this.handlePairVerifyM1(connection, response, tlvData);
610
627
  }
611
- else if (sequence === 3 /* PairingStates.M3 */ && connection._pairVerifyState === 2 /* PairingStates.M2 */) {
612
- this.handlePairVerifyM3(connection, request, response, tlvData);
628
+ else if (sequence === PairingStates.M3 && connection._pairVerifyState === PairingStates.M2) {
629
+ this.handlePairVerifyM3(connection, response, tlvData);
613
630
  }
614
631
  else {
615
632
  // Invalid state/sequence number
616
- response.writeHead(400 /* HAPPairingHTTPCode.BAD_REQUEST */, { 'Content-Type': 'application/pairing+tlv8' });
617
- response.end(tlv.encode(6 /* TLVValues.STATE */, sequence + 1, 7 /* TLVValues.ERROR_CODE */, 1 /* TLVErrorCode.UNKNOWN */));
633
+ response.writeHead(HAPPairingHTTPCode.BAD_REQUEST, { 'Content-Type': 'application/pairing+tlv8' });
634
+ response.end(tlv.encode(TLVValues.STATE, sequence + 1, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
618
635
  }
619
636
  }
620
- handlePairVerifyM1(connection, request, response, tlvData) {
637
+ handlePairVerifyM1(connection, response, tlvData) {
621
638
  debug('[%s] Pair verify step 1/2', this.accessoryInfo.username);
622
- const clientPublicKey = tlvData[3 /* TLVValues.PUBLIC_KEY */]; // Buffer
639
+ const clientPublicKey = tlvData[TLVValues.PUBLIC_KEY]; // Buffer
640
+ if (!clientPublicKey || clientPublicKey.length !== 32) {
641
+ debug('[%s] M1: The Curve25519 public key is missing or does not have 32 bytes', this.accessoryInfo.username);
642
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
643
+ response.end(tlv.encode(TLVValues.SEQUENCE_NUM, PairingStates.M2, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
644
+ connection._pairVerifyState = undefined;
645
+ return;
646
+ }
623
647
  // generate new encryption keys for this session
624
648
  const keyPair = hapCrypto.generateCurve25519KeyPair();
625
649
  const secretKey = Buffer.from(keyPair.secretKey);
@@ -634,19 +658,19 @@ export class HAPServer extends EventEmitter {
634
658
  const outputKey = hapCrypto.HKDF('sha512', encSalt, sharedSec, encInfo, 32).subarray(0, 32);
635
659
  connection.encryption = new HAPEncryption(clientPublicKey, secretKey, publicKey, sharedSec, outputKey);
636
660
  // compose the response data in TLV format
637
- const message = tlv.encode(1 /* TLVValues.USERNAME */, usernameData, 10 /* TLVValues.PROOF */, serverProof);
661
+ const message = tlv.encode(TLVValues.USERNAME, usernameData, TLVValues.PROOF, serverProof);
638
662
  const encrypted = hapCrypto.chacha20_poly1305_encryptAndSeal(outputKey, Buffer.from('PV-Msg02'), null, message);
639
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
640
- response.end(tlv.encode(6 /* TLVValues.SEQUENCE_NUM */, 2 /* PairingStates.M2 */, 5 /* TLVValues.ENCRYPTED_DATA */, Buffer.concat([encrypted.ciphertext, encrypted.authTag]), 3 /* TLVValues.PUBLIC_KEY */, publicKey));
641
- connection._pairVerifyState = 2 /* PairingStates.M2 */;
663
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
664
+ response.end(tlv.encode(TLVValues.SEQUENCE_NUM, PairingStates.M2, TLVValues.ENCRYPTED_DATA, Buffer.concat([encrypted.ciphertext, encrypted.authTag]), TLVValues.PUBLIC_KEY, publicKey));
665
+ connection._pairVerifyState = PairingStates.M2;
642
666
  }
643
- handlePairVerifyM3(connection, request, response, objects) {
667
+ handlePairVerifyM3(connection, response, objects) {
644
668
  debug('[%s] Pair verify step 2/2', this.accessoryInfo.username);
645
- const encryptedData = objects[5 /* TLVValues.ENCRYPTED_DATA */];
669
+ const encryptedData = objects[TLVValues.ENCRYPTED_DATA];
646
670
  if (!encryptedData || encryptedData.length < 16) {
647
671
  debug('[%s] M3: Encrypted data missing or too short', this.accessoryInfo.username);
648
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
649
- response.end(tlv.encode(6 /* TLVValues.STATE */, 4 /* PairingStates.M4 */, 7 /* TLVValues.ERROR_CODE */, 2 /* TLVErrorCode.AUTHENTICATION */));
672
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
673
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M4, TLVValues.ERROR_CODE, TLVErrorCode.AUTHENTICATION));
650
674
  connection._pairVerifyState = undefined;
651
675
  return;
652
676
  }
@@ -654,7 +678,7 @@ export class HAPServer extends EventEmitter {
654
678
  const authTagData = Buffer.alloc(16);
655
679
  encryptedData.copy(messageData, 0, 0, encryptedData.length - 16);
656
680
  encryptedData.copy(authTagData, 0, encryptedData.length - 16, encryptedData.length);
657
- // instance of HAPEncryption (created in handlePairVerifyStepOne)
681
+ // instance of HAPEncryption (created in handlePairVerifyM1)
658
682
  const enc = connection.encryption;
659
683
  let plaintext;
660
684
  try {
@@ -662,8 +686,8 @@ export class HAPServer extends EventEmitter {
662
686
  }
663
687
  catch (error) {
664
688
  debug('[%s] M3: Failed to decrypt and/or verify: %s', this.accessoryInfo.username, error);
665
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
666
- response.end(tlv.encode(6 /* TLVValues.STATE */, 4 /* PairingStates.M4 */, 7 /* TLVValues.ERROR_CODE */, 2 /* TLVErrorCode.AUTHENTICATION */));
689
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
690
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M4, TLVValues.ERROR_CODE, TLVErrorCode.AUTHENTICATION));
667
691
  connection._pairVerifyState = undefined;
668
692
  return;
669
693
  }
@@ -672,18 +696,18 @@ export class HAPServer extends EventEmitter {
672
696
  decoded = tlv.decode(plaintext);
673
697
  }
674
698
  catch (error) {
675
- debug('[%s] M3: Failed to decode decrypted TLV payload: %s', this.accessoryInfo.username, error.message);
676
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
677
- response.end(tlv.encode(6 /* TLVValues.STATE */, 4 /* PairingStates.M4 */, 7 /* TLVValues.ERROR_CODE */, 1 /* TLVErrorCode.UNKNOWN */));
699
+ debug('[%s] M3: Failed to decode decrypted TLV payload: %s', this.accessoryInfo.username, errorMessage(error));
700
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
701
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M4, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
678
702
  connection._pairVerifyState = undefined;
679
703
  return;
680
704
  }
681
- const clientUsername = decoded[1 /* TLVValues.USERNAME */];
682
- const proof = decoded[10 /* TLVValues.PROOF */];
705
+ const clientUsername = decoded[TLVValues.USERNAME];
706
+ const proof = decoded[TLVValues.PROOF];
683
707
  if (!clientUsername || !proof) {
684
708
  debug('[%s] M3: Missing required TLV fields in decrypted payload', this.accessoryInfo.username);
685
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
686
- response.end(tlv.encode(6 /* TLVValues.STATE */, 4 /* PairingStates.M4 */, 7 /* TLVValues.ERROR_CODE */, 1 /* TLVErrorCode.UNKNOWN */));
709
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
710
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M4, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
687
711
  connection._pairVerifyState = undefined;
688
712
  return;
689
713
  }
@@ -694,37 +718,37 @@ export class HAPServer extends EventEmitter {
694
718
  // disagree. Respond with invalid request (seems to match HomeKit Accessory Simulator behavior)
695
719
  if (!clientPublicKey) {
696
720
  debug('[%s] Client %s attempting to verify, but we are not paired; rejecting client', this.accessoryInfo.username, clientUsername);
697
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
698
- response.end(tlv.encode(6 /* TLVValues.STATE */, 4 /* PairingStates.M4 */, 7 /* TLVValues.ERROR_CODE */, 2 /* TLVErrorCode.AUTHENTICATION */));
721
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
722
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M4, TLVValues.ERROR_CODE, TLVErrorCode.AUTHENTICATION));
699
723
  connection._pairVerifyState = undefined;
700
724
  return;
701
725
  }
702
726
  if (!hapCrypto.ed25519Verify(material, proof, clientPublicKey)) {
703
727
  debug('[%s] Client %s provided an invalid signature', this.accessoryInfo.username, clientUsername);
704
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
705
- response.end(tlv.encode(6 /* TLVValues.STATE */, 4 /* PairingStates.M4 */, 7 /* TLVValues.ERROR_CODE */, 2 /* TLVErrorCode.AUTHENTICATION */));
728
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
729
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M4, TLVValues.ERROR_CODE, TLVErrorCode.AUTHENTICATION));
706
730
  connection._pairVerifyState = undefined;
707
731
  return;
708
732
  }
709
733
  debug('[%s] Client %s verification complete', this.accessoryInfo.username, clientUsername);
710
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
711
- response.end(tlv.encode(6 /* TLVValues.SEQUENCE_NUM */, 4 /* PairingStates.M4 */));
734
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
735
+ response.end(tlv.encode(TLVValues.SEQUENCE_NUM, PairingStates.M4));
712
736
  // now that the client has been verified, we must "upgrade" our pseudo-HTTP connection to include
713
737
  // TCP-level encryption. We'll do this by adding some more encryption vars to the session, and using them
714
- // in future calls to onEncrypt, onDecrypt.
738
+ // in future calls to encrypt and decrypt of the HAPConnection.
715
739
  const encSalt = Buffer.from('Control-Salt');
716
740
  const infoRead = Buffer.from('Control-Read-Encryption-Key');
717
741
  const infoWrite = Buffer.from('Control-Write-Encryption-Key');
718
742
  enc.accessoryToControllerKey = hapCrypto.HKDF('sha512', encSalt, enc.sharedSecret, infoRead, 32);
719
743
  enc.controllerToAccessoryKey = hapCrypto.HKDF('sha512', encSalt, enc.sharedSecret, infoWrite, 32);
720
- // Our connection is now completely setup. We now want to subscribe this connection to special
744
+ // Our connection is now completely set up.
721
745
  connection.connectionAuthenticated(clientUsername.toString());
722
746
  connection._pairVerifyState = undefined;
723
747
  }
724
- handlePairings(connection, url, request, data, response) {
725
- // Only accept /pairing request if there is a secure session
748
+ handlePairings(connection, _url, _request, data, response) {
749
+ // Only accept a /pairings request if there is a secure session
726
750
  if (!this.allowInsecureRequest && !connection.isAuthenticated()) {
727
- response.writeHead(470 /* HAPPairingHTTPCode.CONNECTION_AUTHORIZATION_REQUIRED */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
751
+ response.writeHead(HAPPairingHTTPCode.CONNECTION_AUTHORIZATION_REQUIRED, { 'Content-Type': HAPMimeTypes.HAP_JSON });
728
752
  response.end(JSON.stringify({ status: HAPStatus.INSUFFICIENT_PRIVILEGES }));
729
753
  return;
730
754
  }
@@ -733,112 +757,117 @@ export class HAPServer extends EventEmitter {
733
757
  objects = tlv.decode(data);
734
758
  }
735
759
  catch (error) {
736
- debug('[%s] Pairings: failed to decode TLV request: %s', this.accessoryInfo.username, error.message);
737
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
738
- response.end(tlv.encode(6 /* TLVValues.STATE */, 2 /* PairingStates.M2 */, 7 /* TLVValues.ERROR_CODE */, 1 /* TLVErrorCode.UNKNOWN */));
760
+ debug('[%s] Pairings: failed to decode TLV request: %s', this.accessoryInfo.username, errorMessage(error));
761
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
762
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M2, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
739
763
  return;
740
764
  }
741
- if (!objects[0 /* TLVValues.METHOD */] || !objects[6 /* TLVValues.STATE */]) {
742
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
743
- response.end(tlv.encode(6 /* TLVValues.STATE */, 2 /* PairingStates.M2 */, 7 /* TLVValues.ERROR_CODE */, 1 /* TLVErrorCode.UNKNOWN */));
765
+ if (!objects[TLVValues.METHOD] || !objects[TLVValues.STATE]) {
766
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
767
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M2, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
744
768
  return;
745
769
  }
746
- const method = objects[0 /* TLVValues.METHOD */][0]; // value is single byte with request type
747
- const state = objects[6 /* TLVValues.STATE */][0];
748
- if (state !== 1 /* PairingStates.M1 */) {
770
+ const method = objects[TLVValues.METHOD][0]; // value is single byte with request type
771
+ const state = objects[TLVValues.STATE][0];
772
+ if (state !== PairingStates.M1) {
749
773
  debug('[%s] Pairings: received unexpected state %d', this.accessoryInfo.username, state);
750
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
751
- response.end(tlv.encode(6 /* TLVValues.STATE */, 2 /* PairingStates.M2 */, 7 /* TLVValues.ERROR_CODE */, 1 /* TLVErrorCode.UNKNOWN */));
774
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
775
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M2, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
752
776
  return;
753
777
  }
754
- if (method === 3 /* PairMethods.ADD_PAIRING */) {
755
- if (!objects[1 /* TLVValues.IDENTIFIER */] || !objects[3 /* TLVValues.PUBLIC_KEY */] || !objects[11 /* TLVValues.PERMISSIONS */]) {
756
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
757
- response.end(tlv.encode(6 /* TLVValues.STATE */, 2 /* PairingStates.M2 */, 7 /* TLVValues.ERROR_CODE */, 1 /* TLVErrorCode.UNKNOWN */));
778
+ if (method === PairMethods.ADD_PAIRING) {
779
+ // an empty or unknown permission would be stored as it is: an admin given one stops counting as admin, and the stored
780
+ // value makes every later LIST_PAIRINGS fail. A controller's long-term public key is an Ed25519 key of 32 bytes.
781
+ // 0 and 1 are PermissionTypes.USER and ADMIN (a type import only: AccessoryInfo loads Accessory, which loads this file)
782
+ const permissionsValue = objects[TLVValues.PERMISSIONS];
783
+ if (!objects[TLVValues.IDENTIFIER] || objects[TLVValues.PUBLIC_KEY]?.length !== 32 || permissionsValue?.length !== 1
784
+ || permissionsValue[0] > 1) {
785
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
786
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M2, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
758
787
  return;
759
788
  }
760
- const identifier = objects[1 /* TLVValues.IDENTIFIER */].toString();
761
- const publicKey = objects[3 /* TLVValues.PUBLIC_KEY */];
762
- const permissions = objects[11 /* TLVValues.PERMISSIONS */][0];
763
- this.emit("add-pairing" /* HAPServerEventTypes.ADD_PAIRING */, connection, identifier, publicKey, permissions, once((error) => {
789
+ const identifier = objects[TLVValues.IDENTIFIER].toString();
790
+ const publicKey = objects[TLVValues.PUBLIC_KEY];
791
+ const permissions = objects[TLVValues.PERMISSIONS][0];
792
+ this.emit(HAPServerEventTypes.ADD_PAIRING, connection, identifier, publicKey, permissions, once((error) => {
764
793
  if (error > 0) {
765
794
  debug('[%s] Pairings: failed ADD_PAIRING with code %d', this.accessoryInfo.username, error);
766
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
767
- response.end(tlv.encode(6 /* TLVValues.STATE */, 2 /* PairingStates.M2 */, 7 /* TLVValues.ERROR_CODE */, error));
795
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
796
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M2, TLVValues.ERROR_CODE, error));
768
797
  return;
769
798
  }
770
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
771
- response.end(tlv.encode(6 /* TLVValues.STATE */, 2 /* PairingStates.M2 */));
799
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
800
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M2));
772
801
  debug('[%s] Pairings: successfully executed ADD_PAIRING', this.accessoryInfo.username);
773
802
  }));
774
803
  }
775
- else if (method === 4 /* PairMethods.REMOVE_PAIRING */) {
776
- if (!objects[1 /* TLVValues.IDENTIFIER */]) {
777
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
778
- response.end(tlv.encode(6 /* TLVValues.STATE */, 2 /* PairingStates.M2 */, 7 /* TLVValues.ERROR_CODE */, 1 /* TLVErrorCode.UNKNOWN */));
804
+ else if (method === PairMethods.REMOVE_PAIRING) {
805
+ if (!objects[TLVValues.IDENTIFIER]) {
806
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
807
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M2, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
779
808
  return;
780
809
  }
781
- const identifier = objects[1 /* TLVValues.IDENTIFIER */].toString();
782
- this.emit("remove-pairing" /* HAPServerEventTypes.REMOVE_PAIRING */, connection, identifier, once((error) => {
810
+ const identifier = objects[TLVValues.IDENTIFIER].toString();
811
+ this.emit(HAPServerEventTypes.REMOVE_PAIRING, connection, identifier, once((error) => {
783
812
  if (error > 0) {
784
813
  debug('[%s] Pairings: failed REMOVE_PAIRING with code %d', this.accessoryInfo.username, error);
785
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
786
- response.end(tlv.encode(6 /* TLVValues.STATE */, 2 /* PairingStates.M2 */, 7 /* TLVValues.ERROR_CODE */, error));
814
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
815
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M2, TLVValues.ERROR_CODE, error));
787
816
  return;
788
817
  }
789
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
790
- response.end(tlv.encode(6 /* TLVValues.STATE */, 2 /* PairingStates.M2 */));
818
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
819
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M2));
791
820
  debug('[%s] Pairings: successfully executed REMOVE_PAIRING', this.accessoryInfo.username);
792
821
  }));
793
822
  }
794
- else if (method === 5 /* PairMethods.LIST_PAIRINGS */) {
795
- this.emit("list-pairings" /* HAPServerEventTypes.LIST_PAIRINGS */, connection, once((error, data) => {
823
+ else if (method === PairMethods.LIST_PAIRINGS) {
824
+ this.emit(HAPServerEventTypes.LIST_PAIRINGS, connection, once((error, data) => {
796
825
  if (error > 0) {
797
826
  debug('[%s] Pairings: failed LIST_PAIRINGS with code %d', this.accessoryInfo.username, error);
798
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
799
- response.end(tlv.encode(6 /* TLVValues.STATE */, 2 /* PairingStates.M2 */, 7 /* TLVValues.ERROR_CODE */, error));
827
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
828
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M2, TLVValues.ERROR_CODE, error));
800
829
  return;
801
830
  }
802
831
  const tlvList = [];
803
832
  data.forEach((value, index) => {
804
833
  if (index > 0) {
805
- tlvList.push(255 /* TLVValues.SEPARATOR */, Buffer.alloc(0));
834
+ tlvList.push(TLVValues.SEPARATOR, Buffer.alloc(0));
806
835
  }
807
- tlvList.push(1 /* TLVValues.IDENTIFIER */, value.username, 3 /* TLVValues.PUBLIC_KEY */, value.publicKey, 11 /* TLVValues.PERMISSIONS */, value.permission);
836
+ tlvList.push(TLVValues.IDENTIFIER, value.username, TLVValues.PUBLIC_KEY, value.publicKey, TLVValues.PERMISSIONS, value.permission);
808
837
  });
809
- const list = tlv.encode(6 /* TLVValues.STATE */, 2 /* PairingStates.M2 */, ...tlvList);
810
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': "application/pairing+tlv8" /* HAPMimeTypes.PAIRING_TLV8 */ });
838
+ const list = tlv.encode(TLVValues.STATE, PairingStates.M2, ...tlvList);
839
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': HAPMimeTypes.PAIRING_TLV8 });
811
840
  response.end(list);
812
841
  debug('[%s] Pairings: successfully executed LIST_PAIRINGS', this.accessoryInfo.username);
813
842
  }));
814
843
  }
815
844
  else {
816
845
  debug('[%s] Pairings: received unsupported method %d', this.accessoryInfo.username, method);
817
- response.writeHead(200 /* HAPPairingHTTPCode.OK */, { 'Content-Type': 'application/pairing+tlv8' });
818
- response.end(tlv.encode(6 /* TLVValues.STATE */, 2 /* PairingStates.M2 */, 7 /* TLVValues.ERROR_CODE */, 1 /* TLVErrorCode.UNKNOWN */));
846
+ response.writeHead(HAPPairingHTTPCode.OK, { 'Content-Type': 'application/pairing+tlv8' });
847
+ response.end(tlv.encode(TLVValues.STATE, PairingStates.M2, TLVValues.ERROR_CODE, TLVErrorCode.UNKNOWN));
819
848
  }
820
849
  }
821
- handleAccessories(connection, url, request, data, response) {
850
+ handleAccessories(connection, _url, _request, _data, response) {
822
851
  if (!this.allowInsecureRequest && !connection.isAuthenticated()) {
823
- response.writeHead(470 /* HAPPairingHTTPCode.CONNECTION_AUTHORIZATION_REQUIRED */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
852
+ response.writeHead(HAPPairingHTTPCode.CONNECTION_AUTHORIZATION_REQUIRED, { 'Content-Type': HAPMimeTypes.HAP_JSON });
824
853
  response.end(JSON.stringify({ status: HAPStatus.INSUFFICIENT_PRIVILEGES }));
825
854
  return;
826
855
  }
827
856
  // call out to listeners to retrieve the latest accessories JSON
828
- this.emit("accessories" /* HAPServerEventTypes.ACCESSORIES */, connection, once((error, result) => {
857
+ this.emit(HAPServerEventTypes.ACCESSORIES, connection, once((error, result) => {
829
858
  if (error) {
830
- response.writeHead(error.httpCode, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
859
+ response.writeHead(error.httpCode, { 'Content-Type': HAPMimeTypes.HAP_JSON });
831
860
  response.end(JSON.stringify({ status: error.status }));
832
861
  }
833
862
  else {
834
- response.writeHead(200 /* HAPHTTPCode.OK */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
863
+ response.writeHead(HAPHTTPCode.OK, { 'Content-Type': HAPMimeTypes.HAP_JSON });
835
864
  response.end(JSON.stringify(result));
836
865
  }
837
866
  }));
838
867
  }
839
868
  handleCharacteristics(connection, url, request, data, response) {
840
869
  if (!this.allowInsecureRequest && !connection.isAuthenticated()) {
841
- response.writeHead(470 /* HAPPairingHTTPCode.CONNECTION_AUTHORIZATION_REQUIRED */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
870
+ response.writeHead(HAPPairingHTTPCode.CONNECTION_AUTHORIZATION_REQUIRED, { 'Content-Type': HAPMimeTypes.HAP_JSON });
842
871
  response.end(JSON.stringify({ status: HAPStatus.INSUFFICIENT_PRIVILEGES }));
843
872
  return;
844
873
  }
@@ -846,7 +875,7 @@ export class HAPServer extends EventEmitter {
846
875
  const searchParams = url.searchParams;
847
876
  const idParam = searchParams.get('id');
848
877
  if (!idParam) {
849
- response.writeHead(400 /* HAPHTTPCode.BAD_REQUEST */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
878
+ response.writeHead(HAPHTTPCode.BAD_REQUEST, { 'Content-Type': HAPMimeTypes.HAP_JSON });
850
879
  response.end(JSON.stringify({ status: HAPStatus.INVALID_VALUE_IN_REQUEST }));
851
880
  return;
852
881
  }
@@ -854,7 +883,7 @@ export class HAPServer extends EventEmitter {
854
883
  for (const entry of idParam.split(',')) { // ["1.9","2.14"]
855
884
  const split = entry.split('.'); // ["1","9"]
856
885
  if (split.length !== 2 || !/^\d+$/.test(split[0]) || !/^\d+$/.test(split[1])) {
857
- response.writeHead(400 /* HAPHTTPCode.BAD_REQUEST */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
886
+ response.writeHead(HAPHTTPCode.BAD_REQUEST, { 'Content-Type': HAPMimeTypes.HAP_JSON });
858
887
  response.end(JSON.stringify({ status: HAPStatus.INVALID_VALUE_IN_REQUEST }));
859
888
  return;
860
889
  }
@@ -870,9 +899,9 @@ export class HAPServer extends EventEmitter {
870
899
  includeType: consideredTrue(searchParams.get('type')),
871
900
  includeEvent: consideredTrue(searchParams.get('ev')),
872
901
  };
873
- this.emit("get-characteristics" /* HAPServerEventTypes.GET_CHARACTERISTICS */, connection, readRequest, once((error, readResponse) => {
902
+ this.emit(HAPServerEventTypes.GET_CHARACTERISTICS, connection, readRequest, once((error, readResponse) => {
874
903
  if (error) {
875
- response.writeHead(error.httpCode, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
904
+ response.writeHead(error.httpCode, { 'Content-Type': HAPMimeTypes.HAP_JSON });
876
905
  response.end(JSON.stringify({ status: error.status }));
877
906
  return;
878
907
  }
@@ -892,7 +921,7 @@ export class HAPServer extends EventEmitter {
892
921
  }
893
922
  }
894
923
  // 207 "multi-status" is returned when an error occurs reading a characteristic. otherwise 200 is returned
895
- response.writeHead(errorOccurred ? 207 /* HAPHTTPCode.MULTI_STATUS */ : 200 /* HAPHTTPCode.OK */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
924
+ response.writeHead(errorOccurred ? HAPHTTPCode.MULTI_STATUS : HAPHTTPCode.OK, { 'Content-Type': HAPMimeTypes.HAP_JSON });
896
925
  response.end(JSON.stringify({ characteristics }));
897
926
  }));
898
927
  }
@@ -906,20 +935,20 @@ export class HAPServer extends EventEmitter {
906
935
  if (!authorizationBuffer
907
936
  || authorizationBuffer.length !== pincodeBuffer.length
908
937
  || !crypto.timingSafeEqual(authorizationBuffer, pincodeBuffer)) {
909
- response.writeHead(470 /* HAPPairingHTTPCode.CONNECTION_AUTHORIZATION_REQUIRED */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
938
+ response.writeHead(HAPPairingHTTPCode.CONNECTION_AUTHORIZATION_REQUIRED, { 'Content-Type': HAPMimeTypes.HAP_JSON });
910
939
  response.end(JSON.stringify({ status: HAPStatus.INSUFFICIENT_PRIVILEGES }));
911
940
  return;
912
941
  }
913
942
  }
914
- if (data.length === 0) {
915
- response.writeHead(400 /* HAPHTTPCode.BAD_REQUEST */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
943
+ const writeRequest = parseJsonObject(data);
944
+ if (!writeRequest || !Array.isArray(writeRequest.characteristics)) {
945
+ response.writeHead(HAPHTTPCode.BAD_REQUEST, { 'Content-Type': HAPMimeTypes.HAP_JSON });
916
946
  response.end(JSON.stringify({ status: HAPStatus.INVALID_VALUE_IN_REQUEST }));
917
947
  return;
918
948
  }
919
- const writeRequest = JSON.parse(data.toString('utf8'));
920
- this.emit("set-characteristics" /* HAPServerEventTypes.SET_CHARACTERISTICS */, connection, writeRequest, once((error, writeResponse) => {
949
+ this.emit(HAPServerEventTypes.SET_CHARACTERISTICS, connection, writeRequest, once((error, writeResponse) => {
921
950
  if (error) {
922
- response.writeHead(error.httpCode, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
951
+ response.writeHead(error.httpCode, { 'Content-Type': HAPMimeTypes.HAP_JSON });
923
952
  response.end(JSON.stringify({ status: error.status }));
924
953
  return;
925
954
  }
@@ -934,36 +963,37 @@ export class HAPServer extends EventEmitter {
934
963
  }
935
964
  if (multiStatus) {
936
965
  // 207 is "multi-status" since HomeKit may be setting multiple things and any one can fail independently
937
- response.writeHead(207 /* HAPHTTPCode.MULTI_STATUS */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
966
+ response.writeHead(HAPHTTPCode.MULTI_STATUS, { 'Content-Type': HAPMimeTypes.HAP_JSON });
938
967
  response.end(JSON.stringify({ characteristics }));
939
968
  }
940
969
  else {
941
970
  // if everything went fine send 204 no content response
942
- response.writeHead(204 /* HAPHTTPCode.NO_CONTENT */);
971
+ response.writeHead(HAPHTTPCode.NO_CONTENT);
943
972
  response.end();
944
973
  }
945
974
  }));
946
975
  }
947
976
  else {
948
- response.writeHead(400 /* HAPHTTPCode.BAD_REQUEST */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ }); // method not allowed
977
+ response.writeHead(HAPHTTPCode.BAD_REQUEST, { 'Content-Type': HAPMimeTypes.HAP_JSON }); // method not allowed
949
978
  response.end(JSON.stringify({ status: HAPStatus.INVALID_VALUE_IN_REQUEST }));
950
979
  }
951
980
  }
952
- handlePrepareWrite(connection, url, request, data, response) {
981
+ handlePrepareWrite(connection, _url, request, data, response) {
953
982
  if (!this.allowInsecureRequest && !connection.isAuthenticated()) {
954
- response.writeHead(470 /* HAPPairingHTTPCode.CONNECTION_AUTHORIZATION_REQUIRED */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
983
+ response.writeHead(HAPPairingHTTPCode.CONNECTION_AUTHORIZATION_REQUIRED, { 'Content-Type': HAPMimeTypes.HAP_JSON });
955
984
  response.end(JSON.stringify({ status: HAPStatus.INSUFFICIENT_PRIVILEGES }));
956
985
  return;
957
986
  }
958
987
  if (request.method === 'PUT') {
959
- if (data.length === 0) {
960
- response.writeHead(400 /* HAPHTTPCode.BAD_REQUEST */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
988
+ const prepareRequest = parseJsonObject(data);
989
+ if (!prepareRequest) {
990
+ response.writeHead(HAPHTTPCode.BAD_REQUEST, { 'Content-Type': HAPMimeTypes.HAP_JSON });
961
991
  response.end(JSON.stringify({ status: HAPStatus.INVALID_VALUE_IN_REQUEST }));
962
992
  return;
963
993
  }
964
- const prepareRequest = JSON.parse(data.toString());
965
994
  const ttl = prepareRequest.ttl;
966
- if (prepareRequest.pid && typeof ttl === 'number' && ttl > 0 && ttl <= HAPServer.MAX_TIMED_WRITE_TTL) {
995
+ // the pid is a number picked at random by the controller, so 0 is as good as any other
996
+ if (typeof prepareRequest.pid === 'number' && typeof ttl === 'number' && ttl > 0 && ttl <= HAPServer.MAX_TIMED_WRITE_TTL) {
967
997
  debug('[%s] Received prepare write request with pid %d and ttl %d', this.accessoryInfo.username, prepareRequest.pid, prepareRequest.ttl);
968
998
  if (connection.timedWriteTimeout) { // clear any currently existing timeouts
969
999
  clearTimeout(connection.timedWriteTimeout);
@@ -975,20 +1005,20 @@ export class HAPServer extends EventEmitter {
975
1005
  connection.timedWriteTimeout = undefined;
976
1006
  }, ttl);
977
1007
  connection.timedWriteTimeout.unref(); // the HAPConnection clears it when it closes
978
- response.writeHead(200 /* HAPHTTPCode.OK */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
1008
+ response.writeHead(HAPHTTPCode.OK, { 'Content-Type': HAPMimeTypes.HAP_JSON });
979
1009
  response.end(JSON.stringify({ status: HAPStatus.SUCCESS }));
980
1010
  }
981
1011
  else {
982
- response.writeHead(400 /* HAPHTTPCode.BAD_REQUEST */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
1012
+ response.writeHead(HAPHTTPCode.BAD_REQUEST, { 'Content-Type': HAPMimeTypes.HAP_JSON });
983
1013
  response.end(JSON.stringify({ status: HAPStatus.INVALID_VALUE_IN_REQUEST }));
984
1014
  }
985
1015
  }
986
1016
  else {
987
- response.writeHead(400 /* HAPHTTPCode.BAD_REQUEST */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
1017
+ response.writeHead(HAPHTTPCode.BAD_REQUEST, { 'Content-Type': HAPMimeTypes.HAP_JSON });
988
1018
  response.end(JSON.stringify({ status: HAPStatus.INVALID_VALUE_IN_REQUEST }));
989
1019
  }
990
1020
  }
991
- handleResource(connection, url, request, data, response) {
1021
+ handleResource(connection, _url, request, data, response) {
992
1022
  if (!connection.isAuthenticated()) {
993
1023
  const authorization = request.headers?.authorization;
994
1024
  const authorizationBuffer = authorization
@@ -998,34 +1028,50 @@ export class HAPServer extends EventEmitter {
998
1028
  if (!(this.allowInsecureRequest && authorizationBuffer
999
1029
  && authorizationBuffer.length === pincodeBuffer.length
1000
1030
  && crypto.timingSafeEqual(authorizationBuffer, pincodeBuffer))) {
1001
- response.writeHead(470 /* HAPPairingHTTPCode.CONNECTION_AUTHORIZATION_REQUIRED */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
1031
+ response.writeHead(HAPPairingHTTPCode.CONNECTION_AUTHORIZATION_REQUIRED, { 'Content-Type': HAPMimeTypes.HAP_JSON });
1002
1032
  response.end(JSON.stringify({ status: HAPStatus.INSUFFICIENT_PRIVILEGES }));
1003
1033
  return;
1004
1034
  }
1005
1035
  }
1006
1036
  if (request.method === 'POST') {
1007
- if (data.length === 0) {
1008
- response.writeHead(400 /* HAPHTTPCode.BAD_REQUEST */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
1037
+ const resourceRequest = parseJsonObject(data);
1038
+ if (!resourceRequest) {
1039
+ response.writeHead(HAPHTTPCode.BAD_REQUEST, { 'Content-Type': HAPMimeTypes.HAP_JSON });
1009
1040
  response.end(JSON.stringify({ status: HAPStatus.INVALID_VALUE_IN_REQUEST }));
1010
1041
  return;
1011
1042
  }
1012
- const resourceRequest = JSON.parse(data.toString());
1013
1043
  // call out to listeners to retrieve the resource, snapshot only right now
1014
- this.emit("request-resource" /* HAPServerEventTypes.REQUEST_RESOURCE */, resourceRequest, once((error, resource) => {
1044
+ this.emit(HAPServerEventTypes.REQUEST_RESOURCE, resourceRequest, once((error, resource) => {
1015
1045
  if (error) {
1016
- response.writeHead(error.httpCode, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ });
1046
+ response.writeHead(error.httpCode, { 'Content-Type': HAPMimeTypes.HAP_JSON });
1017
1047
  response.end(JSON.stringify({ status: error.status }));
1018
1048
  }
1019
1049
  else {
1020
- response.writeHead(200 /* HAPHTTPCode.OK */, { 'Content-Type': "image/jpeg" /* HAPMimeTypes.IMAGE_JPEG */ });
1050
+ response.writeHead(HAPHTTPCode.OK, { 'Content-Type': HAPMimeTypes.IMAGE_JPEG });
1021
1051
  response.end(resource);
1022
1052
  }
1023
1053
  }));
1024
1054
  }
1025
1055
  else {
1026
- response.writeHead(400 /* HAPHTTPCode.BAD_REQUEST */, { 'Content-Type': "application/hap+json" /* HAPMimeTypes.HAP_JSON */ }); // method not allowed
1056
+ response.writeHead(HAPHTTPCode.BAD_REQUEST, { 'Content-Type': HAPMimeTypes.HAP_JSON }); // method not allowed
1027
1057
  response.end(JSON.stringify({ status: HAPStatus.INVALID_VALUE_IN_REQUEST }));
1028
1058
  }
1029
1059
  }
1030
1060
  }
1061
+ /**
1062
+ * Parses a request body which must be a JSON object.
1063
+ *
1064
+ * @returns undefined for an empty body, for malformed JSON and for JSON that is not an object (e.g. `null` or an array).
1065
+ */
1066
+ function parseJsonObject(data) {
1067
+ try {
1068
+ const parsed = JSON.parse(data.toString('utf8'));
1069
+ return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)
1070
+ ? parsed
1071
+ : undefined;
1072
+ }
1073
+ catch {
1074
+ return undefined;
1075
+ }
1076
+ }
1031
1077
  //# sourceMappingURL=HAPServer.js.map