signalk-multihelm 0.5.0 → 0.7.0

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/plugin/index.js CHANGED
@@ -2,13 +2,15 @@ import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
- import makeMdns from "multicast-dns";
5
+ import { isDeepStrictEqual } from "node:util";
6
+ import crypto, { X509Certificate } from "node:crypto";
6
7
  import http from "node:http";
7
8
  import https from "node:https";
9
+ import net from "node:net";
8
10
  import { pipeline } from "node:stream/promises";
11
+ import tls from "node:tls";
12
+ import makeMdns from "multicast-dns";
9
13
  import { Type } from "typebox";
10
- import { isDeepStrictEqual } from "node:util";
11
- import crypto from "node:crypto";
12
14
  import { Value } from "typebox/value";
13
15
  // src/api.ts
14
16
  var PROPERTY_NAME = "multihelm";
@@ -18,17 +20,31 @@ var PROPERTY_NAME = "multihelm";
18
20
  * device access request that pairs with it.
19
21
  *
20
22
  * Peers are other Signal K servers on the boat's network, addressed by the
21
- * URL the user confirmed. HTTPS peers are verified as usual, so a server
22
- * with a self-signed certificate is reached over its HTTP port instead.
23
+ * URL the user confirmed. An HTTPS peer is trusted the way Node trusts any
24
+ * server or, when no CA that Node knows vouches for it, by the certificate it
25
+ * presented when it was paired (see `locatePeer()`).
23
26
  */
24
27
  var ROUTE_PREFIX = "/plugins/signalk-multihelm";
25
28
  var REQUEST_TIMEOUT_MS$1 = 3e4;
29
+ /**
30
+ * What Node calls a chain whose issuer it does not trust, the one failure a
31
+ * certificate kept from pairing stands in for. Expiry and a name it was not
32
+ * issued for are not among them: pinning must not paper over those.
33
+ */
34
+ var UNTRUSTED_ISSUER = /* @__PURE__ */ new Set([
35
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
36
+ "SELF_SIGNED_CERT_IN_CHAIN",
37
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
38
+ "UNABLE_TO_GET_ISSUER_CERT",
39
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY"
40
+ ]);
26
41
  function helloQuery(from) {
27
42
  if (!from) return "";
28
43
  const query = new URLSearchParams({
29
44
  from: from.serverId,
30
45
  name: from.name
31
46
  });
47
+ if (from.master !== void 0) query.set("master", from.master ? "1" : "0");
32
48
  if (from.signalk) query.set("signalk", from.signalk);
33
49
  if (from.multihelm) query.set("multihelm", from.multihelm);
34
50
  return `?${query.toString()}`;
@@ -43,6 +59,15 @@ var PeerHttpError = class extends Error {
43
59
  this.status = status;
44
60
  }
45
61
  };
62
+ /** How to check the certificate of `target`, an HTTPS URL, trusted by `ca` when it is set. */
63
+ function tlsOptions(target, ca) {
64
+ if (ca) return {
65
+ ca,
66
+ checkServerIdentity: () => void 0,
67
+ allowPartialTrustChain: true
68
+ };
69
+ return target.hostname === "127.0.0.1" ? { rejectUnauthorized: false } : {};
70
+ }
46
71
  function send(method, url, options = {}) {
47
72
  const headers = { ...options.headers };
48
73
  if (options.token) headers.Authorization = `Bearer ${options.token}`;
@@ -54,12 +79,11 @@ function send(method, url, options = {}) {
54
79
  const target = new URL(url);
55
80
  const request = target.protocol === "https:" ? https.request : http.request;
56
81
  return new Promise((resolve, reject) => {
57
- const rejectUnauthorized = target.hostname !== "127.0.0.1";
58
82
  const req = request(target, {
59
83
  method,
60
84
  headers,
61
85
  timeout: REQUEST_TIMEOUT_MS$1,
62
- rejectUnauthorized
86
+ ...tlsOptions(target, options.ca)
63
87
  }, (res) => {
64
88
  resolve({
65
89
  status: res.statusCode ?? 0,
@@ -77,8 +101,11 @@ async function readBody(res) {
77
101
  for await (const chunk of res.stream) chunks.push(chunk);
78
102
  return Buffer.concat(chunks).toString("utf-8");
79
103
  }
80
- async function getJson(url, token) {
81
- const res = await send("GET", url, { token });
104
+ async function getJson(url, token, ca) {
105
+ const res = await send("GET", url, {
106
+ token,
107
+ ca
108
+ });
82
109
  const text = await readBody(res);
83
110
  if (res.status < 200 || res.status >= 300) throw new PeerHttpError(res.status, `HTTP ${String(res.status)} from ${url}`);
84
111
  return JSON.parse(text);
@@ -94,12 +121,96 @@ function normalizePeerUrl(input) {
94
121
  if (url.protocol !== "http:" && url.protocol !== "https:" || url.username || url.password) return null;
95
122
  return `${url.protocol}//${url.host}`;
96
123
  }
97
- async function fetchHello(base, token, from) {
98
- const body = await getJson(`${base}${ROUTE_PREFIX}/hello${helloQuery(from)}`, token);
99
- if (typeof body.serverId !== "string" || typeof body.protocol !== "number") throw new Error(`${base} did not answer as a Multihelm peer`);
124
+ /**
125
+ * Where and how to reach the server at `url`, a normalized address, worked
126
+ * out when pairing with it. An HTTP port that redirects to HTTPS on the same
127
+ * host, as Signal K's does once SSL is on, is followed, and an address that
128
+ * speaks HTTPS only is taken as HTTPS. An HTTPS server that no CA Node knows
129
+ * vouches for is trusted from then on by the top certificate of the chain it
130
+ * presents: the CA when signalk-ssl issued its certificate, the certificate
131
+ * itself when Signal K made it.
132
+ */
133
+ async function locatePeer(url) {
134
+ const typed = new URL(url);
135
+ const target = typed.protocol === "https:" ? typed : await httpsTarget(typed);
136
+ if (!target) return { url };
137
+ const secureUrl = `https://${target.host}`;
138
+ const ca = await untrustedAnchor(target);
139
+ return ca === void 0 ? { url: secureUrl } : {
140
+ url: secureUrl,
141
+ ca
142
+ };
143
+ }
144
+ /** Where HTTP `target` is to be reached over HTTPS instead; null when it is not. */
145
+ async function httpsTarget(target) {
146
+ let res;
147
+ try {
148
+ res = await send("GET", `${target.origin}/signalk`);
149
+ } catch (error) {
150
+ if (error.code === "ECONNRESET") {
151
+ const same = new URL(`https://${target.hostname}:${target.port || "80"}`);
152
+ if (await speaksTls(same)) return same;
153
+ }
154
+ throw error;
155
+ }
156
+ res.stream.resume();
157
+ const location = res.status >= 300 && res.status < 400 ? res.stream.headers.location : void 0;
158
+ if (location === void 0) return null;
159
+ const next = new URL(location, target);
160
+ return next.protocol === "https:" && next.hostname === target.hostname ? new URL(`https://${next.host}`) : null;
161
+ }
162
+ function connectTls(target) {
163
+ const host = target.hostname.replace(/^\[(.*)\]$/, "$1");
164
+ return new Promise((resolve, reject) => {
165
+ const socket = tls.connect({
166
+ host,
167
+ port: Number(target.port || 443),
168
+ ...net.isIP(host) === 0 ? { servername: host } : {},
169
+ rejectUnauthorized: false,
170
+ timeout: REQUEST_TIMEOUT_MS$1
171
+ }, () => {
172
+ resolve(socket);
173
+ });
174
+ socket.on("timeout", () => {
175
+ socket.destroy(/* @__PURE__ */ new Error(`timeout after ${String(REQUEST_TIMEOUT_MS$1)} ms`));
176
+ });
177
+ socket.on("error", reject);
178
+ });
179
+ }
180
+ async function speaksTls(target) {
181
+ try {
182
+ (await connectTls(target)).end();
183
+ return true;
184
+ } catch {
185
+ return false;
186
+ }
187
+ }
188
+ /**
189
+ * The top certificate of the chain `target` presents, as PEM, when Node
190
+ * refuses the chain for its issuer alone; undefined otherwise.
191
+ */
192
+ async function untrustedAnchor(target) {
193
+ const socket = await connectTls(target);
194
+ try {
195
+ const reason = String(socket.authorizationError);
196
+ if (socket.authorized || !UNTRUSTED_ISSUER.has(reason)) return;
197
+ let top = socket.getPeerCertificate(true);
198
+ for (let depth = 0; depth < 10; depth++) {
199
+ const issuer = top.issuerCertificate;
200
+ if (!issuer || issuer.fingerprint256 === top.fingerprint256) break;
201
+ top = issuer;
202
+ }
203
+ return new X509Certificate(top.raw).toString();
204
+ } finally {
205
+ socket.end();
206
+ }
207
+ }
208
+ async function fetchHello(peer, token, from) {
209
+ const body = await getJson(`${peer.url}${ROUTE_PREFIX}/hello${helloQuery(from)}`, token, peer.ca);
210
+ if (typeof body.serverId !== "string" || typeof body.protocol !== "number") throw new Error(`${peer.url} did not answer as a Multihelm peer`);
100
211
  const hello = {
101
212
  serverId: body.serverId,
102
- name: typeof body.name === "string" ? body.name : base,
213
+ name: typeof body.name === "string" ? body.name : peer.url,
103
214
  protocol: body.protocol,
104
215
  datasets: Array.isArray(body.datasets) ? body.datasets.filter((d) => typeof d === "string") : [],
105
216
  master: body.master === true
@@ -112,8 +223,8 @@ async function fetchHello(base, token, from) {
112
223
  ...multihelm ? { multihelm } : {}
113
224
  };
114
225
  }
115
- async function fetchVesselSettings(base, token) {
116
- return getJson(`${base}${ROUTE_PREFIX}/vessel-settings`, token);
226
+ async function fetchVesselSettings(peer, token) {
227
+ return getJson(`${peer.url}${ROUTE_PREFIX}/vessel-settings`, token, peer.ca);
117
228
  }
118
229
  /** A request to a Signal K server's own REST API; throws on any status but 2xx. */
119
230
  async function callServer(method, url, token, body) {
@@ -129,27 +240,44 @@ async function callServer(method, url, token, body) {
129
240
  return text;
130
241
  }
131
242
  }
243
+ /** A request to a paired peer's REST API, trusted as when it was paired; throws on any status but 2xx. */
244
+ async function callPeer(method, peer, path, token, body) {
245
+ const url = `${peer.url}${path}`;
246
+ const res = await send(method, url, {
247
+ token,
248
+ body,
249
+ ca: peer.ca
250
+ });
251
+ const text = await readBody(res);
252
+ if (res.status < 200 || res.status >= 300) throw new PeerHttpError(res.status, `HTTP ${String(res.status)} from ${method} ${url}`);
253
+ try {
254
+ return JSON.parse(text);
255
+ } catch {
256
+ return text;
257
+ }
258
+ }
132
259
  /** A page of a peer's dataset changes; its entries are checked by the caller. */
133
- async function fetchManifest(base, token, dataset, since) {
134
- const body = await getJson(`${base}${ROUTE_PREFIX}/manifest?dataset=${encodeURIComponent(dataset)}&since=${String(since)}`, token);
135
- if (typeof body.cursor !== "number" || !Array.isArray(body.entries)) throw new Error(`${base} sent a malformed manifest`);
260
+ async function fetchManifest(peer, token, dataset, since) {
261
+ const body = await getJson(`${peer.url}${ROUTE_PREFIX}/manifest?dataset=${encodeURIComponent(dataset)}&since=${String(since)}`, token, peer.ca);
262
+ if (typeof body.cursor !== "number" || !Array.isArray(body.entries)) throw new Error(`${peer.url} sent a malformed manifest`);
136
263
  return {
137
264
  cursor: body.cursor,
138
265
  entries: body.entries
139
266
  };
140
267
  }
141
268
  /** Download one file of a peer's entry into `dest`, resuming from what `dest` holds. */
142
- function downloadFile(base, token, file, dest) {
143
- return download(base, token, `file?dataset=${encodeURIComponent(file.dataset)}&key=${encodeURIComponent(file.key)}&file=${encodeURIComponent(file.name)}`, `${file.key}/${file.name}`, dest);
269
+ function downloadFile(peer, token, file, dest) {
270
+ return download(peer, token, `file?dataset=${encodeURIComponent(file.dataset)}&key=${encodeURIComponent(file.key)}&file=${encodeURIComponent(file.name)}`, `${file.key}/${file.name}`, dest);
144
271
  }
145
- async function download(base, token, query, label, dest) {
272
+ async function download(peer, token, query, label, dest) {
146
273
  let offset = 0;
147
274
  try {
148
275
  offset = fs.statSync(dest).size;
149
276
  } catch {}
150
- const res = await send("GET", `${base}${ROUTE_PREFIX}/${query}`, {
277
+ const res = await send("GET", `${peer.url}${ROUTE_PREFIX}/${query}`, {
151
278
  token,
152
- headers: offset > 0 ? { Range: `bytes=${String(offset)}-` } : {}
279
+ headers: offset > 0 ? { Range: `bytes=${String(offset)}-` } : {},
280
+ ca: peer.ca
153
281
  });
154
282
  if (res.status === 206) {
155
283
  await pipeline(res.stream, fs.createWriteStream(dest, { flags: "a" }));
@@ -163,12 +291,15 @@ async function download(base, token, query, label, dest) {
163
291
  throw new PeerHttpError(res.status, `HTTP ${String(res.status)} for ${label}`);
164
292
  }
165
293
  /** Ask the peer for a device token, readonly unless said otherwise. */
166
- async function requestAccess(base, clientId, description, permissions = "readonly") {
167
- const res = await send("POST", `${base}/signalk/v1/access/requests`, { body: {
168
- clientId,
169
- description,
170
- permissions
171
- } });
294
+ async function requestAccess(peer, clientId, description, permissions = "readonly") {
295
+ const res = await send("POST", `${peer.url}/signalk/v1/access/requests`, {
296
+ body: {
297
+ clientId,
298
+ description,
299
+ permissions
300
+ },
301
+ ca: peer.ca
302
+ });
172
303
  const text = await readBody(res);
173
304
  if (res.status === 404) return { kind: "no-security" };
174
305
  if (res.status === 403) return {
@@ -182,14 +313,14 @@ async function requestAccess(base, clientId, description, permissions = "readonl
182
313
  return interpretReply(JSON.parse(text));
183
314
  }
184
315
  /** Follow up an access request that is waiting for approval. */
185
- async function pollAccess(base, href) {
186
- const url = href.startsWith("/") ? `${base}${href}` : href;
187
- if (!url.startsWith(`${base}/`)) return {
316
+ async function pollAccess(peer, href) {
317
+ const url = href.startsWith("/") ? `${peer.url}${href}` : href;
318
+ if (!url.startsWith(`${peer.url}/`)) return {
188
319
  kind: "error",
189
320
  message: "the access request points to another server"
190
321
  };
191
322
  try {
192
- return interpretReply(await getJson(url));
323
+ return interpretReply(await getJson(url, void 0, peer.ca));
193
324
  } catch (error) {
194
325
  if (error instanceof PeerHttpError && error.status === 404) return { kind: "denied" };
195
326
  throw error;
@@ -213,6 +344,744 @@ function interpretReply(raw) {
213
344
  message: "unexpected access request reply"
214
345
  };
215
346
  }
347
+ // src/alarms-from-master.ts
348
+ /**
349
+ * Alarms are matched by path: each server gives its alarms ids of its own,
350
+ * and stations on one NMEA 2000 bus raise the same alarm themselves.
351
+ */
352
+ var NOTIFICATIONS_PATH = "/signalk/v2/api/notifications";
353
+ var ALARMS_POLL_MS = 1e3;
354
+ /** In the data of an alarm shown for the master: the master's server id, and its id for the alarm. */
355
+ var FROM_MASTER = "multihelmMaster";
356
+ var MASTER_ALARM = "multihelmMasterAlarm";
357
+ /**
358
+ * The server's Notifications API, while the server manages notifications:
359
+ * older servers lack it, and with management off it still raises alarms but
360
+ * can no longer clear, silence or acknowledge them.
361
+ */
362
+ function managedNotifications(api) {
363
+ const notifications = api;
364
+ if (typeof notifications?.list !== "function" || typeof notifications.getId !== "function") return null;
365
+ try {
366
+ notifications.getId("signalk-multihelm-probe");
367
+ } catch {
368
+ return null;
369
+ }
370
+ return notifications;
371
+ }
372
+ var ACTIVE = /* @__PURE__ */ new Set([
373
+ "alert",
374
+ "warn",
375
+ "alarm",
376
+ "emergency"
377
+ ]);
378
+ function isActive(state) {
379
+ return typeof state === "string" && ACTIVE.has(state);
380
+ }
381
+ function isRecord$5(value) {
382
+ return typeof value === "object" && value !== null && !Array.isArray(value);
383
+ }
384
+ function errorText$7(error) {
385
+ return error instanceof Error ? error.message : String(error);
386
+ }
387
+ function activeAlarms(listing) {
388
+ if (!isRecord$5(listing)) return [];
389
+ const alarms = [];
390
+ for (const [id, entry] of Object.entries(listing)) {
391
+ if (!isRecord$5(entry) || typeof entry.path !== "string" || !isRecord$5(entry.value)) continue;
392
+ const value = entry.value;
393
+ const status = isRecord$5(value.status) ? value.status : {};
394
+ if (!isActive(value.state)) continue;
395
+ alarms.push({
396
+ id,
397
+ path: entry.path,
398
+ state: value.state,
399
+ message: typeof value.message === "string" ? value.message : "",
400
+ data: isRecord$5(value.data) ? value.data : {},
401
+ silenced: status.silenced === true,
402
+ acknowledged: status.acknowledged === true
403
+ });
404
+ }
405
+ return alarms;
406
+ }
407
+ function isMirror(alarm) {
408
+ return typeof alarm.data[FROM_MASTER] === "string";
409
+ }
410
+ function byPath(alarms) {
411
+ const paths = /* @__PURE__ */ new Map();
412
+ for (const alarm of alarms) if (!paths.has(alarm.path)) paths.set(alarm.path, alarm);
413
+ return paths;
414
+ }
415
+ var MasterAlarms = class {
416
+ host;
417
+ timer = null;
418
+ running = false;
419
+ stopped = false;
420
+ seen = /* @__PURE__ */ new Map();
421
+ constructor(host) {
422
+ this.host = host;
423
+ }
424
+ start() {
425
+ this.timer = setInterval(() => {
426
+ this.sync();
427
+ }, ALARMS_POLL_MS);
428
+ }
429
+ stop() {
430
+ this.stopped = true;
431
+ if (this.timer) clearInterval(this.timer);
432
+ this.timer = null;
433
+ this.clearMirrors(() => false);
434
+ }
435
+ /** One pass; never rejects. */
436
+ async sync() {
437
+ if (this.running || this.stopped) return;
438
+ this.running = true;
439
+ try {
440
+ await this.syncOnce();
441
+ } catch (error) {
442
+ this.host.debug(`Multihelm: the alarms from the master: ${errorText$7(error)}`);
443
+ } finally {
444
+ this.running = false;
445
+ }
446
+ }
447
+ async syncOnce() {
448
+ const master = this.host.master();
449
+ if (!master) {
450
+ this.clearMirrors(() => false);
451
+ return;
452
+ }
453
+ this.clearMirrors((mirror) => mirror.data[FROM_MASTER] === master.id);
454
+ const listing = await callPeer("GET", master.access, NOTIFICATIONS_PATH, master.access.token);
455
+ if (!this.stillFor(master)) return;
456
+ const theirs = byPath(activeAlarms(listing).filter((alarm) => !isMirror(alarm)));
457
+ this.clearMirrors((mirror) => mirror.data["multihelmMaster"] === master.id && mirror.data["multihelmMasterAlarm"] === theirs.get(mirror.path)?.id);
458
+ const seen = /* @__PURE__ */ new Map();
459
+ for (const [path, alarm] of theirs) {
460
+ if (!this.stillFor(master)) return;
461
+ try {
462
+ const here = this.alarmHere(path, alarm, master.id);
463
+ seen.set(here.id, await this.keepInStep(master, here, alarm));
464
+ } catch (error) {
465
+ this.host.debug(`Multihelm: the master's alarm ${path}: ${errorText$7(error)}`);
466
+ }
467
+ }
468
+ this.seen = seen;
469
+ }
470
+ stillFor(master) {
471
+ return !this.stopped && this.host.master()?.id === master.id;
472
+ }
473
+ /**
474
+ * This server's own alarm on the path, or the one shown for the master's.
475
+ * Read again for each alarm, since the server may have raised one of its own while a send waited.
476
+ */
477
+ alarmHere(path, theirs, masterId) {
478
+ const here = activeAlarms(this.host.notifications.list()).filter((a) => a.path === path);
479
+ const own = here.find((alarm) => !isMirror(alarm));
480
+ const mirror = here.find(isMirror);
481
+ if (!own) return this.mirrored(mirror, theirs, masterId);
482
+ if (mirror) this.host.notifications.clear(mirror.id);
483
+ return own;
484
+ }
485
+ mirrored(mirror, theirs, masterId) {
486
+ const notifications = this.host.notifications;
487
+ const data = {
488
+ ...theirs.data,
489
+ [FROM_MASTER]: masterId,
490
+ [MASTER_ALARM]: theirs.id
491
+ };
492
+ const shown = {
493
+ ...theirs,
494
+ data,
495
+ silenced: false,
496
+ acknowledged: false
497
+ };
498
+ if (!mirror) {
499
+ const id = notifications.raise({
500
+ state: theirs.state,
501
+ message: theirs.message,
502
+ path: theirs.path,
503
+ data
504
+ });
505
+ return {
506
+ ...shown,
507
+ id
508
+ };
509
+ }
510
+ if (mirror.state === theirs.state && mirror.message === theirs.message && isDeepStrictEqual(mirror.data, data)) return mirror;
511
+ notifications.update(mirror.id, {
512
+ state: theirs.state,
513
+ message: theirs.message,
514
+ data
515
+ });
516
+ return mirror.state === theirs.state ? {
517
+ ...mirror,
518
+ message: theirs.message,
519
+ data
520
+ } : {
521
+ ...shown,
522
+ id: mirror.id
523
+ };
524
+ }
525
+ async keepInStep(master, here, theirs) {
526
+ const last = this.seen.get(here.id);
527
+ const before = last?.masterId === master.id && last.theirId === theirs.id ? last : null;
528
+ const now = {
529
+ masterId: master.id,
530
+ theirId: theirs.id,
531
+ silenced: here.silenced,
532
+ acknowledged: here.acknowledged,
533
+ unsent: null
534
+ };
535
+ const id = here.id;
536
+ if (theirs.acknowledged && !here.acknowledged) {
537
+ this.host.notifications.acknowledge(id);
538
+ return {
539
+ ...now,
540
+ acknowledged: true
541
+ };
542
+ }
543
+ if (theirs.silenced && !here.silenced && !here.acknowledged) {
544
+ this.host.notifications.silence(id);
545
+ return {
546
+ ...now,
547
+ silenced: true
548
+ };
549
+ }
550
+ if (!before) return now;
551
+ const unsent = here.acknowledged && !theirs.acknowledged && (!before.acknowledged || before.unsent === "acknowledge") ? "acknowledge" : here.silenced && !theirs.silenced && !theirs.acknowledged && (!before.silenced || before.unsent === "silence") ? "silence" : null;
552
+ if (unsent && !await this.sendToMaster(master, theirs, unsent)) return {
553
+ ...now,
554
+ unsent
555
+ };
556
+ return now;
557
+ }
558
+ async sendToMaster(master, alarm, action) {
559
+ const token = await this.host.control.token(master);
560
+ if (token === null || !this.stillFor(master)) return false;
561
+ try {
562
+ await callPeer("POST", master.access, `${NOTIFICATIONS_PATH}/${encodeURIComponent(alarm.id)}/${action}`, token);
563
+ } catch (error) {
564
+ if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) this.host.control.revoked(master.id, token);
565
+ this.host.debug(`Multihelm: sending the ${action} of ${alarm.path} to the master: ${errorText$7(error)}`);
566
+ return false;
567
+ }
568
+ this.host.debug(`Multihelm: sent the ${action} of ${alarm.path} to the master`);
569
+ return true;
570
+ }
571
+ clearMirrors(keep) {
572
+ const notifications = this.host.notifications;
573
+ for (const alarm of activeAlarms(notifications.list())) if (isMirror(alarm) && !keep(alarm)) try {
574
+ notifications.clear(alarm.id);
575
+ } catch (error) {
576
+ this.host.debug(`Multihelm: clearing ${alarm.path}: ${errorText$7(error)}`);
577
+ }
578
+ }
579
+ };
580
+ // src/autopilot-from-master.ts
581
+ /**
582
+ * On a server that is not the master: the master's autopilot, served by this
583
+ * server's Autopilot API. Multihelm registers itself as the autopilot
584
+ * provider here and sends every command on to the master's Autopilot API, so
585
+ * a chartplotter at any station operates the one autopilot the master drives,
586
+ * and only the master sends to it. Its state is read from the master every
587
+ * second and published here as the provider's update.
588
+ *
589
+ * Reading uses the readonly pairing token; commands need the readwrite
590
+ * device token on the master (`MasterControlAccess`), asked for when the
591
+ * master is first found to have an autopilot.
592
+ */
593
+ var AUTOPILOTS_PATH = "/signalk/v2/api/vessels/self/autopilots";
594
+ var STATE_POLL_MS = 1e3;
595
+ var DEVICES_POLL_MS = 1e4;
596
+ /** What the server's Autopilot API makes of a provider's rejection: its status and message. */
597
+ var AutopilotError = class extends Error {
598
+ statusCode;
599
+ constructor(statusCode, message) {
600
+ super(message);
601
+ this.statusCode = statusCode;
602
+ }
603
+ };
604
+ function errorText$6(error) {
605
+ return error instanceof Error ? error.message : String(error);
606
+ }
607
+ function isRecord$4(value) {
608
+ return typeof value === "object" && value !== null && !Array.isArray(value);
609
+ }
610
+ /** The provider answers in the shape the server hands on, so the master's answer passes as it is. */
611
+ function asInfo(value) {
612
+ if (!isRecord$4(value)) throw new AutopilotError(502, "the master sent no autopilot data");
613
+ return value;
614
+ }
615
+ function valueOf(answer) {
616
+ return isRecord$4(answer) ? answer.value : void 0;
617
+ }
618
+ var MasterAutopilot = class {
619
+ host;
620
+ registered = false;
621
+ /** Counts withdrawals, so a read that outlived one publishes nothing. */
622
+ withdrawals = 0;
623
+ devices = [];
624
+ published = /* @__PURE__ */ new Map();
625
+ stateTimer = null;
626
+ devicesTimer = null;
627
+ polling = false;
628
+ stopped = false;
629
+ constructor(host) {
630
+ this.host = host;
631
+ }
632
+ start() {
633
+ this.devicesTimer = setInterval(() => {
634
+ this.run(() => this.findDevices());
635
+ }, DEVICES_POLL_MS);
636
+ this.stateTimer = setInterval(() => {
637
+ this.run(() => this.pollState());
638
+ }, STATE_POLL_MS);
639
+ this.run(() => this.findDevices());
640
+ }
641
+ stop() {
642
+ for (const timer of [this.devicesTimer, this.stateTimer]) if (timer) clearInterval(timer);
643
+ this.devicesTimer = null;
644
+ this.stateTimer = null;
645
+ this.stopped = true;
646
+ this.withdraw();
647
+ }
648
+ /**
649
+ * Called when the role changes. On the master its own provider must have
650
+ * the devices, so this one steps aside before that provider starts.
651
+ */
652
+ roleChanged() {
653
+ if (this.host.isMaster()) this.withdraw();
654
+ else this.run(() => this.findDevices());
655
+ }
656
+ /** The user has to approve this server's request on the master to send it commands. */
657
+ async findDevices() {
658
+ if (this.host.isMaster()) {
659
+ this.withdraw();
660
+ return;
661
+ }
662
+ const master = this.host.master();
663
+ if (!master) return;
664
+ let answer;
665
+ try {
666
+ answer = await callPeer("GET", master.access, AUTOPILOTS_PATH, master.access.token);
667
+ } catch (error) {
668
+ this.host.debug(`Multihelm: the master's autopilots: ${errorText$6(error)}`);
669
+ return;
670
+ }
671
+ const devices = isRecord$4(answer) ? Object.keys(answer).sort() : [];
672
+ if (this.stopped || devices.length === 0 || !this.isCurrent(master)) return;
673
+ this.devices = devices;
674
+ this.host.register(this.provider, devices);
675
+ this.registered = true;
676
+ await this.host.control.token(master);
677
+ }
678
+ async pollState() {
679
+ const master = this.host.master();
680
+ if (this.polling || !this.registered || !master) return;
681
+ this.polling = true;
682
+ const withdrawals = this.withdrawals;
683
+ try {
684
+ for (const device of this.devices) {
685
+ let info;
686
+ try {
687
+ info = asInfo(await this.read(master, device, ""));
688
+ } catch (error) {
689
+ this.host.debug(`Multihelm: the state of the master's autopilot ${device}: ${errorText$6(error)}`);
690
+ continue;
691
+ }
692
+ if (withdrawals !== this.withdrawals) return;
693
+ const update = {
694
+ state: info.state,
695
+ mode: info.mode,
696
+ target: info.target,
697
+ engaged: info.engaged
698
+ };
699
+ const actions = info.options?.actions;
700
+ if (Array.isArray(actions)) update.actions = actions;
701
+ if (!isDeepStrictEqual(this.published.get(device), update)) {
702
+ this.published.set(device, update);
703
+ this.host.update(device, update);
704
+ }
705
+ }
706
+ } finally {
707
+ this.polling = false;
708
+ }
709
+ }
710
+ withdraw() {
711
+ if (this.registered) {
712
+ this.host.unregister();
713
+ this.registered = false;
714
+ this.withdrawals++;
715
+ this.published.clear();
716
+ }
717
+ }
718
+ isCurrent(master) {
719
+ return this.host.master()?.id === master.id;
720
+ }
721
+ masterOrFail() {
722
+ const master = this.host.isMaster() ? null : this.host.master();
723
+ if (!master) throw new AutopilotError(503, "no other server is the master now");
724
+ return master;
725
+ }
726
+ async read(master, device, rest) {
727
+ try {
728
+ return await callPeer("GET", master.access, `${AUTOPILOTS_PATH}/${encodeURIComponent(device)}${rest}`, master.access.token);
729
+ } catch (error) {
730
+ throw this.asAutopilotError(error);
731
+ }
732
+ }
733
+ async send(method, device, rest, body) {
734
+ const master = this.masterOrFail();
735
+ const token = await this.host.control.token(master);
736
+ if (token === null) throw new AutopilotError(403, this.host.control.denied() ? "the master denied Multihelm's request to steer its autopilot; restart Multihelm to ask again" : `approve Multihelm's request "${this.host.control.requestId()}" under Security -> Access Requests on the master to steer from this station`);
737
+ try {
738
+ await callPeer(method, master.access, `${AUTOPILOTS_PATH}/${encodeURIComponent(device)}${rest}`, token, body);
739
+ } catch (error) {
740
+ if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) this.host.control.revoked(master.id, token);
741
+ throw this.asAutopilotError(error);
742
+ }
743
+ this.run(() => this.pollState());
744
+ }
745
+ run(work) {
746
+ work().catch((error) => {
747
+ this.host.error(`Multihelm: the master's autopilot: ${errorText$6(error)}`);
748
+ });
749
+ }
750
+ asAutopilotError(error) {
751
+ if (error instanceof AutopilotError) return error;
752
+ return new AutopilotError(error instanceof PeerHttpError ? error.status : 502, `the master's autopilot: ${errorText$6(error)}`);
753
+ }
754
+ provider = {
755
+ getData: async (device) => asInfo(await this.read(this.masterOrFail(), device, "")),
756
+ getState: async (device) => valueOf(await this.read(this.masterOrFail(), device, "/state")) ?? null,
757
+ getMode: async (device) => valueOf(await this.read(this.masterOrFail(), device, "/mode")) ?? null,
758
+ getTarget: async (device) => valueOf(await this.read(this.masterOrFail(), device, "/target")) ?? null,
759
+ setState: (state, device) => this.send("PUT", device, "/state", { value: state }),
760
+ setMode: (mode, device) => this.send("PUT", device, "/mode", { value: mode }),
761
+ setTarget: (value, device) => this.send("PUT", device, "/target", {
762
+ value,
763
+ units: "rad"
764
+ }),
765
+ adjustTarget: (value, device) => this.send("PUT", device, "/target/adjust", {
766
+ value,
767
+ units: "rad"
768
+ }),
769
+ engage: (device) => this.send("POST", device, "/engage"),
770
+ disengage: (device) => this.send("POST", device, "/disengage"),
771
+ courseCurrentPoint: (device) => this.send("POST", device, "/courseCurrentPoint"),
772
+ courseNextPoint: (device) => this.send("POST", device, "/courseNextPoint"),
773
+ tack: (direction, device) => this.send("POST", device, `/tack/${direction}`),
774
+ gybe: (direction, device) => this.send("POST", device, `/gybe/${direction}`),
775
+ dodge: (value, device) => value === null ? this.send("DELETE", device, "/dodge") : value === 0 ? this.send("POST", device, "/dodge") : this.send("PUT", device, "/dodge", {
776
+ value,
777
+ units: "rad"
778
+ })
779
+ };
780
+ };
781
+ // src/master-control.ts
782
+ function errorText$5(error) {
783
+ return error instanceof Error ? error.message : String(error);
784
+ }
785
+ var MasterControlAccess = class {
786
+ host;
787
+ control;
788
+ /** The access request or poll in flight for each master, shared by everyone waiting for it. */
789
+ asking = /* @__PURE__ */ new Map();
790
+ constructor(host) {
791
+ this.host = host;
792
+ this.control = host.store.loadControlAccess();
793
+ }
794
+ requestId() {
795
+ return `signalk-multihelm-control-${this.host.serverId}`;
796
+ }
797
+ /** The request the user has to approve on the master; null on the master itself. */
798
+ waitingForApproval(isMaster) {
799
+ return !isMaster && this.control?.state === "waiting-approval" ? {
800
+ masterId: this.control.masterId,
801
+ request: this.requestId()
802
+ } : null;
803
+ }
804
+ /** Whether the master denied it; it is asked for again only after a restart. */
805
+ denied() {
806
+ return this.control?.state === "denied";
807
+ }
808
+ /** The master refused `token`: it is asked for again, unless a newer one is saved by now. */
809
+ revoked(masterId, token) {
810
+ if (this.control?.masterId === masterId && this.control.token === token) this.save(null);
811
+ }
812
+ /** The token, empty without security; null until approved. */
813
+ token(master) {
814
+ if (this.host.currentMaster() !== master.id) return Promise.resolve(null);
815
+ let token = this.asking.get(master.id);
816
+ if (!token) {
817
+ token = this.ask(master).finally(() => {
818
+ this.asking.delete(master.id);
819
+ });
820
+ this.asking.set(master.id, token);
821
+ }
822
+ return token;
823
+ }
824
+ async ask(master) {
825
+ if (this.control && this.control.masterId !== master.id) this.save(null);
826
+ if (this.control?.state === "granted") return this.control.token;
827
+ if (this.control?.state === "denied") return null;
828
+ let result;
829
+ try {
830
+ result = this.control?.state === "waiting-approval" && this.control.requestHref ? await pollAccess(master.access, this.control.requestHref) : await requestAccess(master.access, this.requestId(), "Multihelm: send commands to the master from another station", "readwrite");
831
+ } catch (error) {
832
+ this.host.debug(`Multihelm: access request on the master: ${errorText$5(error)}`);
833
+ return null;
834
+ }
835
+ if (this.host.currentMaster() !== master.id) return null;
836
+ switch (result.kind) {
837
+ case "no-security":
838
+ this.save({
839
+ masterId: master.id,
840
+ token: "",
841
+ state: "granted"
842
+ });
843
+ return "";
844
+ case "approved":
845
+ this.save({
846
+ masterId: master.id,
847
+ token: result.token,
848
+ state: "granted"
849
+ });
850
+ return result.token;
851
+ case "pending":
852
+ this.save({
853
+ masterId: master.id,
854
+ token: "",
855
+ requestHref: result.href,
856
+ state: "waiting-approval"
857
+ });
858
+ return null;
859
+ case "denied":
860
+ this.host.store.saveControlAccess(null);
861
+ this.control = {
862
+ masterId: master.id,
863
+ token: "",
864
+ state: "denied"
865
+ };
866
+ return null;
867
+ case "error":
868
+ this.host.debug(`Multihelm: access request on the master: ${result.message}`);
869
+ return null;
870
+ }
871
+ }
872
+ save(access) {
873
+ this.control = access;
874
+ this.host.store.saveControlAccess(access);
875
+ }
876
+ };
877
+ // src/course-from-master.ts
878
+ /**
879
+ * The active destination or route, the same on every server: a server that
880
+ * is not the master takes the master's course over, and a change made here
881
+ * (a destination set at this station, the next point of the route) is sent
882
+ * to the master, which all the others then take over. What is kept in step
883
+ * is the setting itself, never the action that led to it, so two servers
884
+ * that both move on to the next point at an arrival end on the same point.
885
+ *
886
+ * Both servers are read each second through their Course API. This server's
887
+ * course is written with its own admin token, the master's with the control
888
+ * token there. Each server works out the rest of the course (bearings, XTE)
889
+ * from its own position; the start of a leg from the vessel position is
890
+ * where that server was when it took the course over.
891
+ */
892
+ var COURSE_PATH = "/signalk/v2/api/vessels/self/navigation/course";
893
+ var COURSE_POLL_MS = 1e3;
894
+ function isRecord$3(value) {
895
+ return typeof value === "object" && value !== null && !Array.isArray(value);
896
+ }
897
+ function errorText$4(error) {
898
+ return error instanceof Error ? error.message : String(error);
899
+ }
900
+ function asPosition(value) {
901
+ return isRecord$3(value) && typeof value.latitude === "number" && typeof value.longitude === "number" ? {
902
+ latitude: value.latitude,
903
+ longitude: value.longitude
904
+ } : null;
905
+ }
906
+ /** The setting in a Course API answer; null for an answer that is not one. */
907
+ function courseSetting(raw) {
908
+ if (!isRecord$3(raw)) return null;
909
+ const active = raw.activeRoute;
910
+ const next = raw.nextPoint;
911
+ let route = null;
912
+ let point = null;
913
+ if (isRecord$3(active) && typeof active.href === "string") route = {
914
+ href: active.href,
915
+ pointIndex: typeof active.pointIndex === "number" ? active.pointIndex : 0,
916
+ reverse: active.reverse === true
917
+ };
918
+ else if (isRecord$3(next)) {
919
+ const position = asPosition(next.position);
920
+ point = typeof next.href === "string" ? { href: next.href } : position ? { position } : null;
921
+ }
922
+ return {
923
+ route,
924
+ point,
925
+ arrivalCircle: typeof raw.arrivalCircle === "number" ? raw.arrivalCircle : 0,
926
+ targetArrivalTime: typeof raw.targetArrivalTime === "string" ? raw.targetArrivalTime : null
927
+ };
928
+ }
929
+ /** Makes the course `call` reaches, now `from`, into `to`. */
930
+ async function writeCourse(call, from, to) {
931
+ let cleared = false;
932
+ if (to.route) {
933
+ if (!isDeepStrictEqual(from.route, to.route)) await call("PUT", "/activeRoute", {
934
+ ...to.route,
935
+ arrivalCircle: to.arrivalCircle
936
+ });
937
+ } else if (to.point) {
938
+ if (from.route || !isDeepStrictEqual(from.point, to.point)) await call("PUT", "/destination", {
939
+ ...to.point,
940
+ arrivalCircle: to.arrivalCircle
941
+ });
942
+ } else if (from.route || from.point) {
943
+ await call("DELETE", "");
944
+ cleared = true;
945
+ }
946
+ if (from.arrivalCircle !== to.arrivalCircle) await call("PUT", "/arrivalCircle", { value: to.arrivalCircle });
947
+ if ((cleared ? null : from.targetArrivalTime) !== to.targetArrivalTime) await call("PUT", "/targetArrivalTime", { value: to.targetArrivalTime });
948
+ }
949
+ /**
950
+ * Whether `course` lies between `from` and `to`: each part as in one or the
951
+ * other, as after a write from one to the other that stopped part way.
952
+ */
953
+ function onTheWay(course, from, to) {
954
+ const clearing = !to.route && !to.point;
955
+ return Object.keys(course).every((key) => isDeepStrictEqual(course[key], from[key]) || isDeepStrictEqual(course[key], to[key]) || key === "targetArrivalTime" && clearing && course[key] === null);
956
+ }
957
+ var MasterCourse = class {
958
+ host;
959
+ timer = null;
960
+ running = false;
961
+ /** The course both servers last agreed on, and the master it was agreed with. */
962
+ agreed = null;
963
+ /**
964
+ * A course set here whose sending to the master has not completed, and the
965
+ * master's course it was sent over: sent again while the master's course is
966
+ * still on the way from one to the other, and nobody else changed it.
967
+ */
968
+ sending = null;
969
+ stopped = false;
970
+ constructor(host) {
971
+ this.host = host;
972
+ }
973
+ start() {
974
+ this.timer = setInterval(() => {
975
+ this.sync();
976
+ }, COURSE_POLL_MS);
977
+ }
978
+ stop() {
979
+ this.stopped = true;
980
+ if (this.timer) clearInterval(this.timer);
981
+ this.timer = null;
982
+ }
983
+ /** One pass; never rejects. */
984
+ async sync() {
985
+ if (this.running) return;
986
+ this.running = true;
987
+ try {
988
+ await this.syncOnce();
989
+ } catch (error) {
990
+ this.host.debug(`Multihelm: the course from the master: ${errorText$4(error)}`);
991
+ } finally {
992
+ this.running = false;
993
+ }
994
+ }
995
+ async syncOnce() {
996
+ const master = this.host.master();
997
+ if (!master) {
998
+ this.agreed = null;
999
+ this.sending = null;
1000
+ return;
1001
+ }
1002
+ const ownToken = await this.host.own.token();
1003
+ if (ownToken === null) return;
1004
+ const here = this.ownCall(ownToken);
1005
+ const refusedHere = () => {
1006
+ this.host.own.revoked();
1007
+ };
1008
+ const theirs = await this.readMaster(master);
1009
+ const ours = courseSetting(await this.guarded(() => here("GET", ""), refusedHere));
1010
+ if (!theirs || !ours || !this.stillFor(master)) return;
1011
+ const agreed = this.agreed?.masterId === master.id ? this.agreed.course : null;
1012
+ if (isDeepStrictEqual(ours, theirs)) {
1013
+ this.agreed = {
1014
+ masterId: master.id,
1015
+ course: theirs
1016
+ };
1017
+ this.sending = null;
1018
+ return;
1019
+ }
1020
+ const sending = this.sending?.masterId === master.id && isDeepStrictEqual(this.sending.course, ours) ? this.sending : null;
1021
+ const from = sending ? onTheWay(theirs, sending.from, ours) ? sending.from : null : agreed && isDeepStrictEqual(theirs, agreed) ? agreed : null;
1022
+ if (from) {
1023
+ await this.send(master, ours, from, sending !== null);
1024
+ return;
1025
+ }
1026
+ this.sending = null;
1027
+ await this.guarded(() => writeCourse(this.whileFor(master, here), ours, theirs), refusedHere);
1028
+ this.agreed = {
1029
+ masterId: master.id,
1030
+ course: theirs
1031
+ };
1032
+ this.host.debug("Multihelm: took the master's course over");
1033
+ }
1034
+ /**
1035
+ * Sends `ours` to the master, if its course is still `from`, or on the way
1036
+ * from `from` to `ours` when an earlier sending stopped part way.
1037
+ */
1038
+ async send(master, ours, from, resending) {
1039
+ const controlToken = await this.host.control.token(master);
1040
+ if (controlToken === null) return;
1041
+ const theirs = await this.readMaster(master);
1042
+ const unchanged = theirs && (resending ? onTheWay(theirs, from, ours) : isDeepStrictEqual(theirs, from));
1043
+ if (!theirs || !unchanged || !this.stillFor(master)) return;
1044
+ this.sending = {
1045
+ masterId: master.id,
1046
+ from,
1047
+ course: ours
1048
+ };
1049
+ await this.guarded(() => writeCourse(this.whileFor(master, this.masterCall(master, controlToken)), theirs, ours), () => {
1050
+ this.host.control.revoked(master.id, controlToken);
1051
+ });
1052
+ this.sending = null;
1053
+ this.agreed = {
1054
+ masterId: master.id,
1055
+ course: ours
1056
+ };
1057
+ this.host.debug("Multihelm: sent the course set here to the master");
1058
+ }
1059
+ /** `call`, refusing each request once the pass may no longer write for `master`. */
1060
+ whileFor(master, call) {
1061
+ return (method, path, body) => this.stillFor(master) ? call(method, path, body) : Promise.reject(/* @__PURE__ */ new Error("stopped, or the master changed"));
1062
+ }
1063
+ async readMaster(master) {
1064
+ return courseSetting(await callPeer("GET", master.access, COURSE_PATH, master.access.token));
1065
+ }
1066
+ /** Whether a pass begun for `master` may still write: not stopped, and the master unchanged. */
1067
+ stillFor(master) {
1068
+ return !this.stopped && this.host.master()?.id === master.id;
1069
+ }
1070
+ async guarded(work, refused) {
1071
+ try {
1072
+ return await work();
1073
+ } catch (error) {
1074
+ if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) refused();
1075
+ throw error;
1076
+ }
1077
+ }
1078
+ ownCall(token) {
1079
+ return (method, path, body) => callServer(method, `${this.host.ownUrl()}${COURSE_PATH}${path}`, token, body);
1080
+ }
1081
+ masterCall(master, token) {
1082
+ return (method, path, body) => callPeer(method, master.access, `${COURSE_PATH}${path}`, token, body);
1083
+ }
1084
+ };
216
1085
  // src/discovery.ts
217
1086
  /**
218
1087
  * Finds the other Signal K servers on the network, to offer them for pairing.
@@ -330,6 +1199,11 @@ var ConfigSchema = Type.Object({
330
1199
  description: "Set this on one server only. Plugins that run on the master alone run here, and the other servers use them through this one.",
331
1200
  default: false
332
1201
  }),
1202
+ syncResources: Type.Boolean({
1203
+ title: "Keep routes and waypoints in step",
1204
+ description: "Routes, waypoints, regions and notes, kept the same on every server of the boat: a change on one reaches the others, with no master.",
1205
+ default: true
1206
+ }),
333
1207
  followVessel: Type.Boolean({
334
1208
  title: "Take the vessel data over from the master",
335
1209
  description: "Name, MMSI, call sign, dimensions and ship type from Server -> Settings. Changes made here are replaced by the master's.",
@@ -349,17 +1223,32 @@ var ConfigSchema = Type.Object({
349
1223
  title: "Answer this server's History API from the master",
350
1224
  description: "While the master has a history provider (signalk-questdb, for example), history graphs on this server show the master's history, so it is kept once on the boat. Does nothing on the master, while the master has no history, or before Signal K 2.32.0.",
351
1225
  default: true
1226
+ }),
1227
+ autopilotFromMaster: Type.Boolean({
1228
+ title: "Operate the master's autopilot from this server",
1229
+ description: "This server's Autopilot API serves the master's autopilot, so a chartplotter here operates it, while only the master sends to it. Put the autopilot provider plugin on the list of plugins that run on the master only. Does nothing on the master.",
1230
+ default: true
1231
+ }),
1232
+ courseFromMaster: Type.Boolean({
1233
+ title: "Keep the course the same as on the master",
1234
+ description: "This server takes the master's active destination or route over, and a destination or route set here is sent to the master, so every station follows the same course. Does nothing on the master.",
1235
+ default: true
1236
+ }),
1237
+ alarmsFromMaster: Type.Boolean({
1238
+ title: "Show the master's alarms here",
1239
+ description: "Every active alarm on the master also sounds here, and silencing or acknowledging an alarm here does it on the master and every other station. An alarm this server raises itself on the same path is not shown twice. Does nothing on the master, or on a server without the Notifications API or with notification management off.",
1240
+ default: true
352
1241
  })
353
1242
  });
354
1243
  // src/source-priorities.ts
355
- function isRecord$1(value) {
1244
+ function isRecord$2(value) {
356
1245
  return typeof value === "object" && value !== null && !Array.isArray(value);
357
1246
  }
358
1247
  function isText(value) {
359
1248
  return typeof value === "string" && value !== "";
360
1249
  }
361
1250
  function group(value) {
362
- if (!isRecord$1(value) || !isText(value.id) || !Array.isArray(value.sources) || !value.sources.every(isText) || value.inactive !== void 0 && typeof value.inactive !== "boolean") return null;
1251
+ if (!isRecord$2(value) || !isText(value.id) || !Array.isArray(value.sources) || !value.sources.every(isText) || value.inactive !== void 0 && typeof value.inactive !== "boolean") return null;
363
1252
  const sources = value.sources;
364
1253
  return value.inactive === void 0 ? {
365
1254
  id: value.id,
@@ -372,7 +1261,7 @@ function group(value) {
372
1261
  }
373
1262
  /** The server takes a timeout as an integer or a string of one, and keeps a number. */
374
1263
  function entry(value) {
375
- if (!isRecord$1(value) || !isText(value.sourceRef)) return null;
1264
+ if (!isRecord$2(value) || !isText(value.sourceRef)) return null;
376
1265
  const timeout = typeof value.timeout === "string" && /^-?\d+$/.test(value.timeout) ? Number(value.timeout) : value.timeout;
377
1266
  return typeof timeout === "number" && Number.isInteger(timeout) ? {
378
1267
  sourceRef: value.sourceRef,
@@ -388,7 +1277,7 @@ function allOrNull(items, parse) {
388
1277
  * would replace a server's whole set with less than the master meant.
389
1278
  */
390
1279
  function parseSourcePriorities(raw) {
391
- if (!isRecord$1(raw) || !Array.isArray(raw.groups) || !isRecord$1(raw.overrides)) return null;
1280
+ if (!isRecord$2(raw) || !Array.isArray(raw.groups) || !isRecord$2(raw.overrides)) return null;
392
1281
  const groups = allOrNull(raw.groups, group);
393
1282
  const overrides = {};
394
1283
  for (const [path, list] of Object.entries(raw.overrides)) {
@@ -397,7 +1286,7 @@ function parseSourcePriorities(raw) {
397
1286
  overrides[path] = entries;
398
1287
  }
399
1288
  const defaults = raw.defaults ?? {};
400
- if (!groups || !isRecord$1(defaults)) return null;
1289
+ if (!groups || !isRecord$2(defaults)) return null;
401
1290
  const { fallbackMs } = defaults;
402
1291
  if (fallbackMs === void 0) return {
403
1292
  groups,
@@ -441,12 +1330,12 @@ var SELF = "vessels.self";
441
1330
  function isMetaPath(path) {
442
1331
  return /^[A-Za-z0-9_:-]+(\.[A-Za-z0-9_:-]+)*$/.test(path);
443
1332
  }
444
- function isRecord(value) {
1333
+ function isRecord$1(value) {
445
1334
  return typeof value === "object" && value !== null && !Array.isArray(value);
446
1335
  }
447
1336
  function pathValues(list) {
448
1337
  if (!Array.isArray(list)) return [];
449
- return list.flatMap((pv) => isRecord(pv) && typeof pv.path === "string" ? [{
1338
+ return list.flatMap((pv) => isRecord$1(pv) && typeof pv.path === "string" ? [{
450
1339
  path: pv.path,
451
1340
  value: pv.value
452
1341
  }] : []);
@@ -458,7 +1347,7 @@ function num(value) {
458
1347
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
459
1348
  }
460
1349
  function field(value, key) {
461
- return isRecord(value) ? value[key] : void 0;
1350
+ return isRecord$1(value) ? value[key] : void 0;
462
1351
  }
463
1352
  function vesselData(values) {
464
1353
  const length = values.get("design.length");
@@ -479,10 +1368,10 @@ function vesselSettingsFromDeltas(deltas) {
479
1368
  const values = /* @__PURE__ */ new Map();
480
1369
  const meta = {};
481
1370
  if (Array.isArray(deltas)) for (const delta of deltas) {
482
- if (!isRecord(delta) || delta.context !== SELF || !Array.isArray(delta.updates)) continue;
1371
+ if (!isRecord$1(delta) || delta.context !== SELF || !Array.isArray(delta.updates)) continue;
483
1372
  for (const update of delta.updates) {
484
- if (!isRecord(update)) continue;
485
- for (const { path, value } of pathValues(update.values)) if (path === "" && isRecord(value)) for (const [k, v] of Object.entries(value)) values.set(k, v);
1373
+ if (!isRecord$1(update)) continue;
1374
+ for (const { path, value } of pathValues(update.values)) if (path === "" && isRecord$1(value)) for (const [k, v] of Object.entries(value)) values.set(k, v);
486
1375
  else if (path !== "") values.set(path, value);
487
1376
  for (const { path, value } of pathValues(update.meta)) if (isMetaPath(path)) meta[path] = value;
488
1377
  }
@@ -494,7 +1383,7 @@ function vesselSettingsFromDeltas(deltas) {
494
1383
  }
495
1384
  /** A peer's answer, kept to the shape above; anything else is dropped. */
496
1385
  function parseVesselSettings(raw) {
497
- if (!isRecord(raw) || !isRecord(raw.vessel) || !isRecord(raw.meta)) return null;
1386
+ if (!isRecord$1(raw) || !isRecord$1(raw.vessel) || !isRecord$1(raw.meta)) return null;
498
1387
  const v = raw.vessel;
499
1388
  const vessel = {};
500
1389
  for (const key of [
@@ -517,7 +1406,7 @@ function parseVesselSettings(raw) {
517
1406
  if (n !== void 0) vessel[key] = n;
518
1407
  }
519
1408
  const meta = {};
520
- for (const [path, value] of Object.entries(raw.meta)) if (isMetaPath(path) && isRecord(value)) meta[path] = value;
1409
+ for (const [path, value] of Object.entries(raw.meta)) if (isMetaPath(path) && isRecord$1(value)) meta[path] = value;
521
1410
  const priorities = parseSourcePriorities(raw.priorities);
522
1411
  return priorities ? {
523
1412
  vessel,
@@ -534,11 +1423,10 @@ function parseVesselSettings(raw) {
534
1423
  * and source priorities over from the master. They are read from the
535
1424
  * master with the pairing token and written here through this server's own
536
1425
  * REST API, the way its settings pages write them, so they survive a
537
- * restart. Writing needs an admin device token on this server, asked for
538
- * once; until it is approved nothing is written. Metadata of a path the
1426
+ * restart, with this server's admin device token on itself. Metadata of a path the
539
1427
  * master has none for stays as it is, unless it was the master's before.
540
1428
  */
541
- function errorText$2(error) {
1429
+ function errorText$3(error) {
542
1430
  return error instanceof Error ? error.message : String(error);
543
1431
  }
544
1432
  /** A master where none are set yet would wipe the ones a server kept from before Multihelm. */
@@ -582,7 +1470,6 @@ function metaUrl(base, path) {
582
1470
  }
583
1471
  var MasterFollower = class {
584
1472
  host;
585
- access;
586
1473
  prioritiesWritten = new WrittenValues();
587
1474
  metaWritten = new WrittenValues();
588
1475
  /**
@@ -594,23 +1481,10 @@ var MasterFollower = class {
594
1481
  followedMetaSaved;
595
1482
  constructor(host) {
596
1483
  this.host = host;
597
- this.access = host.store.loadOwnAccess();
598
1484
  const followed = host.store.loadFollowedMeta();
599
1485
  this.followedMeta = new Set(followed);
600
1486
  this.followedMetaSaved = JSON.stringify(followed.sort());
601
1487
  }
602
- /** Whether the user has to approve this server's own access request. */
603
- waitingForApproval() {
604
- return this.access.state === "waiting-approval";
605
- }
606
- /** The identifier of the access request on this server, as Security -> Access Requests lists it. */
607
- accessRequestId() {
608
- return `signalk-multihelm-self-${this.host.serverId}`;
609
- }
610
- /** Whether the user denied it; it is asked for again only after a restart. */
611
- denied() {
612
- return this.access.state === "denied";
613
- }
614
1488
  async run() {
615
1489
  const { followVessel, followMeta, followPriorities } = this.host;
616
1490
  const master = this.host.master();
@@ -618,9 +1492,9 @@ var MasterFollower = class {
618
1492
  if (!followVessel && !followMeta && !followPriorities || !master || !local) return;
619
1493
  let remote;
620
1494
  try {
621
- remote = parseVesselSettings(await fetchVesselSettings(master.url, master.token));
1495
+ remote = parseVesselSettings(await fetchVesselSettings(master, master.token));
622
1496
  } catch (error) {
623
- this.host.debug(`Multihelm: vessel settings from the master: ${errorText$2(error)}`);
1497
+ this.host.debug(`Multihelm: vessel settings from the master: ${errorText$3(error)}`);
624
1498
  return;
625
1499
  }
626
1500
  if (!remote) return;
@@ -633,7 +1507,7 @@ var MasterFollower = class {
633
1507
  const metaChanged = followMeta ? [...this.followedMeta].filter((p) => this.metaWritten.due(p, remote.meta[p], local.meta[p])) : [];
634
1508
  const priorities = followPriorities ? this.prioritiesToWrite(remote.priorities, local.priorities) : null;
635
1509
  if (!vesselChanged && metaChanged.length === 0 && !priorities) return;
636
- const token = await this.ownToken();
1510
+ const token = await this.host.access.token();
637
1511
  if (token === null) return;
638
1512
  const base = this.host.ownUrl();
639
1513
  try {
@@ -648,11 +1522,8 @@ var MasterFollower = class {
648
1522
  this.prioritiesWritten.wrote("", priorities);
649
1523
  }
650
1524
  } catch (error) {
651
- if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) this.setAccess({
652
- token: "",
653
- state: "none"
654
- });
655
- this.host.error(`Multihelm: taking over the master's vessel settings: ${errorText$2(error)}`);
1525
+ if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) this.host.access.revoked();
1526
+ this.host.error(`Multihelm: taking over the master's vessel settings: ${errorText$3(error)}`);
656
1527
  }
657
1528
  if (followMeta) this.saveFollowedMeta();
658
1529
  }
@@ -664,7 +1535,7 @@ var MasterFollower = class {
664
1535
  this.host.store.saveFollowedMeta(paths);
665
1536
  this.followedMetaSaved = text;
666
1537
  } catch (error) {
667
- this.host.error(`Multihelm: saving the paths that follow the master: ${errorText$2(error)}`);
1538
+ this.host.error(`Multihelm: saving the paths that follow the master: ${errorText$3(error)}`);
668
1539
  }
669
1540
  }
670
1541
  prioritiesToWrite(remote, local) {
@@ -678,54 +1549,177 @@ var MasterFollower = class {
678
1549
  for (const key of VESSEL_FIELDS) body[key] = vessel[key];
679
1550
  await callServer("PUT", `${base}/skServer/vessel`, token, body);
680
1551
  }
681
- setAccess(access) {
682
- this.access = access;
683
- this.host.store.saveOwnAccess(access);
684
- }
685
- async ownToken() {
686
- const base = this.host.ownUrl();
687
- if (this.access.state === "granted") return this.access.token;
688
- if (this.access.state === "denied") return null;
689
- let result;
690
- try {
691
- result = this.access.state === "waiting-approval" && this.access.requestHref ? await pollAccess(base, this.access.requestHref) : await requestAccess(base, this.accessRequestId(), "Multihelm: take the vessel settings over from the master", "admin");
692
- } catch (error) {
693
- this.host.debug(`Multihelm: access request on this server: ${errorText$2(error)}`);
694
- return null;
695
- }
696
- switch (result.kind) {
697
- case "no-security":
698
- this.setAccess({
699
- token: "",
700
- state: "granted"
701
- });
702
- return "";
703
- case "approved":
704
- this.setAccess({
705
- token: result.token,
706
- state: "granted"
707
- });
708
- return result.token;
709
- case "pending":
710
- this.setAccess({
711
- token: "",
712
- requestHref: result.href,
713
- state: "waiting-approval"
714
- });
715
- return null;
716
- case "denied":
717
- this.host.store.saveOwnAccess({
718
- token: "",
719
- state: "none"
720
- });
721
- this.access = {
722
- token: "",
723
- state: "denied"
724
- };
725
- return null;
726
- case "error":
727
- this.host.debug(`Multihelm: access request on this server: ${result.message}`);
728
- return null;
1552
+ };
1553
+ // src/master-plugins.ts
1554
+ /**
1555
+ * Plugins that run on the boat's master only, such as an autopilot provider
1556
+ * that must not send from more than one server. The list is the same on
1557
+ * every server, kept in step as a dataset with no master, so a server that
1558
+ * becomes the master already knows it. Each server switches those plugins
1559
+ * on or off through its own REST API, as the admin UI does, so the state
1560
+ * survives a restart and the admin UI shows it.
1561
+ */
1562
+ var SETTINGS_DATASET = "signalk-multihelm/settings";
1563
+ var MASTER_PLUGINS_KEY = "master-plugins";
1564
+ var FILE$1 = "plugins.json";
1565
+ var PLUGIN_ID$1 = /^[\w.@-]{1,100}$/;
1566
+ var MAX_PLUGINS = 100;
1567
+ function parsePluginIds(raw) {
1568
+ if (!Array.isArray(raw) || raw.length > MAX_PLUGINS) return null;
1569
+ const ids = [];
1570
+ for (const id of raw) {
1571
+ if (typeof id !== "string" || !PLUGIN_ID$1.test(id)) return null;
1572
+ ids.push(id);
1573
+ }
1574
+ return [...new Set(ids)].sort();
1575
+ }
1576
+ function errorText$2(error) {
1577
+ return error instanceof Error ? error.message : String(error);
1578
+ }
1579
+ /** The list, kept in a file of its own under `dir`, since a dataset entry is made of files. */
1580
+ var MasterPluginList = class {
1581
+ onChange;
1582
+ file;
1583
+ current;
1584
+ /** Writes one after the other, so two cannot share the temporary file or publish out of order. */
1585
+ writes = Promise.resolve();
1586
+ constructor(dir, onChange) {
1587
+ this.onChange = onChange;
1588
+ this.file = path.join(dir, FILE$1);
1589
+ this.current = this.read();
1590
+ }
1591
+ ids() {
1592
+ return this.current;
1593
+ }
1594
+ set(ids) {
1595
+ return this.queued(() => this.write(ids));
1596
+ }
1597
+ dataset = {
1598
+ id: SETTINGS_DATASET,
1599
+ isValidKey: (key) => key === MASTER_PLUGINS_KEY,
1600
+ list: async () => {
1601
+ let stat;
1602
+ try {
1603
+ stat = await fs.promises.stat(this.file);
1604
+ } catch {
1605
+ return [];
1606
+ }
1607
+ return [{
1608
+ key: MASTER_PLUGINS_KEY,
1609
+ meta: null,
1610
+ files: [{
1611
+ name: FILE$1,
1612
+ path: this.file,
1613
+ size: stat.size,
1614
+ mtimeMs: stat.mtimeMs
1615
+ }]
1616
+ }];
1617
+ },
1618
+ apply: async (entry) => {
1619
+ const file = entry.files.find((f) => f.name === FILE$1);
1620
+ if (!file || entry.files.length !== 1) throw new Error(`the plugin list has one file, ${String(entry.files.length)} came`);
1621
+ const ids = parsePluginIds(JSON.parse(await fs.promises.readFile(file.path, "utf8")));
1622
+ if (!ids) throw new Error("not a list of plugin ids");
1623
+ await this.queued(() => this.write(ids));
1624
+ },
1625
+ remove: async () => {
1626
+ await this.queued(async () => {
1627
+ await fs.promises.rm(this.file, { force: true });
1628
+ this.changed([]);
1629
+ });
1630
+ return true;
1631
+ }
1632
+ };
1633
+ queued(work) {
1634
+ const result = this.writes.then(work);
1635
+ this.writes = result.catch(() => void 0);
1636
+ return result;
1637
+ }
1638
+ read() {
1639
+ try {
1640
+ return parsePluginIds(JSON.parse(fs.readFileSync(this.file, "utf8"))) ?? [];
1641
+ } catch {
1642
+ return [];
1643
+ }
1644
+ }
1645
+ async write(ids) {
1646
+ const sorted = parsePluginIds(ids);
1647
+ if (!sorted) throw new Error("not a list of plugin ids");
1648
+ const text = JSON.stringify(sorted);
1649
+ let had = null;
1650
+ try {
1651
+ had = await fs.promises.readFile(this.file, "utf8");
1652
+ } catch {}
1653
+ if (had !== text) {
1654
+ await fs.promises.mkdir(path.dirname(this.file), { recursive: true });
1655
+ const tmp = `${this.file}.part`;
1656
+ await fs.promises.writeFile(tmp, text);
1657
+ await fs.promises.rename(tmp, this.file);
1658
+ }
1659
+ this.changed(sorted);
1660
+ }
1661
+ changed(ids) {
1662
+ const before = JSON.stringify(this.current);
1663
+ this.current = ids;
1664
+ if (JSON.stringify(ids) !== before) this.onChange();
1665
+ }
1666
+ };
1667
+ function pluginUrl(base, id, rest = "") {
1668
+ return `${base}/plugins/${encodeURIComponent(id)}${rest}`;
1669
+ }
1670
+ /** Switches the listed plugins on this server to what its role wants; one run at a time. */
1671
+ var MasterOnlyPlugins = class {
1672
+ host;
1673
+ running = false;
1674
+ again = false;
1675
+ constructor(host) {
1676
+ this.host = host;
1677
+ }
1678
+ apply() {
1679
+ if (this.running) {
1680
+ this.again = true;
1681
+ return;
1682
+ }
1683
+ this.running = true;
1684
+ this.applyOnce().catch((error) => {
1685
+ this.host.error(`Multihelm: switching the plugins that run on the master: ${errorText$2(error)}`);
1686
+ }).finally(() => {
1687
+ this.running = false;
1688
+ if (this.again) {
1689
+ this.again = false;
1690
+ this.apply();
1691
+ }
1692
+ });
1693
+ }
1694
+ async applyOnce() {
1695
+ const wanted = this.host.wanted();
1696
+ const ids = this.host.ids().filter((id) => id !== this.host.selfId);
1697
+ if (wanted === null || ids.length === 0) return;
1698
+ const token = await this.host.access.token();
1699
+ if (token === null) return;
1700
+ const base = this.host.ownUrl();
1701
+ for (const id of ids) try {
1702
+ if ((await callServer("GET", pluginUrl(base, id), token))?.enabled === wanted) continue;
1703
+ const options = await callServer("GET", pluginUrl(base, id, "/config"), token);
1704
+ if (this.host.wanted() !== wanted) return;
1705
+ if (!this.host.ids().includes(id)) continue;
1706
+ const body = typeof options === "object" && options !== null && !Array.isArray(options) ? {
1707
+ ...options,
1708
+ enabled: wanted
1709
+ } : { enabled: wanted };
1710
+ await callServer("POST", pluginUrl(base, id, "/config"), token, body);
1711
+ this.host.debug(`Multihelm: ${wanted ? "started" : "stopped"} ${id}, which runs on the master only`);
1712
+ } catch (error) {
1713
+ if (error instanceof PeerHttpError && error.status === 404) {
1714
+ this.host.debug(`Multihelm: ${id}, set to run on the master only, is not installed here`);
1715
+ continue;
1716
+ }
1717
+ if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) {
1718
+ this.host.access.revoked();
1719
+ this.host.error(`Multihelm: this server refused its own admin token: ${errorText$2(error)}`);
1720
+ return;
1721
+ }
1722
+ this.host.error(`Multihelm: cannot ${wanted ? "start" : "stop"} ${id}, which runs on the master only: ${errorText$2(error)}`);
729
1723
  }
730
1724
  }
731
1725
  };
@@ -990,7 +1984,8 @@ var MasterProxy = class {
990
1984
  Authorization: `Bearer ${master.token}`
991
1985
  } : headers,
992
1986
  agent: secure ? this.agents.https : this.agents.http,
993
- timeout: REQUEST_TIMEOUT_MS
1987
+ timeout: REQUEST_TIMEOUT_MS,
1988
+ ...secure && master.ca !== void 0 ? tlsOptions(url, master.ca) : {}
994
1989
  });
995
1990
  upstream.on("timeout", () => {
996
1991
  upstream.destroy(/* @__PURE__ */ new Error(`timeout after ${String(REQUEST_TIMEOUT_MS)} ms`));
@@ -1187,14 +2182,42 @@ async function hashFile(file) {
1187
2182
  function errorText$1(error) {
1188
2183
  return error instanceof Error ? error.message : String(error);
1189
2184
  }
2185
+ /** What Node calls a certificate chain that does not lead to a certificate it trusts. */
2186
+ var UNTRUSTED_CERTIFICATE = /* @__PURE__ */ new Set([
2187
+ ...UNTRUSTED_ISSUER,
2188
+ "CERT_SIGNATURE_FAILURE",
2189
+ "CERT_UNTRUSTED",
2190
+ "CERT_REJECTED"
2191
+ ]);
2192
+ function errorCode(error) {
2193
+ return error?.code;
2194
+ }
2195
+ function isRedirect(error) {
2196
+ return error instanceof PeerHttpError && error.status >= 300 && error.status < 400;
2197
+ }
2198
+ /** Pairing the peer again mends it: its certificate changed, or it went over to HTTPS. */
2199
+ function needsPairingAgain(error) {
2200
+ const code = errorCode(error);
2201
+ return isRedirect(error) || typeof code === "string" && UNTRUSTED_CERTIFICATE.has(code);
2202
+ }
2203
+ /** `error` in words when it is about the peer's certificate or a redirect; null otherwise. */
2204
+ function connectionText(error) {
2205
+ if (isRedirect(error)) return "it redirects to another address, likely its HTTPS one; pair it again";
2206
+ const code = errorCode(error);
2207
+ if (typeof code !== "string") return null;
2208
+ if (UNTRUSTED_CERTIFICATE.has(code)) return "its certificate is not the one it had when paired; pair it again if it was changed on purpose";
2209
+ if (code === "ERR_TLS_CERT_ALTNAME_INVALID") return "its certificate is issued for another name; pair it by that name";
2210
+ if (code === "CERT_HAS_EXPIRED") return "its certificate has expired";
2211
+ return null;
2212
+ }
1190
2213
  /** Said without the address, which the panel shows anyway. */
1191
2214
  function helloErrorText(error) {
1192
- if (!(error instanceof PeerHttpError)) return errorText$1(error);
2215
+ if (!(error instanceof PeerHttpError)) return connectionText(error) ?? errorText$1(error);
1193
2216
  switch (error.status) {
1194
2217
  case 404: return "Multihelm is not running there";
1195
2218
  case 401:
1196
2219
  case 403: return "access was revoked on the peer";
1197
- default: return `HTTP ${String(error.status)}`;
2220
+ default: return connectionText(error) ?? `HTTP ${String(error.status)}`;
1198
2221
  }
1199
2222
  }
1200
2223
  function toListed(entry) {
@@ -1238,6 +2261,9 @@ var Multihelm = class {
1238
2261
  announcedStatus = "";
1239
2262
  masterTimer = null;
1240
2263
  checkingMasters = false;
2264
+ checkMastersAgain = false;
2265
+ /** Whether the paired peers were asked once since the start, so the role is known. */
2266
+ mastersChecked = false;
1241
2267
  pairingTimer = null;
1242
2268
  pollingPairings = false;
1243
2269
  serverId;
@@ -1257,6 +2283,7 @@ var Multihelm = class {
1257
2283
  });
1258
2284
  };
1259
2285
  this.timer = setTimeout(tick, 0);
2286
+ this.checkMasters();
1260
2287
  this.masterTimer = setInterval(() => {
1261
2288
  this.checkMasters();
1262
2289
  }, MASTER_CHECK_INTERVAL_MS);
@@ -1287,26 +2314,42 @@ var Multihelm = class {
1287
2314
  * for a round nor races one.
1288
2315
  */
1289
2316
  async checkMasters() {
1290
- if (this.checkingMasters || this.stopped) return;
2317
+ if (this.stopped) return;
2318
+ if (this.checkingMasters) {
2319
+ this.checkMastersAgain = true;
2320
+ return;
2321
+ }
1291
2322
  this.checkingMasters = true;
1292
2323
  try {
1293
2324
  await Promise.all(this.peers.filter((p) => p.state === "paired" && p.id !== "").map(async (peer) => {
2325
+ const { url, ca } = peer;
2326
+ const current = () => !this.stopped && this.peers.includes(peer) && peer.url === url && peer.ca === ca;
1294
2327
  let hello;
1295
2328
  try {
1296
- hello = await fetchHello(peer.url, peer.token, this.helloFrom());
2329
+ hello = await fetchHello(peer, peer.token, this.helloFrom());
1297
2330
  } catch (error) {
1298
- if (!this.stopped && this.peers.includes(peer)) this.helloErrors.set(peer.url, helloErrorText(error));
2331
+ if (current()) this.helloErrors.set(url, helloErrorText(error));
1299
2332
  return;
1300
2333
  }
1301
- if (this.stopped || !this.peers.includes(peer) || hello.serverId !== peer.id) return;
1302
- this.answered(peer.url, hello);
1303
- if (hello.master) this.masterSeen.set(peer.url, Date.now());
1304
- else this.masterSeen.delete(peer.url);
2334
+ if (!current() || hello.serverId !== peer.id) return;
2335
+ this.answered(url, hello);
2336
+ if (hello.master) this.masterSeen.set(url, Date.now());
2337
+ else this.masterSeen.delete(url);
1305
2338
  }));
1306
2339
  } finally {
1307
2340
  this.checkingMasters = false;
1308
2341
  }
1309
- if (!this.stopped) this.announceRole();
2342
+ if (this.stopped) return;
2343
+ this.mastersChecked = true;
2344
+ this.announceRole();
2345
+ if (this.checkMastersAgain) {
2346
+ this.checkMastersAgain = false;
2347
+ await this.checkMasters();
2348
+ }
2349
+ }
2350
+ /** Whether the role is known: the paired peers were asked since the start. */
2351
+ roleKnown() {
2352
+ return this.mastersChecked;
1310
2353
  }
1311
2354
  /**
1312
2355
  * Follows up the pairing requests waiting for approval, between rounds. At
@@ -1407,10 +2450,15 @@ var Multihelm = class {
1407
2450
  /** Where to reach the master, with the pairing token; null when this server is it or there is none. */
1408
2451
  masterAccess() {
1409
2452
  const peer = this.masterCandidates()[0]?.peer;
1410
- return peer ? {
2453
+ if (!peer) return null;
2454
+ return peer.ca === void 0 ? {
1411
2455
  url: peer.url,
1412
2456
  token: peer.token
1413
- } : null;
2457
+ } : {
2458
+ url: peer.url,
2459
+ token: peer.token,
2460
+ ca: peer.ca
2461
+ };
1414
2462
  }
1415
2463
  /** More than one server is set to be the master: the user should set one only. */
1416
2464
  masterConflict() {
@@ -1500,6 +2548,7 @@ var Multihelm = class {
1500
2548
  return {
1501
2549
  serverId: this.serverId,
1502
2550
  name: this.host.serverName(),
2551
+ master: this.host.isMaster(),
1503
2552
  ...this.versions()
1504
2553
  };
1505
2554
  }
@@ -1531,6 +2580,8 @@ var Multihelm = class {
1531
2580
  if (oldest) this.pairedBy.delete(oldest.id);
1532
2581
  }
1533
2582
  if (!known || known.name !== server.name || known.signalk !== server.signalk || known.multihelm !== server.multihelm || now - this.pairedBySavedAt >= PAIRED_BY_SAVE_MS) this.savePairedBySoon();
2583
+ const peer = this.peers.find((p) => p.state === "paired" && p.id === from.serverId);
2584
+ if (peer && from.master !== void 0 && this.masterSeen.has(peer.url) !== from.master) this.checkMasters();
1534
2585
  }
1535
2586
  /** The servers paired with this one, by name. */
1536
2587
  pairedByInfo() {
@@ -1592,7 +2643,10 @@ var Multihelm = class {
1592
2643
  if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) {
1593
2644
  peer.state = "needs-pairing";
1594
2645
  peer.lastError = "access was revoked on the peer";
1595
- } else peer.lastError = errorText$1(error);
2646
+ } else {
2647
+ if (needsPairingAgain(error)) peer.state = "needs-pairing";
2648
+ peer.lastError = connectionText(error) ?? errorText$1(error);
2649
+ }
1596
2650
  this.host.debug(`Multihelm: ${peer.name}: ${peer.lastError}`);
1597
2651
  }
1598
2652
  }
@@ -1600,7 +2654,7 @@ var Multihelm = class {
1600
2654
  const id = dataset.definition.id;
1601
2655
  let manifest;
1602
2656
  try {
1603
- manifest = await fetchManifest(peer.url, peer.token, id, peer.cursors[id] ?? 0);
2657
+ manifest = await fetchManifest(peer, peer.token, id, peer.cursors[id] ?? 0);
1604
2658
  } catch (error) {
1605
2659
  if (error instanceof PeerHttpError && error.status === 404) {
1606
2660
  if (peer.lastError?.startsWith(`${id}:`)) delete peer.lastError;
@@ -1700,7 +2754,7 @@ var Multihelm = class {
1700
2754
  return null;
1701
2755
  }
1702
2756
  this.host.debug(`Multihelm: fetching ${id} ${remote.key} ${file.name} from ${peer.name}`);
1703
- await downloadFile(peer.url, peer.token, {
2757
+ await downloadFile(peer, peer.token, {
1704
2758
  dataset: id,
1705
2759
  key: remote.key,
1706
2760
  name: file.name
@@ -1763,9 +2817,17 @@ var Multihelm = class {
1763
2817
  */
1764
2818
  pair(input) {
1765
2819
  return this.serialize(async () => {
1766
- const url = normalizePeerUrl(input);
1767
- if (!url) throw new Error("not a server address");
1768
- let peer = this.peers.find((p) => p.url === url);
2820
+ const typed = normalizePeerUrl(input);
2821
+ if (!typed) throw new Error("not a server address");
2822
+ const address = await locatePeer(typed);
2823
+ const url = address.url;
2824
+ const result = await requestAccess(address, `signalk-multihelm-${this.serverId}-${crypto.randomUUID().slice(0, 8)}`, `Multihelm on ${this.host.serverName()}`);
2825
+ let peer = this.peers.find((p) => p.url === url) ?? this.peers.find((p) => p.url === typed);
2826
+ if (peer && result.kind === "error") throw new Error(result.message);
2827
+ if (peer && peer.url !== url) {
2828
+ this.forgetAnswers(peer.url);
2829
+ peer.url = url;
2830
+ }
1769
2831
  if (!peer) {
1770
2832
  peer = {
1771
2833
  id: "",
@@ -1777,7 +2839,8 @@ var Multihelm = class {
1777
2839
  };
1778
2840
  this.peers.push(peer);
1779
2841
  }
1780
- const result = await requestAccess(url, `signalk-multihelm-${this.serverId}-${crypto.randomUUID().slice(0, 8)}`, `Multihelm on ${this.host.serverName()}`);
2842
+ if (address.ca === void 0) delete peer.ca;
2843
+ else peer.ca = address.ca;
1781
2844
  this.applyAccessResult(peer, result);
1782
2845
  if (peer.state === "paired") await this.helloLocked(peer);
1783
2846
  this.store.savePeers(this.peers);
@@ -1791,14 +2854,17 @@ var Multihelm = class {
1791
2854
  return this.serialize(() => {
1792
2855
  const before = this.peers.length;
1793
2856
  this.peers = this.peers.filter((p) => p.url !== url);
1794
- this.masterSeen.delete(url);
1795
- this.answers.delete(url);
1796
- this.helloErrors.delete(url);
2857
+ this.forgetAnswers(url);
1797
2858
  this.store.savePeers(this.peers);
1798
2859
  this.announceRole();
1799
2860
  return Promise.resolve(this.peers.length !== before);
1800
2861
  });
1801
2862
  }
2863
+ forgetAnswers(url) {
2864
+ this.masterSeen.delete(url);
2865
+ this.answers.delete(url);
2866
+ this.helloErrors.delete(url);
2867
+ }
1802
2868
  applyAccessResult(peer, result) {
1803
2869
  switch (result.kind) {
1804
2870
  case "no-security":
@@ -1829,7 +2895,7 @@ var Multihelm = class {
1829
2895
  async pollPairingLocked(peer) {
1830
2896
  if (peer.state !== "waiting-approval" || !peer.requestHref) return;
1831
2897
  try {
1832
- this.applyAccessResult(peer, await pollAccess(peer.url, peer.requestHref));
2898
+ this.applyAccessResult(peer, await pollAccess(peer, peer.requestHref));
1833
2899
  if (peer.state === "paired") await this.helloLocked(peer);
1834
2900
  } catch (error) {
1835
2901
  peer.lastError = errorText$1(error);
@@ -1837,7 +2903,7 @@ var Multihelm = class {
1837
2903
  }
1838
2904
  async helloLocked(peer) {
1839
2905
  try {
1840
- const hello = await fetchHello(peer.url, peer.token, this.helloFrom());
2906
+ const hello = await fetchHello(peer, peer.token, this.helloFrom());
1841
2907
  if (hello.serverId === this.serverId) {
1842
2908
  peer.state = "needs-pairing";
1843
2909
  peer.lastError = "this is this server itself";
@@ -1851,6 +2917,10 @@ var Multihelm = class {
1851
2917
  else this.masterSeen.delete(peer.url);
1852
2918
  } catch (error) {
1853
2919
  this.helloErrors.set(peer.url, helloErrorText(error));
2920
+ if (needsPairingAgain(error)) {
2921
+ peer.state = "needs-pairing";
2922
+ peer.lastError = connectionText(error) ?? errorText$1(error);
2923
+ }
1854
2924
  }
1855
2925
  }
1856
2926
  };
@@ -1869,9 +2939,11 @@ function helloFrom(req) {
1869
2939
  if (!SERVER_ID.test(serverId) || name === "") return null;
1870
2940
  const signalk = queryString(req, "signalk");
1871
2941
  const multihelm = queryString(req, "multihelm");
2942
+ const master = queryString(req, "master");
1872
2943
  return {
1873
2944
  serverId,
1874
2945
  name,
2946
+ ...master === "1" || master === "0" ? { master: master === "1" } : {},
1875
2947
  ...VERSION.test(signalk) ? { signalk } : {},
1876
2948
  ...VERSION.test(multihelm) ? { multihelm } : {}
1877
2949
  };
@@ -1879,7 +2951,7 @@ function helloFrom(req) {
1879
2951
  function errorText(error) {
1880
2952
  return error instanceof Error ? error.message : String(error);
1881
2953
  }
1882
- function registerRoutes(router, multihelm, discovered, vesselSettings = () => null, masterProxy = () => null, ownAccess = () => null) {
2954
+ function registerRoutes(router, multihelm, discovered, vesselSettings = () => null, masterProxy = () => null, ownAccess = () => null, masterPlugins = () => null, controlAccess = () => null) {
1883
2955
  const scoped = router.access;
1884
2956
  const available = typeof scoped === "function";
1885
2957
  const readonly = available ? scoped.call(router, "readonly") : { get(path, handler) {
@@ -1962,7 +3034,9 @@ function registerRoutes(router, multihelm, discovered, vesselSettings = () => nu
1962
3034
  peers: mh?.peerInfo() ?? [],
1963
3035
  pairedBy: mh?.pairedByInfo() ?? [],
1964
3036
  discovered: mh ? discovered() : [],
1965
- ownAccess: mh ? ownAccess() : null
3037
+ ownAccess: mh ? ownAccess() : null,
3038
+ masterPlugins: masterPlugins()?.ids() ?? [],
3039
+ controlAccess: mh ? controlAccess() : null
1966
3040
  };
1967
3041
  res.json(status);
1968
3042
  });
@@ -1986,11 +3060,374 @@ function registerRoutes(router, multihelm, discovered, vesselSettings = () => nu
1986
3060
  const id = queryString(req, "id");
1987
3061
  res.status(mh.forgetPairedBy(id) ? 200 : 404).json({ removed: id });
1988
3062
  }));
3063
+ router.put("/master-plugins", async (req, res) => {
3064
+ const list = masterPlugins();
3065
+ if (!list) {
3066
+ res.status(503).json({ error: "Multihelm is not running" });
3067
+ return;
3068
+ }
3069
+ const ids = parsePluginIds(req.body?.plugins);
3070
+ if (!ids) {
3071
+ res.status(400).json({ error: "plugins must be a list of plugin ids" });
3072
+ return;
3073
+ }
3074
+ try {
3075
+ await list.set(ids);
3076
+ res.json({ plugins: list.ids() });
3077
+ } catch (error) {
3078
+ res.status(500).json({ error: errorText(error) });
3079
+ }
3080
+ });
1989
3081
  router.post("/run", running((mh, _req, res) => {
1990
3082
  mh.runRound();
1991
3083
  res.status(202).json({ started: true });
1992
3084
  }));
1993
3085
  }
3086
+ // src/resources-dataset.ts
3087
+ /**
3088
+ * The `resources` dataset: the routes, waypoints, regions and notes of this
3089
+ * server, one entry per resource keyed `<type>/<id>`, kept in step between
3090
+ * the boat's servers with no master. They are read and written through the
3091
+ * server's Resources API, so every provider is covered and every change
3092
+ * reaches the clients as a delta. Each resource is mirrored as a JSON file
3093
+ * in the data dir, because a dataset entry is made of files.
3094
+ */
3095
+ var RESOURCES_DATASET = "signalk-multihelm/resources";
3096
+ var RESOURCE_TYPES = [
3097
+ "routes",
3098
+ "waypoints",
3099
+ "regions",
3100
+ "notes"
3101
+ ];
3102
+ var FILE = "resource.json";
3103
+ /** What the server's Resources API requires of an id for these types. */
3104
+ var RESOURCE_ID = /^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$/;
3105
+ /** Added by the provider on every read, not part of the resource. */
3106
+ var READ_ONLY_FIELDS = /* @__PURE__ */ new Set(["timestamp", "$source"]);
3107
+ var STORED_CHECKS = 20;
3108
+ var STORED_CHECK_MS = 100;
3109
+ var DELETE_CONFIRM_MS = 2e3;
3110
+ /** Plugins reach the Resources API in process; a server without it has nothing to keep in step. */
3111
+ function hasResourcesApi(app) {
3112
+ return typeof app.resourcesApi?.setResource === "function";
3113
+ }
3114
+ function isResourceType(type) {
3115
+ return RESOURCE_TYPES.includes(type);
3116
+ }
3117
+ function isResourceKey(key) {
3118
+ const [type, id, ...rest] = key.split("/");
3119
+ return rest.length === 0 && type !== void 0 && isResourceType(type) && RESOURCE_ID.test(id ?? "");
3120
+ }
3121
+ /** The resource a `resources.<type>.<id>` delta path names, or null. */
3122
+ function resourceOfPath(deltaPath) {
3123
+ const [root, type, id, ...rest] = deltaPath.split(".");
3124
+ return root === "resources" && rest.length === 0 && type !== void 0 && isResourceType(type) && RESOURCE_ID.test(id ?? "") ? {
3125
+ type,
3126
+ id: id ?? ""
3127
+ } : null;
3128
+ }
3129
+ function isRecord(value) {
3130
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3131
+ }
3132
+ /** Sorted keys, so the same resource always gives the same file and nothing churns. */
3133
+ function canonical(value) {
3134
+ if (Array.isArray(value)) return value.map(canonical);
3135
+ if (isRecord(value)) return Object.fromEntries(Object.keys(value).sort().map((k) => [k, canonical(value[k])]));
3136
+ return value;
3137
+ }
3138
+ function resourceText(resource) {
3139
+ const stored = Object.fromEntries(Object.entries(resource).filter(([k]) => !READ_ONLY_FIELDS.has(k)));
3140
+ return JSON.stringify(canonical(stored));
3141
+ }
3142
+ function splitKey(key) {
3143
+ const [type, id] = key.split("/");
3144
+ return {
3145
+ type,
3146
+ id
3147
+ };
3148
+ }
3149
+ var sleep = (ms) => new Promise((resolve) => {
3150
+ setTimeout(resolve, ms);
3151
+ });
3152
+ function resourcesDataset(host) {
3153
+ const mirrorPath = (type, id) => path.join(host.mirrorDir, type, `${id}.json`);
3154
+ async function mirrored(type) {
3155
+ const found = /* @__PURE__ */ new Map();
3156
+ let names;
3157
+ try {
3158
+ names = await fs.promises.readdir(path.join(host.mirrorDir, type));
3159
+ } catch (error) {
3160
+ if (error.code === "ENOENT") return found;
3161
+ throw error;
3162
+ }
3163
+ for (const name of names) {
3164
+ const id = name.replace(/\.json$/, "");
3165
+ if (name.endsWith(".json") && RESOURCE_ID.test(id)) found.set(id, await fs.promises.readFile(path.join(host.mirrorDir, type, name), "utf8"));
3166
+ }
3167
+ return found;
3168
+ }
3169
+ /** Rewrites a mirror file only when its resource changed, so its time stays what was hashed. */
3170
+ async function mirror(type, id, text, had) {
3171
+ if (had !== text) {
3172
+ const file = mirrorPath(type, id);
3173
+ await fs.promises.mkdir(path.dirname(file), { recursive: true });
3174
+ const tmp = `${file}.part`;
3175
+ await fs.promises.writeFile(tmp, text);
3176
+ await fs.promises.rename(tmp, file);
3177
+ }
3178
+ pendingRemovals.delete(`${type}/${id}`);
3179
+ }
3180
+ /**
3181
+ * The resources of one type, added to and updated from the server's
3182
+ * listing but never shortened by it: the Resources API leaves a failing
3183
+ * provider out of its answer, so a resource missing from it may still be
3184
+ * there. Deletions come from the server's deltas instead (`deleted`).
3185
+ */
3186
+ async function current(type) {
3187
+ const readAt = deletions;
3188
+ const known = await mirrored(type);
3189
+ let listed;
3190
+ try {
3191
+ listed = await host.list(type);
3192
+ } catch (error) {
3193
+ host.debug(`Multihelm: cannot list the ${type}: ${error instanceof Error ? error.message : String(error)}`);
3194
+ return known;
3195
+ }
3196
+ for (const [id, resource] of Object.entries(listed)) {
3197
+ if (!RESOURCE_ID.test(id) || !isRecord(resource)) continue;
3198
+ const key = `${type}/${id}`;
3199
+ if (deletedHere.has(key) || (deletedAt.get(key) ?? 0) > readAt) {
3200
+ known.delete(id);
3201
+ continue;
3202
+ }
3203
+ const text = resourceText(resource);
3204
+ await mirror(type, id, text, known.get(id));
3205
+ known.set(id, text);
3206
+ }
3207
+ return known;
3208
+ }
3209
+ /**
3210
+ * Deleted on this server and not written again since: a listing read
3211
+ * before the deletion must not bring them back.
3212
+ */
3213
+ const deletedHere = /* @__PURE__ */ new Set();
3214
+ /** When each was last deleted, counted in deletions: a listing read before then is stale for it. */
3215
+ const deletedAt = /* @__PURE__ */ new Map();
3216
+ let deletions = 0;
3217
+ const awaitingDeletion = /* @__PURE__ */ new Map();
3218
+ /** Deleted on the server, but their mirror files could not be removed yet. */
3219
+ const pendingRemovals = /* @__PURE__ */ new Set();
3220
+ /** Mirror files are written and removed one after the other, so a deletion cannot race a rewrite. */
3221
+ let mirrorWork = Promise.resolve();
3222
+ function exclusive(work) {
3223
+ const result = mirrorWork.then(work);
3224
+ mirrorWork = result.catch(() => void 0);
3225
+ return result;
3226
+ }
3227
+ async function removeMirror(key) {
3228
+ const { type, id } = splitKey(key);
3229
+ try {
3230
+ await fs.promises.rm(mirrorPath(type, id), { force: true });
3231
+ pendingRemovals.delete(key);
3232
+ } catch (error) {
3233
+ pendingRemovals.add(key);
3234
+ host.error(`Multihelm: cannot remove the copy of ${key}, trying again: ${error instanceof Error ? error.message : String(error)}`);
3235
+ }
3236
+ }
3237
+ /** The Resources API answers before the provider has written: wait until it has. */
3238
+ async function whenStored(type, id, text, wanted) {
3239
+ for (let check = 0; check < STORED_CHECKS && wanted(); check++) {
3240
+ const resource = (await host.list(type))[id];
3241
+ if (isRecord(resource) && resourceText(resource) === text) return;
3242
+ await sleep(STORED_CHECK_MS);
3243
+ }
3244
+ if (!wanted()) return;
3245
+ throw new Error(`the server did not store ${type}/${id}`);
3246
+ }
3247
+ /** Only the server's delta says a deletion was stored; a listing that lacks the resource may just be failing. */
3248
+ function whenDeleted(key) {
3249
+ return new Promise((resolve, reject) => {
3250
+ const timer = setTimeout(() => {
3251
+ awaitingDeletion.delete(key);
3252
+ reject(/* @__PURE__ */ new Error(`the server did not delete ${key}`));
3253
+ }, DELETE_CONFIRM_MS);
3254
+ awaitingDeletion.set(key, () => {
3255
+ clearTimeout(timer);
3256
+ resolve();
3257
+ });
3258
+ });
3259
+ }
3260
+ async function deleted(type, id) {
3261
+ const key = `${type}/${id}`;
3262
+ deletedHere.add(key);
3263
+ deletedAt.set(key, ++deletions);
3264
+ await exclusive(() => removeMirror(key));
3265
+ awaitingDeletion.get(key)?.();
3266
+ awaitingDeletion.delete(key);
3267
+ }
3268
+ const dataset = {
3269
+ id: RESOURCES_DATASET,
3270
+ isValidKey: isResourceKey,
3271
+ list: async () => {
3272
+ const entries = [];
3273
+ for (const key of [...pendingRemovals]) await exclusive(async () => {
3274
+ if (pendingRemovals.has(key)) await removeMirror(key);
3275
+ });
3276
+ for (const type of RESOURCE_TYPES) for (const id of (await exclusive(() => current(type))).keys()) {
3277
+ if (pendingRemovals.has(`${type}/${id}`)) continue;
3278
+ const file = mirrorPath(type, id);
3279
+ const stat = await fs.promises.stat(file);
3280
+ entries.push({
3281
+ key: `${type}/${id}`,
3282
+ meta: null,
3283
+ files: [{
3284
+ name: FILE,
3285
+ path: file,
3286
+ size: stat.size,
3287
+ mtimeMs: stat.mtimeMs
3288
+ }]
3289
+ });
3290
+ }
3291
+ return entries;
3292
+ },
3293
+ apply: async (entry) => {
3294
+ const file = entry.files.find((f) => f.name === FILE);
3295
+ if (!file || entry.files.length !== 1) throw new Error(`a resource has one file, ${entry.key} has ${String(entry.files.length)}`);
3296
+ const { type, id } = splitKey(entry.key);
3297
+ const resource = JSON.parse(await fs.promises.readFile(file.path, "utf8"));
3298
+ if (!isRecord(resource)) throw new Error(`${entry.key} is not a resource`);
3299
+ const text = resourceText(resource);
3300
+ deletedHere.delete(entry.key);
3301
+ const setAt = deletions;
3302
+ const notDeletedSince = () => (deletedAt.get(entry.key) ?? 0) <= setAt;
3303
+ await host.set(type, id, resource);
3304
+ await whenStored(type, id, text, notDeletedSince);
3305
+ await exclusive(async () => {
3306
+ if (notDeletedSince()) await mirror(type, id, text);
3307
+ });
3308
+ },
3309
+ /**
3310
+ * A delete the server refuses is taken as done: it cannot say whether
3311
+ * the resource is already gone or its provider failed, and should it
3312
+ * still be there, the next listing offers it to the peers again. A
3313
+ * failure can bring a deleted route back, but never lose one.
3314
+ */
3315
+ remove: async (key) => {
3316
+ const { type, id } = splitKey(key);
3317
+ const confirmed = whenDeleted(key);
3318
+ try {
3319
+ await host.delete(type, id);
3320
+ } catch (error) {
3321
+ awaitingDeletion.get(key)?.();
3322
+ host.debug(`Multihelm: the server refused to delete ${key}: ${error instanceof Error ? error.message : String(error)}`);
3323
+ await exclusive(() => removeMirror(key));
3324
+ return true;
3325
+ }
3326
+ await confirmed;
3327
+ return true;
3328
+ }
3329
+ };
3330
+ function written(type, id) {
3331
+ deletedHere.delete(`${type}/${id}`);
3332
+ }
3333
+ return {
3334
+ dataset,
3335
+ deleted,
3336
+ written
3337
+ };
3338
+ }
3339
+ // src/own-access.ts
3340
+ /**
3341
+ * This server's admin device token on itself, for writing what follows the
3342
+ * master through the server's own REST API: vessel settings, and which
3343
+ * plugins run. Asked for once; until the user approves it nothing is written.
3344
+ */
3345
+ var OwnServerAccess = class {
3346
+ host;
3347
+ access;
3348
+ /** One request or poll at a time, shared by everyone waiting for the token. */
3349
+ asking = null;
3350
+ constructor(host) {
3351
+ this.host = host;
3352
+ this.access = host.store.loadOwnAccess();
3353
+ }
3354
+ /** Whether the user has to approve this server's own access request. */
3355
+ waitingForApproval() {
3356
+ return this.access.state === "waiting-approval";
3357
+ }
3358
+ /** The identifier of the access request on this server, as Security -> Access Requests lists it. */
3359
+ requestId() {
3360
+ return `signalk-multihelm-self-${this.host.serverId}`;
3361
+ }
3362
+ /** Whether the user denied it; it is asked for again only after a restart. */
3363
+ denied() {
3364
+ return this.access.state === "denied";
3365
+ }
3366
+ /** The server refused the token: it is asked for again. */
3367
+ revoked() {
3368
+ this.save({
3369
+ token: "",
3370
+ state: "none"
3371
+ });
3372
+ }
3373
+ /** The token, empty without security; null while there is none to use. */
3374
+ token() {
3375
+ if (this.access.state === "granted") return Promise.resolve(this.access.token);
3376
+ if (this.access.state === "denied") return Promise.resolve(null);
3377
+ this.asking ??= this.ask().finally(() => {
3378
+ this.asking = null;
3379
+ });
3380
+ return this.asking;
3381
+ }
3382
+ async ask() {
3383
+ const base = this.host.ownUrl();
3384
+ let result;
3385
+ try {
3386
+ result = this.access.state === "waiting-approval" && this.access.requestHref ? await pollAccess({ url: base }, this.access.requestHref) : await requestAccess({ url: base }, this.requestId(), "Multihelm: write the settings that follow the master on this server", "admin");
3387
+ } catch (error) {
3388
+ this.host.debug(`Multihelm: access request on this server: ${error instanceof Error ? error.message : String(error)}`);
3389
+ return null;
3390
+ }
3391
+ switch (result.kind) {
3392
+ case "no-security":
3393
+ this.save({
3394
+ token: "",
3395
+ state: "granted"
3396
+ });
3397
+ return "";
3398
+ case "approved":
3399
+ this.save({
3400
+ token: result.token,
3401
+ state: "granted"
3402
+ });
3403
+ return result.token;
3404
+ case "pending":
3405
+ this.save({
3406
+ token: "",
3407
+ requestHref: result.href,
3408
+ state: "waiting-approval"
3409
+ });
3410
+ return null;
3411
+ case "denied":
3412
+ this.host.store.saveOwnAccess({
3413
+ token: "",
3414
+ state: "none"
3415
+ });
3416
+ this.access = {
3417
+ token: "",
3418
+ state: "denied"
3419
+ };
3420
+ return null;
3421
+ case "error":
3422
+ this.host.debug(`Multihelm: access request on this server: ${result.message}`);
3423
+ return null;
3424
+ }
3425
+ }
3426
+ save(access) {
3427
+ this.access = access;
3428
+ this.host.store.saveOwnAccess(access);
3429
+ }
3430
+ };
1994
3431
  // src/store.ts
1995
3432
  /**
1996
3433
  * Multihelm state on disk, in the plugin's data dir: this server's id, its
@@ -2003,6 +3440,8 @@ var PeerSchema = Type.Object({
2003
3440
  name: Type.String(),
2004
3441
  /** Base URL of the peer's Signal K server, e.g. `http://192.168.1.20:3000`. */
2005
3442
  url: Type.String(),
3443
+ /** PEM of the certificate its HTTPS chain must lead to; see `PeerAddress`. */
3444
+ ca: Type.Optional(Type.String()),
2006
3445
  /** Readonly device token; empty when the peer runs without security. */
2007
3446
  token: Type.String(),
2008
3447
  /** Set while an access request waits for approval on the peer. */
@@ -2030,6 +3469,18 @@ var OwnAccessSchema = Type.Object({
2030
3469
  Type.Literal("denied")
2031
3470
  ])
2032
3471
  });
3472
+ /** A readwrite device token on the master, for sending it commands such as the autopilot's. */
3473
+ var ControlAccessSchema = Type.Object({
3474
+ /** The master's server id: a token for one master is no use for another. */
3475
+ masterId: Type.String(),
3476
+ token: Type.String(),
3477
+ requestHref: Type.Optional(Type.String()),
3478
+ state: Type.Union([
3479
+ Type.Literal("waiting-approval"),
3480
+ Type.Literal("granted"),
3481
+ Type.Literal("denied")
3482
+ ])
3483
+ });
2033
3484
  var PathsFileSchema = Type.Array(Type.String());
2034
3485
  /** A server that asked this one for its `hello`, which a server does while paired with it. */
2035
3486
  var PairedServerSchema = Type.Object({
@@ -2093,6 +3544,18 @@ var MultihelmStore = class {
2093
3544
  saveOwnAccess(access) {
2094
3545
  writeAtomic(path.join(this.dir, "own-access.json"), JSON.stringify(access), 384);
2095
3546
  }
3547
+ loadControlAccess() {
3548
+ const raw = readJson(path.join(this.dir, "control-access.json"));
3549
+ return Value.Check(ControlAccessSchema, raw) ? raw : null;
3550
+ }
3551
+ saveControlAccess(access) {
3552
+ const file = path.join(this.dir, "control-access.json");
3553
+ if (access === null) {
3554
+ fs.rmSync(file, { force: true });
3555
+ return;
3556
+ }
3557
+ writeAtomic(file, JSON.stringify(access), 384);
3558
+ }
2096
3559
  /** The paths whose metadata this server takes over from the master. */
2097
3560
  loadFollowedMeta() {
2098
3561
  const raw = readJson(path.join(this.dir, "followed-meta.json"));
@@ -2132,13 +3595,22 @@ function multihelmVersion() {
2132
3595
  return;
2133
3596
  }
2134
3597
  }
2135
- var APPROVE_HINT = "approve Multihelm's request under Security -> Access Requests on this server to take the vessel settings over";
2136
- var DENIED_HINT = "the access request on this server was denied, so the vessel settings are not taken over; restart the plugin to ask again";
3598
+ var APPROVE_HINT = "approve Multihelm's request under Security -> Access Requests on this server to take the vessel settings over and switch the plugins that run on the master";
3599
+ var DENIED_HINT = "the access request on this server was denied, so the vessel settings are not taken over and no plugin is switched for the master; restart the plugin to ask again";
2137
3600
  function statusText(role, master, conflict) {
2138
3601
  if (conflict) return `${role === "master" ? "Master" : `Member, master: ${master?.name ?? "?"}`}. More than one server is set to be the master: set one only`;
2139
3602
  if (role === "master") return "Master of the boat's servers";
2140
3603
  return master ? `Member, master: ${master.name}` : "Member, no master found";
2141
3604
  }
3605
+ /** Registering is plugin API; withdrawing before the plugin stops is reached on the server's own autopilot API. */
3606
+ function autopilotWithdrawal(app) {
3607
+ const api = app.autopilotApi;
3608
+ const unRegister = api?.unRegister;
3609
+ if (typeof app.registerAutopilotProvider !== "function" || typeof unRegister !== "function") return null;
3610
+ return () => {
3611
+ unRegister.call(api, PLUGIN_ID);
3612
+ };
3613
+ }
2142
3614
  function src_default(app) {
2143
3615
  const host = app;
2144
3616
  let multihelm = null;
@@ -2146,7 +3618,9 @@ function src_default(app) {
2146
3618
  let masterProxy = null;
2147
3619
  let stopRoleStatus = null;
2148
3620
  let stopFollowing = null;
2149
- let masterFollower = null;
3621
+ let ownAccess = null;
3622
+ let masterPluginList = null;
3623
+ let masterControl = null;
2150
3624
  function localVesselSettings() {
2151
3625
  const deltas = host.config?.baseDeltaEditor?.deltas;
2152
3626
  if (deltas === void 0) return null;
@@ -2164,11 +3638,51 @@ function src_default(app) {
2164
3638
  return `http://127.0.0.1:${String(Number(process.env.PORT) || settings?.port || 3e3)}`;
2165
3639
  }
2166
3640
  function ownAccessState() {
2167
- if (masterFollower?.waitingForApproval()) return {
3641
+ if (ownAccess?.waitingForApproval()) return {
2168
3642
  state: "waiting-approval",
2169
- request: masterFollower.accessRequestId()
3643
+ request: ownAccess.requestId()
3644
+ };
3645
+ return ownAccess?.denied() ? { state: "denied" } : null;
3646
+ }
3647
+ /** Deletions are learnt from the server's deltas: only they show that one was stored. */
3648
+ function syncResources(mh) {
3649
+ const sync = resourcesDataset({
3650
+ list: (type) => app.resourcesApi.listResources(type, {}),
3651
+ set: (type, id, resource) => app.resourcesApi.setResource(type, id, resource),
3652
+ delete: (type, id) => app.resourcesApi.deleteResource(type, id),
3653
+ mirrorDir: path.join(app.getDataDirPath(), "resources"),
3654
+ debug: (msg) => {
3655
+ app.debug(msg);
3656
+ },
3657
+ error: (msg) => {
3658
+ app.error(msg);
3659
+ }
3660
+ });
3661
+ const handle = mh.registerDataset(sync.dataset);
3662
+ const unsubscribes = [];
3663
+ app.subscriptionmanager.subscribe({
3664
+ context: "vessels.self",
3665
+ subscribe: [{
3666
+ path: "resources.*",
3667
+ policy: "instant"
3668
+ }]
3669
+ }, unsubscribes, (error) => {
3670
+ app.error(`Multihelm: following resource deletions: ${String(error)}`);
3671
+ }, (delta) => {
3672
+ for (const update of delta.updates) for (const { path: valuePath, value } of "values" in update ? update.values : []) {
3673
+ const resource = resourceOfPath(valuePath);
3674
+ if (resource && value !== null) sync.written(resource.type, resource.id);
3675
+ else if (resource) sync.deleted(resource.type, resource.id).then(() => {
3676
+ handle.changed();
3677
+ }, (error) => {
3678
+ app.error(`Multihelm: cannot follow the deletion of ${resource.type}/${resource.id}: ${error instanceof Error ? error.message : String(error)}`);
3679
+ });
3680
+ }
3681
+ }, void 0, "all");
3682
+ return () => {
3683
+ for (const unsubscribe of unsubscribes) unsubscribe();
3684
+ handle.unregister();
2170
3685
  };
2171
- return masterFollower?.denied() ? { state: "denied" } : null;
2172
3686
  }
2173
3687
  function publish(value) {
2174
3688
  app.emitPropertyValue(PROPERTY_NAME, value);
@@ -2202,6 +3716,7 @@ function src_default(app) {
2202
3716
  discovery = new ServerDiscovery(() => host.config?.getExternalPort?.());
2203
3717
  discovery.start();
2204
3718
  mh.start();
3719
+ const stopResources = settings.syncResources !== false && hasResourcesApi(app) ? syncResources(mh) : null;
2205
3720
  publish({
2206
3721
  apiVersion: 1,
2207
3722
  registerDataset: (definition) => mh.registerDataset(definition),
@@ -2214,10 +3729,44 @@ function src_default(app) {
2214
3729
  masterPath: (target) => `${ROUTE_PREFIX}${MASTER_ROUTE}${target}`,
2215
3730
  fetchMaster: (target) => proxy.fetch(target)
2216
3731
  });
2217
- const follower = new MasterFollower({
3732
+ const access = new OwnServerAccess({
2218
3733
  store,
2219
3734
  serverId: mh.serverId,
2220
3735
  ownUrl,
3736
+ debug: (msg) => {
3737
+ app.debug(msg);
3738
+ }
3739
+ });
3740
+ ownAccess = access;
3741
+ const masterPlugins = new MasterOnlyPlugins({
3742
+ ids: () => pluginList.ids(),
3743
+ wanted: () => !mh.roleKnown() ? null : mh.role() === "master" ? true : mh.master() ? false : null,
3744
+ access,
3745
+ ownUrl,
3746
+ selfId: PLUGIN_ID,
3747
+ debug: (msg) => {
3748
+ app.debug(msg);
3749
+ },
3750
+ error: (msg) => {
3751
+ app.error(msg);
3752
+ }
3753
+ });
3754
+ const pluginList = new MasterPluginList(path.join(app.getDataDirPath(), "master-plugins"), () => {
3755
+ masterPlugins.apply();
3756
+ settingsHandle.changed();
3757
+ });
3758
+ const settingsHandle = mh.registerDataset(pluginList.dataset);
3759
+ masterPluginList = pluginList;
3760
+ const pluginsTimer = setInterval(() => {
3761
+ masterPlugins.apply();
3762
+ }, ROUND_INTERVAL_MS);
3763
+ const stopRolePlugins = mh.onRoleChanged(() => {
3764
+ masterPlugins.apply();
3765
+ });
3766
+ const follower = new MasterFollower({
3767
+ store,
3768
+ access,
3769
+ ownUrl,
2221
3770
  localSettings: localVesselSettings,
2222
3771
  master: () => mh.masterAccess(),
2223
3772
  followVessel: settings.followVessel !== false,
@@ -2230,11 +3779,10 @@ function src_default(app) {
2230
3779
  app.error(msg);
2231
3780
  }
2232
3781
  });
2233
- masterFollower = follower;
2234
3782
  const showRole = () => {
2235
3783
  const text = statusText(mh.role(), mh.master(), mh.masterConflict());
2236
- if (follower.waitingForApproval()) app.setPluginStatus(`${text}; ${APPROVE_HINT}`);
2237
- else if (follower.denied()) app.setPluginStatus(`${text}; ${DENIED_HINT}`);
3784
+ if (access.waitingForApproval()) app.setPluginStatus(`${text}; ${APPROVE_HINT}`);
3785
+ else if (access.denied()) app.setPluginStatus(`${text}; ${DENIED_HINT}`);
2238
3786
  else app.setPluginStatus(text);
2239
3787
  };
2240
3788
  let following = false;
@@ -2269,15 +3817,96 @@ function src_default(app) {
2269
3817
  app.error(`Multihelm: serving the master's history: ${error instanceof Error ? error.message : String(error)}`);
2270
3818
  });
2271
3819
  };
3820
+ const control = new MasterControlAccess({
3821
+ store,
3822
+ serverId: mh.serverId,
3823
+ currentMaster: () => mh.role() === "master" ? null : mh.master()?.id ?? null,
3824
+ debug: (msg) => {
3825
+ app.debug(msg);
3826
+ }
3827
+ });
3828
+ masterControl = control;
3829
+ const withdrawAutopilot = autopilotWithdrawal(app);
3830
+ const autopilot = settings.autopilotFromMaster !== false && withdrawAutopilot ? new MasterAutopilot({
3831
+ control,
3832
+ master: () => {
3833
+ const access = mh.masterAccess();
3834
+ const master = mh.master();
3835
+ return access && master ? {
3836
+ id: master.id,
3837
+ access
3838
+ } : null;
3839
+ },
3840
+ isMaster: () => mh.role() === "master",
3841
+ register: (provider, devices) => {
3842
+ app.registerAutopilotProvider(provider, devices);
3843
+ },
3844
+ unregister: withdrawAutopilot,
3845
+ update: (device, info) => {
3846
+ app.autopilotUpdate(device, info);
3847
+ },
3848
+ debug: (msg) => {
3849
+ app.debug(msg);
3850
+ },
3851
+ error: (msg) => {
3852
+ app.error(msg);
3853
+ }
3854
+ }) : null;
3855
+ autopilot?.start();
3856
+ const course = settings.courseFromMaster !== false ? new MasterCourse({
3857
+ master: () => {
3858
+ const masterAccess = mh.masterAccess();
3859
+ const master = mh.role() === "master" ? null : mh.master();
3860
+ return masterAccess && master ? {
3861
+ id: master.id,
3862
+ access: masterAccess
3863
+ } : null;
3864
+ },
3865
+ control,
3866
+ own: access,
3867
+ ownUrl,
3868
+ debug: (msg) => {
3869
+ app.debug(msg);
3870
+ }
3871
+ }) : null;
3872
+ course?.start();
3873
+ const notifications = managedNotifications(app.notifications);
3874
+ const alarms = settings.alarmsFromMaster !== false && notifications ? new MasterAlarms({
3875
+ master: () => {
3876
+ const masterAccess = mh.masterAccess();
3877
+ const master = mh.role() === "master" ? null : mh.master();
3878
+ return masterAccess && master ? {
3879
+ id: master.id,
3880
+ access: masterAccess
3881
+ } : null;
3882
+ },
3883
+ control,
3884
+ notifications,
3885
+ debug: (msg) => {
3886
+ app.debug(msg);
3887
+ }
3888
+ }) : null;
3889
+ alarms?.start();
3890
+ const stopRoleAutopilot = mh.onRoleChanged(() => {
3891
+ autopilot?.roleChanged();
3892
+ });
2272
3893
  const historyTimer = setInterval(checkHistory, ROUND_INTERVAL_MS);
2273
3894
  const stopRoleHistory = mh.onRoleChanged(checkHistory);
2274
3895
  checkHistory();
2275
3896
  stopFollowing = () => {
3897
+ clearInterval(pluginsTimer);
3898
+ stopRolePlugins();
3899
+ settingsHandle.unregister();
3900
+ stopRoleAutopilot();
3901
+ autopilot?.stop();
3902
+ course?.stop();
3903
+ alarms?.stop();
2276
3904
  clearInterval(followTimer);
2277
3905
  stopRoleFollow();
2278
3906
  clearInterval(historyTimer);
2279
3907
  stopRoleHistory();
2280
3908
  history?.stop();
3909
+ stopResources?.();
2281
3910
  };
2282
3911
  stopRoleStatus = mh.onStatusChanged(showRole);
2283
3912
  showRole();
@@ -2285,7 +3914,9 @@ function src_default(app) {
2285
3914
  stop() {
2286
3915
  stopFollowing?.();
2287
3916
  stopFollowing = null;
2288
- masterFollower = null;
3917
+ ownAccess = null;
3918
+ masterPluginList = null;
3919
+ masterControl = null;
2289
3920
  stopRoleStatus?.();
2290
3921
  stopRoleStatus = null;
2291
3922
  if (multihelm) publish({ apiVersion: 1 });
@@ -2297,7 +3928,7 @@ function src_default(app) {
2297
3928
  discovery = null;
2298
3929
  },
2299
3930
  registerWithRouter(router) {
2300
- registerRoutes(router, () => multihelm, () => discovery?.list() ?? [], localVesselSettings, () => masterProxy, ownAccessState);
3931
+ registerRoutes(router, () => multihelm, () => discovery?.list() ?? [], localVesselSettings, () => masterProxy, ownAccessState, () => masterPluginList, () => masterControl?.waitingForApproval(multihelm?.role() === "master") ?? null);
2301
3932
  }
2302
3933
  };
2303
3934
  }