signalk-multihelm 0.0.0 → 0.1.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.
@@ -0,0 +1,1556 @@
1
+ import os from "node:os";
2
+ import { Type } from "typebox";
3
+ import makeMdns from "multicast-dns";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import fs from "node:fs";
6
+ import http from "node:http";
7
+ import https from "node:https";
8
+ import { pipeline } from "node:stream/promises";
9
+ import crypto from "node:crypto";
10
+ import path from "node:path";
11
+ import { Value } from "typebox/value";
12
+ // src/api.ts
13
+ var PROPERTY_NAME = "multihelm";
14
+ // src/discovery.ts
15
+ /**
16
+ * Finds the other Signal K servers on the network, to offer them for pairing.
17
+ *
18
+ * Every Signal K server announces its REST API as `_signalk-http._tcp` (or
19
+ * `_signalk-https._tcp`) over mDNS. The server's own discovery turns these
20
+ * into data-connection suggestions only, so Multihelm asks for them itself
21
+ * while it runs. Found servers are only shown; the user pairs with one.
22
+ */
23
+ var SERVICES = ["_signalk-http._tcp.local", "_signalk-https._tcp.local"];
24
+ var QUERY_INTERVAL_MS = 3e4;
25
+ /** A server not heard of for this long is dropped from the list. */
26
+ var FORGET_AFTER_MS = 18e4;
27
+ function txtRecord(answer) {
28
+ const result = {};
29
+ const data = Array.isArray(answer.data) ? answer.data : [answer.data];
30
+ for (const entry of data) {
31
+ const text = typeof entry === "string" ? entry : Buffer.from(entry).toString("utf-8");
32
+ const eq = text.indexOf("=");
33
+ if (eq > 0) result[text.slice(0, eq)] = text.slice(eq + 1);
34
+ }
35
+ return result;
36
+ }
37
+ function ownAddresses() {
38
+ const result = /* @__PURE__ */ new Set();
39
+ for (const list of Object.values(os.networkInterfaces())) for (const info of list ?? []) result.add(info.address);
40
+ return result;
41
+ }
42
+ var ServerDiscovery = class {
43
+ ownPort;
44
+ mdns = null;
45
+ timer = null;
46
+ instances = /* @__PURE__ */ new Map();
47
+ addresses = /* @__PURE__ */ new Map();
48
+ found = /* @__PURE__ */ new Map();
49
+ constructor(ownPort) {
50
+ this.ownPort = ownPort;
51
+ }
52
+ start() {
53
+ if (this.mdns) return;
54
+ try {
55
+ this.mdns = makeMdns();
56
+ } catch {
57
+ this.mdns = null;
58
+ return;
59
+ }
60
+ this.mdns.on("response", (response) => {
61
+ this.takeRecords([...response.answers, ...response.additionals]);
62
+ });
63
+ this.mdns.on("error", () => {});
64
+ const query = () => {
65
+ this.mdns?.query(SERVICES.map((name) => ({
66
+ name,
67
+ type: "PTR"
68
+ })));
69
+ };
70
+ query();
71
+ this.timer = setInterval(query, QUERY_INTERVAL_MS);
72
+ }
73
+ stop() {
74
+ if (this.timer) {
75
+ clearInterval(this.timer);
76
+ this.timer = null;
77
+ }
78
+ this.mdns?.destroy();
79
+ this.mdns = null;
80
+ }
81
+ list() {
82
+ const now = Date.now();
83
+ for (const [key, server] of this.found) if (now - server.lastSeen > FORGET_AFTER_MS) this.found.delete(key);
84
+ return [...this.found.values()].sort((a, b) => a.name.localeCompare(b.name));
85
+ }
86
+ /** Fold in the records of one mDNS response. */
87
+ takeRecords(records) {
88
+ for (const record of records) if (record.type === "PTR" && SERVICES.includes(record.name)) {
89
+ const instance = record.data;
90
+ if (!this.instances.has(instance)) this.instances.set(instance, {
91
+ service: record.name,
92
+ txt: {}
93
+ });
94
+ }
95
+ for (const record of records) if (record.type === "SRV") {
96
+ const instance = this.instances.get(record.name);
97
+ if (instance) {
98
+ const srv = record.data;
99
+ instance.target = srv.target;
100
+ instance.port = srv.port;
101
+ }
102
+ } else if (record.type === "TXT") {
103
+ const instance = this.instances.get(record.name);
104
+ if (instance) instance.txt = txtRecord(record);
105
+ } else if (record.type === "A") this.addresses.set(record.name, record.data);
106
+ const own = ownAddresses();
107
+ for (const [instance, info] of this.instances) {
108
+ if (!info.target || info.port === void 0) continue;
109
+ const address = this.addresses.get(info.target);
110
+ if (!address) continue;
111
+ if (own.has(address) && info.port === this.ownPort()) continue;
112
+ const url = `${info.service.startsWith("_signalk-https") ? "https" : "http"}://${address}:${String(info.port)}`;
113
+ const server = {
114
+ name: instance.replace(`.${info.service}`, ""),
115
+ url,
116
+ lastSeen: Date.now()
117
+ };
118
+ if (info.txt.vname) server.vessel = info.txt.vname;
119
+ this.found.set(url, server);
120
+ }
121
+ }
122
+ };
123
+ // src/peer-client.ts
124
+ /**
125
+ * HTTP client for a Multihelm peer: its routes, and the Signal K
126
+ * device access request that pairs with it.
127
+ *
128
+ * Peers are other Signal K servers on the boat's network, addressed by the
129
+ * URL the user confirmed. HTTPS peers are verified as usual, so a server
130
+ * with a self-signed certificate is reached over its HTTP port instead.
131
+ */
132
+ var ROUTE_PREFIX = "/plugins/signalk-multihelm";
133
+ var REQUEST_TIMEOUT_MS = 3e4;
134
+ var PeerHttpError = class extends Error {
135
+ status;
136
+ constructor(status, message) {
137
+ super(message);
138
+ this.status = status;
139
+ }
140
+ };
141
+ function send(method, url, options = {}) {
142
+ const headers = { ...options.headers };
143
+ if (options.token) headers.Authorization = `Bearer ${options.token}`;
144
+ let payload;
145
+ if (options.body !== void 0) {
146
+ payload = JSON.stringify(options.body);
147
+ headers["Content-Type"] = "application/json";
148
+ }
149
+ const target = new URL(url);
150
+ const request = target.protocol === "https:" ? https.request : http.request;
151
+ return new Promise((resolve, reject) => {
152
+ const rejectUnauthorized = target.hostname !== "127.0.0.1";
153
+ const req = request(target, {
154
+ method,
155
+ headers,
156
+ timeout: REQUEST_TIMEOUT_MS,
157
+ rejectUnauthorized
158
+ }, (res) => {
159
+ resolve({
160
+ status: res.statusCode ?? 0,
161
+ stream: res
162
+ });
163
+ });
164
+ req.on("timeout", () => req.destroy(/* @__PURE__ */ new Error(`timeout after ${String(REQUEST_TIMEOUT_MS)} ms`)));
165
+ req.on("error", reject);
166
+ if (payload !== void 0) req.write(payload);
167
+ req.end();
168
+ });
169
+ }
170
+ async function readBody(res) {
171
+ const chunks = [];
172
+ for await (const chunk of res.stream) chunks.push(chunk);
173
+ return Buffer.concat(chunks).toString("utf-8");
174
+ }
175
+ async function getJson(url, token) {
176
+ const res = await send("GET", url, { token });
177
+ const text = await readBody(res);
178
+ if (res.status < 200 || res.status >= 300) throw new PeerHttpError(res.status, `HTTP ${String(res.status)} from ${url}`);
179
+ return JSON.parse(text);
180
+ }
181
+ /** `host:port` or a URL, reduced to `http(s)://host:port`; null when it is neither. */
182
+ function normalizePeerUrl(input) {
183
+ let url;
184
+ try {
185
+ url = new URL(input.includes("://") ? input : `http://${input}`);
186
+ } catch {
187
+ return null;
188
+ }
189
+ if (url.protocol !== "http:" && url.protocol !== "https:" || url.username || url.password) return null;
190
+ return `${url.protocol}//${url.host}`;
191
+ }
192
+ async function fetchHello(base, token) {
193
+ const body = await getJson(`${base}${ROUTE_PREFIX}/hello`, token);
194
+ if (typeof body.serverId !== "string" || typeof body.protocol !== "number") throw new Error(`${base} did not answer as a Multihelm peer`);
195
+ return {
196
+ serverId: body.serverId,
197
+ name: typeof body.name === "string" ? body.name : base,
198
+ protocol: body.protocol,
199
+ datasets: Array.isArray(body.datasets) ? body.datasets.filter((d) => typeof d === "string") : [],
200
+ master: body.master === true
201
+ };
202
+ }
203
+ async function fetchVesselSettings(base, token) {
204
+ return getJson(`${base}${ROUTE_PREFIX}/vessel-settings`, token);
205
+ }
206
+ /** A request to a Signal K server's own REST API; throws on any status but 2xx. */
207
+ async function callServer(method, url, token, body) {
208
+ const res = await send(method, url, {
209
+ token,
210
+ body
211
+ });
212
+ const text = await readBody(res);
213
+ if (res.status < 200 || res.status >= 300) throw new PeerHttpError(res.status, `HTTP ${String(res.status)} from ${method} ${url}`);
214
+ try {
215
+ return JSON.parse(text);
216
+ } catch {
217
+ return text;
218
+ }
219
+ }
220
+ /** A page of a peer's dataset changes; its entries are checked by the caller. */
221
+ async function fetchManifest(base, token, dataset, since) {
222
+ const body = await getJson(`${base}${ROUTE_PREFIX}/manifest?dataset=${encodeURIComponent(dataset)}&since=${String(since)}`, token);
223
+ if (typeof body.cursor !== "number" || !Array.isArray(body.entries)) throw new Error(`${base} sent a malformed manifest`);
224
+ return {
225
+ cursor: body.cursor,
226
+ entries: body.entries
227
+ };
228
+ }
229
+ /** Download one file of a peer's entry into `dest`, resuming from what `dest` holds. */
230
+ function downloadFile(base, token, file, dest) {
231
+ return download(base, token, `file?dataset=${encodeURIComponent(file.dataset)}&key=${encodeURIComponent(file.key)}&file=${encodeURIComponent(file.name)}`, `${file.key}/${file.name}`, dest);
232
+ }
233
+ async function download(base, token, query, label, dest) {
234
+ let offset = 0;
235
+ try {
236
+ offset = fs.statSync(dest).size;
237
+ } catch {}
238
+ const res = await send("GET", `${base}${ROUTE_PREFIX}/${query}`, {
239
+ token,
240
+ headers: offset > 0 ? { Range: `bytes=${String(offset)}-` } : {}
241
+ });
242
+ if (res.status === 206) {
243
+ await pipeline(res.stream, fs.createWriteStream(dest, { flags: "a" }));
244
+ return;
245
+ }
246
+ if (res.status === 200) {
247
+ await pipeline(res.stream, fs.createWriteStream(dest));
248
+ return;
249
+ }
250
+ res.stream.resume();
251
+ throw new PeerHttpError(res.status, `HTTP ${String(res.status)} for ${label}`);
252
+ }
253
+ /** Ask the peer for a device token, readonly unless said otherwise. */
254
+ async function requestAccess(base, clientId, description, permissions = "readonly") {
255
+ const res = await send("POST", `${base}/signalk/v1/access/requests`, { body: {
256
+ clientId,
257
+ description,
258
+ permissions
259
+ } });
260
+ const text = await readBody(res);
261
+ if (res.status === 404) return { kind: "no-security" };
262
+ if (res.status === 403) return {
263
+ kind: "error",
264
+ message: "the peer does not accept device access requests"
265
+ };
266
+ if (res.status !== 200 && res.status !== 202) return {
267
+ kind: "error",
268
+ message: `HTTP ${String(res.status)} from the access request`
269
+ };
270
+ return interpretReply(JSON.parse(text));
271
+ }
272
+ /** Follow up an access request that is waiting for approval. */
273
+ async function pollAccess(base, href) {
274
+ const url = href.startsWith("/") ? `${base}${href}` : href;
275
+ if (!url.startsWith(`${base}/`)) return {
276
+ kind: "error",
277
+ message: "the access request points to another server"
278
+ };
279
+ try {
280
+ return interpretReply(await getJson(url));
281
+ } catch (error) {
282
+ if (error instanceof PeerHttpError && error.status === 404) return { kind: "denied" };
283
+ throw error;
284
+ }
285
+ }
286
+ function interpretReply(raw) {
287
+ const reply = raw;
288
+ if (reply.state === "PENDING" && typeof reply.href === "string") return {
289
+ kind: "pending",
290
+ href: reply.href
291
+ };
292
+ if (reply.state === "COMPLETED") {
293
+ const token = reply.accessRequest?.token;
294
+ return token ? {
295
+ kind: "approved",
296
+ token
297
+ } : { kind: "denied" };
298
+ }
299
+ return {
300
+ kind: "error",
301
+ message: "unexpected access request reply"
302
+ };
303
+ }
304
+ // src/vessel-settings.ts
305
+ var VESSEL_FIELDS = [
306
+ "name",
307
+ "mmsi",
308
+ "uuid",
309
+ "draft",
310
+ "length",
311
+ "beam",
312
+ "height",
313
+ "aisShipType",
314
+ "callsignVhf"
315
+ ];
316
+ var SELF = "vessels.self";
317
+ /** A path whose metadata can be read and written: dot-separated segments, none empty. */
318
+ function isMetaPath(path) {
319
+ return /^[A-Za-z0-9_:-]+(\.[A-Za-z0-9_:-]+)*$/.test(path);
320
+ }
321
+ function isRecord(value) {
322
+ return typeof value === "object" && value !== null && !Array.isArray(value);
323
+ }
324
+ function pathValues(list) {
325
+ if (!Array.isArray(list)) return [];
326
+ return list.flatMap((pv) => isRecord(pv) && typeof pv.path === "string" ? [{
327
+ path: pv.path,
328
+ value: pv.value
329
+ }] : []);
330
+ }
331
+ function text(value) {
332
+ return typeof value === "string" && value !== "" ? value : void 0;
333
+ }
334
+ function num(value) {
335
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
336
+ }
337
+ function field(value, key) {
338
+ return isRecord(value) ? value[key] : void 0;
339
+ }
340
+ function vesselData(values) {
341
+ const length = values.get("design.length");
342
+ const data = {
343
+ name: text(values.get("name")),
344
+ mmsi: text(values.get("mmsi")),
345
+ uuid: text(values.get("uuid")),
346
+ draft: num(field(values.get("design.draft"), "maximum")),
347
+ length: num(length) ?? num(field(length, "overall")),
348
+ beam: num(values.get("design.beam")),
349
+ height: num(values.get("design.airHeight")),
350
+ aisShipType: num(field(values.get("design.aisShipType"), "id")),
351
+ callsignVhf: text(field(values.get("communication"), "callsignVhf"))
352
+ };
353
+ return Object.fromEntries(Object.entries(data).filter(([, v]) => v !== void 0));
354
+ }
355
+ function vesselSettingsFromDeltas(deltas) {
356
+ const values = /* @__PURE__ */ new Map();
357
+ const meta = {};
358
+ if (Array.isArray(deltas)) for (const delta of deltas) {
359
+ if (!isRecord(delta) || delta.context !== SELF || !Array.isArray(delta.updates)) continue;
360
+ for (const update of delta.updates) {
361
+ if (!isRecord(update)) continue;
362
+ for (const { path, value } of pathValues(update.values)) if (path === "" && isRecord(value)) for (const [k, v] of Object.entries(value)) values.set(k, v);
363
+ else if (path !== "") values.set(path, value);
364
+ for (const { path, value } of pathValues(update.meta)) if (isMetaPath(path)) meta[path] = value;
365
+ }
366
+ }
367
+ return {
368
+ vessel: vesselData(values),
369
+ meta
370
+ };
371
+ }
372
+ /** A peer's answer, kept to the shape above; anything else is dropped. */
373
+ function parseVesselSettings(raw) {
374
+ if (!isRecord(raw) || !isRecord(raw.vessel) || !isRecord(raw.meta)) return null;
375
+ const v = raw.vessel;
376
+ const vessel = {};
377
+ for (const key of [
378
+ "name",
379
+ "mmsi",
380
+ "uuid",
381
+ "callsignVhf"
382
+ ]) {
383
+ const t = text(v[key]);
384
+ if (t !== void 0) vessel[key] = t;
385
+ }
386
+ for (const key of [
387
+ "draft",
388
+ "length",
389
+ "beam",
390
+ "height",
391
+ "aisShipType"
392
+ ]) {
393
+ const n = num(v[key]);
394
+ if (n !== void 0) vessel[key] = n;
395
+ }
396
+ const meta = {};
397
+ for (const [path, value] of Object.entries(raw.meta)) if (isMetaPath(path) && isRecord(value)) meta[path] = value;
398
+ return {
399
+ vessel,
400
+ meta
401
+ };
402
+ }
403
+ // src/follow-master.ts
404
+ /**
405
+ * On a server that is not the master: takes the vessel data and path
406
+ * metadata over from the master. They are read from the master with the
407
+ * pairing token and written here through this server's own REST API, the
408
+ * way its settings pages write them, so they survive a restart. Writing
409
+ * needs an admin device token on this server, asked for once; until it is
410
+ * approved nothing is written.
411
+ */
412
+ function errorText$2(error) {
413
+ return error instanceof Error ? error.message : String(error);
414
+ }
415
+ function metaUrl(base, path) {
416
+ return `${base}/signalk/v1/api/vessels/self/${path.split(".").map((s) => encodeURIComponent(s)).join("/")}/meta`;
417
+ }
418
+ var MasterFollower = class {
419
+ host;
420
+ access;
421
+ constructor(host) {
422
+ this.host = host;
423
+ this.access = host.store.loadOwnAccess();
424
+ }
425
+ /** Whether the user has to approve this server's own access request. */
426
+ waitingForApproval() {
427
+ return this.access.state === "waiting-approval";
428
+ }
429
+ /** Whether the user denied it; it is asked for again only after a restart. */
430
+ denied() {
431
+ return this.access.state === "denied";
432
+ }
433
+ async run() {
434
+ const { followVessel, followMeta } = this.host;
435
+ const master = this.host.master();
436
+ const local = this.host.localSettings();
437
+ if (!followVessel && !followMeta || !master || !local) return;
438
+ let remote;
439
+ try {
440
+ remote = parseVesselSettings(await fetchVesselSettings(master.url, master.token));
441
+ } catch (error) {
442
+ this.host.debug(`Multihelm: vessel settings from the master: ${errorText$2(error)}`);
443
+ return;
444
+ }
445
+ if (!remote) return;
446
+ const vesselChanged = followVessel && VESSEL_FIELDS.some((k) => remote.vessel[k] !== local.vessel[k]);
447
+ const metaChanged = followMeta ? [.../* @__PURE__ */ new Set([...Object.keys(remote.meta), ...Object.keys(local.meta)])].filter((p) => !isDeepStrictEqual(remote.meta[p], local.meta[p])) : [];
448
+ if (!vesselChanged && metaChanged.length === 0) return;
449
+ const token = await this.ownToken();
450
+ if (token === null) return;
451
+ const base = this.host.ownUrl();
452
+ try {
453
+ if (vesselChanged) await this.writeVessel(base, token, remote.vessel);
454
+ for (const path of metaChanged) {
455
+ const value = remote.meta[path];
456
+ await (value === void 0 ? callServer("DELETE", metaUrl(base, path), token) : callServer("PUT", metaUrl(base, path), token, { value }));
457
+ }
458
+ } catch (error) {
459
+ if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) this.setAccess({
460
+ token: "",
461
+ state: "none"
462
+ });
463
+ this.host.error(`Multihelm: taking over the master's vessel settings: ${errorText$2(error)}`);
464
+ }
465
+ }
466
+ /** The vessel route writes every field, so the ones that stay here are sent back as they are. */
467
+ async writeVessel(base, token, vessel) {
468
+ const current = await callServer("GET", `${base}/skServer/vessel`, token);
469
+ const body = typeof current === "object" && current !== null ? { ...current } : {};
470
+ for (const key of VESSEL_FIELDS) body[key] = vessel[key];
471
+ await callServer("PUT", `${base}/skServer/vessel`, token, body);
472
+ }
473
+ setAccess(access) {
474
+ this.access = access;
475
+ this.host.store.saveOwnAccess(access);
476
+ }
477
+ async ownToken() {
478
+ const base = this.host.ownUrl();
479
+ if (this.access.state === "granted") return this.access.token;
480
+ if (this.access.state === "denied") return null;
481
+ let result;
482
+ try {
483
+ result = this.access.state === "waiting-approval" && this.access.requestHref ? await pollAccess(base, this.access.requestHref) : await requestAccess(base, `signalk-multihelm-self-${this.host.serverId}`, "Multihelm: take the vessel settings over from the master", "admin");
484
+ } catch (error) {
485
+ this.host.debug(`Multihelm: access request on this server: ${errorText$2(error)}`);
486
+ return null;
487
+ }
488
+ switch (result.kind) {
489
+ case "no-security":
490
+ this.setAccess({
491
+ token: "",
492
+ state: "granted"
493
+ });
494
+ return "";
495
+ case "approved":
496
+ this.setAccess({
497
+ token: result.token,
498
+ state: "granted"
499
+ });
500
+ return result.token;
501
+ case "pending":
502
+ this.setAccess({
503
+ token: "",
504
+ requestHref: result.href,
505
+ state: "waiting-approval"
506
+ });
507
+ return null;
508
+ case "denied":
509
+ this.host.store.saveOwnAccess({
510
+ token: "",
511
+ state: "none"
512
+ });
513
+ this.access = {
514
+ token: "",
515
+ state: "denied"
516
+ };
517
+ return null;
518
+ case "error":
519
+ this.host.debug(`Multihelm: access request on this server: ${result.message}`);
520
+ return null;
521
+ }
522
+ }
523
+ };
524
+ var FILE_NAME = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,127}$/;
525
+ var SHA256 = /^[0-9a-f]{64}$/;
526
+ /** Positive when `a` wins over `b`, negative when `b` wins, 0 when equal. */
527
+ function compareVersions(a, b) {
528
+ if (a.counter !== b.counter) return a.counter - b.counter;
529
+ if (a.origin === b.origin) return 0;
530
+ return a.origin > b.origin ? 1 : -1;
531
+ }
532
+ function emptyLibrary() {
533
+ return {
534
+ seq: 0,
535
+ entries: {}
536
+ };
537
+ }
538
+ function fingerprint(meta, files) {
539
+ const canonical = JSON.stringify({
540
+ meta: meta ?? null,
541
+ files: [...files].sort((a, b) => a.name.localeCompare(b.name)).map((f) => [
542
+ f.name,
543
+ f.size,
544
+ f.mtimeMs
545
+ ])
546
+ });
547
+ return crypto.createHash("sha256").update(canonical).digest("hex");
548
+ }
549
+ function isValidFileName(name) {
550
+ return FILE_NAME.test(name) && !name.includes("..");
551
+ }
552
+ /** The shape checks every entry a peer sends must pass before anything else looks at it. */
553
+ function isWellFormedRemote(raw) {
554
+ if (typeof raw !== "object" || raw === null) return false;
555
+ const entry = raw;
556
+ if (typeof entry.key !== "string" || entry.key.length === 0 || entry.key.length > 512 || entry.key.includes("\0") || typeof entry.version?.counter !== "number" || !Number.isInteger(entry.version.counter) || entry.version.counter < 1 || typeof entry.version.origin !== "string" || !Array.isArray(entry.files)) return false;
557
+ if (entry.deletedAt !== void 0 && typeof entry.deletedAt !== "number") return false;
558
+ const names = /* @__PURE__ */ new Set();
559
+ for (const file of entry.files) {
560
+ const f = file;
561
+ if (typeof f.name !== "string" || !isValidFileName(f.name) || names.has(f.name) || typeof f.size !== "number" || !Number.isInteger(f.size) || f.size < 0 || typeof f.sha256 !== "string" || !SHA256.test(f.sha256)) return false;
562
+ names.add(f.name);
563
+ }
564
+ return true;
565
+ }
566
+ /**
567
+ * Bring the library up to date with what the dataset lists: new or changed
568
+ * entries get a new local version (once their files have settled), entries
569
+ * gone become tombstones, tombstones past retention are dropped.
570
+ */
571
+ function applyListing(library, listed, serverId, now) {
572
+ const changed = [];
573
+ const seen = /* @__PURE__ */ new Set();
574
+ for (const item of listed) {
575
+ seen.add(item.key);
576
+ const prev = library.entries[item.key];
577
+ const files = item.files.map((f) => ({
578
+ name: f.name,
579
+ size: f.size,
580
+ mtimeMs: f.mtimeMs
581
+ }));
582
+ const print = fingerprint(item.meta, files);
583
+ if (prev && prev.deletedAt === void 0 && prev.fingerprint === print) {
584
+ if (prev.declined) delete prev.declined;
585
+ continue;
586
+ }
587
+ if (files.filter((f) => !prev?.files.some((o) => o.name === f.name && o.size === f.size && o.mtimeMs === f.mtimeMs)).some((f) => now - f.mtimeMs < 3e4)) continue;
588
+ for (const file of files) {
589
+ const old = prev?.files.find((f) => f.name === file.name && f.size === file.size && f.mtimeMs === file.mtimeMs);
590
+ if (old?.sha256 !== void 0) file.sha256 = old.sha256;
591
+ }
592
+ library.seq++;
593
+ library.entries[item.key] = {
594
+ key: item.key,
595
+ meta: item.meta,
596
+ files,
597
+ fingerprint: print,
598
+ version: {
599
+ counter: (prev?.version.counter ?? 0) + 1,
600
+ origin: serverId
601
+ },
602
+ seq: library.seq
603
+ };
604
+ changed.push(item.key);
605
+ }
606
+ for (const entry of Object.values(library.entries)) {
607
+ if (seen.has(entry.key) || entry.declined) continue;
608
+ if (entry.deletedAt === void 0) {
609
+ library.seq++;
610
+ library.entries[entry.key] = {
611
+ key: entry.key,
612
+ meta: null,
613
+ files: [],
614
+ fingerprint: "",
615
+ version: {
616
+ counter: entry.version.counter + 1,
617
+ origin: serverId
618
+ },
619
+ deletedAt: now,
620
+ seq: library.seq
621
+ };
622
+ } else if (now - entry.deletedAt > 2592e6) Reflect.deleteProperty(library.entries, entry.key);
623
+ }
624
+ return { changed };
625
+ }
626
+ function isOfferable(entry) {
627
+ return entry.deletedAt !== void 0 || entry.files.every((f) => f.sha256 !== void 0);
628
+ }
629
+ function toRemote(entry) {
630
+ const remote = {
631
+ key: entry.key,
632
+ meta: entry.meta,
633
+ files: entry.files.map((f) => ({
634
+ name: f.name,
635
+ size: f.size,
636
+ sha256: f.sha256 ?? ""
637
+ })),
638
+ version: entry.version
639
+ };
640
+ if (entry.deletedAt !== void 0) remote.deletedAt = entry.deletedAt;
641
+ return remote;
642
+ }
643
+ /** Entries changed after `since`. One not hashed yet stops the page, so the cursor never skips it. */
644
+ function manifestSince(library, since) {
645
+ let cursor = since;
646
+ const entries = [];
647
+ for (const entry of Object.values(library.entries).sort((a, b) => a.seq - b.seq)) {
648
+ if (entry.seq <= since || entry.declined) {
649
+ if (entry.seq > cursor) cursor = entry.seq;
650
+ continue;
651
+ }
652
+ if (!isOfferable(entry)) break;
653
+ cursor = entry.seq;
654
+ entries.push(toRemote(entry));
655
+ }
656
+ return {
657
+ cursor,
658
+ entries
659
+ };
660
+ }
661
+ /** Take over a peer's version, with what this server holds for it now (null: nothing). */
662
+ function recordRemote(library, remote, local) {
663
+ library.seq++;
664
+ const files = local ? local.files.map((f) => {
665
+ const file = {
666
+ name: f.name,
667
+ size: f.size,
668
+ mtimeMs: f.mtimeMs
669
+ };
670
+ const sha256 = remote.files.find((r) => r.name === f.name && r.size === f.size)?.sha256;
671
+ if (sha256 !== void 0) file.sha256 = sha256;
672
+ return file;
673
+ }) : [];
674
+ const entry = {
675
+ key: remote.key,
676
+ meta: local ? local.meta : remote.meta,
677
+ files,
678
+ fingerprint: local ? fingerprint(local.meta, files) : "",
679
+ version: remote.version,
680
+ seq: library.seq
681
+ };
682
+ if (remote.deletedAt !== void 0) entry.deletedAt = remote.deletedAt;
683
+ else if (!local) entry.declined = true;
684
+ library.entries[remote.key] = entry;
685
+ }
686
+ var ROUND_INTERVAL_MS = 6e4;
687
+ /**
688
+ * Paired peers are asked whether they are set to be the master this often,
689
+ * on a timer of its own, so a long round of transfers does not hold it up.
690
+ */
691
+ var MASTER_CHECK_INTERVAL_MS = 3e4;
692
+ 5 * MASTER_CHECK_INTERVAL_MS;
693
+ async function hashFile(file) {
694
+ const hash = crypto.createHash("sha256");
695
+ await pipeline(fs.createReadStream(file), hash);
696
+ return hash.digest("hex");
697
+ }
698
+ function errorText$1(error) {
699
+ return error instanceof Error ? error.message : String(error);
700
+ }
701
+ function toListed(entry) {
702
+ return {
703
+ key: entry.key,
704
+ meta: entry.meta,
705
+ files: entry.files.map((f) => ({
706
+ name: f.name,
707
+ size: f.size,
708
+ mtimeMs: f.mtimeMs
709
+ }))
710
+ };
711
+ }
712
+ var Multihelm = class {
713
+ store;
714
+ host;
715
+ peers;
716
+ datasets = /* @__PURE__ */ new Map();
717
+ queue = Promise.resolve();
718
+ timer = null;
719
+ soon = null;
720
+ /** Rounds run on their own between start and stop. */
721
+ started = false;
722
+ /** Set by stop: work under way ends at the next step. */
723
+ stopped = false;
724
+ /** Peer URL → when it last answered as set to be the master. */
725
+ masterSeen = /* @__PURE__ */ new Map();
726
+ roleListeners = /* @__PURE__ */ new Set();
727
+ statusListeners = /* @__PURE__ */ new Set();
728
+ /** What the role listeners were last told: role and master id. */
729
+ announcedRole = "";
730
+ /** What the status listeners were last told: role, master id and conflict. */
731
+ announcedStatus = "";
732
+ masterTimer = null;
733
+ checkingMasters = false;
734
+ serverId;
735
+ constructor(store, host) {
736
+ this.store = store;
737
+ this.host = host;
738
+ this.peers = store.loadPeers();
739
+ this.serverId = store.serverId();
740
+ }
741
+ start() {
742
+ this.started = true;
743
+ this.stopped = false;
744
+ const tick = () => {
745
+ this.runRound().finally(() => {
746
+ if (!this.stopped) this.timer = setTimeout(tick, ROUND_INTERVAL_MS);
747
+ });
748
+ };
749
+ this.timer = setTimeout(tick, 0);
750
+ this.masterTimer = setInterval(() => {
751
+ this.checkMasters();
752
+ }, MASTER_CHECK_INTERVAL_MS);
753
+ }
754
+ stop() {
755
+ this.started = false;
756
+ this.stopped = true;
757
+ for (const timer of [this.timer, this.soon]) if (timer) clearTimeout(timer);
758
+ this.timer = null;
759
+ this.soon = null;
760
+ if (this.masterTimer) {
761
+ clearInterval(this.masterTimer);
762
+ this.masterTimer = null;
763
+ }
764
+ }
765
+ /**
766
+ * Asks every paired peer whether it is set to be the master. Runs outside
767
+ * the work queue and touches nothing but `masterSeen`, so it neither waits
768
+ * for a round nor races one.
769
+ */
770
+ async checkMasters() {
771
+ if (this.checkingMasters || this.stopped) return;
772
+ this.checkingMasters = true;
773
+ try {
774
+ await Promise.all(this.peers.filter((p) => p.state === "paired" && p.id !== "").map(async (peer) => {
775
+ let hello;
776
+ try {
777
+ hello = await fetchHello(peer.url, peer.token);
778
+ } catch {
779
+ return;
780
+ }
781
+ if (this.stopped || !this.peers.includes(peer) || hello.serverId !== peer.id) return;
782
+ if (hello.master) this.masterSeen.set(peer.url, Date.now());
783
+ else this.masterSeen.delete(peer.url);
784
+ }));
785
+ } finally {
786
+ this.checkingMasters = false;
787
+ }
788
+ if (!this.stopped) this.announceRole();
789
+ }
790
+ /** Run `task` after every task queued before it. */
791
+ serialize(task) {
792
+ const run = this.queue.then(task, task);
793
+ this.queue = run.catch(() => void 0);
794
+ return run;
795
+ }
796
+ registerDataset(definition) {
797
+ if (this.datasets.has(definition.id)) throw new Error(`dataset ${definition.id} is already registered`);
798
+ this.datasets.set(definition.id, {
799
+ definition,
800
+ library: this.store.loadLibrary(definition.id),
801
+ listed: /* @__PURE__ */ new Map()
802
+ });
803
+ this.changedSoon();
804
+ return {
805
+ changed: () => {
806
+ this.changedSoon();
807
+ },
808
+ unregister: () => {
809
+ if (this.datasets.get(definition.id)?.definition === definition) this.datasets.delete(definition.id);
810
+ }
811
+ };
812
+ }
813
+ datasetIds() {
814
+ return [...this.datasets.keys()].sort();
815
+ }
816
+ /** A round a few seconds from now, so a burst of changes makes one round. */
817
+ changedSoon() {
818
+ if (!this.started || this.soon) return;
819
+ this.soon = setTimeout(() => {
820
+ this.soon = null;
821
+ this.runRound();
822
+ }, 2e3);
823
+ }
824
+ /** One listing of every dataset, then one round with every paired peer. */
825
+ runRound() {
826
+ return this.serialize(async () => {
827
+ for (const dataset of this.datasets.values()) await this.listLocked(dataset);
828
+ for (const peer of this.peers) {
829
+ if (this.stopped) break;
830
+ await this.pollPairingLocked(peer);
831
+ if (peer.state === "paired") await this.helloLocked(peer);
832
+ if (peer.state === "paired") await this.syncPeerLocked(peer);
833
+ }
834
+ this.store.savePeers(this.peers);
835
+ this.announceRole();
836
+ });
837
+ }
838
+ /** The servers set to be the master that count now, this one included, smallest id first. */
839
+ masterCandidates() {
840
+ const now = Date.now();
841
+ const candidates = [];
842
+ if (this.host.isMaster()) candidates.push({
843
+ id: this.serverId,
844
+ peer: null
845
+ });
846
+ for (const peer of this.peers) {
847
+ const seen = this.masterSeen.get(peer.url);
848
+ if (peer.state === "paired" && peer.id !== "" && seen !== void 0 && now - seen <= 15e4) candidates.push({
849
+ id: peer.id,
850
+ peer
851
+ });
852
+ }
853
+ return candidates.sort((x, y) => x.id < y.id ? -1 : x.id > y.id ? 1 : 0);
854
+ }
855
+ role() {
856
+ return this.masterCandidates()[0]?.peer === null ? "master" : "member";
857
+ }
858
+ master() {
859
+ const peer = this.masterCandidates()[0]?.peer;
860
+ return peer ? this.infoOf(peer) : null;
861
+ }
862
+ /** Where to reach the master, with the pairing token; null when this server is it or there is none. */
863
+ masterAccess() {
864
+ const peer = this.masterCandidates()[0]?.peer;
865
+ return peer ? {
866
+ url: peer.url,
867
+ token: peer.token
868
+ } : null;
869
+ }
870
+ /** More than one server is set to be the master: the user should set one only. */
871
+ masterConflict() {
872
+ return this.masterCandidates().length > 1;
873
+ }
874
+ /** Calls `cb` whenever the role, the master or `masterConflict()` changes. */
875
+ onStatusChanged(cb) {
876
+ this.statusListeners.add(cb);
877
+ return () => {
878
+ this.statusListeners.delete(cb);
879
+ };
880
+ }
881
+ onRoleChanged(cb) {
882
+ this.roleListeners.add(cb);
883
+ return () => {
884
+ this.roleListeners.delete(cb);
885
+ };
886
+ }
887
+ announceRole() {
888
+ const role = this.role();
889
+ const master = this.master();
890
+ const now = `${role}:${master?.id ?? ""}`;
891
+ const status = `${now}:${String(this.masterConflict())}`;
892
+ if (now !== this.announcedRole) {
893
+ this.announcedRole = now;
894
+ for (const cb of this.roleListeners) try {
895
+ cb(role, master);
896
+ } catch (error) {
897
+ this.host.error(`Multihelm: a role listener failed: ${errorText$1(error)}`);
898
+ }
899
+ }
900
+ if (status !== this.announcedStatus) {
901
+ this.announcedStatus = status;
902
+ for (const cb of this.statusListeners) try {
903
+ cb();
904
+ } catch (error) {
905
+ this.host.error(`Multihelm: a status listener failed: ${errorText$1(error)}`);
906
+ }
907
+ }
908
+ }
909
+ async listLocked(dataset) {
910
+ const id = dataset.definition.id;
911
+ let listed;
912
+ try {
913
+ listed = await dataset.definition.list();
914
+ } catch (error) {
915
+ this.host.error(`Multihelm: listing ${id} failed: ${errorText$1(error)}`);
916
+ return;
917
+ }
918
+ dataset.listed = new Map(listed.map((e) => [e.key, e]));
919
+ const { changed } = applyListing(dataset.library, listed.map(toListed), this.serverId, Date.now());
920
+ for (const key of changed) {
921
+ const entry = dataset.library.entries[key];
922
+ const local = dataset.listed.get(key);
923
+ if (!entry || !local) continue;
924
+ for (const file of entry.files) {
925
+ if (this.stopped) break;
926
+ const source = local.files.find((f) => f.name === file.name);
927
+ if (!source || file.sha256 !== void 0) continue;
928
+ try {
929
+ file.sha256 = await hashFile(source.path);
930
+ } catch (error) {
931
+ this.host.debug(`Multihelm: cannot hash ${source.path}: ${errorText$1(error)}`);
932
+ }
933
+ }
934
+ }
935
+ this.store.saveLibrary(id, dataset.library);
936
+ }
937
+ hello() {
938
+ return {
939
+ serverId: this.serverId,
940
+ name: this.host.serverName(),
941
+ protocol: 1,
942
+ datasets: this.datasetIds(),
943
+ master: this.host.isMaster()
944
+ };
945
+ }
946
+ manifest(datasetId, since) {
947
+ const dataset = this.datasets.get(datasetId);
948
+ return dataset ? manifestSince(dataset.library, since) : null;
949
+ }
950
+ /** Absolute path of a file this server offers, or null. */
951
+ servableFile(datasetId, key, name) {
952
+ const dataset = this.datasets.get(datasetId);
953
+ const entry = dataset?.library.entries[key];
954
+ if (!dataset || !entry || entry.deletedAt !== void 0) return null;
955
+ const file = entry.files.find((f) => f.name === name);
956
+ const local = dataset.listed.get(key)?.files.find((f) => f.name === name);
957
+ if (!file?.sha256 || !local || local.size !== file.size || local.mtimeMs !== file.mtimeMs) return null;
958
+ return local.path;
959
+ }
960
+ async syncPeerLocked(peer) {
961
+ try {
962
+ for (const dataset of this.datasets.values()) {
963
+ if (this.stopped) return;
964
+ await this.syncDatasetLocked(peer, dataset);
965
+ }
966
+ peer.lastSeen = Date.now();
967
+ peer.lastSync = Date.now();
968
+ } catch (error) {
969
+ if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) {
970
+ peer.state = "needs-pairing";
971
+ peer.lastError = "access was revoked on the peer";
972
+ } else peer.lastError = errorText$1(error);
973
+ this.host.debug(`Multihelm: ${peer.name}: ${peer.lastError}`);
974
+ }
975
+ }
976
+ async syncDatasetLocked(peer, dataset) {
977
+ const id = dataset.definition.id;
978
+ let manifest;
979
+ try {
980
+ manifest = await fetchManifest(peer.url, peer.token, id, peer.cursors[id] ?? 0);
981
+ } catch (error) {
982
+ if (error instanceof PeerHttpError && error.status === 404) return;
983
+ throw error;
984
+ }
985
+ try {
986
+ for (const raw of manifest.entries) {
987
+ if (this.stopped) return;
988
+ if (!await this.applyRemote(peer, dataset, raw)) return;
989
+ }
990
+ peer.cursors[id] = manifest.cursor;
991
+ if (peer.lastError?.startsWith(`${id}:`)) delete peer.lastError;
992
+ } finally {
993
+ this.store.saveLibrary(id, dataset.library);
994
+ }
995
+ }
996
+ /** Apply one entry of a peer's manifest; false when it failed and is tried again. */
997
+ async applyRemote(peer, dataset, raw) {
998
+ const { definition, library } = dataset;
999
+ if (!isWellFormedRemote(raw) || definition.isValidKey && !definition.isValidKey(raw.key)) {
1000
+ this.host.debug(`Multihelm: ignoring a malformed ${definition.id} entry from ${peer.name}`);
1001
+ return true;
1002
+ }
1003
+ const remote = raw;
1004
+ const local = library.entries[remote.key];
1005
+ if (local && compareVersions(remote.version, local.version) <= 0) return true;
1006
+ const fail = (error) => {
1007
+ peer.lastError = `${definition.id}: ${remote.key}: ${errorText$1(error)}`;
1008
+ this.host.debug(`Multihelm: ${peer.lastError}`);
1009
+ return false;
1010
+ };
1011
+ if (remote.deletedAt !== void 0) {
1012
+ if (!local || local.deletedAt !== void 0 || local.declined) {
1013
+ recordRemote(library, remote, null);
1014
+ return true;
1015
+ }
1016
+ try {
1017
+ if (await definition.remove(remote.key)) recordRemote(library, remote, null);
1018
+ else {
1019
+ library.seq++;
1020
+ library.entries[remote.key] = {
1021
+ ...local,
1022
+ version: {
1023
+ counter: remote.version.counter + 1,
1024
+ origin: this.serverId
1025
+ },
1026
+ seq: library.seq
1027
+ };
1028
+ }
1029
+ return true;
1030
+ } catch (error) {
1031
+ return fail(error);
1032
+ }
1033
+ }
1034
+ try {
1035
+ const incoming = await this.fetchFiles(peer, dataset, remote);
1036
+ if (!incoming) return false;
1037
+ await definition.apply(incoming);
1038
+ await this.cleanIncoming(definition.id, incoming);
1039
+ const after = (await definition.list()).find((e) => e.key === remote.key);
1040
+ if (after) dataset.listed.set(after.key, after);
1041
+ recordRemote(library, remote, after ? toListed(after) : null);
1042
+ return true;
1043
+ } catch (error) {
1044
+ return fail(error);
1045
+ }
1046
+ }
1047
+ /** The peer's entry with every file verified on this server's disk, or null on failure. */
1048
+ async fetchFiles(peer, dataset, remote) {
1049
+ const id = dataset.definition.id;
1050
+ const mine = dataset.library.entries[remote.key];
1051
+ const listed = dataset.listed.get(remote.key);
1052
+ const incomingDir = this.store.incomingDir(id);
1053
+ await fs.promises.mkdir(incomingDir, { recursive: true });
1054
+ const files = [];
1055
+ for (const file of remote.files) {
1056
+ const own = mine?.files.find((f) => f.name === file.name && f.sha256 === file.sha256 && f.size === file.size) ? listed?.files.find((f) => f.name === file.name) : void 0;
1057
+ if (own && own.size === file.size) {
1058
+ files.push({
1059
+ name: file.name,
1060
+ path: own.path,
1061
+ size: file.size,
1062
+ sha256: file.sha256,
1063
+ unchanged: true
1064
+ });
1065
+ continue;
1066
+ }
1067
+ const dest = path.join(incomingDir, file.sha256);
1068
+ const already = await fs.promises.stat(dest).then((s) => s.size, () => 0);
1069
+ if (already > file.size) await fs.promises.rm(dest, { force: true });
1070
+ if (already !== file.size) {
1071
+ const free = await fs.promises.statfs(incomingDir);
1072
+ if (free.bavail * free.bsize < (file.size - already) * 1.05) {
1073
+ peer.lastError = `${id}: not enough free space for ${remote.key}`;
1074
+ return null;
1075
+ }
1076
+ this.host.debug(`Multihelm: fetching ${id} ${remote.key} ${file.name} from ${peer.name}`);
1077
+ await downloadFile(peer.url, peer.token, {
1078
+ dataset: id,
1079
+ key: remote.key,
1080
+ name: file.name
1081
+ }, dest);
1082
+ }
1083
+ if ((await fs.promises.stat(dest)).size !== file.size || await hashFile(dest) !== file.sha256) {
1084
+ await fs.promises.rm(dest, { force: true });
1085
+ peer.lastError = `${id}: ${remote.key} arrived damaged; it is fetched again`;
1086
+ return null;
1087
+ }
1088
+ files.push({
1089
+ name: file.name,
1090
+ path: dest,
1091
+ size: file.size,
1092
+ sha256: file.sha256,
1093
+ unchanged: false
1094
+ });
1095
+ }
1096
+ return {
1097
+ key: remote.key,
1098
+ meta: remote.meta,
1099
+ files
1100
+ };
1101
+ }
1102
+ /** Files the dataset copied rather than moved are left in the work folder; remove them. */
1103
+ async cleanIncoming(datasetId, entry) {
1104
+ const dir = this.store.incomingDir(datasetId);
1105
+ for (const file of entry.files) if (!file.unchanged && path.dirname(file.path) === dir) await fs.promises.rm(file.path, { force: true });
1106
+ }
1107
+ peerInfo() {
1108
+ return this.peers.map((p) => this.infoOf(p));
1109
+ }
1110
+ infoOf(p) {
1111
+ const info = {
1112
+ id: p.id,
1113
+ name: p.name,
1114
+ url: p.url,
1115
+ state: p.state
1116
+ };
1117
+ if (p.lastSeen !== void 0) info.lastSeen = p.lastSeen;
1118
+ if (p.lastSync !== void 0) info.lastSync = p.lastSync;
1119
+ if (p.lastError !== void 0) info.lastError = p.lastError;
1120
+ const seen = this.masterSeen.get(p.url);
1121
+ if (seen !== void 0 && Date.now() - seen <= 15e4) info.master = true;
1122
+ return info;
1123
+ }
1124
+ /**
1125
+ * Pair with the server at `input`: without security it is paired at once,
1126
+ * otherwise a readonly device access request waits for approval there.
1127
+ */
1128
+ pair(input) {
1129
+ return this.serialize(async () => {
1130
+ const url = normalizePeerUrl(input);
1131
+ if (!url) throw new Error("not a server address");
1132
+ let peer = this.peers.find((p) => p.url === url);
1133
+ if (!peer) {
1134
+ peer = {
1135
+ id: "",
1136
+ name: url,
1137
+ url,
1138
+ token: "",
1139
+ state: "needs-pairing",
1140
+ cursors: {}
1141
+ };
1142
+ this.peers.push(peer);
1143
+ }
1144
+ const result = await requestAccess(url, `signalk-multihelm-${this.serverId}-${crypto.randomUUID().slice(0, 8)}`, `Multihelm on ${this.host.serverName()}`);
1145
+ this.applyAccessResult(peer, result);
1146
+ if (peer.state === "paired") await this.helloLocked(peer);
1147
+ this.store.savePeers(this.peers);
1148
+ const info = this.peerInfo().find((p) => p.url === url);
1149
+ if (!info) throw new Error("peer vanished");
1150
+ if (peer.state === "paired") this.changedSoon();
1151
+ return info;
1152
+ });
1153
+ }
1154
+ unpair(url) {
1155
+ return this.serialize(() => {
1156
+ const before = this.peers.length;
1157
+ this.peers = this.peers.filter((p) => p.url !== url);
1158
+ this.masterSeen.delete(url);
1159
+ this.store.savePeers(this.peers);
1160
+ this.announceRole();
1161
+ return Promise.resolve(this.peers.length !== before);
1162
+ });
1163
+ }
1164
+ applyAccessResult(peer, result) {
1165
+ switch (result.kind) {
1166
+ case "no-security":
1167
+ peer.token = "";
1168
+ peer.state = "paired";
1169
+ delete peer.requestHref;
1170
+ break;
1171
+ case "approved":
1172
+ peer.token = result.token;
1173
+ peer.state = "paired";
1174
+ delete peer.requestHref;
1175
+ delete peer.lastError;
1176
+ break;
1177
+ case "pending":
1178
+ peer.requestHref = result.href;
1179
+ peer.state = "waiting-approval";
1180
+ break;
1181
+ case "denied":
1182
+ peer.state = "needs-pairing";
1183
+ delete peer.requestHref;
1184
+ peer.lastError = "the access request was denied";
1185
+ break;
1186
+ case "error":
1187
+ peer.state = "needs-pairing";
1188
+ peer.lastError = result.message;
1189
+ }
1190
+ }
1191
+ async pollPairingLocked(peer) {
1192
+ if (peer.state !== "waiting-approval" || !peer.requestHref) return;
1193
+ try {
1194
+ this.applyAccessResult(peer, await pollAccess(peer.url, peer.requestHref));
1195
+ if (peer.state === "paired") await this.helloLocked(peer);
1196
+ } catch (error) {
1197
+ peer.lastError = errorText$1(error);
1198
+ }
1199
+ }
1200
+ async helloLocked(peer) {
1201
+ try {
1202
+ const hello = await fetchHello(peer.url, peer.token);
1203
+ if (hello.serverId === this.serverId) {
1204
+ peer.state = "needs-pairing";
1205
+ peer.lastError = "this is this server itself";
1206
+ return;
1207
+ }
1208
+ peer.id = hello.serverId;
1209
+ peer.name = hello.name;
1210
+ peer.lastSeen = Date.now();
1211
+ if (hello.master) this.masterSeen.set(peer.url, peer.lastSeen);
1212
+ else this.masterSeen.delete(peer.url);
1213
+ } catch (error) {
1214
+ peer.lastError = error instanceof PeerHttpError && error.status === 404 ? "Multihelm is not running there" : errorText$1(error);
1215
+ }
1216
+ }
1217
+ };
1218
+ // src/routes.ts
1219
+ var MAX_URL_LENGTH = 300;
1220
+ function queryString(req, name) {
1221
+ const value = req.query[name];
1222
+ return typeof value === "string" ? value : "";
1223
+ }
1224
+ function errorText(error) {
1225
+ return error instanceof Error ? error.message : String(error);
1226
+ }
1227
+ function registerRoutes(router, multihelm, discovered, vesselSettings = () => null) {
1228
+ const scoped = router.access;
1229
+ const available = typeof scoped === "function";
1230
+ const readonly = available ? scoped.call(router, "readonly") : { get(path, handler) {
1231
+ router.get(path, handler);
1232
+ return this;
1233
+ } };
1234
+ const running = (handler) => async (req, res) => {
1235
+ const mh = multihelm();
1236
+ if (!mh) {
1237
+ res.status(503).json({ error: "Multihelm is not running" });
1238
+ return;
1239
+ }
1240
+ try {
1241
+ await handler(mh, req, res);
1242
+ } catch (error) {
1243
+ res.status(500).json({ error: errorText(error) });
1244
+ }
1245
+ };
1246
+ readonly.get("/hello", running((mh, _req, res) => {
1247
+ res.json(mh.hello());
1248
+ }));
1249
+ readonly.get("/vessel-settings", running((_mh, _req, res) => {
1250
+ const settings = vesselSettings();
1251
+ if (!settings) {
1252
+ res.status(501).json({ error: "this server does not expose its vessel settings" });
1253
+ return;
1254
+ }
1255
+ res.json(settings);
1256
+ }));
1257
+ readonly.get("/manifest", running((mh, req, res) => {
1258
+ const since = Number(queryString(req, "since") || "0");
1259
+ if (!Number.isInteger(since) || since < 0) {
1260
+ res.status(400).json({ error: "since must be a non-negative integer" });
1261
+ return;
1262
+ }
1263
+ const manifest = mh.manifest(queryString(req, "dataset"), since);
1264
+ if (!manifest) {
1265
+ res.status(404).json({ error: "no such dataset" });
1266
+ return;
1267
+ }
1268
+ res.json(manifest);
1269
+ }));
1270
+ readonly.get("/file", running((mh, req, res) => {
1271
+ const file = mh.servableFile(queryString(req, "dataset"), queryString(req, "key"), queryString(req, "file"));
1272
+ if (!file) {
1273
+ res.status(404).json({ error: "no such file" });
1274
+ return;
1275
+ }
1276
+ res.sendFile(file, {
1277
+ acceptRanges: true,
1278
+ dotfiles: "allow"
1279
+ });
1280
+ }));
1281
+ router.get("/status", (_req, res) => {
1282
+ const mh = multihelm();
1283
+ res.json({
1284
+ available,
1285
+ running: mh !== null,
1286
+ serverId: mh?.serverId ?? null,
1287
+ role: mh?.role() ?? null,
1288
+ master: mh?.master() ?? null,
1289
+ masterConflict: mh?.masterConflict() ?? false,
1290
+ datasets: mh?.datasetIds() ?? [],
1291
+ peers: mh?.peerInfo() ?? [],
1292
+ discovered: mh ? discovered() : []
1293
+ });
1294
+ });
1295
+ router.post("/peers", running(async (mh, req, res) => {
1296
+ const url = req.body?.url;
1297
+ if (typeof url !== "string" || url.length === 0 || url.length > MAX_URL_LENGTH) {
1298
+ res.status(400).json({ error: "url is required" });
1299
+ return;
1300
+ }
1301
+ try {
1302
+ res.json(await mh.pair(url));
1303
+ } catch (error) {
1304
+ res.status(400).json({ error: errorText(error) });
1305
+ }
1306
+ }));
1307
+ router.delete("/peers", running(async (mh, req, res) => {
1308
+ const url = queryString(req, "url");
1309
+ res.status(await mh.unpair(url) ? 200 : 404).json({ removed: url });
1310
+ }));
1311
+ router.post("/run", running((mh, _req, res) => {
1312
+ mh.runRound();
1313
+ res.status(202).json({ started: true });
1314
+ }));
1315
+ }
1316
+ // src/store.ts
1317
+ /**
1318
+ * Multihelm state on disk, in the plugin's data dir: this server's id, its
1319
+ * paired peers and one library per dataset. Peers hold access tokens, so
1320
+ * their file is readable by the server's user only.
1321
+ */
1322
+ var PeerSchema = Type.Object({
1323
+ /** The peer's server id, from its `hello`; empty until it answered once. */
1324
+ id: Type.String(),
1325
+ name: Type.String(),
1326
+ /** Base URL of the peer's Signal K server, e.g. `http://192.168.1.20:3000`. */
1327
+ url: Type.String(),
1328
+ /** Readonly device token; empty when the peer runs without security. */
1329
+ token: Type.String(),
1330
+ /** Set while an access request waits for approval on the peer. */
1331
+ requestHref: Type.Optional(Type.String()),
1332
+ state: Type.Union([
1333
+ Type.Literal("waiting-approval"),
1334
+ Type.Literal("paired"),
1335
+ Type.Literal("needs-pairing")
1336
+ ]),
1337
+ /** Per dataset, the peer's change sequence this server has applied up to. */
1338
+ cursors: Type.Record(Type.String(), Type.Integer({ minimum: 0 })),
1339
+ lastSeen: Type.Optional(Type.Number()),
1340
+ lastSync: Type.Optional(Type.Number()),
1341
+ lastError: Type.Optional(Type.String())
1342
+ });
1343
+ var PeersFileSchema = Type.Array(PeerSchema);
1344
+ /** This server's admin device token on itself, for writing what follows the master. */
1345
+ var OwnAccessSchema = Type.Object({
1346
+ token: Type.String(),
1347
+ requestHref: Type.Optional(Type.String()),
1348
+ state: Type.Union([
1349
+ Type.Literal("none"),
1350
+ Type.Literal("waiting-approval"),
1351
+ Type.Literal("granted"),
1352
+ Type.Literal("denied")
1353
+ ])
1354
+ });
1355
+ var LibraryFileSchema = Type.Object({
1356
+ seq: Type.Integer({ minimum: 0 }),
1357
+ entries: Type.Record(Type.String(), Type.Any())
1358
+ });
1359
+ function writeAtomic(file, data, mode) {
1360
+ const tmp = `${file}.${String(process.pid)}.tmp`;
1361
+ fs.writeFileSync(tmp, data, mode === void 0 ? void 0 : { mode });
1362
+ fs.renameSync(tmp, file);
1363
+ }
1364
+ function readJson(file) {
1365
+ try {
1366
+ return JSON.parse(fs.readFileSync(file, "utf-8"));
1367
+ } catch {
1368
+ return;
1369
+ }
1370
+ }
1371
+ var MultihelmStore = class {
1372
+ dir;
1373
+ constructor(dataDir) {
1374
+ this.dir = dataDir;
1375
+ fs.mkdirSync(path.join(dataDir, "datasets"), { recursive: true });
1376
+ }
1377
+ /** Where a peer's files for `dataset` wait until they are verified and applied. */
1378
+ incomingDir(dataset) {
1379
+ return path.join(this.dir, "incoming", encodeURIComponent(dataset));
1380
+ }
1381
+ libraryFile(dataset) {
1382
+ return path.join(this.dir, "datasets", `${encodeURIComponent(dataset)}.json`);
1383
+ }
1384
+ loadLibrary(dataset) {
1385
+ const raw = readJson(this.libraryFile(dataset));
1386
+ return Value.Check(LibraryFileSchema, raw) ? raw : emptyLibrary();
1387
+ }
1388
+ saveLibrary(dataset, library) {
1389
+ writeAtomic(this.libraryFile(dataset), JSON.stringify(library));
1390
+ }
1391
+ loadPeers() {
1392
+ const raw = readJson(path.join(this.dir, "peers.json"));
1393
+ return Value.Check(PeersFileSchema, raw) ? raw : [];
1394
+ }
1395
+ savePeers(peers) {
1396
+ writeAtomic(path.join(this.dir, "peers.json"), JSON.stringify(peers, null, 2), 384);
1397
+ }
1398
+ loadOwnAccess() {
1399
+ const raw = readJson(path.join(this.dir, "own-access.json"));
1400
+ return Value.Check(OwnAccessSchema, raw) ? raw : {
1401
+ token: "",
1402
+ state: "none"
1403
+ };
1404
+ }
1405
+ saveOwnAccess(access) {
1406
+ writeAtomic(path.join(this.dir, "own-access.json"), JSON.stringify(access), 384);
1407
+ }
1408
+ /** A random id made once per installation: every server of a boat shares its vessel id. */
1409
+ serverId() {
1410
+ const file = path.join(this.dir, "server-id");
1411
+ try {
1412
+ const id = fs.readFileSync(file, "utf-8").trim();
1413
+ if (id) return id;
1414
+ } catch {}
1415
+ const id = crypto.randomUUID();
1416
+ writeAtomic(file, id);
1417
+ return id;
1418
+ }
1419
+ };
1420
+ // src/index.ts
1421
+ var PLUGIN_ID = "signalk-multihelm";
1422
+ var ConfigSchema = Type.Object({
1423
+ master: Type.Boolean({
1424
+ title: "This server is the boat's master",
1425
+ 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.",
1426
+ default: false
1427
+ }),
1428
+ followVessel: Type.Boolean({
1429
+ title: "Take the vessel data over from the master",
1430
+ description: "Name, MMSI, call sign, dimensions and ship type from Server -> Settings. Changes made here are replaced by the master's.",
1431
+ default: true
1432
+ }),
1433
+ followMetadata: Type.Boolean({
1434
+ title: "Take the path metadata over from the master",
1435
+ description: "Display names, units, zones and alarm limits set for paths. Changes made here are replaced by the master's.",
1436
+ default: true
1437
+ })
1438
+ });
1439
+ var APPROVE_HINT = "approve Multihelm's request under Security -> Access Requests on this server to take the vessel settings over";
1440
+ 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";
1441
+ function statusText(role, master, conflict) {
1442
+ if (conflict) return `${role === "master" ? "Master" : `Member, master: ${master?.name ?? "?"}`}. More than one server is set to be the master: set one only`;
1443
+ if (role === "master") return "Master of the boat's servers";
1444
+ return master ? `Member, master: ${master.name}` : "Member, no master found";
1445
+ }
1446
+ function src_default(app) {
1447
+ const host = app;
1448
+ let multihelm = null;
1449
+ let discovery = null;
1450
+ let stopRoleStatus = null;
1451
+ let stopFollowing = null;
1452
+ function localVesselSettings() {
1453
+ const deltas = host.config?.baseDeltaEditor?.deltas;
1454
+ return deltas === void 0 ? null : vesselSettingsFromDeltas(deltas);
1455
+ }
1456
+ /** The port this server listens on, as the server itself works it out. */
1457
+ function ownUrl() {
1458
+ const settings = host.config?.settings;
1459
+ if (settings?.ssl) return `https://127.0.0.1:${String(Number(process.env.SSLPORT) || settings.sslport || 3443)}`;
1460
+ return `http://127.0.0.1:${String(Number(process.env.PORT) || settings?.port || 3e3)}`;
1461
+ }
1462
+ function publish(value) {
1463
+ app.emitPropertyValue(PROPERTY_NAME, value);
1464
+ }
1465
+ return {
1466
+ id: PLUGIN_ID,
1467
+ name: "Multihelm",
1468
+ description: "Keeps the Signal K servers of one boat in step, and knows which one is the boat's master",
1469
+ schema: () => ConfigSchema,
1470
+ start(config) {
1471
+ const settings = config;
1472
+ const isMaster = settings.master === true;
1473
+ const store = new MultihelmStore(app.getDataDirPath());
1474
+ const mh = new Multihelm(store, {
1475
+ serverName: () => os.hostname(),
1476
+ isMaster: () => isMaster,
1477
+ debug: (msg) => {
1478
+ app.debug(msg);
1479
+ },
1480
+ error: (msg) => {
1481
+ app.error(msg);
1482
+ }
1483
+ });
1484
+ multihelm = mh;
1485
+ discovery = new ServerDiscovery(() => host.config?.getExternalPort?.());
1486
+ discovery.start();
1487
+ mh.start();
1488
+ publish({
1489
+ apiVersion: 1,
1490
+ registerDataset: (definition) => mh.registerDataset(definition),
1491
+ peers: () => mh.peerInfo(),
1492
+ serverId: () => mh.serverId,
1493
+ role: () => mh.role(),
1494
+ master: () => mh.master(),
1495
+ onRoleChanged: (cb) => mh.onRoleChanged(cb)
1496
+ });
1497
+ const follower = new MasterFollower({
1498
+ store,
1499
+ serverId: mh.serverId,
1500
+ ownUrl,
1501
+ localSettings: localVesselSettings,
1502
+ master: () => mh.masterAccess(),
1503
+ followVessel: settings.followVessel !== false,
1504
+ followMeta: settings.followMetadata !== false,
1505
+ debug: (msg) => {
1506
+ app.debug(msg);
1507
+ },
1508
+ error: (msg) => {
1509
+ app.error(msg);
1510
+ }
1511
+ });
1512
+ const showRole = () => {
1513
+ const text = statusText(mh.role(), mh.master(), mh.masterConflict());
1514
+ if (follower.waitingForApproval()) app.setPluginStatus(`${text}; ${APPROVE_HINT}`);
1515
+ else if (follower.denied()) app.setPluginStatus(`${text}; ${DENIED_HINT}`);
1516
+ else app.setPluginStatus(text);
1517
+ };
1518
+ let following = false;
1519
+ const follow = () => {
1520
+ if (following) return;
1521
+ following = true;
1522
+ follower.run().catch((error) => {
1523
+ app.error(`Multihelm: taking over the master's vessel settings: ${error instanceof Error ? error.message : String(error)}`);
1524
+ }).finally(() => {
1525
+ following = false;
1526
+ showRole();
1527
+ });
1528
+ };
1529
+ const followTimer = setInterval(follow, ROUND_INTERVAL_MS);
1530
+ const stopRoleFollow = mh.onRoleChanged(follow);
1531
+ stopFollowing = () => {
1532
+ clearInterval(followTimer);
1533
+ stopRoleFollow();
1534
+ };
1535
+ stopRoleStatus = mh.onStatusChanged(showRole);
1536
+ showRole();
1537
+ },
1538
+ stop() {
1539
+ stopFollowing?.();
1540
+ stopFollowing = null;
1541
+ stopRoleStatus?.();
1542
+ stopRoleStatus = null;
1543
+ if (multihelm) publish({ apiVersion: 1 });
1544
+ multihelm?.stop();
1545
+ multihelm = null;
1546
+ discovery?.stop();
1547
+ discovery = null;
1548
+ },
1549
+ registerWithRouter(router) {
1550
+ registerRoutes(router, () => multihelm, () => discovery?.list() ?? [], localVesselSettings);
1551
+ }
1552
+ };
1553
+ }
1554
+ export { src_default as default };
1555
+
1556
+ //# sourceMappingURL=index.js.map