-
Notifications
You must be signed in to change notification settings - Fork 10
/
BridgeFinder.ts
192 lines (163 loc) · 6.1 KB
/
BridgeFinder.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import debug from 'debug';
import { EventEmitter } from 'events';
import ipaddress = require('ip-address');
import mdns = require('multicast-dns');
import dnspacket = require('dns-packet');
import { Protocol, MDNSServiceDiscovery, MDNSService } from 'tinkerhub-mdns';
import TypedEmitter from 'typed-emitter';
import { SmartBridge, LEAP_PORT } from './SmartBridge';
import { LeapClient } from './LeapClient';
const logDebug = debug('leap:protocol:discovery');
interface BridgeFinderEvents {
discovered: (bridge: SmartBridge) => void;
failed: (error: Error) => void;
}
type HostAndPort = {
host: string;
port: number;
};
export type SecretStorage = {
ca: string;
key: string;
cert: string;
};
export class BridgeFinder extends (EventEmitter as new () => TypedEmitter<BridgeFinderEvents>) {
private discovery: MDNSServiceDiscovery;
private secrets: Map<string, SecretStorage> = new Map();
constructor(secrets: Map<string, SecretStorage>) {
super();
this.secrets = secrets;
this.discovery = new MDNSServiceDiscovery({
type: 'lutron',
protocol: Protocol.TCP,
});
this.discovery.onAvailable((svc: MDNSService) => {
this.handleDiscovery(svc)
.then((bridge: SmartBridge) => {
this.emit('discovered', bridge);
})
.catch((e) => {
logDebug('failed to handle discovery:', e);
this.emit('failed', e);
});
});
}
public destroy(): void {
this.discovery.destroy();
}
private extractIp(haps: HostAndPort[]): string | undefined {
for (const hostandport of haps) {
logDebug('checking', hostandport);
// prefer the ipv6 address, but only if it's reachable
//
// FIXME: this code is untested in real life, as my home network is
// ipv4 only.
const _ip = hostandport.host;
try {
const addr = new ipaddress.Address6(_ip);
if (!addr.isLinkLocal() && !addr.isLoopback()) {
// TODO is this sufficient?
return _ip;
break;
}
} catch (e) {
// try again, but as ipv4
logDebug('was not ipv6:', e);
try {
const _ = new ipaddress.Address4(_ip);
return _ip;
} catch (e) {
// okay, apparently it's some garbage. log it and move on
logDebug('could not parse HostAndPort', hostandport, 'because', e);
}
}
}
return undefined;
}
private getHostnameFromIP(ip: string): Promise<string | undefined> {
// n.b. this must not end with a dot. see https://github.com/mafintosh/dns-packet/issues/62
const reversed = ip.split('.').reverse().join('.').concat('.in-addr.arpa');
const _id = Math.floor(Math.random() * (65535 - 1 + 1)) + 1;
let lookupResolve: (info: string) => void = (info: string) => {
// this gets replaced
};
let lookupReject: (err: Error) => void = (err: Error) => {
// this gets replaced
};
const lookupPromise = new Promise<string>((resolve, reject) => {
lookupResolve = resolve;
lookupReject = reject;
});
const resolver = mdns({
multicast: true,
ttl: 1,
port: 0,
});
const timeout = setTimeout(lookupReject, 1000, 'got tired of waiting');
resolver.on('response', (packet: any) => {
if (packet.id === _id) {
clearTimeout(timeout);
lookupResolve(packet.answers[0].data as string);
}
});
// TODO this might not be the minimal argument possible
// see https://github.com/mafintosh/multicast-dns/issues/13
resolver.query(
{
// tslint:disable:no-bitwise
flags: dnspacket.RECURSION_DESIRED | dnspacket.AUTHENTIC_DATA,
id: _id,
questions: [
{
name: reversed,
type: 'PTR',
class: 'IN',
},
],
additionals: [
{
name: '.',
type: 'OPT',
udpPayloadSize: 0x1000,
},
],
},
{
port: 5353,
address: '224.0.0.251',
},
);
return lookupPromise;
}
private async handleDiscovery(svc: MDNSService): Promise<SmartBridge> {
if (svc.data.get('systype') !== 'SmartBridge') {
logDebug('invalid responder was', svc);
throw new Error('invalid responder to discovery request');
}
const ipaddr = this.extractIp(svc.addresses);
logDebug('got useful ipaddr', ipaddr);
if (!ipaddr) {
logDebug('thing without useful address:', svc);
throw new Error('could not get a useful address');
}
let bridgeID;
const hostname = await this.getHostnameFromIP(ipaddr);
logDebug('got hostname from IP:', hostname);
try {
// If the format of the hub hostname changes, this match can break,
// and will appear as your credentials not working any longer
bridgeID = hostname!.match(/[Ll]utron-(?<id>\w+)\.local/)!.groups!.id;
} catch {
bridgeID = ipaddr.replace('.', '_');
}
logDebug('extracted bridge ID:', bridgeID);
if (this.secrets.has(bridgeID)) {
const these = this.secrets.get(bridgeID)!;
const client = new LeapClient(ipaddr, LEAP_PORT, these.ca, these.key, these.cert);
await client.connect();
return new SmartBridge(bridgeID, client);
} else {
throw new Error('no credentials for bridge ID ' + bridgeID);
}
}
}