@homelib/xiaomi 0.0.0-wip.01265bf1cc90
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +19 -0
- package/README.md +26 -0
- package/bld/library/backend/client.d.ts +73 -0
- package/bld/library/backend/client.js +490 -0
- package/bld/library/backend/client.js.map +1 -0
- package/bld/library/backend/constants.d.ts +7 -0
- package/bld/library/backend/constants.js +11 -0
- package/bld/library/backend/constants.js.map +1 -0
- package/bld/library/backend/index.d.ts +3 -0
- package/bld/library/backend/index.js +4 -0
- package/bld/library/backend/index.js.map +1 -0
- package/bld/library/backend/oauth.d.ts +24 -0
- package/bld/library/backend/oauth.js +121 -0
- package/bld/library/backend/oauth.js.map +1 -0
- package/bld/library/binding.d.ts +44 -0
- package/bld/library/binding.js +212 -0
- package/bld/library/binding.js.map +1 -0
- package/bld/library/cloud/client.d.ts +27 -0
- package/bld/library/cloud/client.js +109 -0
- package/bld/library/cloud/client.js.map +1 -0
- package/bld/library/cloud/constants.d.ts +9 -0
- package/bld/library/cloud/constants.js +11 -0
- package/bld/library/cloud/constants.js.map +1 -0
- package/bld/library/cloud/device.d.ts +84 -0
- package/bld/library/cloud/device.js +686 -0
- package/bld/library/cloud/device.js.map +1 -0
- package/bld/library/cloud/index.d.ts +5 -0
- package/bld/library/cloud/index.js +6 -0
- package/bld/library/cloud/index.js.map +1 -0
- package/bld/library/cloud/mqtt.d.ts +69 -0
- package/bld/library/cloud/mqtt.js +517 -0
- package/bld/library/cloud/mqtt.js.map +1 -0
- package/bld/library/cloud/transport.d.ts +8 -0
- package/bld/library/cloud/transport.js +34 -0
- package/bld/library/cloud/transport.js.map +1 -0
- package/bld/library/command.d.ts +6 -0
- package/bld/library/command.js +6 -0
- package/bld/library/command.js.map +1 -0
- package/bld/library/configuration.d.ts +62 -0
- package/bld/library/configuration.js +303 -0
- package/bld/library/configuration.js.map +1 -0
- package/bld/library/device.d.ts +69 -0
- package/bld/library/device.js +266 -0
- package/bld/library/device.js.map +1 -0
- package/bld/library/devices/air-conditioner.d.ts +48 -0
- package/bld/library/devices/air-conditioner.js +155 -0
- package/bld/library/devices/air-conditioner.js.map +1 -0
- package/bld/library/devices/command-effect.d.ts +35 -0
- package/bld/library/devices/command-effect.js +269 -0
- package/bld/library/devices/command-effect.js.map +1 -0
- package/bld/library/devices/dehumidifier.d.ts +41 -0
- package/bld/library/devices/dehumidifier.js +124 -0
- package/bld/library/devices/dehumidifier.js.map +1 -0
- package/bld/library/devices/fan.d.ts +37 -0
- package/bld/library/devices/fan.js +135 -0
- package/bld/library/devices/fan.js.map +1 -0
- package/bld/library/devices/index.d.ts +9 -0
- package/bld/library/devices/index.js +10 -0
- package/bld/library/devices/index.js.map +1 -0
- package/bld/library/devices/light.d.ts +22 -0
- package/bld/library/devices/light.js +112 -0
- package/bld/library/devices/light.js.map +1 -0
- package/bld/library/devices/pet-feeder.d.ts +36 -0
- package/bld/library/devices/pet-feeder.js +116 -0
- package/bld/library/devices/pet-feeder.js.map +1 -0
- package/bld/library/devices/placeholder.d.ts +3 -0
- package/bld/library/devices/placeholder.js +4 -0
- package/bld/library/devices/placeholder.js.map +1 -0
- package/bld/library/devices/temperature-humidity-sensor.d.ts +14 -0
- package/bld/library/devices/temperature-humidity-sensor.js +56 -0
- package/bld/library/devices/temperature-humidity-sensor.js.map +1 -0
- package/bld/library/devices/value-range.d.ts +2 -0
- package/bld/library/devices/value-range.js +6 -0
- package/bld/library/devices/value-range.js.map +1 -0
- package/bld/library/endpoint-connection.d.ts +168 -0
- package/bld/library/endpoint-connection.js +510 -0
- package/bld/library/endpoint-connection.js.map +1 -0
- package/bld/library/index.d.ts +26 -0
- package/bld/library/index.js +33 -0
- package/bld/library/index.js.map +1 -0
- package/bld/library/local/certificate.d.ts +31 -0
- package/bld/library/local/certificate.js +298 -0
- package/bld/library/local/certificate.js.map +1 -0
- package/bld/library/local/controller.d.ts +70 -0
- package/bld/library/local/controller.js +498 -0
- package/bld/library/local/controller.js.map +1 -0
- package/bld/library/local/discovery.d.ts +29 -0
- package/bld/library/local/discovery.js +321 -0
- package/bld/library/local/discovery.js.map +1 -0
- package/bld/library/local/index.d.ts +6 -0
- package/bld/library/local/index.js +7 -0
- package/bld/library/local/index.js.map +1 -0
- package/bld/library/local/message.d.ts +11 -0
- package/bld/library/local/message.js +128 -0
- package/bld/library/local/message.js.map +1 -0
- package/bld/library/local/mqtt.d.ts +113 -0
- package/bld/library/local/mqtt.js +1074 -0
- package/bld/library/local/mqtt.js.map +1 -0
- package/bld/library/local/routed-message-client.d.ts +49 -0
- package/bld/library/local/routed-message-client.js +326 -0
- package/bld/library/local/routed-message-client.js.map +1 -0
- package/bld/library/miot/index.d.ts +4 -0
- package/bld/library/miot/index.js +5 -0
- package/bld/library/miot/index.js.map +1 -0
- package/bld/library/miot/matcher.d.ts +84 -0
- package/bld/library/miot/matcher.js +326 -0
- package/bld/library/miot/matcher.js.map +1 -0
- package/bld/library/miot/request.d.ts +33 -0
- package/bld/library/miot/request.js +57 -0
- package/bld/library/miot/request.js.map +1 -0
- package/bld/library/miot/result.d.ts +8 -0
- package/bld/library/miot/result.js +5 -0
- package/bld/library/miot/result.js.map +1 -0
- package/bld/library/miot/spec.d.ts +96 -0
- package/bld/library/miot/spec.js +86 -0
- package/bld/library/miot/spec.js.map +1 -0
- package/bld/library/provider.d.ts +78 -0
- package/bld/library/provider.js +600 -0
- package/bld/library/provider.js.map +1 -0
- package/bld/library/session-manager.d.ts +34 -0
- package/bld/library/session-manager.js +177 -0
- package/bld/library/session-manager.js.map +1 -0
- package/bld/library/session.d.ts +36 -0
- package/bld/library/session.js +370 -0
- package/bld/library/session.js.map +1 -0
- package/bld/library/storage.d.ts +2 -0
- package/bld/library/storage.js +66 -0
- package/bld/library/storage.js.map +1 -0
- package/bld/library/terminal/bindings.d.ts +3 -0
- package/bld/library/terminal/bindings.js +306 -0
- package/bld/library/terminal/bindings.js.map +1 -0
- package/bld/library/terminal/index.d.ts +2 -0
- package/bld/library/terminal/index.js +3 -0
- package/bld/library/terminal/index.js.map +1 -0
- package/bld/library/terminal/provider-details.d.ts +3 -0
- package/bld/library/terminal/provider-details.js +477 -0
- package/bld/library/terminal/provider-details.js.map +1 -0
- package/package.json +29 -0
- package/src/library/backend/client.ts +737 -0
- package/src/library/backend/constants.ts +17 -0
- package/src/library/backend/index.ts +3 -0
- package/src/library/backend/oauth.ts +170 -0
- package/src/library/binding.ts +387 -0
- package/src/library/cloud/client.ts +155 -0
- package/src/library/cloud/constants.ts +19 -0
- package/src/library/cloud/device.ts +938 -0
- package/src/library/cloud/index.ts +5 -0
- package/src/library/cloud/mqtt.ts +671 -0
- package/src/library/cloud/transport.ts +46 -0
- package/src/library/command.ts +7 -0
- package/src/library/configuration.ts +480 -0
- package/src/library/device.ts +601 -0
- package/src/library/devices/air-conditioner.ts +171 -0
- package/src/library/devices/command-effect.ts +425 -0
- package/src/library/devices/dehumidifier.ts +131 -0
- package/src/library/devices/fan.ts +140 -0
- package/src/library/devices/index.ts +9 -0
- package/src/library/devices/light.ts +119 -0
- package/src/library/devices/pet-feeder.ts +129 -0
- package/src/library/devices/placeholder.ts +3 -0
- package/src/library/devices/temperature-humidity-sensor.ts +49 -0
- package/src/library/devices/value-range.ts +14 -0
- package/src/library/endpoint-connection.ts +841 -0
- package/src/library/index.ts +71 -0
- package/src/library/local/certificate.ts +401 -0
- package/src/library/local/controller.ts +693 -0
- package/src/library/local/discovery.ts +485 -0
- package/src/library/local/index.ts +6 -0
- package/src/library/local/message.ts +174 -0
- package/src/library/local/mqtt.ts +1555 -0
- package/src/library/local/routed-message-client.ts +377 -0
- package/src/library/miot/index.ts +4 -0
- package/src/library/miot/matcher.ts +683 -0
- package/src/library/miot/request.ts +70 -0
- package/src/library/miot/result.ts +14 -0
- package/src/library/miot/spec.ts +114 -0
- package/src/library/provider.ts +745 -0
- package/src/library/session-manager.ts +224 -0
- package/src/library/session.ts +528 -0
- package/src/library/storage.ts +83 -0
- package/src/library/terminal/bindings.tsx +692 -0
- package/src/library/terminal/index.ts +2 -0
- package/src/library/terminal/provider-details.tsx +871 -0
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
import {X509Certificate, createHash} from 'node:crypto';
|
|
2
|
+
import {type RemoteInfo, createSocket} from 'node:dgram';
|
|
3
|
+
import {isIP} from 'node:net';
|
|
4
|
+
import {networkInterfaces} from 'node:os';
|
|
5
|
+
import {connect as connectTls} from 'node:tls';
|
|
6
|
+
|
|
7
|
+
import {Bonjour, type Service} from 'bonjour-service';
|
|
8
|
+
|
|
9
|
+
import {isMipsGatewayCertificate} from './certificate.js';
|
|
10
|
+
|
|
11
|
+
export {getVirtualDid} from './certificate.js';
|
|
12
|
+
|
|
13
|
+
const CENTRAL_SERVICE_TYPE = 'miot-central';
|
|
14
|
+
const DEFAULT_DISCOVERY_TIMEOUT = 5_000;
|
|
15
|
+
const UDP_DISCOVERY_PORT = 54_321;
|
|
16
|
+
const UDP_DISCOVERY_TIMEOUT = 1_500;
|
|
17
|
+
const TLS_PROBE_TIMEOUT = 1_500;
|
|
18
|
+
const MIPS_PORTS = [18_883, 8_883] as const;
|
|
19
|
+
|
|
20
|
+
export type CentralGatewayCandidate = {
|
|
21
|
+
readonly did: string;
|
|
22
|
+
readonly homeId: string;
|
|
23
|
+
readonly homeName: string;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export type CentralRoute = {
|
|
27
|
+
/** The DID that actually answered discovery, never a placeholder candidate. */
|
|
28
|
+
readonly did: string;
|
|
29
|
+
readonly groupId: string;
|
|
30
|
+
readonly homeName: string;
|
|
31
|
+
readonly address: string;
|
|
32
|
+
readonly port: number;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export type CentralProfile = {
|
|
36
|
+
readonly did: string;
|
|
37
|
+
readonly groupId: string;
|
|
38
|
+
readonly role: number;
|
|
39
|
+
readonly suiteMqtt: boolean;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export type DiscoverCentralRoutesOptions = {
|
|
43
|
+
readonly candidates: readonly CentralGatewayCandidate[];
|
|
44
|
+
readonly userId: string;
|
|
45
|
+
readonly virtualDid: string;
|
|
46
|
+
readonly timeout?: number;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
type DiscoveredEndpoint = {
|
|
50
|
+
readonly did: string;
|
|
51
|
+
readonly groupId: string;
|
|
52
|
+
readonly homeName: string;
|
|
53
|
+
readonly address: string;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
export async function discoverCentralRoutes(
|
|
57
|
+
options: DiscoverCentralRoutesOptions,
|
|
58
|
+
): Promise<readonly CentralRoute[]> {
|
|
59
|
+
if (options.candidates.length === 0) {
|
|
60
|
+
return [];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const candidates = new Map(
|
|
64
|
+
options.candidates.map(candidate => [candidate.did, candidate]),
|
|
65
|
+
);
|
|
66
|
+
const timeout = normalizeTimeout(options.timeout);
|
|
67
|
+
const mdnsEndpoints = await discoverMdnsEndpoints(candidates, timeout);
|
|
68
|
+
const mdnsRoutes = await resolveMipsPorts(mdnsEndpoints);
|
|
69
|
+
const remainingCandidates = new Map(candidates);
|
|
70
|
+
|
|
71
|
+
for (const route of mdnsRoutes) {
|
|
72
|
+
remainingCandidates.delete(route.did);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const udpMatches = await discoverUdpEndpoints(
|
|
76
|
+
remainingCandidates,
|
|
77
|
+
options.userId,
|
|
78
|
+
options.virtualDid,
|
|
79
|
+
Math.min(timeout, UDP_DISCOVERY_TIMEOUT),
|
|
80
|
+
);
|
|
81
|
+
|
|
82
|
+
const udpRoutes = await resolveMipsPorts(udpMatches);
|
|
83
|
+
return [...mdnsRoutes, ...udpRoutes];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function calcGroupId(
|
|
87
|
+
userId: string | number,
|
|
88
|
+
homeId: string | number,
|
|
89
|
+
): string {
|
|
90
|
+
return createHash('sha1')
|
|
91
|
+
.update(`${userId}central_service${homeId}`)
|
|
92
|
+
.digest('hex')
|
|
93
|
+
.slice(0, 16);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function parseCentralProfile(
|
|
97
|
+
encodedProfile: string,
|
|
98
|
+
): CentralProfile | undefined {
|
|
99
|
+
if (
|
|
100
|
+
encodedProfile.length === 0 ||
|
|
101
|
+
!/^[A-Za-z\d+/]+={0,2}$/u.test(encodedProfile)
|
|
102
|
+
) {
|
|
103
|
+
return undefined;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
let profile: Buffer;
|
|
107
|
+
|
|
108
|
+
try {
|
|
109
|
+
profile = Buffer.from(encodedProfile, 'base64');
|
|
110
|
+
} catch {
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (profile.length < 23) {
|
|
115
|
+
return undefined;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const did = profile.readBigUInt64BE(1).toString();
|
|
119
|
+
const role = profile[20]! >> 4;
|
|
120
|
+
const suiteMqtt = (profile[22]! & 0b10) !== 0;
|
|
121
|
+
|
|
122
|
+
if (did === '0' || role !== 1 || !suiteMqtt) {
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return {
|
|
127
|
+
did,
|
|
128
|
+
groupId: Buffer.from(profile.subarray(9, 17)).reverse().toString('hex'),
|
|
129
|
+
role,
|
|
130
|
+
suiteMqtt,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function discoverMdnsEndpoints(
|
|
135
|
+
candidates: ReadonlyMap<string, CentralGatewayCandidate>,
|
|
136
|
+
timeout: number,
|
|
137
|
+
): Promise<readonly DiscoveredEndpoint[]> {
|
|
138
|
+
return new Promise(resolve => {
|
|
139
|
+
const endpoints = new Map<string, DiscoveredEndpoint>();
|
|
140
|
+
const bonjour = new Bonjour(undefined, () => undefined);
|
|
141
|
+
const browser = bonjour.find({type: CENTRAL_SERVICE_TYPE, protocol: 'tcp'});
|
|
142
|
+
let settled = false;
|
|
143
|
+
|
|
144
|
+
const finish = (): void => {
|
|
145
|
+
if (settled) {
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
settled = true;
|
|
150
|
+
clearTimeout(timer);
|
|
151
|
+
browser.stop();
|
|
152
|
+
bonjour.destroy();
|
|
153
|
+
resolve([...endpoints.values()]);
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
const timer = setTimeout(finish, timeout);
|
|
157
|
+
|
|
158
|
+
browser.on('up', service => {
|
|
159
|
+
const endpoint = readMdnsEndpoint(service, candidates);
|
|
160
|
+
|
|
161
|
+
if (endpoint !== undefined) {
|
|
162
|
+
endpoints.set(`${endpoint.did}@${endpoint.address}`, endpoint);
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function readMdnsEndpoint(
|
|
169
|
+
service: Service,
|
|
170
|
+
candidates: ReadonlyMap<string, CentralGatewayCandidate>,
|
|
171
|
+
): DiscoveredEndpoint | undefined {
|
|
172
|
+
const encodedProfile = readProfile(service.txt?.profile);
|
|
173
|
+
const profile =
|
|
174
|
+
encodedProfile === undefined
|
|
175
|
+
? undefined
|
|
176
|
+
: parseCentralProfile(encodedProfile);
|
|
177
|
+
const candidate =
|
|
178
|
+
profile === undefined ? undefined : candidates.get(profile.did);
|
|
179
|
+
const address = service.addresses?.find(value => isIP(value) === 4);
|
|
180
|
+
|
|
181
|
+
if (
|
|
182
|
+
profile === undefined ||
|
|
183
|
+
candidate === undefined ||
|
|
184
|
+
address === undefined ||
|
|
185
|
+
!Number.isSafeInteger(service.port) ||
|
|
186
|
+
service.port < 1 ||
|
|
187
|
+
service.port > 65_535
|
|
188
|
+
) {
|
|
189
|
+
return undefined;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
return {
|
|
193
|
+
did: profile.did,
|
|
194
|
+
groupId: profile.groupId,
|
|
195
|
+
homeName: candidate.homeName,
|
|
196
|
+
address,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function readProfile(value: unknown): string | undefined {
|
|
201
|
+
if (typeof value === 'string') {
|
|
202
|
+
return value;
|
|
203
|
+
} else if (Buffer.isBuffer(value)) {
|
|
204
|
+
return value.toString('utf8');
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
return undefined;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async function discoverUdpEndpoints(
|
|
211
|
+
candidates: ReadonlyMap<string, CentralGatewayCandidate>,
|
|
212
|
+
userId: string,
|
|
213
|
+
virtualDid: string,
|
|
214
|
+
timeout: number,
|
|
215
|
+
): Promise<readonly DiscoveredEndpoint[]> {
|
|
216
|
+
const matches = await probeUdpCandidates(candidates, virtualDid, timeout);
|
|
217
|
+
|
|
218
|
+
return matches.map(match => {
|
|
219
|
+
const candidate = candidates.get(match.did)!;
|
|
220
|
+
|
|
221
|
+
return {
|
|
222
|
+
did: match.did,
|
|
223
|
+
groupId: calcGroupId(userId, candidate.homeId),
|
|
224
|
+
homeName: candidate.homeName,
|
|
225
|
+
address: match.address,
|
|
226
|
+
};
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function probeUdpCandidates(
|
|
231
|
+
candidates: ReadonlyMap<string, CentralGatewayCandidate>,
|
|
232
|
+
virtualDid: string,
|
|
233
|
+
timeout: number,
|
|
234
|
+
): Promise<readonly {readonly did: string; readonly address: string}[]> {
|
|
235
|
+
const validCandidateDids = new Set(
|
|
236
|
+
[...candidates.keys()].filter(isUnsigned64BitDecimal),
|
|
237
|
+
);
|
|
238
|
+
|
|
239
|
+
if (validCandidateDids.size === 0 || !isUnsigned64BitDecimal(virtualDid)) {
|
|
240
|
+
return Promise.resolve([]);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
return new Promise(resolve => {
|
|
244
|
+
const socket = createSocket({type: 'udp4', reuseAddr: true});
|
|
245
|
+
const matches = new Map<
|
|
246
|
+
string,
|
|
247
|
+
{readonly did: string; readonly address: string}
|
|
248
|
+
>();
|
|
249
|
+
let settled = false;
|
|
250
|
+
|
|
251
|
+
const finish = (): void => {
|
|
252
|
+
if (settled) {
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
settled = true;
|
|
257
|
+
clearTimeout(timer);
|
|
258
|
+
|
|
259
|
+
try {
|
|
260
|
+
socket.close();
|
|
261
|
+
} catch {
|
|
262
|
+
// Binding failures can emit error before the UDP socket starts.
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
resolve([...matches.values()]);
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
const timer = setTimeout(finish, timeout);
|
|
269
|
+
|
|
270
|
+
socket.on('message', (message: Buffer, remote: RemoteInfo) => {
|
|
271
|
+
const did = readUdpResponseDid(message);
|
|
272
|
+
|
|
273
|
+
if (did !== undefined && validCandidateDids.has(did)) {
|
|
274
|
+
matches.set(`${did}@${remote.address}`, {
|
|
275
|
+
did,
|
|
276
|
+
address: remote.address,
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
});
|
|
280
|
+
socket.on('error', finish);
|
|
281
|
+
socket.bind(0, '0.0.0.0', () => {
|
|
282
|
+
try {
|
|
283
|
+
socket.setBroadcast(true);
|
|
284
|
+
} catch {
|
|
285
|
+
finish();
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const packets = [createMiotHelloPacket(), createMdidPacket(virtualDid)];
|
|
290
|
+
|
|
291
|
+
for (const address of getUdpProbeAddresses()) {
|
|
292
|
+
for (const packet of packets) {
|
|
293
|
+
socket.send(packet, UDP_DISCOVERY_PORT, address, () => undefined);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function readUdpResponseDid(message: Buffer): string | undefined {
|
|
301
|
+
if (
|
|
302
|
+
message.length < 12 ||
|
|
303
|
+
message[0] !== 0x21 ||
|
|
304
|
+
message[1] !== 0x31 ||
|
|
305
|
+
message.readUInt16BE(2) > message.length
|
|
306
|
+
) {
|
|
307
|
+
return undefined;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const did = message.readBigUInt64BE(4).toString();
|
|
311
|
+
|
|
312
|
+
return did === '0' ? undefined : did;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function createMiotHelloPacket(): Buffer {
|
|
316
|
+
const packet = Buffer.alloc(32, 0xff);
|
|
317
|
+
|
|
318
|
+
packet.writeUInt16BE(0x2131, 0);
|
|
319
|
+
packet.writeUInt16BE(32, 2);
|
|
320
|
+
return packet;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function createMdidPacket(virtualDid: string): Buffer {
|
|
324
|
+
const packet = Buffer.alloc(32);
|
|
325
|
+
|
|
326
|
+
packet.writeUInt16BE(0x2131, 0);
|
|
327
|
+
packet.writeUInt16BE(32, 2);
|
|
328
|
+
packet.fill(0xff, 4, 16);
|
|
329
|
+
packet.write('MDID', 16, 'ascii');
|
|
330
|
+
packet.writeBigUInt64BE(BigInt(virtualDid), 20);
|
|
331
|
+
return packet;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function getUdpProbeAddresses(): readonly string[] {
|
|
335
|
+
const addresses = new Set<string>(['255.255.255.255']);
|
|
336
|
+
|
|
337
|
+
for (const records of Object.values(networkInterfaces())) {
|
|
338
|
+
for (const record of records ?? []) {
|
|
339
|
+
if (record.family !== 'IPv4' || record.internal) {
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
const address = ipv4ToInteger(record.address);
|
|
344
|
+
const mask = ipv4ToInteger(record.netmask);
|
|
345
|
+
|
|
346
|
+
if (address === undefined || mask === undefined) {
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
addresses.add(integerToIpv4((address | ~mask) >>> 0));
|
|
351
|
+
|
|
352
|
+
// Unicast probes make discovery work on networks that filter broadcasts.
|
|
353
|
+
// Keep it bounded to the current /24 even when a virtual interface has a
|
|
354
|
+
// much larger prefix.
|
|
355
|
+
const classCNetwork = address & 0xffffff00;
|
|
356
|
+
|
|
357
|
+
for (let host = 1; host < 255; host += 1) {
|
|
358
|
+
addresses.add(integerToIpv4((classCNetwork | host) >>> 0));
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
return [...addresses];
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
async function resolveMipsPorts(
|
|
367
|
+
endpoints: readonly DiscoveredEndpoint[],
|
|
368
|
+
): Promise<readonly CentralRoute[]> {
|
|
369
|
+
const unresolved = new Map(
|
|
370
|
+
endpoints.map(endpoint => [
|
|
371
|
+
`${endpoint.did}@${endpoint.address}`,
|
|
372
|
+
endpoint,
|
|
373
|
+
]),
|
|
374
|
+
);
|
|
375
|
+
const routes: CentralRoute[] = [];
|
|
376
|
+
|
|
377
|
+
for (const port of MIPS_PORTS) {
|
|
378
|
+
const probes = await Promise.all(
|
|
379
|
+
[...unresolved.entries()].map(async ([key, endpoint]) => ({
|
|
380
|
+
key,
|
|
381
|
+
endpoint,
|
|
382
|
+
valid: await hasMipsTlsCertificate(
|
|
383
|
+
endpoint.address,
|
|
384
|
+
port,
|
|
385
|
+
endpoint.did,
|
|
386
|
+
),
|
|
387
|
+
})),
|
|
388
|
+
);
|
|
389
|
+
|
|
390
|
+
for (const probe of probes) {
|
|
391
|
+
if (!probe.valid) {
|
|
392
|
+
continue;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
unresolved.delete(probe.key);
|
|
396
|
+
routes.push({...probe.endpoint, port});
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
return routes;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function hasMipsTlsCertificate(
|
|
404
|
+
address: string,
|
|
405
|
+
port: number,
|
|
406
|
+
gatewayDid: string,
|
|
407
|
+
): Promise<boolean> {
|
|
408
|
+
return new Promise(resolve => {
|
|
409
|
+
// Discovery has no client credential yet, so this deliberately performs an
|
|
410
|
+
// unauthenticated probe and only inspects the peer identity. The actual
|
|
411
|
+
// MQTT connection validates the CA and supplies the client certificate.
|
|
412
|
+
const socket = connectTls({
|
|
413
|
+
host: address,
|
|
414
|
+
port,
|
|
415
|
+
rejectUnauthorized: false,
|
|
416
|
+
});
|
|
417
|
+
let settled = false;
|
|
418
|
+
|
|
419
|
+
const finish = (result: boolean): void => {
|
|
420
|
+
if (settled) {
|
|
421
|
+
return;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
settled = true;
|
|
425
|
+
clearTimeout(timer);
|
|
426
|
+
socket.destroy();
|
|
427
|
+
resolve(result);
|
|
428
|
+
};
|
|
429
|
+
|
|
430
|
+
const timer = setTimeout(() => finish(false), TLS_PROBE_TIMEOUT);
|
|
431
|
+
|
|
432
|
+
socket.once('secureConnect', () => {
|
|
433
|
+
try {
|
|
434
|
+
const peer = socket.getPeerCertificate();
|
|
435
|
+
const certificate =
|
|
436
|
+
peer.raw === undefined ? undefined : new X509Certificate(peer.raw);
|
|
437
|
+
|
|
438
|
+
finish(
|
|
439
|
+
certificate !== undefined &&
|
|
440
|
+
isMipsGatewayCertificate(certificate, gatewayDid),
|
|
441
|
+
);
|
|
442
|
+
} catch {
|
|
443
|
+
finish(false);
|
|
444
|
+
}
|
|
445
|
+
});
|
|
446
|
+
socket.once('error', () => finish(false));
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function normalizeTimeout(timeout: number | undefined): number {
|
|
451
|
+
if (timeout === undefined) {
|
|
452
|
+
return DEFAULT_DISCOVERY_TIMEOUT;
|
|
453
|
+
} else if (!Number.isFinite(timeout) || timeout < 0) {
|
|
454
|
+
throw new TypeError('Local MQTT discovery timeout must be non-negative.');
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
return timeout;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function isUnsigned64BitDecimal(value: string): boolean {
|
|
461
|
+
if (!/^(?:0|[1-9]\d*)$/u.test(value)) {
|
|
462
|
+
return false;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
const integer = BigInt(value);
|
|
466
|
+
|
|
467
|
+
return integer <= BigInt('18446744073709551615');
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function ipv4ToInteger(address: string): number | undefined {
|
|
471
|
+
if (isIP(address) !== 4) {
|
|
472
|
+
return undefined;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
return address
|
|
476
|
+
.split('.')
|
|
477
|
+
.map(Number)
|
|
478
|
+
.reduce((value, octet) => ((value << 8) | octet) >>> 0, 0);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
function integerToIpv4(value: number): string {
|
|
482
|
+
return [24, 16, 8, 0]
|
|
483
|
+
.map(offset => String((value >>> offset) & 0xff))
|
|
484
|
+
.join('.');
|
|
485
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
const HEADER_SIZE = 5;
|
|
2
|
+
const UINT32_MAX = 0xffffffff;
|
|
3
|
+
|
|
4
|
+
const enum MipsMessageField {
|
|
5
|
+
Id = 0,
|
|
6
|
+
ReturnTopic = 1,
|
|
7
|
+
Payload = 2,
|
|
8
|
+
From = 3,
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export type MipsMessage = {
|
|
12
|
+
readonly id: number;
|
|
13
|
+
readonly returnTopic?: string;
|
|
14
|
+
readonly payload?: string;
|
|
15
|
+
readonly from?: string;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export class MipsMessageError extends Error {
|
|
19
|
+
override readonly name = 'MipsMessageError';
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function encodeMipsMessage(message: MipsMessage): Buffer {
|
|
23
|
+
assertMessageId(message.id);
|
|
24
|
+
|
|
25
|
+
const fields = [encodeIdField(message.id)];
|
|
26
|
+
|
|
27
|
+
if (message.from !== undefined) {
|
|
28
|
+
fields.push(encodeStringField(MipsMessageField.From, message.from, 'from'));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (message.returnTopic !== undefined) {
|
|
32
|
+
fields.push(
|
|
33
|
+
encodeStringField(
|
|
34
|
+
MipsMessageField.ReturnTopic,
|
|
35
|
+
message.returnTopic,
|
|
36
|
+
'return topic',
|
|
37
|
+
),
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (message.payload !== undefined) {
|
|
42
|
+
fields.push(
|
|
43
|
+
encodeStringField(MipsMessageField.Payload, message.payload, 'payload'),
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return Buffer.concat(fields);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function decodeMipsMessage(data: Uint8Array): MipsMessage {
|
|
51
|
+
const buffer = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
|
52
|
+
let offset = 0;
|
|
53
|
+
let id: number | undefined;
|
|
54
|
+
let returnTopic: string | undefined;
|
|
55
|
+
let payload: string | undefined;
|
|
56
|
+
let from: string | undefined;
|
|
57
|
+
const seenFieldSet = new Set<number>();
|
|
58
|
+
|
|
59
|
+
while (offset < buffer.length) {
|
|
60
|
+
if (buffer.length - offset < HEADER_SIZE) {
|
|
61
|
+
throw new MipsMessageError('Truncated MIPS message field header.');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const length = buffer.readUInt32LE(offset);
|
|
65
|
+
const type = buffer[offset + 4];
|
|
66
|
+
const dataOffset = offset + HEADER_SIZE;
|
|
67
|
+
const remaining = buffer.length - dataOffset;
|
|
68
|
+
|
|
69
|
+
if (length > remaining) {
|
|
70
|
+
throw new MipsMessageError('MIPS message field exceeds payload bounds.');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (type === undefined) {
|
|
74
|
+
throw new MipsMessageError('Missing MIPS message field type.');
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const fieldData = buffer.subarray(dataOffset, dataOffset + length);
|
|
78
|
+
|
|
79
|
+
if (isKnownField(type)) {
|
|
80
|
+
if (seenFieldSet.has(type)) {
|
|
81
|
+
throw new MipsMessageError('Duplicate MIPS message field.');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
seenFieldSet.add(type);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (type === MipsMessageField.Id) {
|
|
88
|
+
if (fieldData.length !== 4) {
|
|
89
|
+
throw new MipsMessageError('Invalid MIPS message ID field length.');
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
id = fieldData.readUInt32LE(0);
|
|
93
|
+
} else if (type === MipsMessageField.ReturnTopic) {
|
|
94
|
+
returnTopic = decodeStringField(fieldData, 'return topic');
|
|
95
|
+
} else if (type === MipsMessageField.Payload) {
|
|
96
|
+
payload = decodeStringField(fieldData, 'payload');
|
|
97
|
+
} else if (type === MipsMessageField.From) {
|
|
98
|
+
from = decodeStringField(fieldData, 'from');
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
offset = dataOffset + length;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (id === undefined) {
|
|
105
|
+
throw new MipsMessageError('MIPS message has no ID field.');
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
return {id, returnTopic, payload, from};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function encodeIdField(id: number): Buffer {
|
|
112
|
+
const field = Buffer.alloc(HEADER_SIZE + 4);
|
|
113
|
+
field.writeUInt32LE(4, 0);
|
|
114
|
+
field[4] = MipsMessageField.Id;
|
|
115
|
+
field.writeUInt32LE(id, HEADER_SIZE);
|
|
116
|
+
return field;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function encodeStringField(
|
|
120
|
+
type: MipsMessageField,
|
|
121
|
+
value: string,
|
|
122
|
+
name: string,
|
|
123
|
+
): Buffer {
|
|
124
|
+
if (value.includes('\0')) {
|
|
125
|
+
throw new MipsMessageError(`MIPS message ${name} contains a null byte.`);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const encoded = Buffer.from(value, 'utf8');
|
|
129
|
+
const length = encoded.length + 1;
|
|
130
|
+
|
|
131
|
+
if (length > UINT32_MAX) {
|
|
132
|
+
throw new MipsMessageError(`MIPS message ${name} is too long.`);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const field = Buffer.alloc(HEADER_SIZE + length);
|
|
136
|
+
field.writeUInt32LE(length, 0);
|
|
137
|
+
field[4] = type;
|
|
138
|
+
encoded.copy(field, HEADER_SIZE);
|
|
139
|
+
return field;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function decodeStringField(data: Buffer, name: string): string {
|
|
143
|
+
// Requests conventionally include the trailing NUL, while real central
|
|
144
|
+
// gateways also emit replies whose TLV length excludes it.
|
|
145
|
+
const content =
|
|
146
|
+
data.length > 0 && data[data.length - 1] === 0
|
|
147
|
+
? data.subarray(0, -1)
|
|
148
|
+
: data;
|
|
149
|
+
|
|
150
|
+
if (content.includes(0)) {
|
|
151
|
+
throw new MipsMessageError(`MIPS message ${name} contains a null byte.`);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
try {
|
|
155
|
+
return new TextDecoder('utf-8', {fatal: true}).decode(content);
|
|
156
|
+
} catch {
|
|
157
|
+
throw new MipsMessageError(`MIPS message ${name} is not valid UTF-8.`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function assertMessageId(id: number): void {
|
|
162
|
+
if (!Number.isInteger(id) || id < 0 || id > UINT32_MAX) {
|
|
163
|
+
throw new MipsMessageError('Invalid MIPS message ID.');
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function isKnownField(type: number): boolean {
|
|
168
|
+
return (
|
|
169
|
+
type === MipsMessageField.Id ||
|
|
170
|
+
type === MipsMessageField.ReturnTopic ||
|
|
171
|
+
type === MipsMessageField.Payload ||
|
|
172
|
+
type === MipsMessageField.From
|
|
173
|
+
);
|
|
174
|
+
}
|