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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["REQUEST_TIMEOUT_MS","isRecord","errorText","errorText"],"sources":["../src/api.ts","../src/peer-client.ts","../src/discovery.ts","../src/config.ts","../src/source-priorities.ts","../src/vessel-settings.ts","../src/follow-master.ts","../src/history-from-master.ts","../src/master-proxy.ts","../src/library.ts","../src/multihelm.ts","../src/routes.ts","../src/store.ts","../src/index.ts"],"sourcesContent":["/**\n * What other plugins use. Multihelm publishes it as the PropertyValue\n * `multihelm`: `{ apiVersion: 1, ...MultihelmApi }` from its start, and\n * `{ apiVersion: 1 }` without the methods after its stop. A plugin acts on\n * the last value, registers its datasets again whenever the methods\n * reappear, and unregisters them in its own `stop()`.\n *\n * Compatibility: `apiVersion` changes only with a change users must know\n * about; everything else grows by addition.\n */\n\nexport const API_VERSION = 1\nexport const PROPERTY_NAME = 'multihelm'\n\n/** One file of an entry on this server. */\nexport interface DatasetFile {\n /** Unique within the entry: letters, digits, `.`, `_`, `-`, not starting with `.`. */\n name: string\n /** Absolute path on this server. */\n path: string\n size: number\n mtimeMs: number\n}\n\nexport interface DatasetEntry {\n /** Unique within the dataset, e.g. a path relative to the dataset's folder. */\n key: string\n /** Small JSON value replicated with the entry, e.g. `{ enabled: true }`. */\n meta: unknown\n files: DatasetFile[]\n}\n\n/** A peer's entry to take over; every file has arrived whole and matches its hash. */\nexport interface IncomingEntry {\n key: string\n meta: unknown\n files: {\n name: string\n /**\n * Absolute path of the verified file: in Multihelm's work folder for a\n * file that changed (move it into place), or the dataset's own copy for\n * one that did not.\n */\n path: string\n size: number\n sha256: string\n /** True when `path` is the dataset's own unchanged file. */\n unchanged: boolean\n }[]\n}\n\nexport interface DatasetDefinition {\n /** Unique across plugins: `<plugin id>/<name>`. */\n id: string\n /** What this server holds now. Called once per round, and after each `apply`. */\n list: () => Promise<DatasetEntry[]>\n /** Take over a peer's entry. Throwing leaves it to be tried again next round. */\n apply: (entry: IncomingEntry) => Promise<void>\n /**\n * A peer deleted the entry. Return false to keep it here: it is then\n * offered back to the peers as a change of this server's.\n */\n remove: (key: string) => Promise<boolean>\n /** Checked on every key a peer sends, before `apply` or `remove` sees it. */\n isValidKey?: (key: string) => boolean\n}\n\nexport interface DatasetHandle {\n /** Something changed here: look sooner than the next round. */\n changed: () => void\n unregister: () => void\n}\n\nexport interface PeerInfo {\n id: string\n name: string\n url: string\n state: 'waiting-approval' | 'paired' | 'needs-pairing'\n lastSeen?: number\n lastSync?: number\n lastError?: string\n /** The peer is set to be the boat's master, and answered within the last rounds. */\n master?: boolean\n /** A paired peer answered within the last rounds. */\n online?: boolean\n /** The peer's Signal K server version, once it said. */\n signalk?: string\n /** The peer's Multihelm version, once it said. */\n multihelm?: string\n}\n\n/**\n * `master`: this server is the boat's master. `member`: another server is,\n * or none is. The master is set by hand on one server; when several are set,\n * the one with the smallest server id is the master.\n */\nexport type Role = 'master' | 'member'\n\nexport interface MasterRouteHandle {\n unregister: () => void\n}\n\nexport interface MasterResponse {\n status: number\n /** The response headers that matter to a reader: type, length, caching. */\n headers: Record<string, string>\n body: Buffer\n}\n\nexport interface MultihelmApi {\n registerDataset: (definition: DatasetDefinition) => DatasetHandle\n peers: () => PeerInfo[]\n /** This server's id among the boat's servers. */\n serverId: () => string\n role: () => Role\n /** The peer that is the master; null when this server is the master or there is none. */\n master: () => PeerInfo | null\n /**\n * Calls `cb` whenever this server's role or the master changes; returns a\n * function that stops the calls. A master-mode plugin starts its work when\n * its server becomes the master and stops it when it no longer is.\n */\n onRoleChanged: (cb: (role: Role, master: PeerInfo | null) => void) => () => void\n /**\n * Lets this server serve the master's GET requests under `prefix` (a path\n * ending in `/`, e.g. `/signalk/v1/api/resources/charts/`) at\n * `masterPath(...)`, to anyone who may read on this server; the prefix\n * without its `/` is served too, where a collection is listed. Admin and\n * access routes are refused.\n */\n registerMasterRoute: (prefix: string) => MasterRouteHandle\n /** Where this server serves the master's `path`, e.g. for a tile URL handed to a browser. */\n masterPath: (path: string) => string\n /** Reads the master's `path`, under a registered prefix; rejects when there is no master. */\n fetchMaster: (path: string) => Promise<MasterResponse>\n}\n\nexport type MultihelmProperty = { apiVersion: typeof API_VERSION } & Partial<MultihelmApi>\n","/**\n * HTTP client for a Multihelm peer: its routes, and the Signal K\n * device access request that pairs with it.\n *\n * Peers are other Signal K servers on the boat's network, addressed by the\n * URL the user confirmed. HTTPS peers are verified as usual, so a server\n * with a self-signed certificate is reached over its HTTP port instead.\n */\n\nimport fs from 'node:fs'\nimport http from 'node:http'\nimport https from 'node:https'\nimport { pipeline } from 'node:stream/promises'\n\nexport const ROUTE_PREFIX = '/plugins/signalk-multihelm'\nconst REQUEST_TIMEOUT_MS = 30_000\n\nexport interface Hello {\n serverId: string\n name: string\n protocol: number\n datasets: string[]\n /** This server is set to be the boat's master. */\n master: boolean\n /** The Signal K server's version; older Multihelm versions leave it out. */\n signalk?: string\n /** Multihelm's version; older Multihelm versions leave it out. */\n multihelm?: string\n}\n\n/**\n * The server asking for a peer's `hello`, sent along so the peer can list\n * the servers paired with it. Older peers ignore it.\n */\nexport interface HelloFrom {\n serverId: string\n name: string\n signalk?: string\n multihelm?: string\n}\n\nfunction helloQuery(from: HelloFrom | undefined): string {\n if (!from) {\n return ''\n }\n const query = new URLSearchParams({ from: from.serverId, name: from.name })\n if (from.signalk) {\n query.set('signalk', from.signalk)\n }\n if (from.multihelm) {\n query.set('multihelm', from.multihelm)\n }\n return `?${query.toString()}`\n}\n\nfunction optionalText(value: unknown): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined\n}\n\nexport interface Manifest {\n cursor: number\n entries: unknown[]\n}\n\ninterface RawResponse {\n status: number\n stream: http.IncomingMessage\n}\n\nexport class PeerHttpError extends Error {\n constructor(\n readonly status: number,\n message: string\n ) {\n super(message)\n }\n}\n\nfunction send(\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n url: string,\n options: { token?: string; body?: unknown; headers?: Record<string, string> } = {}\n): Promise<RawResponse> {\n const headers: Record<string, string> = { ...options.headers }\n if (options.token) {\n headers.Authorization = `Bearer ${options.token}`\n }\n let payload: string | undefined\n if (options.body !== undefined) {\n payload = JSON.stringify(options.body)\n headers['Content-Type'] = 'application/json'\n }\n const target = new URL(url)\n const request = target.protocol === 'https:' ? https.request : http.request\n return new Promise((resolve, reject) => {\n // This server itself, reached over loopback, may well have a self-signed certificate.\n const rejectUnauthorized = target.hostname !== '127.0.0.1'\n const req = request(\n target,\n { method, headers, timeout: REQUEST_TIMEOUT_MS, rejectUnauthorized },\n (res) => {\n resolve({ status: res.statusCode ?? 0, stream: res })\n }\n )\n req.on('timeout', () =>\n req.destroy(new Error(`timeout after ${String(REQUEST_TIMEOUT_MS)} ms`))\n )\n req.on('error', reject)\n if (payload !== undefined) {\n req.write(payload)\n }\n req.end()\n })\n}\n\nasync function readBody(res: RawResponse): Promise<string> {\n const chunks: Buffer[] = []\n for await (const chunk of res.stream) {\n chunks.push(chunk as Buffer)\n }\n return Buffer.concat(chunks).toString('utf-8')\n}\n\nasync function getJson(url: string, token?: string): Promise<unknown> {\n const res = await send('GET', url, { token })\n const text = await readBody(res)\n if (res.status < 200 || res.status >= 300) {\n throw new PeerHttpError(res.status, `HTTP ${String(res.status)} from ${url}`)\n }\n return JSON.parse(text) as unknown\n}\n\n/** `host:port` or a URL, reduced to `http(s)://host:port`; null when it is neither. */\nexport function normalizePeerUrl(input: string): string | null {\n let url: URL\n try {\n url = new URL(input.includes('://') ? input : `http://${input}`)\n } catch {\n return null\n }\n if ((url.protocol !== 'http:' && url.protocol !== 'https:') || url.username || url.password) {\n return null\n }\n return `${url.protocol}//${url.host}`\n}\n\nexport async function fetchHello(base: string, token?: string, from?: HelloFrom): Promise<Hello> {\n const body = (await getJson(\n `${base}${ROUTE_PREFIX}/hello${helloQuery(from)}`,\n token\n )) as Partial<Hello>\n if (typeof body.serverId !== 'string' || typeof body.protocol !== 'number') {\n throw new Error(`${base} did not answer as a Multihelm peer`)\n }\n const hello: Hello = {\n serverId: body.serverId,\n name: typeof body.name === 'string' ? body.name : base,\n protocol: body.protocol,\n datasets: Array.isArray(body.datasets)\n ? body.datasets.filter((d): d is string => typeof d === 'string')\n : [],\n master: (body as { master?: unknown }).master === true\n }\n const signalk = optionalText(body.signalk)\n const multihelm = optionalText(body.multihelm)\n return {\n ...hello,\n ...(signalk ? { signalk } : {}),\n ...(multihelm ? { multihelm } : {})\n }\n}\n\nexport async function fetchVesselSettings(base: string, token: string): Promise<unknown> {\n return getJson(`${base}${ROUTE_PREFIX}/vessel-settings`, token)\n}\n\n/** A request to a Signal K server's own REST API; throws on any status but 2xx. */\nexport async function callServer(\n method: 'GET' | 'PUT' | 'DELETE',\n url: string,\n token: string,\n body?: unknown\n): Promise<unknown> {\n const res = await send(method, url, { token, body })\n const text = await readBody(res)\n if (res.status < 200 || res.status >= 300) {\n throw new PeerHttpError(res.status, `HTTP ${String(res.status)} from ${method} ${url}`)\n }\n try {\n return JSON.parse(text) as unknown\n } catch {\n return text\n }\n}\n\n/** A page of a peer's dataset changes; its entries are checked by the caller. */\nexport async function fetchManifest(\n base: string,\n token: string,\n dataset: string,\n since: number\n): Promise<Manifest> {\n const body = (await getJson(\n `${base}${ROUTE_PREFIX}/manifest?dataset=${encodeURIComponent(dataset)}&since=${String(since)}`,\n token\n )) as Partial<Manifest>\n if (typeof body.cursor !== 'number' || !Array.isArray(body.entries)) {\n throw new Error(`${base} sent a malformed manifest`)\n }\n return { cursor: body.cursor, entries: body.entries }\n}\n\n/** Download one file of a peer's entry into `dest`, resuming from what `dest` holds. */\nexport function downloadFile(\n base: string,\n token: string,\n file: { dataset: string; key: string; name: string },\n dest: string\n): Promise<void> {\n const query =\n `file?dataset=${encodeURIComponent(file.dataset)}` +\n `&key=${encodeURIComponent(file.key)}&file=${encodeURIComponent(file.name)}`\n return download(base, token, query, `${file.key}/${file.name}`, dest)\n}\n\nasync function download(\n base: string,\n token: string,\n query: string,\n label: string,\n dest: string\n): Promise<void> {\n let offset = 0\n try {\n offset = fs.statSync(dest).size\n } catch {\n // Nothing to resume.\n }\n const url = `${base}${ROUTE_PREFIX}/${query}`\n const res = await send('GET', url, {\n token,\n headers: offset > 0 ? { Range: `bytes=${String(offset)}-` } : {}\n })\n if (res.status === 206) {\n await pipeline(res.stream, fs.createWriteStream(dest, { flags: 'a' }))\n return\n }\n if (res.status === 200) {\n await pipeline(res.stream, fs.createWriteStream(dest))\n return\n }\n res.stream.resume()\n throw new PeerHttpError(res.status, `HTTP ${String(res.status)} for ${label}`)\n}\n\nexport type AccessRequestResult =\n | { kind: 'no-security' }\n | { kind: 'pending'; href: string }\n | { kind: 'approved'; token: string }\n | { kind: 'denied' }\n | { kind: 'error'; message: string }\n\n/** Ask the peer for a device token, readonly unless said otherwise. */\nexport async function requestAccess(\n base: string,\n clientId: string,\n description: string,\n permissions: 'readonly' | 'admin' = 'readonly'\n): Promise<AccessRequestResult> {\n const res = await send('POST', `${base}/signalk/v1/access/requests`, {\n body: { clientId, description, permissions }\n })\n const text = await readBody(res)\n if (res.status === 404) {\n return { kind: 'no-security' }\n }\n if (res.status === 403) {\n return { kind: 'error', message: 'the peer does not accept device access requests' }\n }\n if (res.status !== 200 && res.status !== 202) {\n return { kind: 'error', message: `HTTP ${String(res.status)} from the access request` }\n }\n return interpretReply(JSON.parse(text) as unknown)\n}\n\n/** Follow up an access request that is waiting for approval. */\nexport async function pollAccess(base: string, href: string): Promise<AccessRequestResult> {\n const url = href.startsWith('/') ? `${base}${href}` : href\n if (!url.startsWith(`${base}/`)) {\n return { kind: 'error', message: 'the access request points to another server' }\n }\n try {\n return interpretReply(await getJson(url))\n } catch (error) {\n if (error instanceof PeerHttpError && error.status === 404) {\n return { kind: 'denied' }\n }\n throw error\n }\n}\n\nfunction interpretReply(raw: unknown): AccessRequestResult {\n const reply = raw as {\n state?: string\n href?: string\n accessRequest?: { permission?: string; token?: string }\n }\n if (reply.state === 'PENDING' && typeof reply.href === 'string') {\n return { kind: 'pending', href: reply.href }\n }\n if (reply.state === 'COMPLETED') {\n const token = reply.accessRequest?.token\n return token ? { kind: 'approved', token } : { kind: 'denied' }\n }\n return { kind: 'error', message: 'unexpected access request reply' }\n}\n","/**\n * Finds the other Signal K servers on the network, to offer them for pairing.\n *\n * Every Signal K server announces its REST API as `_signalk-http._tcp` (or\n * `_signalk-https._tcp`) over mDNS. The server's own discovery turns these\n * into data-connection suggestions only, so Multihelm asks for them itself\n * while it runs. Found servers are only shown; the user pairs with one.\n */\n\nimport os from 'node:os'\n\nimport makeMdns from 'multicast-dns'\nimport type { Answer, TxtAnswer } from 'dns-packet'\n\nimport { normalizePeerUrl } from './peer-client.js'\n\nconst SERVICES = ['_signalk-http._tcp.local', '_signalk-https._tcp.local']\nconst QUERY_INTERVAL_MS = 30_000\n/** A server not heard of for this long is dropped from the list. */\nconst FORGET_AFTER_MS = 3 * 60_000\n\nexport interface DiscoveredServer {\n /** The mDNS instance name, usually the host name. */\n name: string\n url: string\n /** The vessel name from the announcement, when it has one. */\n vessel?: string\n lastSeen: number\n}\n\ninterface Instance {\n service: string\n target?: string\n port?: number\n txt: Record<string, string>\n}\n\nfunction txtRecord(answer: TxtAnswer): Record<string, string> {\n const result: Record<string, string> = {}\n const data = Array.isArray(answer.data) ? answer.data : [answer.data]\n for (const entry of data) {\n const text = typeof entry === 'string' ? entry : Buffer.from(entry).toString('utf-8')\n const eq = text.indexOf('=')\n if (eq > 0) {\n result[text.slice(0, eq)] = text.slice(eq + 1)\n }\n }\n return result\n}\n\nfunction ownAddresses(): Set<string> {\n const result = new Set<string>()\n for (const list of Object.values(os.networkInterfaces())) {\n for (const info of list ?? []) {\n result.add(info.address)\n }\n }\n return result\n}\n\nexport class ServerDiscovery {\n private mdns: ReturnType<typeof makeMdns> | null = null\n private timer: NodeJS.Timeout | null = null\n private readonly instances = new Map<string, Instance>()\n private readonly addresses = new Map<string, string>()\n private readonly found = new Map<string, DiscoveredServer>()\n\n constructor(private readonly ownPort: () => number | undefined) {}\n\n start(): void {\n if (this.mdns) {\n return\n }\n try {\n this.mdns = makeMdns()\n } catch {\n this.mdns = null\n return\n }\n this.mdns.on('response', (response) => {\n this.takeRecords([...response.answers, ...response.additionals])\n })\n this.mdns.on('error', () => {\n // No multicast on this network; the list stays empty and pairing by address still works.\n })\n const query = (): void => {\n this.mdns?.query(SERVICES.map((name) => ({ name, type: 'PTR' as const })))\n }\n query()\n this.timer = setInterval(query, QUERY_INTERVAL_MS)\n }\n\n stop(): void {\n if (this.timer) {\n clearInterval(this.timer)\n this.timer = null\n }\n this.mdns?.destroy()\n this.mdns = null\n }\n\n list(): DiscoveredServer[] {\n const now = Date.now()\n for (const [key, server] of this.found) {\n if (now - server.lastSeen > FORGET_AFTER_MS) {\n this.found.delete(key)\n }\n }\n return [...this.found.values()].sort((a, b) => a.name.localeCompare(b.name))\n }\n\n /** Fold in the records of one mDNS response. */\n takeRecords(records: Answer[]): void {\n for (const record of records) {\n if (record.type === 'PTR' && SERVICES.includes(record.name)) {\n const instance = record.data\n if (!this.instances.has(instance)) {\n this.instances.set(instance, { service: record.name, txt: {} })\n }\n }\n }\n for (const record of records) {\n if (record.type === 'SRV') {\n const instance = this.instances.get(record.name)\n if (instance) {\n const srv = record.data\n instance.target = srv.target\n instance.port = srv.port\n }\n } else if (record.type === 'TXT') {\n const instance = this.instances.get(record.name)\n if (instance) {\n instance.txt = txtRecord(record)\n }\n } else if (record.type === 'A') {\n this.addresses.set(record.name, record.data)\n }\n }\n const own = ownAddresses()\n for (const [instance, info] of this.instances) {\n if (!info.target || info.port === undefined) {\n continue\n }\n const address = this.addresses.get(info.target)\n if (!address) {\n continue\n }\n if (own.has(address) && info.port === this.ownPort()) {\n continue\n }\n const scheme = info.service.startsWith('_signalk-https') ? 'https' : 'http'\n // Spelled as a paired peer's address is, so the two can be matched.\n const url = normalizePeerUrl(`${scheme}://${address}:${String(info.port)}`)\n if (!url) {\n continue\n }\n const server: DiscoveredServer = {\n name: instance.replace(`.${info.service}`, ''),\n url,\n lastSeen: Date.now()\n }\n if (info.txt.vname) {\n server.vessel = info.txt.vname\n }\n this.found.set(url, server)\n }\n }\n}\n","import { Type, type Static } from 'typebox'\n\nexport const ConfigSchema = Type.Object({\n master: Type.Boolean({\n title: \"This server is the boat's master\",\n description:\n 'Set this on one server only. Plugins that run on the master alone run here, and the other servers use them through this one.',\n default: false\n }),\n followVessel: Type.Boolean({\n title: 'Take the vessel data over from the master',\n description:\n \"Name, MMSI, call sign, dimensions and ship type from Server -> Settings. Changes made here are replaced by the master's.\",\n default: true\n }),\n followMetadata: Type.Boolean({\n title: 'Take the path metadata over from the master',\n description:\n \"Display names, units, zones and alarm limits set for paths. Changes made here are replaced by the master's.\",\n default: true\n }),\n followSourcePriorities: Type.Boolean({\n title: 'Take the source priorities over from the master',\n description:\n \"Which source wins for a path, from Data -> Source Priorities. They name sources by connection, so give the NMEA 2000 bus the same connection name on every server. Changes made here are replaced by the master's.\",\n default: true\n }),\n historyFromMaster: Type.Boolean({\n title: \"Answer this server's History API from the master\",\n description:\n \"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.\",\n default: true\n })\n})\n\n/** The settings as stored; any of them may be missing (see `start()`). */\nexport type Settings = Partial<Static<typeof ConfigSchema>>\n","/**\n * The source priorities the user set under Data -> Source Priorities, in the\n * shape of the server's `/skServer/priorities`: which source wins for a path\n * while it sends, and how long until the next one takes over.\n */\n\nexport interface PriorityGroup {\n id: string\n sources: string[]\n inactive?: boolean\n}\n\nexport interface PriorityEntry {\n sourceRef: string\n timeout: number\n}\n\nexport interface SourcePriorities {\n groups: PriorityGroup[]\n /** Signal K path -> its sources, best first. */\n overrides: Record<string, PriorityEntry[]>\n defaults: { fallbackMs?: number }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isText(value: unknown): value is string {\n return typeof value === 'string' && value !== ''\n}\n\nfunction group(value: unknown): PriorityGroup | null {\n if (\n !isRecord(value) ||\n !isText(value.id) ||\n !Array.isArray(value.sources) ||\n !(value.sources as unknown[]).every(isText) ||\n (value.inactive !== undefined && typeof value.inactive !== 'boolean')\n ) {\n return null\n }\n const sources = value.sources as string[]\n return value.inactive === undefined\n ? { id: value.id, sources }\n : { id: value.id, sources, inactive: value.inactive }\n}\n\n/** The server takes a timeout as an integer or a string of one, and keeps a number. */\nfunction entry(value: unknown): PriorityEntry | null {\n if (!isRecord(value) || !isText(value.sourceRef)) {\n return null\n }\n const timeout =\n typeof value.timeout === 'string' && /^-?\\d+$/.test(value.timeout)\n ? Number(value.timeout)\n : value.timeout\n return typeof timeout === 'number' && Number.isInteger(timeout)\n ? { sourceRef: value.sourceRef, timeout }\n : null\n}\n\nfunction allOrNull<T>(items: unknown[], parse: (item: unknown) => T | null): T[] | null {\n const parsed = items.map(parse)\n return parsed.every((item) => item !== null) ? parsed : null\n}\n\n/**\n * Null unless every part has the shape above: a priorities list cut short\n * would replace a server's whole set with less than the master meant.\n */\nexport function parseSourcePriorities(raw: unknown): SourcePriorities | null {\n if (!isRecord(raw) || !Array.isArray(raw.groups) || !isRecord(raw.overrides)) {\n return null\n }\n const groups = allOrNull(raw.groups as unknown[], group)\n const overrides: Record<string, PriorityEntry[]> = {}\n for (const [path, list] of Object.entries(raw.overrides)) {\n const entries = Array.isArray(list) ? allOrNull(list as unknown[], entry) : null\n if (!entries) {\n return null\n }\n overrides[path] = entries\n }\n const defaults = raw.defaults ?? {}\n if (!groups || !isRecord(defaults)) {\n return null\n }\n const { fallbackMs } = defaults\n if (fallbackMs === undefined) {\n return { groups, overrides, defaults: {} }\n }\n return typeof fallbackMs === 'number' && fallbackMs > 0 && Number.isFinite(fallbackMs)\n ? { groups, overrides, defaults: { fallbackMs } }\n : null\n}\n\n/** What this server holds in its settings, read the way `/skServer/priorities` answers. */\nexport function sourcePrioritiesFromSettings(settings: {\n priorityGroups?: unknown\n priorityOverrides?: unknown\n priorityDefaults?: unknown\n}): SourcePriorities | null {\n return parseSourcePriorities({\n groups: settings.priorityGroups ?? [],\n overrides: settings.priorityOverrides ?? {},\n defaults: settings.priorityDefaults ?? {}\n })\n}\n","/**\n * What the user set for this vessel on the server: the vessel data from\n * Server -> Settings and the metadata set for paths (display names, units,\n * zones). The server keeps both as its base deltas, sent again at every\n * start; they are the self vessel's part of those deltas.\n */\n\nimport { parseSourcePriorities, type SourcePriorities } from './source-priorities.js'\n\n/** The fields of the server's `/skServer/vessel` that follow the master. */\nexport interface VesselData {\n name?: string\n mmsi?: string\n uuid?: string\n draft?: number\n length?: number\n beam?: number\n height?: number\n aisShipType?: number\n callsignVhf?: string\n}\n\nexport const VESSEL_FIELDS = [\n 'name',\n 'mmsi',\n 'uuid',\n 'draft',\n 'length',\n 'beam',\n 'height',\n 'aisShipType',\n 'callsignVhf'\n] as const satisfies readonly (keyof VesselData)[]\n\nexport interface VesselSettings {\n vessel: VesselData\n /** Signal K path -> its metadata. */\n meta: Record<string, unknown>\n /** Absent from a server that does not send them, such as an older Multihelm. */\n priorities?: SourcePriorities\n}\n\nconst SELF = 'vessels.self'\n\n/** A path whose metadata can be read and written: dot-separated segments, none empty. */\nexport function isMetaPath(path: string): boolean {\n return /^[A-Za-z0-9_:-]+(\\.[A-Za-z0-9_:-]+)*$/.test(path)\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction pathValues(list: unknown): { path: string; value: unknown }[] {\n if (!Array.isArray(list)) {\n return []\n }\n return (list as unknown[]).flatMap((pv) =>\n isRecord(pv) && typeof pv.path === 'string' ? [{ path: pv.path, value: pv.value }] : []\n )\n}\n\nfunction text(value: unknown): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined\n}\n\nfunction num(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\nfunction field(value: unknown, key: string): unknown {\n return isRecord(value) ? value[key] : undefined\n}\n\nfunction vesselData(values: Map<string, unknown>): VesselData {\n const length = values.get('design.length')\n const data: VesselData = {\n name: text(values.get('name')),\n mmsi: text(values.get('mmsi')),\n uuid: text(values.get('uuid')),\n draft: num(field(values.get('design.draft'), 'maximum')),\n length: num(length) ?? num(field(length, 'overall')),\n beam: num(values.get('design.beam')),\n height: num(values.get('design.airHeight')),\n aisShipType: num(field(values.get('design.aisShipType'), 'id')),\n callsignVhf: text(field(values.get('communication'), 'callsignVhf'))\n }\n return Object.fromEntries(Object.entries(data).filter(([, v]) => v !== undefined))\n}\n\nexport function vesselSettingsFromDeltas(deltas: unknown): VesselSettings {\n const values = new Map<string, unknown>()\n const meta: Record<string, unknown> = {}\n if (Array.isArray(deltas)) {\n for (const delta of deltas as unknown[]) {\n if (!isRecord(delta) || delta.context !== SELF || !Array.isArray(delta.updates)) {\n continue\n }\n for (const update of delta.updates as unknown[]) {\n if (!isRecord(update)) {\n continue\n }\n for (const { path, value } of pathValues(update.values)) {\n if (path === '' && isRecord(value)) {\n for (const [k, v] of Object.entries(value)) {\n values.set(k, v)\n }\n } else if (path !== '') {\n values.set(path, value)\n }\n }\n for (const { path, value } of pathValues(update.meta)) {\n if (isMetaPath(path)) {\n meta[path] = value\n }\n }\n }\n }\n }\n return { vessel: vesselData(values), meta }\n}\n\n/** A peer's answer, kept to the shape above; anything else is dropped. */\nexport function parseVesselSettings(raw: unknown): VesselSettings | null {\n if (!isRecord(raw) || !isRecord(raw.vessel) || !isRecord(raw.meta)) {\n return null\n }\n const v = raw.vessel\n const vessel: VesselData = {}\n for (const key of ['name', 'mmsi', 'uuid', 'callsignVhf'] as const) {\n const t = text(v[key])\n if (t !== undefined) {\n vessel[key] = t\n }\n }\n for (const key of ['draft', 'length', 'beam', 'height', 'aisShipType'] as const) {\n const n = num(v[key])\n if (n !== undefined) {\n vessel[key] = n\n }\n }\n const meta: Record<string, unknown> = {}\n for (const [path, value] of Object.entries(raw.meta)) {\n if (isMetaPath(path) && isRecord(value)) {\n meta[path] = value\n }\n }\n const priorities = parseSourcePriorities(raw.priorities)\n return priorities ? { vessel, meta, priorities } : { vessel, meta }\n}\n","/**\n * On a server that is not the master: takes the vessel data, path metadata\n * and source priorities over from the master. They are read from the\n * master with the pairing token and written here through this server's own\n * REST API, the way its settings pages write them, so they survive a\n * restart. Writing needs an admin device token on this server, asked for\n * once; until it is approved nothing is written. Metadata of a path the\n * master has none for stays as it is, unless it was the master's before.\n */\n\nimport { isDeepStrictEqual } from 'node:util'\n\nimport {\n PeerHttpError,\n callServer,\n fetchVesselSettings,\n pollAccess,\n requestAccess,\n type AccessRequestResult\n} from './peer-client.js'\nimport type { SourcePriorities } from './source-priorities.js'\nimport type { MultihelmStore, OwnAccess } from './store.js'\nimport {\n VESSEL_FIELDS,\n parseVesselSettings,\n type VesselData,\n type VesselSettings\n} from './vessel-settings.js'\n\nexport interface FollowHost {\n store: MultihelmStore\n serverId: string\n /** This server, over loopback: `http(s)://127.0.0.1:<port>`. */\n ownUrl: () => string\n /** What this server holds now; null when the server does not expose it. */\n localSettings: () => VesselSettings | null\n /** The master to follow, or null when this server is the master or there is none. */\n master: () => { url: string; token: string } | null\n followVessel: boolean\n followMeta: boolean\n followPriorities: boolean\n debug: (msg: string) => void\n error: (msg: string) => void\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/** A master where none are set yet would wipe the ones a server kept from before Multihelm. */\nfunction hasPriorities(priorities: SourcePriorities): boolean {\n return priorities.groups.length > 0 || Object.keys(priorities.overrides).length > 0\n}\n\n/**\n * What was last written here and what this server kept of it, seen a round\n * later. A server may keep a value differently from how it was written (a\n * base delta file with the same path twice keeps the older one in force), so\n * a value is not written again until the master's or this server's changes.\n */\nclass WrittenValues {\n private readonly written = new Map<string, { target: unknown; kept?: { value: unknown } }>()\n\n /** Whether `target` is to be written over `local`. */\n due(key: string, target: unknown, local: unknown): boolean {\n if (isDeepStrictEqual(target, local)) {\n this.written.delete(key)\n return false\n }\n const last = this.written.get(key)\n if (last && isDeepStrictEqual(last.target, target)) {\n if (!last.kept) {\n last.kept = { value: local }\n return false\n }\n if (isDeepStrictEqual(last.kept.value, local)) {\n return false\n }\n }\n return true\n }\n\n wrote(key: string, target: unknown): void {\n this.written.set(key, { target })\n }\n\n /** What is not looked at in a round may have changed meanwhile, so it is forgotten. */\n keepOnly(keys: ReadonlySet<string>): void {\n for (const key of this.written.keys()) {\n if (!keys.has(key)) {\n this.written.delete(key)\n }\n }\n }\n}\n\nfunction metaUrl(base: string, path: string): string {\n const segments = path.split('.').map((s) => encodeURIComponent(s))\n return `${base}/signalk/v1/api/vessels/self/${segments.join('/')}/meta`\n}\n\nexport class MasterFollower {\n private access: OwnAccess\n private readonly prioritiesWritten = new WrittenValues()\n private readonly metaWritten = new WrittenValues()\n /**\n * The paths whose metadata is the master's: all it has, and the ones it\n * had until they are gone here too.\n */\n private followedMeta: Set<string>\n /** The list as last saved; a failed save is tried again the next round. */\n private followedMetaSaved: string\n\n constructor(private readonly host: FollowHost) {\n this.access = host.store.loadOwnAccess()\n const followed = host.store.loadFollowedMeta()\n this.followedMeta = new Set(followed)\n this.followedMetaSaved = JSON.stringify(followed.sort())\n }\n\n /** Whether the user has to approve this server's own access request. */\n waitingForApproval(): boolean {\n return this.access.state === 'waiting-approval'\n }\n\n /** The identifier of the access request on this server, as Security -> Access Requests lists it. */\n accessRequestId(): string {\n return `signalk-multihelm-self-${this.host.serverId}`\n }\n\n /** Whether the user denied it; it is asked for again only after a restart. */\n denied(): boolean {\n return this.access.state === 'denied'\n }\n\n async run(): Promise<void> {\n const { followVessel, followMeta, followPriorities } = this.host\n const master = this.host.master()\n const local = this.host.localSettings()\n if ((!followVessel && !followMeta && !followPriorities) || !master || !local) {\n return\n }\n let remote: VesselSettings | null\n try {\n remote = parseVesselSettings(await fetchVesselSettings(master.url, master.token))\n } catch (error) {\n this.host.debug(`Multihelm: vessel settings from the master: ${errorText(error)}`)\n return\n }\n if (!remote) {\n return\n }\n const vesselChanged =\n followVessel && VESSEL_FIELDS.some((k) => remote.vessel[k] !== local.vessel[k])\n if (followMeta) {\n this.followedMeta = new Set([\n ...Object.keys(remote.meta),\n ...[...this.followedMeta].filter((p) => local.meta[p] !== undefined)\n ])\n this.metaWritten.keepOnly(this.followedMeta)\n this.saveFollowedMeta()\n }\n const metaChanged = followMeta\n ? [...this.followedMeta].filter((p) => this.metaWritten.due(p, remote.meta[p], local.meta[p]))\n : []\n const priorities = followPriorities\n ? this.prioritiesToWrite(remote.priorities, local.priorities)\n : null\n if (!vesselChanged && metaChanged.length === 0 && !priorities) {\n return\n }\n const token = await this.ownToken()\n if (token === null) {\n return\n }\n const base = this.host.ownUrl()\n try {\n if (vesselChanged) {\n await this.writeVessel(base, token, remote.vessel)\n }\n for (const path of metaChanged) {\n const value = remote.meta[path]\n await (value === undefined\n ? callServer('DELETE', metaUrl(base, path), token)\n : callServer('PUT', metaUrl(base, path), token, { value }))\n this.metaWritten.wrote(path, value)\n }\n if (priorities) {\n await callServer('PUT', `${base}/skServer/priorities`, token, priorities)\n this.prioritiesWritten.wrote('', priorities)\n }\n } catch (error) {\n if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) {\n this.setAccess({ token: '', state: 'none' })\n }\n this.host.error(`Multihelm: taking over the master's vessel settings: ${errorText(error)}`)\n }\n if (followMeta) {\n this.saveFollowedMeta()\n }\n }\n\n private saveFollowedMeta(): void {\n const paths = [...this.followedMeta].sort()\n const text = JSON.stringify(paths)\n if (text === this.followedMetaSaved) {\n return\n }\n try {\n this.host.store.saveFollowedMeta(paths)\n this.followedMetaSaved = text\n } catch (error) {\n this.host.error(`Multihelm: saving the paths that follow the master: ${errorText(error)}`)\n }\n }\n\n private prioritiesToWrite(\n remote: SourcePriorities | undefined,\n local: SourcePriorities | undefined\n ): SourcePriorities | null {\n if (!remote || !hasPriorities(remote) || !local) {\n return null\n }\n return this.prioritiesWritten.due('', remote, local) ? remote : null\n }\n\n /** The vessel route writes every field, so the ones that stay here are sent back as they are. */\n private async writeVessel(base: string, token: string, vessel: VesselData): Promise<void> {\n const current = await callServer('GET', `${base}/skServer/vessel`, token)\n const body: Record<string, unknown> =\n typeof current === 'object' && current !== null ? { ...current } : {}\n for (const key of VESSEL_FIELDS) {\n body[key] = vessel[key]\n }\n await callServer('PUT', `${base}/skServer/vessel`, token, body)\n }\n\n private setAccess(access: OwnAccess): void {\n this.access = access\n this.host.store.saveOwnAccess(access)\n }\n\n private async ownToken(): Promise<string | null> {\n const base = this.host.ownUrl()\n if (this.access.state === 'granted') {\n return this.access.token\n }\n if (this.access.state === 'denied') {\n return null\n }\n let result: AccessRequestResult\n try {\n result =\n this.access.state === 'waiting-approval' && this.access.requestHref\n ? await pollAccess(base, this.access.requestHref)\n : await requestAccess(\n base,\n this.accessRequestId(),\n 'Multihelm: take the vessel settings over from the master',\n 'admin'\n )\n } catch (error) {\n this.host.debug(`Multihelm: access request on this server: ${errorText(error)}`)\n return null\n }\n switch (result.kind) {\n case 'no-security':\n this.setAccess({ token: '', state: 'granted' })\n return ''\n case 'approved':\n this.setAccess({ token: result.token, state: 'granted' })\n return result.token\n case 'pending':\n this.setAccess({ token: '', requestHref: result.href, state: 'waiting-approval' })\n return null\n case 'denied':\n this.host.store.saveOwnAccess({ token: '', state: 'none' })\n this.access = { token: '', state: 'denied' }\n return null\n case 'error':\n this.host.debug(`Multihelm: access request on this server: ${result.message}`)\n return null\n }\n }\n}\n","/**\n * On a server that is not the master, answers this server's History API\n * from the master's, so the history is kept once on the boat. It registers\n * as a history provider only while the master has one itself.\n */\n\nimport type {\n ContextsRequest,\n ContextsResponse,\n HistoryProvider,\n PathSpec,\n PathsRequest,\n PathsResponse,\n ValuesRequest,\n ValuesResponse\n} from '@signalk/server-api/history'\n\nimport type { MasterResponse, MasterRouteHandle } from './api.js'\n\nexport const HISTORY_PREFIX = '/signalk/v2/api/history/'\nconst HTTP_OK = 200\nconst HTTP_NOT_FOUND = 404\n\nexport interface MasterHistoryHost {\n registerMasterRoute: (prefix: string) => MasterRouteHandle\n fetchMaster: (path: string) => Promise<MasterResponse>\n /** This server is a member and another server is the master. */\n hasMaster: () => boolean\n register: (provider: HistoryProvider) => void\n unregister: () => void\n debug: (msg: string) => void\n}\n\ntype RangeRequest = ContextsRequest & { context?: string }\n\nfunction rangeParams(request: RangeRequest): URLSearchParams {\n const params = new URLSearchParams()\n if (request.from !== undefined) {\n params.set('from', request.from.toString())\n }\n if (request.to !== undefined) {\n params.set('to', request.to.toString())\n }\n if (request.duration !== undefined) {\n params.set('duration', request.duration.toString())\n }\n if (request.context !== undefined) {\n params.set('context', request.context)\n }\n return params\n}\n\nexport function pathExpression(spec: PathSpec): string {\n const parameters = spec.parameter.map((p) => `:${p}`).join('')\n const source = spec.sourceRef ? `|${spec.sourceRef}` : ''\n return `${spec.path}:${spec.aggregate}${parameters}${source}`\n}\n\nexport function valuesQuery(request: ValuesRequest): string {\n const params = rangeParams(request)\n params.set('paths', request.pathSpecs.map(pathExpression).join(','))\n if (request.resolution !== undefined) {\n params.set('resolution', String(request.resolution))\n }\n if (request.sourcePolicy !== undefined) {\n params.set('sourcePolicy', request.sourcePolicy)\n }\n return params.toString()\n}\n\n/** Before Signal K 2.32.0 a plugin cannot withdraw its history provider, so it must not register one. */\nexport function canWithdrawHistoryProvider(app: object): boolean {\n return (\n typeof (app as { unregisterHistoryApiProvider?: unknown }).unregisterHistoryApiProvider ===\n 'function'\n )\n}\n\nexport class MasterHistory {\n private registered = false\n /** Only the latest check may act on its answer; stop() outdates every check in flight. */\n private latestCheck = 0\n private route: MasterRouteHandle | null = null\n private readonly provider: HistoryProvider = {\n getValues: (request: ValuesRequest) =>\n this.read<ValuesResponse>(`values?${valuesQuery(request)}`),\n getPaths: (request: PathsRequest) =>\n this.read<PathsResponse>(`paths?${rangeParams(request).toString()}`),\n getContexts: (request: ContextsRequest) =>\n this.read<ContextsResponse>(`contexts?${rangeParams(request).toString()}`)\n }\n\n constructor(private readonly host: MasterHistoryHost) {}\n\n /** Registers while the master has a history provider, and withdraws otherwise. */\n async check(): Promise<void> {\n const thisCheck = ++this.latestCheck\n if (!this.host.hasMaster()) {\n this.withdraw()\n return\n }\n this.route ??= this.host.registerMasterRoute(HISTORY_PREFIX)\n let providers: unknown\n try {\n providers = await this.masterProviders()\n } catch (error) {\n // A master that answers again soon keeps serving the history meanwhile.\n this.host.debug(\n `Multihelm: cannot ask the master for its history providers: ${error instanceof Error ? error.message : String(error)}`\n )\n return\n }\n if (thisCheck !== this.latestCheck) {\n return\n }\n const masterHasHistory =\n typeof providers === 'object' && providers !== null && Object.keys(providers).length > 0\n if (masterHasHistory && this.host.hasMaster()) {\n if (!this.registered) {\n this.host.register(this.provider)\n this.registered = true\n this.host.debug(\"Multihelm: serving the master's history\")\n }\n } else {\n this.withdraw()\n }\n }\n\n stop(): void {\n this.latestCheck++\n this.withdraw()\n this.route?.unregister()\n this.route = null\n }\n\n private withdraw(): void {\n if (this.registered) {\n this.host.unregister()\n this.registered = false\n this.host.debug(\"Multihelm: no longer serving the master's history\")\n }\n }\n\n /** A master without the History API has no providers; any other failure says nothing. */\n private async masterProviders(): Promise<unknown> {\n const answer = await this.host.fetchMaster(`${HISTORY_PREFIX}_providers`)\n if (answer.status === HTTP_NOT_FOUND) {\n return {}\n }\n if (answer.status !== HTTP_OK) {\n throw new Error(`HTTP ${String(answer.status)}`)\n }\n return JSON.parse(answer.body.toString('utf-8')) as unknown\n }\n\n private async read<T>(query: string): Promise<T> {\n const answer = await this.host.fetchMaster(`${HISTORY_PREFIX}${query}`)\n if (answer.status !== HTTP_OK) {\n throw new Error(`the master's History API answered HTTP ${String(answer.status)}`)\n }\n return JSON.parse(answer.body.toString('utf-8')) as T\n }\n}\n","/**\n * Serves what the boat's master provides at this server's own\n * `/plugins/signalk-multihelm/master/<path>`, so a browser at this station\n * talks to its own server only: no token for the master, no CORS, no mixed\n * content. Only paths under a prefix a plugin registered are forwarded,\n * always to the paired master and with its readonly pairing token; the\n * caller's credentials stay here.\n */\n\nimport http from 'node:http'\nimport https from 'node:https'\n\nimport type { MasterResponse, MasterRouteHandle } from './api.js'\nimport { ROUTE_PREFIX } from './peer-client.js'\n\nexport const MASTER_ROUTE = '/master'\nconst REQUEST_TIMEOUT_MS = 30_000\n/** Largest body `fetch` reads into memory; the route itself streams. */\nconst MAX_FETCH_BYTES = 16 * 1024 * 1024\n\nconst SAFE_PATH = /^\\/[A-Za-z0-9\\-._~!$&'()*+,;=:@%/]*$/\n/** Encoded `.`, `/`, `\\` and NUL, which could turn into a traversal after decoding. */\nconst ENCODED_SEPARATOR = /%(2e|2f|5c|00)/i\nconst FORBIDDEN_PREFIXES = [\n '/admin',\n '/skServer',\n '/signalk/v1/access',\n '/signalk/v1/auth',\n `${ROUTE_PREFIX}/`\n]\n\nconst FORWARDED_REQUEST_HEADERS = [\n 'accept',\n 'accept-encoding',\n 'if-none-match',\n 'if-modified-since',\n 'range'\n]\nconst FORWARDED_RESPONSE_HEADERS = [\n 'accept-ranges',\n 'cache-control',\n 'content-encoding',\n 'content-length',\n 'content-range',\n 'content-type',\n 'etag',\n 'expires',\n 'last-modified',\n 'vary'\n]\n\nexport interface MasterAccess {\n url: string\n /** Empty when the master runs without security. */\n token: string\n}\n\nexport class MasterProxyError extends Error {\n constructor(\n readonly status: number,\n message: string\n ) {\n super(message)\n }\n}\n\nexport function isSafePath(path: string): boolean {\n if (!SAFE_PATH.test(path) || path.includes('//') || ENCODED_SEPARATOR.test(path)) {\n return false\n }\n return path\n .split('/')\n .slice(1)\n .every((segment) => segment !== '.' && segment !== '..')\n}\n\nexport function isValidPrefix(prefix: string): boolean {\n return (\n prefix.length > 1 &&\n prefix.endsWith('/') &&\n isSafePath(prefix) &&\n // Express and Signal K match routes regardless of case.\n !FORBIDDEN_PREFIXES.some((forbidden) =>\n prefix.toLowerCase().startsWith(forbidden.toLowerCase())\n )\n )\n}\n\nfunction headersFrom(source: http.IncomingHttpHeaders, names: string[]): Record<string, string> {\n const headers: Record<string, string> = {}\n for (const name of names) {\n const value = source[name]\n if (typeof value === 'string') {\n headers[name] = value\n }\n }\n return headers\n}\n\nexport class MasterProxy {\n private readonly prefixes = new Map<symbol, string>()\n private readonly agents = {\n http: new http.Agent({ keepAlive: true }),\n https: new https.Agent({ keepAlive: true })\n }\n\n constructor(private readonly master: () => MasterAccess | null) {}\n\n register(prefix: string): MasterRouteHandle {\n if (!isValidPrefix(prefix)) {\n throw new Error(`not a path prefix Multihelm forwards to the master: ${prefix}`)\n }\n const id = Symbol(prefix)\n this.prefixes.set(id, prefix)\n return {\n unregister: () => {\n this.prefixes.delete(id)\n }\n }\n }\n\n /** The path and query of `target` when it may be forwarded, else null. */\n allowed(target: string): string | null {\n const queryAt = target.indexOf('?')\n const path = queryAt === -1 ? target : target.slice(0, queryAt)\n if (!isSafePath(path)) {\n return null\n }\n for (const prefix of this.prefixes.values()) {\n // A collection is listed at the prefix without its slash.\n if (path.startsWith(prefix) || path === prefix.slice(0, -1)) {\n return target\n }\n }\n return null\n }\n\n /** Forwards a GET that arrived at `<route>/master<target>` and streams the answer back. */\n forward(target: string, req: http.IncomingMessage, res: http.ServerResponse): void {\n let upstream: http.ClientRequest\n try {\n upstream = this.request(target, headersFrom(req.headers, FORWARDED_REQUEST_HEADERS))\n } catch (error) {\n const status = error instanceof MasterProxyError ? error.status : 500\n res.statusCode = status\n res.setHeader('Content-Type', 'application/json')\n res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }))\n return\n }\n upstream.on('response', (answer) => {\n res.writeHead(\n answer.statusCode ?? 502,\n headersFrom(answer.headers, FORWARDED_RESPONSE_HEADERS)\n )\n answer.on('error', (error) => {\n res.destroy(error)\n })\n answer.pipe(res)\n })\n upstream.on('error', (error) => {\n if (res.headersSent) {\n res.destroy(error)\n return\n }\n res.statusCode = error.message.startsWith('timeout') ? 504 : 502\n res.setHeader('Content-Type', 'application/json')\n res.end(JSON.stringify({ error: `the master did not answer: ${error.message}` }))\n })\n res.on('close', () => {\n if (!res.writableFinished) {\n upstream.destroy()\n }\n })\n upstream.end()\n }\n\n /** Reads a path under a registered prefix from the master, for plugins on this server. */\n fetch(target: string): Promise<MasterResponse> {\n return new Promise((resolve, reject) => {\n const upstream = this.request(target, {})\n upstream.on('response', (answer) => {\n const chunks: Buffer[] = []\n let size = 0\n answer.on('data', (chunk: Buffer) => {\n size += chunk.length\n if (size > MAX_FETCH_BYTES) {\n upstream.destroy(new Error(`answer larger than ${String(MAX_FETCH_BYTES)} bytes`))\n return\n }\n chunks.push(chunk)\n })\n answer.on('end', () => {\n resolve({\n status: answer.statusCode ?? 0,\n headers: headersFrom(answer.headers, FORWARDED_RESPONSE_HEADERS),\n body: Buffer.concat(chunks)\n })\n })\n answer.on('error', reject)\n })\n upstream.on('error', reject)\n upstream.end()\n })\n }\n\n stop(): void {\n this.prefixes.clear()\n this.agents.http.destroy()\n this.agents.https.destroy()\n }\n\n private request(target: string, headers: Record<string, string>): http.ClientRequest {\n const allowed = this.allowed(target)\n if (allowed === null) {\n throw new MasterProxyError(404, 'no plugin forwards this path to the master')\n }\n const master = this.master()\n if (!master) {\n throw new MasterProxyError(503, 'no other server is the master now')\n }\n const url = new URL(`${master.url}${allowed}`)\n const secure = url.protocol === 'https:'\n const request = secure ? https.request : http.request\n const upstream = request(url, {\n method: 'GET',\n headers: master.token ? { ...headers, Authorization: `Bearer ${master.token}` } : headers,\n agent: secure ? this.agents.https : this.agents.http,\n timeout: REQUEST_TIMEOUT_MS\n })\n upstream.on('timeout', () => {\n upstream.destroy(new Error(`timeout after ${String(REQUEST_TIMEOUT_MS)} ms`))\n })\n return upstream\n }\n}\n","/**\n * One dataset's library: the entries this server holds, with the version\n * every server agrees on without a master.\n *\n * Each entry carries a counter and the server that last changed it. A local\n * change takes the counter one past the entry's current one, so a change\n * made after seeing a peer's version wins over it. Two servers changing the\n * same entry without seeing each other's change tie on the counter; the\n * higher server id wins, so every server picks the same one without\n * comparing clocks.\n */\n\nimport crypto from 'node:crypto'\n\nexport interface Version {\n counter: number\n /** The server id that made this version. */\n origin: string\n}\n\n/** A file of an entry as peers see it. */\nexport interface FileInfo {\n name: string\n size: number\n sha256: string\n}\n\n/** A file of an entry as this server holds it. */\nexport interface LocalFile {\n name: string\n size: number\n mtimeMs: number\n sha256?: string\n}\n\nexport interface Entry {\n key: string\n meta: unknown\n files: LocalFile[]\n /** Of `meta` and each file's name, size and time on this server; notices local changes. */\n fingerprint: string\n version: Version\n /** Set when the entry was deleted; it is kept as a tombstone. */\n deletedAt?: number\n /**\n * A peer's entry the dataset did not take (it lists nothing under the\n * key afterwards). Not a deletion: no tombstone is made for it.\n */\n declined?: boolean\n /** Local change sequence, for `manifest?since=`. */\n seq: number\n}\n\nexport interface RemoteEntry {\n key: string\n meta: unknown\n files: FileInfo[]\n version: Version\n deletedAt?: number\n}\n\nexport interface Library {\n seq: number\n entries: Record<string, Entry>\n}\n\nexport const TOMBSTONE_RETENTION_MS = 30 * 24 * 60 * 60 * 1000\n\n/** A file written less than this long ago may still be growing, so its entry waits. */\nexport const SETTLE_MS = 30_000\n\nconst FILE_NAME = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,127}$/\nconst SHA256 = /^[0-9a-f]{64}$/\n\n/** Positive when `a` wins over `b`, negative when `b` wins, 0 when equal. */\nexport function compareVersions(a: Version, b: Version): number {\n if (a.counter !== b.counter) {\n return a.counter - b.counter\n }\n if (a.origin === b.origin) {\n return 0\n }\n return a.origin > b.origin ? 1 : -1\n}\n\nexport function emptyLibrary(): Library {\n return { seq: 0, entries: {} }\n}\n\nexport function fingerprint(meta: unknown, files: readonly LocalFile[]): string {\n const canonical = JSON.stringify({\n meta: meta ?? null,\n files: [...files]\n .sort((a, b) => a.name.localeCompare(b.name))\n .map((f) => [f.name, f.size, f.mtimeMs])\n })\n return crypto.createHash('sha256').update(canonical).digest('hex')\n}\n\nexport function isValidFileName(name: string): boolean {\n return FILE_NAME.test(name) && !name.includes('..')\n}\n\n/** The shape checks every entry a peer sends must pass before anything else looks at it. */\nexport function isWellFormedRemote(raw: unknown): raw is RemoteEntry {\n if (typeof raw !== 'object' || raw === null) {\n return false\n }\n const entry = raw as Partial<RemoteEntry>\n if (\n typeof entry.key !== 'string' ||\n entry.key.length === 0 ||\n entry.key.length > 512 ||\n entry.key.includes('\\0') ||\n typeof entry.version?.counter !== 'number' ||\n !Number.isInteger(entry.version.counter) ||\n entry.version.counter < 1 ||\n typeof entry.version.origin !== 'string' ||\n !Array.isArray(entry.files)\n ) {\n return false\n }\n if (entry.deletedAt !== undefined && typeof entry.deletedAt !== 'number') {\n return false\n }\n const names = new Set<string>()\n for (const file of entry.files as unknown[]) {\n const f = file as Partial<FileInfo>\n if (\n typeof f.name !== 'string' ||\n !isValidFileName(f.name) ||\n names.has(f.name) ||\n typeof f.size !== 'number' ||\n !Number.isInteger(f.size) ||\n f.size < 0 ||\n typeof f.sha256 !== 'string' ||\n !SHA256.test(f.sha256)\n ) {\n return false\n }\n names.add(f.name)\n }\n return true\n}\n\n/** One entry as the dataset lists it now. */\nexport interface ListedEntry {\n key: string\n meta: unknown\n files: { name: string; size: number; mtimeMs: number }[]\n}\n\nexport interface ScanResult {\n /** Keys whose entry changed and needs its files hashed. */\n changed: string[]\n}\n\n/**\n * Bring the library up to date with what the dataset lists: new or changed\n * entries get a new local version (once their files have settled), entries\n * gone become tombstones, tombstones past retention are dropped.\n */\nexport function applyListing(\n library: Library,\n listed: readonly ListedEntry[],\n serverId: string,\n now: number\n): ScanResult {\n const changed: string[] = []\n const seen = new Set<string>()\n for (const item of listed) {\n seen.add(item.key)\n const prev = library.entries[item.key]\n const files: LocalFile[] = item.files.map((f) => ({\n name: f.name,\n size: f.size,\n mtimeMs: f.mtimeMs\n }))\n const print = fingerprint(item.meta, files)\n if (prev && prev.deletedAt === undefined && prev.fingerprint === print) {\n if (prev.declined) {\n delete prev.declined\n }\n continue\n }\n // A change of meta alone goes out at once; only a file may still be growing.\n const changedFiles = files.filter(\n (f) =>\n !prev?.files.some((o) => o.name === f.name && o.size === f.size && o.mtimeMs === f.mtimeMs)\n )\n if (changedFiles.some((f) => now - f.mtimeMs < SETTLE_MS)) {\n continue\n }\n // Keep the hashes of files that did not change.\n for (const file of files) {\n const old = prev?.files.find(\n (f) => f.name === file.name && f.size === file.size && f.mtimeMs === file.mtimeMs\n )\n if (old?.sha256 !== undefined) {\n file.sha256 = old.sha256\n }\n }\n library.seq++\n library.entries[item.key] = {\n key: item.key,\n meta: item.meta,\n files,\n fingerprint: print,\n version: { counter: (prev?.version.counter ?? 0) + 1, origin: serverId },\n seq: library.seq\n }\n changed.push(item.key)\n }\n for (const entry of Object.values(library.entries)) {\n if (seen.has(entry.key) || entry.declined) {\n continue\n }\n if (entry.deletedAt === undefined) {\n library.seq++\n library.entries[entry.key] = {\n key: entry.key,\n meta: null,\n files: [],\n fingerprint: '',\n version: { counter: entry.version.counter + 1, origin: serverId },\n deletedAt: now,\n seq: library.seq\n }\n } else if (now - entry.deletedAt > TOMBSTONE_RETENTION_MS) {\n Reflect.deleteProperty(library.entries, entry.key)\n }\n }\n return { changed }\n}\n\nfunction isOfferable(entry: Entry): boolean {\n return entry.deletedAt !== undefined || entry.files.every((f) => f.sha256 !== undefined)\n}\n\nexport function toRemote(entry: Entry): RemoteEntry {\n const remote: RemoteEntry = {\n key: entry.key,\n meta: entry.meta,\n files: entry.files.map((f) => ({ name: f.name, size: f.size, sha256: f.sha256 ?? '' })),\n version: entry.version\n }\n if (entry.deletedAt !== undefined) {\n remote.deletedAt = entry.deletedAt\n }\n return remote\n}\n\n/** Entries changed after `since`. One not hashed yet stops the page, so the cursor never skips it. */\nexport function manifestSince(\n library: Library,\n since: number\n): { cursor: number; entries: RemoteEntry[] } {\n let cursor = since\n const entries: RemoteEntry[] = []\n for (const entry of Object.values(library.entries).sort((a, b) => a.seq - b.seq)) {\n if (entry.seq <= since || entry.declined) {\n if (entry.seq > cursor) {\n cursor = entry.seq\n }\n continue\n }\n if (!isOfferable(entry)) {\n break\n }\n cursor = entry.seq\n entries.push(toRemote(entry))\n }\n return { cursor, entries }\n}\n\n/** Take over a peer's version, with what this server holds for it now (null: nothing). */\nexport function recordRemote(\n library: Library,\n remote: RemoteEntry,\n local: ListedEntry | null\n): void {\n library.seq++\n const files: LocalFile[] = local\n ? local.files.map((f) => {\n const file: LocalFile = { name: f.name, size: f.size, mtimeMs: f.mtimeMs }\n const sha256 = remote.files.find((r) => r.name === f.name && r.size === f.size)?.sha256\n if (sha256 !== undefined) {\n file.sha256 = sha256\n }\n return file\n })\n : []\n const entry: Entry = {\n key: remote.key,\n meta: local ? local.meta : remote.meta,\n files,\n fingerprint: local ? fingerprint(local.meta, files) : '',\n version: remote.version,\n seq: library.seq\n }\n if (remote.deletedAt !== undefined) {\n entry.deletedAt = remote.deletedAt\n } else if (!local) {\n entry.declined = true\n }\n library.entries[remote.key] = entry\n}\n","/**\n * Membership and dataset replication between the Signal K servers of a boat.\n *\n * Every server keeps a full copy of each registered dataset. Each round it\n * lists its own datasets, then asks every paired peer for the entries that\n * changed there and takes over those whose version wins over its own (see\n * `library.ts`). Replication has no master: any server may change or delete an\n * entry and the others follow, also a server that was off at the time.\n *\n * All work is serialized: a round, a pairing step and a registration never\n * run at the same time, so each library is changed by one of them at a time.\n */\n\nimport crypto from 'node:crypto'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { pipeline } from 'node:stream/promises'\n\nimport type {\n DatasetDefinition,\n DatasetEntry,\n DatasetHandle,\n IncomingEntry,\n PeerInfo,\n Role\n} from './api.js'\nimport {\n applyListing,\n compareVersions,\n isWellFormedRemote,\n manifestSince,\n recordRemote,\n type Library,\n type ListedEntry,\n type RemoteEntry\n} from './library.js'\nimport {\n PeerHttpError,\n downloadFile,\n fetchHello,\n fetchManifest,\n normalizePeerUrl,\n pollAccess,\n requestAccess,\n type AccessRequestResult,\n type Hello,\n type HelloFrom\n} from './peer-client.js'\nimport type { PairedByInfo } from './status.js'\nimport type { MultihelmStore, PairedServer, Peer } from './store.js'\n\nexport const PROTOCOL = 1\nexport const ROUND_INTERVAL_MS = 60_000\n/**\n * Paired peers are asked whether they are set to be the master this often,\n * on a timer of its own, so a long round of transfers does not hold it up.\n */\nexport const MASTER_CHECK_INTERVAL_MS = 30_000\n/**\n * A peer set to be the master counts as the master while it answered this\n * recently, so a few missed answers do not move the role.\n */\nexport const MASTER_STALE_MS = 5 * MASTER_CHECK_INTERVAL_MS\n/** Every peer asks every 30 s, so a sighting is saved only now and then. */\nconst PAIRED_BY_SAVE_MS = 10 * 60_000\n/** Without security anyone may ask, so writes of that list are gathered, never one per request. */\nconst PAIRED_BY_FLUSH_MS = 10_000\n/** Without security anyone may ask for `hello`; the list stays small. */\nconst MAX_PAIRED_BY = 32\n/** A pairing request waiting for approval is followed this often, so an approval shows at once. */\nexport const PAIRING_POLL_MS = 5_000\n/** Free space kept beyond an incoming file, as a fraction of its size. */\nconst FREE_SPACE_MARGIN = 0.05\n\nexport interface MultihelmHost {\n serverName: () => string\n /** The user set this server to be the boat's master. */\n isMaster: () => boolean\n /** What this server runs, for the peers to show. */\n versions?: () => { signalk?: string; multihelm?: string }\n debug: (msg: string) => void\n error: (msg: string) => void\n}\n\ninterface Dataset {\n definition: DatasetDefinition\n library: Library\n /** The last listing, for serving files: key → entry. */\n listed: Map<string, DatasetEntry>\n}\n\nexport async function hashFile(file: string): Promise<string> {\n const hash = crypto.createHash('sha256')\n await pipeline(fs.createReadStream(file), hash)\n return hash.digest('hex')\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/** Said without the address, which the panel shows anyway. */\nfunction helloErrorText(error: unknown): string {\n if (!(error instanceof PeerHttpError)) {\n return errorText(error)\n }\n switch (error.status) {\n case 404:\n return 'Multihelm is not running there'\n case 401:\n case 403:\n return 'access was revoked on the peer'\n default:\n return `HTTP ${String(error.status)}`\n }\n}\n\nfunction toListed(entry: DatasetEntry): ListedEntry {\n return {\n key: entry.key,\n meta: entry.meta,\n files: entry.files.map((f) => ({ name: f.name, size: f.size, mtimeMs: f.mtimeMs }))\n }\n}\n\nexport class Multihelm {\n private peers: Peer[]\n private readonly datasets = new Map<string, Dataset>()\n private queue: Promise<unknown> = Promise.resolve()\n private timer: NodeJS.Timeout | null = null\n private soon: NodeJS.Timeout | null = null\n /** Rounds run on their own between start and stop. */\n private started = false\n /** Set by stop: work under way ends at the next step. */\n private stopped = false\n /** Peer URL → when it last answered as set to be the master. */\n private readonly masterSeen = new Map<string, number>()\n /** Peer URL → its last `hello`, and when. */\n private readonly answers = new Map<string, { at: number; hello: Hello }>()\n /** Peer URL → why its last `hello` failed. */\n private readonly helloErrors = new Map<string, string>()\n /** Server id → a server that asks this one for its `hello`. */\n private readonly pairedBy: Map<string, PairedServer>\n private pairedBySavedAt = 0\n private pairedByTimer: NodeJS.Timeout | null = null\n private readonly roleListeners = new Set<(role: Role, master: PeerInfo | null) => void>()\n private readonly statusListeners = new Set<() => void>()\n /** What the role listeners were last told: role and master id. */\n private announcedRole = ''\n /** What the status listeners were last told: role, master id and conflict. */\n private announcedStatus = ''\n private masterTimer: NodeJS.Timeout | null = null\n private checkingMasters = false\n private pairingTimer: NodeJS.Timeout | null = null\n private pollingPairings = false\n readonly serverId: string\n\n constructor(\n private readonly store: MultihelmStore,\n private readonly host: MultihelmHost\n ) {\n this.peers = store.loadPeers()\n this.serverId = store.serverId()\n this.pairedBy = new Map(store.loadPairedBy().map((s) => [s.id, s]))\n }\n\n start(): void {\n this.started = true\n this.stopped = false\n const tick = (): void => {\n void this.runRound().finally(() => {\n if (!this.stopped) {\n this.timer = setTimeout(tick, ROUND_INTERVAL_MS)\n }\n })\n }\n this.timer = setTimeout(tick, 0)\n this.masterTimer = setInterval(() => {\n void this.checkMasters()\n }, MASTER_CHECK_INTERVAL_MS)\n this.pairingTimer = setInterval(() => {\n this.pollPairings().catch((error: unknown) => {\n this.host.error(`Multihelm: following a pairing request: ${errorText(error)}`)\n })\n }, PAIRING_POLL_MS)\n }\n\n stop(): void {\n this.started = false\n this.stopped = true\n for (const timer of [this.timer, this.soon]) {\n if (timer) {\n clearTimeout(timer)\n }\n }\n this.timer = null\n this.soon = null\n for (const timer of [this.masterTimer, this.pairingTimer]) {\n if (timer) {\n clearInterval(timer)\n }\n }\n this.masterTimer = null\n this.pairingTimer = null\n if (this.pairedByTimer) {\n clearTimeout(this.pairedByTimer)\n this.pairedByTimer = null\n this.savePairedBy()\n }\n }\n\n /**\n * Asks every paired peer whether it is set to be the master. Runs outside\n * the work queue and touches nothing but what it keeps of the answers, so it neither waits\n * for a round nor races one.\n */\n async checkMasters(): Promise<void> {\n if (this.checkingMasters || this.stopped) {\n return\n }\n this.checkingMasters = true\n try {\n await Promise.all(\n this.peers\n .filter((p) => p.state === 'paired' && p.id !== '')\n .map(async (peer) => {\n let hello\n try {\n hello = await fetchHello(peer.url, peer.token, this.helloFrom())\n } catch (error) {\n if (!this.stopped && this.peers.includes(peer)) {\n this.helloErrors.set(peer.url, helloErrorText(error))\n }\n return // It counts until its last answer is stale.\n }\n // Unpaired or stopped meanwhile, or another server at that address now.\n if (this.stopped || !this.peers.includes(peer) || hello.serverId !== peer.id) {\n return\n }\n this.answered(peer.url, hello)\n if (hello.master) {\n this.masterSeen.set(peer.url, Date.now())\n } else {\n this.masterSeen.delete(peer.url)\n }\n })\n )\n } finally {\n this.checkingMasters = false\n }\n // stop() may have run during the awaits above.\n if (!(this.stopped as boolean)) {\n this.announceRole()\n }\n }\n\n /**\n * Follows up the pairing requests waiting for approval, between rounds. At\n * most one waits in the queue, so a long round does not pile them up.\n */\n async pollPairings(): Promise<void> {\n const waiting = (): Peer[] => this.peers.filter((p) => p.state === 'waiting-approval')\n if (this.pollingPairings || this.stopped || waiting().length === 0) {\n return\n }\n this.pollingPairings = true\n try {\n await this.serialize(async () => {\n let paired = false\n for (const peer of waiting()) {\n if (this.stopped) {\n break\n }\n await this.pollPairingLocked(peer)\n paired ||= peer.state === 'paired'\n }\n this.store.savePeers(this.peers)\n this.announceRole()\n if (paired) {\n this.changedSoon()\n }\n })\n } finally {\n this.pollingPairings = false\n }\n }\n\n /** Run `task` after every task queued before it. */\n private serialize<T>(task: () => Promise<T>): Promise<T> {\n const run = this.queue.then(task, task)\n this.queue = run.catch(() => undefined)\n return run\n }\n\n // --- datasets -------------------------------------------------------\n\n registerDataset(definition: DatasetDefinition): DatasetHandle {\n if (this.datasets.has(definition.id)) {\n throw new Error(`dataset ${definition.id} is already registered`)\n }\n this.datasets.set(definition.id, {\n definition,\n library: this.store.loadLibrary(definition.id),\n listed: new Map()\n })\n this.changedSoon()\n return {\n changed: () => {\n this.changedSoon()\n },\n unregister: () => {\n if (this.datasets.get(definition.id)?.definition === definition) {\n this.datasets.delete(definition.id)\n }\n }\n }\n }\n\n datasetIds(): string[] {\n return [...this.datasets.keys()].sort()\n }\n\n /** A round a few seconds from now, so a burst of changes makes one round. */\n private changedSoon(): void {\n if (!this.started || this.soon) {\n return\n }\n this.soon = setTimeout(() => {\n this.soon = null\n void this.runRound()\n }, 2_000)\n }\n\n /** One listing of every dataset, then one round with every paired peer. */\n runRound(): Promise<void> {\n return this.serialize(async () => {\n for (const dataset of this.datasets.values()) {\n await this.listLocked(dataset)\n }\n for (const peer of this.peers) {\n if (this.stopped) {\n break\n }\n await this.pollPairingLocked(peer)\n if (peer.state === 'paired') {\n await this.helloLocked(peer)\n }\n if (peer.state === 'paired') {\n await this.syncPeerLocked(peer)\n }\n }\n this.store.savePeers(this.peers)\n this.announceRole()\n })\n }\n\n // --- master role ----------------------------------------------------\n\n /** The servers set to be the master that count now, this one included, smallest id first. */\n private masterCandidates(): { id: string; peer: Peer | null }[] {\n const now = Date.now()\n const candidates: { id: string; peer: Peer | null }[] = []\n if (this.host.isMaster()) {\n candidates.push({ id: this.serverId, peer: null })\n }\n for (const peer of this.peers) {\n const seen = this.masterSeen.get(peer.url)\n if (\n peer.state === 'paired' &&\n peer.id !== '' &&\n seen !== undefined &&\n now - seen <= MASTER_STALE_MS\n ) {\n candidates.push({ id: peer.id, peer })\n }\n }\n return candidates.sort((x, y) => (x.id < y.id ? -1 : x.id > y.id ? 1 : 0))\n }\n\n role(): Role {\n return this.masterCandidates()[0]?.peer === null ? 'master' : 'member'\n }\n\n master(): PeerInfo | null {\n const peer = this.masterCandidates()[0]?.peer\n return peer ? this.infoOf(peer) : null\n }\n\n /** Where to reach the master, with the pairing token; null when this server is it or there is none. */\n masterAccess(): { url: string; token: string } | null {\n const peer = this.masterCandidates()[0]?.peer\n return peer ? { url: peer.url, token: peer.token } : null\n }\n\n /** More than one server is set to be the master: the user should set one only. */\n masterConflict(): boolean {\n return this.masterCandidates().length > 1\n }\n\n /** Calls `cb` whenever the role, the master or `masterConflict()` changes. */\n onStatusChanged(cb: () => void): () => void {\n this.statusListeners.add(cb)\n return () => {\n this.statusListeners.delete(cb)\n }\n }\n\n onRoleChanged(cb: (role: Role, master: PeerInfo | null) => void): () => void {\n this.roleListeners.add(cb)\n return () => {\n this.roleListeners.delete(cb)\n }\n }\n\n private announceRole(): void {\n const role = this.role()\n const master = this.master()\n const now = `${role}:${master?.id ?? ''}`\n const status = `${now}:${String(this.masterConflict())}`\n if (now !== this.announcedRole) {\n this.announcedRole = now\n for (const cb of this.roleListeners) {\n try {\n cb(role, master)\n } catch (error) {\n this.host.error(`Multihelm: a role listener failed: ${errorText(error)}`)\n }\n }\n }\n if (status !== this.announcedStatus) {\n this.announcedStatus = status\n for (const cb of this.statusListeners) {\n try {\n cb()\n } catch (error) {\n this.host.error(`Multihelm: a status listener failed: ${errorText(error)}`)\n }\n }\n }\n }\n\n private async listLocked(dataset: Dataset): Promise<void> {\n const id = dataset.definition.id\n let listed: DatasetEntry[]\n try {\n listed = await dataset.definition.list()\n } catch (error) {\n this.host.error(`Multihelm: listing ${id} failed: ${errorText(error)}`)\n return\n }\n dataset.listed = new Map(listed.map((e) => [e.key, e]))\n const { changed } = applyListing(\n dataset.library,\n listed.map(toListed),\n this.serverId,\n Date.now()\n )\n for (const key of changed) {\n const entry = dataset.library.entries[key]\n const local = dataset.listed.get(key)\n if (!entry || !local) {\n continue\n }\n for (const file of entry.files) {\n if (this.stopped) {\n break\n }\n const source = local.files.find((f) => f.name === file.name)\n if (!source || file.sha256 !== undefined) {\n continue\n }\n try {\n file.sha256 = await hashFile(source.path)\n } catch (error) {\n this.host.debug(`Multihelm: cannot hash ${source.path}: ${errorText(error)}`)\n }\n }\n }\n // Hashes stay unknown for entries whose files could not be read: those are held back.\n this.store.saveLibrary(id, dataset.library)\n }\n\n // --- serving --------------------------------------------------------\n\n hello(): Hello {\n return {\n serverId: this.serverId,\n name: this.host.serverName(),\n protocol: PROTOCOL,\n datasets: this.datasetIds(),\n master: this.host.isMaster(),\n ...this.versions()\n }\n }\n\n private versions(): { signalk?: string; multihelm?: string } {\n const { signalk, multihelm } = this.host.versions?.() ?? {}\n return { ...(signalk ? { signalk } : {}), ...(multihelm ? { multihelm } : {}) }\n }\n\n private helloFrom(): HelloFrom {\n return { serverId: this.serverId, name: this.host.serverName(), ...this.versions() }\n }\n\n private answered(url: string, hello: Hello): void {\n this.answers.set(url, { at: Date.now(), hello })\n this.helloErrors.delete(url)\n }\n\n /**\n * Notes a server that asked for this one's `hello`. Its last sighting is\n * saved with any change to what it is, and otherwise once in a while.\n */\n sawPairedServer(from: HelloFrom): void {\n if (from.serverId === this.serverId) {\n return\n }\n const now = Date.now()\n const known = this.pairedBy.get(from.serverId)\n const server: PairedServer = {\n id: from.serverId,\n name: from.name,\n ...(from.signalk ? { signalk: from.signalk } : {}),\n ...(from.multihelm ? { multihelm: from.multihelm } : {}),\n lastSeen: now\n }\n this.pairedBy.set(server.id, server)\n if (this.pairedBy.size > MAX_PAIRED_BY) {\n const oldest = [...this.pairedBy.values()].sort((x, y) => x.lastSeen - y.lastSeen)[0]\n if (oldest) {\n this.pairedBy.delete(oldest.id)\n }\n }\n const changed =\n !known ||\n known.name !== server.name ||\n known.signalk !== server.signalk ||\n known.multihelm !== server.multihelm\n if (changed || now - this.pairedBySavedAt >= PAIRED_BY_SAVE_MS) {\n this.savePairedBySoon()\n }\n }\n\n /** The servers paired with this one, by name. */\n pairedByInfo(): PairedByInfo[] {\n const now = Date.now()\n return [...this.pairedBy.values()]\n .sort((x, y) => x.name.localeCompare(y.name))\n .map((s) => ({ ...s, online: now - s.lastSeen <= MASTER_STALE_MS }))\n }\n\n /** Drops a server from that list; it comes back when it asks again. */\n forgetPairedBy(id: string): boolean {\n const removed = this.pairedBy.delete(id)\n if (removed) {\n this.savePairedBy()\n }\n return removed\n }\n\n private savePairedBySoon(): void {\n if (this.pairedByTimer) {\n return\n }\n this.pairedByTimer = setTimeout(() => {\n this.pairedByTimer = null\n this.savePairedBy()\n }, PAIRED_BY_FLUSH_MS)\n this.pairedByTimer.unref()\n }\n\n private savePairedBy(): void {\n this.pairedBySavedAt = Date.now()\n try {\n this.store.savePairedBy([...this.pairedBy.values()])\n } catch (error) {\n this.host.error(`Multihelm: saving the servers paired with this one: ${errorText(error)}`)\n }\n }\n\n manifest(datasetId: string, since: number): { cursor: number; entries: RemoteEntry[] } | null {\n const dataset = this.datasets.get(datasetId)\n return dataset ? manifestSince(dataset.library, since) : null\n }\n\n /** Absolute path of a file this server offers, or null. */\n servableFile(datasetId: string, key: string, name: string): string | null {\n const dataset = this.datasets.get(datasetId)\n const entry = dataset?.library.entries[key]\n if (!dataset || !entry || entry.deletedAt !== undefined) {\n return null\n }\n const file = entry.files.find((f) => f.name === name)\n const local = dataset.listed.get(key)?.files.find((f) => f.name === name)\n if (!file?.sha256 || !local || local.size !== file.size || local.mtimeMs !== file.mtimeMs) {\n return null\n }\n return local.path\n }\n\n // --- pulling --------------------------------------------------------\n\n /** Errors with one dataset are cleared by that dataset's next sync. */\n private isDatasetError(text: string): boolean {\n return [...this.datasets.keys()].some((id) => text.startsWith(`${id}:`))\n }\n\n private async syncPeerLocked(peer: Peer): Promise<void> {\n try {\n for (const dataset of this.datasets.values()) {\n if (this.stopped) {\n return\n }\n await this.syncDatasetLocked(peer, dataset)\n }\n peer.lastSync = Date.now()\n if (peer.lastError !== undefined && !this.isDatasetError(peer.lastError)) {\n delete peer.lastError\n }\n } catch (error) {\n if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) {\n peer.state = 'needs-pairing'\n peer.lastError = 'access was revoked on the peer'\n } else {\n peer.lastError = errorText(error)\n }\n this.host.debug(`Multihelm: ${peer.name}: ${peer.lastError}`)\n }\n }\n\n private async syncDatasetLocked(peer: Peer, dataset: Dataset): Promise<void> {\n const id = dataset.definition.id\n let manifest\n try {\n manifest = await fetchManifest(peer.url, peer.token, id, peer.cursors[id] ?? 0)\n } catch (error) {\n if (error instanceof PeerHttpError && error.status === 404) {\n if (peer.lastError?.startsWith(`${id}:`)) {\n delete peer.lastError\n }\n return // The peer does not have this dataset.\n }\n throw error\n }\n try {\n for (const raw of manifest.entries) {\n if (this.stopped) {\n return\n }\n // Stop at the first entry that fails, so the cursor never skips it.\n if (!(await this.applyRemote(peer, dataset, raw))) {\n return\n }\n }\n peer.cursors[id] = manifest.cursor\n if (peer.lastError?.startsWith(`${id}:`)) {\n delete peer.lastError\n }\n } finally {\n this.store.saveLibrary(id, dataset.library)\n }\n }\n\n /** Apply one entry of a peer's manifest; false when it failed and is tried again. */\n private async applyRemote(peer: Peer, dataset: Dataset, raw: unknown): Promise<boolean> {\n const { definition, library } = dataset\n if (!isWellFormedRemote(raw) || (definition.isValidKey && !definition.isValidKey(raw.key))) {\n this.host.debug(`Multihelm: ignoring a malformed ${definition.id} entry from ${peer.name}`)\n return true\n }\n const remote = raw\n const local = library.entries[remote.key]\n if (local && compareVersions(remote.version, local.version) <= 0) {\n return true\n }\n const fail = (error: unknown): false => {\n peer.lastError = `${definition.id}: ${remote.key}: ${errorText(error)}`\n this.host.debug(`Multihelm: ${peer.lastError}`)\n return false\n }\n\n if (remote.deletedAt !== undefined) {\n if (!local || local.deletedAt !== undefined || local.declined) {\n recordRemote(library, remote, null)\n return true\n }\n try {\n if (await definition.remove(remote.key)) {\n recordRemote(library, remote, null)\n } else {\n // Kept here: offer it back as this server's change.\n library.seq++\n library.entries[remote.key] = {\n ...local,\n version: { counter: remote.version.counter + 1, origin: this.serverId },\n seq: library.seq\n }\n }\n return true\n } catch (error) {\n return fail(error)\n }\n }\n\n try {\n const incoming = await this.fetchFiles(peer, dataset, remote)\n if (!incoming) {\n return false\n }\n await definition.apply(incoming)\n await this.cleanIncoming(definition.id, incoming)\n const after = (await definition.list()).find((e) => e.key === remote.key)\n if (after) {\n dataset.listed.set(after.key, after)\n }\n recordRemote(library, remote, after ? toListed(after) : null)\n return true\n } catch (error) {\n return fail(error)\n }\n }\n\n /** The peer's entry with every file verified on this server's disk, or null on failure. */\n private async fetchFiles(\n peer: Peer,\n dataset: Dataset,\n remote: RemoteEntry\n ): Promise<IncomingEntry | null> {\n const id = dataset.definition.id\n const mine = dataset.library.entries[remote.key]\n const listed = dataset.listed.get(remote.key)\n const incomingDir = this.store.incomingDir(id)\n await fs.promises.mkdir(incomingDir, { recursive: true })\n const files: IncomingEntry['files'] = []\n for (const file of remote.files) {\n const have = mine?.files.find(\n (f) => f.name === file.name && f.sha256 === file.sha256 && f.size === file.size\n )\n const own = have ? listed?.files.find((f) => f.name === file.name) : undefined\n if (own && own.size === file.size) {\n files.push({\n name: file.name,\n path: own.path,\n size: file.size,\n sha256: file.sha256,\n unchanged: true\n })\n continue\n }\n const dest = path.join(incomingDir, file.sha256)\n const already = await fs.promises.stat(dest).then(\n (s) => s.size,\n () => 0\n )\n if (already > file.size) {\n await fs.promises.rm(dest, { force: true })\n }\n if (already !== file.size) {\n const free = await fs.promises.statfs(incomingDir)\n if (free.bavail * free.bsize < (file.size - already) * (1 + FREE_SPACE_MARGIN)) {\n peer.lastError = `${id}: not enough free space for ${remote.key}`\n return null\n }\n this.host.debug(`Multihelm: fetching ${id} ${remote.key} ${file.name} from ${peer.name}`)\n await downloadFile(\n peer.url,\n peer.token,\n { dataset: id, key: remote.key, name: file.name },\n dest\n )\n }\n const size = (await fs.promises.stat(dest)).size\n if (size !== file.size || (await hashFile(dest)) !== file.sha256) {\n await fs.promises.rm(dest, { force: true })\n peer.lastError = `${id}: ${remote.key} arrived damaged; it is fetched again`\n return null\n }\n files.push({\n name: file.name,\n path: dest,\n size: file.size,\n sha256: file.sha256,\n unchanged: false\n })\n }\n return { key: remote.key, meta: remote.meta, files }\n }\n\n /** Files the dataset copied rather than moved are left in the work folder; remove them. */\n private async cleanIncoming(datasetId: string, entry: IncomingEntry): Promise<void> {\n const dir = this.store.incomingDir(datasetId)\n for (const file of entry.files) {\n if (!file.unchanged && path.dirname(file.path) === dir) {\n await fs.promises.rm(file.path, { force: true })\n }\n }\n }\n\n // --- peers ----------------------------------------------------------\n\n peerInfo(): PeerInfo[] {\n return this.peers.map((p) => this.infoOf(p))\n }\n\n private infoOf(p: Peer): PeerInfo {\n const info: PeerInfo = { id: p.id, name: p.name, url: p.url, state: p.state }\n if (p.lastSeen !== undefined) {\n info.lastSeen = p.lastSeen\n }\n if (p.lastSync !== undefined) {\n info.lastSync = p.lastSync\n }\n if (p.lastError !== undefined) {\n info.lastError = p.lastError\n }\n const now = Date.now()\n const answer = this.answers.get(p.url)\n if (answer) {\n info.lastSeen = Math.max(info.lastSeen ?? 0, answer.at)\n if (answer.hello.signalk) {\n info.signalk = answer.hello.signalk\n }\n if (answer.hello.multihelm) {\n info.multihelm = answer.hello.multihelm\n }\n }\n const helloError = this.helloErrors.get(p.url)\n if (helloError !== undefined && p.state === 'paired') {\n info.lastError = helloError\n }\n if (p.state === 'paired') {\n info.online = info.lastSeen !== undefined && now - info.lastSeen <= MASTER_STALE_MS\n }\n const seen = this.masterSeen.get(p.url)\n if (seen !== undefined && now - seen <= MASTER_STALE_MS) {\n info.master = true\n }\n return info\n }\n\n /**\n * Pair with the server at `input`: without security it is paired at once,\n * otherwise a readonly device access request waits for approval there.\n */\n pair(input: string): Promise<PeerInfo> {\n return this.serialize(async () => {\n const url = normalizePeerUrl(input)\n if (!url) {\n throw new Error('not a server address')\n }\n let peer = this.peers.find((p) => p.url === url)\n if (!peer) {\n peer = { id: '', name: url, url, token: '', state: 'needs-pairing', cursors: {} }\n this.peers.push(peer)\n }\n const result = await requestAccess(\n url,\n `signalk-multihelm-${this.serverId}-${crypto.randomUUID().slice(0, 8)}`,\n `Multihelm on ${this.host.serverName()}`\n )\n this.applyAccessResult(peer, result)\n if (peer.state === 'paired') {\n await this.helloLocked(peer)\n }\n this.store.savePeers(this.peers)\n const info = this.peerInfo().find((p) => p.url === url)\n if (!info) {\n throw new Error('peer vanished')\n }\n if (peer.state === 'paired') {\n this.changedSoon()\n }\n return info\n })\n }\n\n unpair(url: string): Promise<boolean> {\n return this.serialize(() => {\n const before = this.peers.length\n this.peers = this.peers.filter((p) => p.url !== url)\n this.masterSeen.delete(url)\n this.answers.delete(url)\n this.helloErrors.delete(url)\n this.store.savePeers(this.peers)\n this.announceRole()\n return Promise.resolve(this.peers.length !== before)\n })\n }\n\n private applyAccessResult(peer: Peer, result: AccessRequestResult): void {\n switch (result.kind) {\n case 'no-security':\n peer.token = ''\n peer.state = 'paired'\n delete peer.requestHref\n break\n case 'approved':\n peer.token = result.token\n peer.state = 'paired'\n delete peer.requestHref\n delete peer.lastError\n break\n case 'pending':\n peer.requestHref = result.href\n peer.state = 'waiting-approval'\n break\n case 'denied':\n peer.state = 'needs-pairing'\n delete peer.requestHref\n peer.lastError = 'the access request was denied'\n break\n case 'error':\n peer.state = 'needs-pairing'\n peer.lastError = result.message\n break\n }\n }\n\n private async pollPairingLocked(peer: Peer): Promise<void> {\n if (peer.state !== 'waiting-approval' || !peer.requestHref) {\n return\n }\n try {\n this.applyAccessResult(peer, await pollAccess(peer.url, peer.requestHref))\n // applyAccessResult changed the state; read it afresh.\n if ((peer.state as Peer['state']) === 'paired') {\n await this.helloLocked(peer)\n }\n } catch (error) {\n peer.lastError = errorText(error)\n }\n }\n\n private async helloLocked(peer: Peer): Promise<void> {\n try {\n const hello = await fetchHello(peer.url, peer.token, this.helloFrom())\n if (hello.serverId === this.serverId) {\n peer.state = 'needs-pairing'\n peer.lastError = 'this is this server itself'\n return\n }\n peer.id = hello.serverId\n peer.name = hello.name\n peer.lastSeen = Date.now()\n this.answered(peer.url, hello)\n if (hello.master) {\n this.masterSeen.set(peer.url, peer.lastSeen)\n } else {\n this.masterSeen.delete(peer.url)\n }\n } catch (error) {\n this.helloErrors.set(peer.url, helloErrorText(error))\n }\n }\n}\n","/**\n * Routes under `/plugins/signalk-multihelm/`.\n *\n * Peers read `hello`, `manifest`, `file` and `vessel-settings` with the readonly device token\n * they got when pairing, so those are registered with readonly access\n * (`router.access`, signalk-server 2.31 and later). Without it plugin routes\n * are admin-only, a readonly token cannot reach them, and `status` says\n * Multihelm is unavailable. `master/…` serves the master's answers to anyone\n * who may read here. Pairing and the status page stay admin-only.\n */\n\nimport type { IRouter, Request, Response } from 'express'\n\nimport type { DiscoveredServer } from './discovery.js'\nimport { MASTER_ROUTE, type MasterProxy } from './master-proxy.js'\nimport type { Multihelm } from './multihelm.js'\nimport type { HelloFrom } from './peer-client.js'\nimport type { OwnAccessState, Status } from './status.js'\nimport type { VesselSettings } from './vessel-settings.js'\n\ntype Handler = (req: Request, res: Response) => void | Promise<void>\n\ninterface AccessScopedRouter {\n get: (path: string, handler: Handler) => AccessScopedRouter\n}\n\ntype RouterWithAccess = IRouter & {\n access?: (level: 'readonly' | 'readwrite' | 'admin') => AccessScopedRouter\n}\n\nconst MAX_URL_LENGTH = 300\n\nfunction queryString(req: Request, name: string): string {\n const value = (req.query as Record<string, unknown>)[name]\n return typeof value === 'string' ? value : ''\n}\n\nconst SERVER_ID = /^[\\w-]{1,64}$/\nconst VERSION = /^[\\w.+-]{1,32}$/\n\n/** The server asking, when it said; what does not fit is left out. */\nfunction helloFrom(req: Request): HelloFrom | null {\n const serverId = queryString(req, 'from')\n const name = queryString(req, 'name').trim().slice(0, 100)\n if (!SERVER_ID.test(serverId) || name === '') {\n return null\n }\n const signalk = queryString(req, 'signalk')\n const multihelm = queryString(req, 'multihelm')\n return {\n serverId,\n name,\n ...(VERSION.test(signalk) ? { signalk } : {}),\n ...(VERSION.test(multihelm) ? { multihelm } : {})\n }\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nexport function registerRoutes(\n router: IRouter,\n multihelm: () => Multihelm | null,\n discovered: () => DiscoveredServer[],\n vesselSettings: () => VesselSettings | null = () => null,\n masterProxy: () => MasterProxy | null = () => null,\n ownAccess: () => OwnAccessState = () => null\n): void {\n const scoped = (router as RouterWithAccess).access\n const available = typeof scoped === 'function'\n const readonly: AccessScopedRouter = available\n ? scoped.call(router, 'readonly')\n : {\n get(path, handler) {\n router.get(path, handler)\n return this\n }\n }\n\n const running =\n (handler: (mh: Multihelm, req: Request, res: Response) => void | Promise<void>) =>\n async (req: Request, res: Response): Promise<void> => {\n const mh = multihelm()\n if (!mh) {\n res.status(503).json({ error: 'Multihelm is not running' })\n return\n }\n try {\n await handler(mh, req, res)\n } catch (error) {\n res.status(500).json({ error: errorText(error) })\n }\n }\n\n readonly.get(\n '/hello',\n running((mh, req, res) => {\n const from = helloFrom(req)\n if (from) {\n mh.sawPairedServer(from)\n }\n res.json(mh.hello())\n })\n )\n\n readonly.get(\n '/vessel-settings',\n running((_mh, _req, res) => {\n const settings = vesselSettings()\n if (!settings) {\n res.status(501).json({ error: 'this server does not expose its vessel settings' })\n return\n }\n res.json(settings)\n })\n )\n\n readonly.get(\n '/manifest',\n running((mh, req, res) => {\n const since = Number(queryString(req, 'since') || '0')\n if (!Number.isInteger(since) || since < 0) {\n res.status(400).json({ error: 'since must be a non-negative integer' })\n return\n }\n const manifest = mh.manifest(queryString(req, 'dataset'), since)\n if (!manifest) {\n res.status(404).json({ error: 'no such dataset' })\n return\n }\n res.json(manifest)\n })\n )\n\n readonly.get(\n '/file',\n running((mh, req, res) => {\n const file = mh.servableFile(\n queryString(req, 'dataset'),\n queryString(req, 'key'),\n queryString(req, 'file')\n )\n if (!file) {\n res.status(404).json({ error: 'no such file' })\n return\n }\n // Only files the dataset lists get here; the server's data dir sits under `.signalk`.\n res.sendFile(file, { acceptRanges: true, dotfiles: 'allow' })\n })\n )\n\n const forwardToMaster: Handler = (req, res) => {\n const proxy = masterProxy()\n if (!proxy) {\n res.status(503).json({ error: 'Multihelm is not running' })\n return\n }\n proxy.forward(req.url.slice(MASTER_ROUTE.length), req, res)\n }\n // The master's answer goes to whoever may read here; this server's own security decides who that is.\n // Express 4, which signalk-server runs, and Express 5 spell a wildcard differently.\n try {\n readonly.get(`${MASTER_ROUTE}/*`, forwardToMaster)\n } catch {\n readonly.get(`${MASTER_ROUTE}/*path`, forwardToMaster)\n }\n\n router.get('/status', (_req: Request, res: Response) => {\n const mh = multihelm()\n const status: Status = {\n available,\n running: mh !== null,\n serverId: mh?.serverId ?? null,\n name: mh?.hello().name ?? '',\n role: mh?.role() ?? null,\n master: mh?.master() ?? null,\n masterConflict: mh?.masterConflict() ?? false,\n datasets: mh?.datasetIds() ?? [],\n peers: mh?.peerInfo() ?? [],\n pairedBy: mh?.pairedByInfo() ?? [],\n discovered: mh ? discovered() : [],\n ownAccess: mh ? ownAccess() : null\n }\n res.json(status)\n })\n\n router.post(\n '/peers',\n running(async (mh, req, res) => {\n const url = (req.body as { url?: unknown } | undefined)?.url\n if (typeof url !== 'string' || url.length === 0 || url.length > MAX_URL_LENGTH) {\n res.status(400).json({ error: 'url is required' })\n return\n }\n try {\n res.json(await mh.pair(url))\n } catch (error) {\n res.status(400).json({ error: errorText(error) })\n }\n })\n )\n\n router.delete(\n '/peers',\n running(async (mh, req, res) => {\n const url = queryString(req, 'url')\n res.status((await mh.unpair(url)) ? 200 : 404).json({ removed: url })\n })\n )\n\n router.delete(\n '/paired-by',\n running((mh, req, res) => {\n const id = queryString(req, 'id')\n res.status(mh.forgetPairedBy(id) ? 200 : 404).json({ removed: id })\n })\n )\n\n router.post(\n '/run',\n running((mh, _req, res) => {\n void mh.runRound()\n res.status(202).json({ started: true })\n })\n )\n}\n","/**\n * Multihelm state on disk, in the plugin's data dir: this server's id, its\n * paired peers and one library per dataset. Peers hold access tokens, so\n * their file is readable by the server's user only.\n */\n\nimport crypto from 'node:crypto'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { Type, type Static } from 'typebox'\nimport { Value } from 'typebox/value'\n\nimport { emptyLibrary, type Library } from './library.js'\n\nexport const PeerSchema = Type.Object({\n /** The peer's server id, from its `hello`; empty until it answered once. */\n id: Type.String(),\n name: Type.String(),\n /** Base URL of the peer's Signal K server, e.g. `http://192.168.1.20:3000`. */\n url: Type.String(),\n /** Readonly device token; empty when the peer runs without security. */\n token: Type.String(),\n /** Set while an access request waits for approval on the peer. */\n requestHref: Type.Optional(Type.String()),\n state: Type.Union([\n Type.Literal('waiting-approval'),\n Type.Literal('paired'),\n Type.Literal('needs-pairing')\n ]),\n /** Per dataset, the peer's change sequence this server has applied up to. */\n cursors: Type.Record(Type.String(), Type.Integer({ minimum: 0 })),\n lastSeen: Type.Optional(Type.Number()),\n lastSync: Type.Optional(Type.Number()),\n lastError: Type.Optional(Type.String())\n})\n\nexport type Peer = Static<typeof PeerSchema>\n\nconst PeersFileSchema = Type.Array(PeerSchema)\n\n/** This server's admin device token on itself, for writing what follows the master. */\nexport const OwnAccessSchema = Type.Object({\n token: Type.String(),\n requestHref: Type.Optional(Type.String()),\n state: Type.Union([\n Type.Literal('none'),\n Type.Literal('waiting-approval'),\n Type.Literal('granted'),\n Type.Literal('denied')\n ])\n})\n\nexport type OwnAccess = Static<typeof OwnAccessSchema>\n\nconst PathsFileSchema = Type.Array(Type.String())\n\n/** A server that asked this one for its `hello`, which a server does while paired with it. */\nexport const PairedServerSchema = Type.Object({\n id: Type.String(),\n name: Type.String(),\n signalk: Type.Optional(Type.String()),\n multihelm: Type.Optional(Type.String()),\n lastSeen: Type.Number()\n})\n\nexport type PairedServer = Static<typeof PairedServerSchema>\n\nconst PairedServersFileSchema = Type.Array(PairedServerSchema)\n\nconst LibraryFileSchema = Type.Object({\n seq: Type.Integer({ minimum: 0 }),\n entries: Type.Record(Type.String(), Type.Any())\n})\n\nfunction writeAtomic(file: string, data: string, mode?: number): void {\n const tmp = `${file}.${String(process.pid)}.tmp`\n fs.writeFileSync(tmp, data, mode === undefined ? undefined : { mode })\n fs.renameSync(tmp, file)\n}\n\nfunction readJson(file: string): unknown {\n try {\n return JSON.parse(fs.readFileSync(file, 'utf-8')) as unknown\n } catch {\n return undefined\n }\n}\n\nexport class MultihelmStore {\n readonly dir: string\n\n constructor(dataDir: string) {\n this.dir = dataDir\n fs.mkdirSync(path.join(dataDir, 'datasets'), { recursive: true })\n }\n\n /** Where a peer's files for `dataset` wait until they are verified and applied. */\n incomingDir(dataset: string): string {\n return path.join(this.dir, 'incoming', encodeURIComponent(dataset))\n }\n\n private libraryFile(dataset: string): string {\n return path.join(this.dir, 'datasets', `${encodeURIComponent(dataset)}.json`)\n }\n\n loadLibrary(dataset: string): Library {\n const raw = readJson(this.libraryFile(dataset))\n return Value.Check(LibraryFileSchema, raw) ? raw : emptyLibrary()\n }\n\n saveLibrary(dataset: string, library: Library): void {\n writeAtomic(this.libraryFile(dataset), JSON.stringify(library))\n }\n\n loadPeers(): Peer[] {\n const raw = readJson(path.join(this.dir, 'peers.json'))\n return Value.Check(PeersFileSchema, raw) ? raw : []\n }\n\n savePeers(peers: readonly Peer[]): void {\n writeAtomic(path.join(this.dir, 'peers.json'), JSON.stringify(peers, null, 2), 0o600)\n }\n\n loadOwnAccess(): OwnAccess {\n const raw = readJson(path.join(this.dir, 'own-access.json'))\n return Value.Check(OwnAccessSchema, raw) ? raw : { token: '', state: 'none' }\n }\n\n saveOwnAccess(access: OwnAccess): void {\n writeAtomic(path.join(this.dir, 'own-access.json'), JSON.stringify(access), 0o600)\n }\n\n /** The paths whose metadata this server takes over from the master. */\n loadFollowedMeta(): string[] {\n const raw = readJson(path.join(this.dir, 'followed-meta.json'))\n return Value.Check(PathsFileSchema, raw) ? raw : []\n }\n\n saveFollowedMeta(paths: readonly string[]): void {\n writeAtomic(path.join(this.dir, 'followed-meta.json'), JSON.stringify(paths))\n }\n\n loadPairedBy(): PairedServer[] {\n const raw = readJson(path.join(this.dir, 'paired-by.json'))\n return Value.Check(PairedServersFileSchema, raw) ? raw : []\n }\n\n savePairedBy(servers: readonly PairedServer[]): void {\n writeAtomic(path.join(this.dir, 'paired-by.json'), JSON.stringify(servers))\n }\n\n /** A random id made once per installation: every server of a boat shares its vessel id. */\n serverId(): string {\n const file = path.join(this.dir, 'server-id')\n try {\n const id = fs.readFileSync(file, 'utf-8').trim()\n if (id) {\n return id\n }\n } catch {\n // First start.\n }\n const id = crypto.randomUUID()\n writeAtomic(file, id)\n return id\n }\n}\n","import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nimport type { Plugin, ServerAPI } from '@signalk/server-api'\n\nimport {\n API_VERSION,\n PROPERTY_NAME,\n type MultihelmProperty,\n type PeerInfo,\n type Role\n} from './api.js'\nimport { ServerDiscovery } from './discovery.js'\nimport { ConfigSchema } from './config.js'\nimport { MasterFollower } from './follow-master.js'\nimport { MasterHistory, canWithdrawHistoryProvider } from './history-from-master.js'\nimport { MASTER_ROUTE, MasterProxy } from './master-proxy.js'\nimport { Multihelm, ROUND_INTERVAL_MS } from './multihelm.js'\nimport { ROUTE_PREFIX } from './peer-client.js'\nimport { registerRoutes } from './routes.js'\nimport type { OwnAccessState } from './status.js'\nimport { MultihelmStore } from './store.js'\nimport { sourcePrioritiesFromSettings } from './source-priorities.js'\nimport { vesselSettingsFromDeltas, type VesselSettings } from './vessel-settings.js'\n\nconst PLUGIN_ID = 'signalk-multihelm'\n\n/** The bundle and the sources both sit one folder below `package.json`. */\nfunction multihelmVersion(): string | undefined {\n try {\n const file = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'package.json')\n const { version } = JSON.parse(fs.readFileSync(file, 'utf-8')) as { version?: unknown }\n return typeof version === 'string' ? version : undefined\n } catch {\n return undefined\n }\n}\n\ntype Config = {\n master?: unknown\n followVessel?: unknown\n followMetadata?: unknown\n followSourcePriorities?: unknown\n historyFromMaster?: unknown\n}\n\nconst APPROVE_HINT =\n \"approve Multihelm's request under Security -> Access Requests on this server to take the vessel settings over\"\n\nconst DENIED_HINT =\n 'the access request on this server was denied, so the vessel settings are not taken over; restart the plugin to ask again'\n\nfunction statusText(role: Role, master: PeerInfo | null, conflict: boolean): string {\n if (conflict) {\n return `${role === 'master' ? 'Master' : `Member, master: ${master?.name ?? '?'}`}. More than one server is set to be the master: set one only`\n }\n if (role === 'master') {\n return \"Master of the boat's servers\"\n }\n return master ? `Member, master: ${master.name}` : 'Member, no master found'\n}\n\n/** The parts of the server the typed API leaves out. */\ntype Host = ServerAPI & {\n config?: {\n version?: string\n getExternalPort?: () => number\n baseDeltaEditor?: { deltas?: unknown }\n settings?: {\n ssl?: boolean\n port?: number\n sslport?: number\n priorityGroups?: unknown\n priorityOverrides?: unknown\n priorityDefaults?: unknown\n }\n }\n}\n\nexport default function (app: ServerAPI): Plugin {\n const host = app as Host\n let multihelm: Multihelm | null = null\n let discovery: ServerDiscovery | null = null\n let masterProxy: MasterProxy | null = null\n let stopRoleStatus: (() => void) | null = null\n let stopFollowing: (() => void) | null = null\n let masterFollower: MasterFollower | null = null\n\n function localVesselSettings(): VesselSettings | null {\n const deltas = host.config?.baseDeltaEditor?.deltas\n if (deltas === undefined) {\n return null\n }\n const settings = vesselSettingsFromDeltas(deltas)\n const priorities = host.config?.settings\n ? sourcePrioritiesFromSettings(host.config.settings)\n : null\n return priorities ? { ...settings, priorities } : settings\n }\n\n /** The port this server listens on, as the server itself works it out. */\n function ownUrl(): string {\n const settings = host.config?.settings\n if (settings?.ssl) {\n return `https://127.0.0.1:${String(Number(process.env.SSLPORT) || settings.sslport || 3443)}`\n }\n return `http://127.0.0.1:${String(Number(process.env.PORT) || settings?.port || 3000)}`\n }\n\n function ownAccessState(): OwnAccessState {\n if (masterFollower?.waitingForApproval()) {\n return { state: 'waiting-approval', request: masterFollower.accessRequestId() }\n }\n return masterFollower?.denied() ? { state: 'denied' } : null\n }\n\n function publish(value: MultihelmProperty): void {\n app.emitPropertyValue(PROPERTY_NAME, value)\n }\n\n return {\n id: PLUGIN_ID,\n name: 'Multihelm',\n description:\n \"Keeps the Signal K servers of one boat in step, and knows which one is the boat's master\",\n schema: () => ConfigSchema,\n\n start(config: object) {\n // Schema defaults are not applied at runtime: a never configured plugin gets {}.\n const settings = config as Config\n const isMaster = settings.master === true\n const store = new MultihelmStore(app.getDataDirPath())\n const mh = new Multihelm(store, {\n serverName: () => os.hostname(),\n isMaster: () => isMaster,\n versions: () => ({ signalk: host.config?.version, multihelm: multihelmVersion() }),\n debug: (msg) => {\n app.debug(msg)\n },\n error: (msg) => {\n app.error(msg)\n }\n })\n multihelm = mh\n const proxy = new MasterProxy(() => mh.masterAccess())\n masterProxy = proxy\n discovery = new ServerDiscovery(() => host.config?.getExternalPort?.())\n discovery.start()\n mh.start()\n publish({\n apiVersion: API_VERSION,\n registerDataset: (definition) => mh.registerDataset(definition),\n peers: () => mh.peerInfo(),\n serverId: () => mh.serverId,\n role: () => mh.role(),\n master: () => mh.master(),\n onRoleChanged: (cb) => mh.onRoleChanged(cb),\n registerMasterRoute: (prefix) => proxy.register(prefix),\n masterPath: (target) => `${ROUTE_PREFIX}${MASTER_ROUTE}${target}`,\n fetchMaster: (target) => proxy.fetch(target)\n })\n const follower = new MasterFollower({\n store,\n serverId: mh.serverId,\n ownUrl,\n localSettings: localVesselSettings,\n master: () => mh.masterAccess(),\n followVessel: settings.followVessel !== false,\n followMeta: settings.followMetadata !== false,\n followPriorities: settings.followSourcePriorities !== false,\n debug: (msg) => {\n app.debug(msg)\n },\n error: (msg) => {\n app.error(msg)\n }\n })\n masterFollower = follower\n const showRole = (): void => {\n const text = statusText(mh.role(), mh.master(), mh.masterConflict())\n if (follower.waitingForApproval()) {\n app.setPluginStatus(`${text}; ${APPROVE_HINT}`)\n } else if (follower.denied()) {\n app.setPluginStatus(`${text}; ${DENIED_HINT}`)\n } else {\n app.setPluginStatus(text)\n }\n }\n let following = false\n const follow = (): void => {\n if (following) {\n return\n }\n following = true\n void follower\n .run()\n .catch((error: unknown) => {\n app.error(\n `Multihelm: taking over the master's vessel settings: ${error instanceof Error ? error.message : String(error)}`\n )\n })\n .finally(() => {\n following = false\n showRole()\n })\n }\n const followTimer = setInterval(follow, ROUND_INTERVAL_MS)\n const stopRoleFollow = mh.onRoleChanged(follow)\n const history =\n settings.historyFromMaster !== false && canWithdrawHistoryProvider(app)\n ? new MasterHistory({\n registerMasterRoute: (prefix) => proxy.register(prefix),\n fetchMaster: (target) => proxy.fetch(target),\n hasMaster: () => mh.masterAccess() !== null,\n register: (provider) => {\n app.registerHistoryApiProvider(provider)\n },\n unregister: () => {\n app.unregisterHistoryApiProvider()\n },\n debug: (msg) => {\n app.debug(msg)\n }\n })\n : null\n const checkHistory = (): void => {\n history?.check().catch((error: unknown) => {\n app.error(\n `Multihelm: serving the master's history: ${error instanceof Error ? error.message : String(error)}`\n )\n })\n }\n const historyTimer = setInterval(checkHistory, ROUND_INTERVAL_MS)\n const stopRoleHistory = mh.onRoleChanged(checkHistory)\n checkHistory()\n stopFollowing = () => {\n clearInterval(followTimer)\n stopRoleFollow()\n clearInterval(historyTimer)\n stopRoleHistory()\n history?.stop()\n }\n stopRoleStatus = mh.onStatusChanged(showRole)\n showRole()\n },\n\n stop() {\n stopFollowing?.()\n stopFollowing = null\n masterFollower = null\n stopRoleStatus?.()\n stopRoleStatus = null\n if (multihelm) {\n publish({ apiVersion: API_VERSION })\n }\n multihelm?.stop()\n multihelm = null\n masterProxy?.stop()\n masterProxy = null\n discovery?.stop()\n discovery = null\n },\n\n registerWithRouter(router) {\n registerRoutes(\n router,\n () => multihelm,\n () => discovery?.list() ?? [],\n localVesselSettings,\n () => masterProxy,\n ownAccess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A,kBAAkB;KAChB,IAAI,6BAA6B;IACnC;IACA,QAAQ,QAAQ;KACd,IAAI,MAAM,GAAG;IACf;GACF,CAAC,IACD;GACN,MAAM,qBAA2B;IAC/B,SAAS,MAAM,CAAC,CAAC,OAAO,UAAmB;KACzC,IAAI,MACF,4CAA4C,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GACnG;IACF,CAAC;GACH;GACA,MAAM,eAAe,YAAY,cAAc,iBAAiB;GAChE,MAAM,kBAAkB,GAAG,cAAc,YAAY;GACrD,aAAa;GACb,sBAAsB;IACpB,cAAc,WAAW;IACzB,eAAe;IACf,cAAc,YAAY;IAC1B,gBAAgB;IAChB,SAAS,KAAK;GAChB;GACA,iBAAiB,GAAG,gBAAgB,QAAQ;GAC5C,SAAS;EACX;EAEA,OAAO;GACL,gBAAgB;GAChB,gBAAgB;GAChB,iBAAiB;GACjB,iBAAiB;GACjB,iBAAiB;GACjB,IAAI,WACF,QAAQ,EAAE,YAAA,EAAwB,CAAC;GAErC,WAAW,KAAK;GAChB,YAAY;GACZ,aAAa,KAAK;GAClB,cAAc;GACd,WAAW,KAAK;GAChB,YAAY;EACd;EAEA,mBAAmB,QAAQ;GACzB,eACE,cACM,iBACA,WAAW,KAAK,KAAK,CAAC,GAC5B,2BACM,aACN,cACF;EACF;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":["REQUEST_TIMEOUT_MS","isRecord","errorText","errorText","isRecord","errorText","isRecord","errorText","isRecord","isRecord","errorText","FILE","PLUGIN_ID","errorText","errorText"],"sources":["../src/api.ts","../src/peer-client.ts","../src/alarms-from-master.ts","../src/autopilot-from-master.ts","../src/master-control.ts","../src/course-from-master.ts","../src/discovery.ts","../src/config.ts","../src/source-priorities.ts","../src/vessel-settings.ts","../src/follow-master.ts","../src/master-plugins.ts","../src/history-from-master.ts","../src/master-proxy.ts","../src/library.ts","../src/multihelm.ts","../src/routes.ts","../src/resources-dataset.ts","../src/own-access.ts","../src/store.ts","../src/index.ts"],"sourcesContent":["/**\n * What other plugins use. Multihelm publishes it as the PropertyValue\n * `multihelm`: `{ apiVersion: 1, ...MultihelmApi }` from its start, and\n * `{ apiVersion: 1 }` without the methods after its stop. A plugin acts on\n * the last value, registers its datasets again whenever the methods\n * reappear, and unregisters them in its own `stop()`.\n *\n * Compatibility: `apiVersion` changes only with a change users must know\n * about; everything else grows by addition.\n */\n\nexport const API_VERSION = 1\nexport const PROPERTY_NAME = 'multihelm'\n\n/** One file of an entry on this server. */\nexport interface DatasetFile {\n /** Unique within the entry: letters, digits, `.`, `_`, `-`, not starting with `.`. */\n name: string\n /** Absolute path on this server. */\n path: string\n size: number\n mtimeMs: number\n}\n\nexport interface DatasetEntry {\n /** Unique within the dataset, e.g. a path relative to the dataset's folder. */\n key: string\n /** Small JSON value replicated with the entry, e.g. `{ enabled: true }`. */\n meta: unknown\n files: DatasetFile[]\n}\n\n/** A peer's entry to take over; every file has arrived whole and matches its hash. */\nexport interface IncomingEntry {\n key: string\n meta: unknown\n files: {\n name: string\n /**\n * Absolute path of the verified file: in Multihelm's work folder for a\n * file that changed (move it into place), or the dataset's own copy for\n * one that did not.\n */\n path: string\n size: number\n sha256: string\n /** True when `path` is the dataset's own unchanged file. */\n unchanged: boolean\n }[]\n}\n\nexport interface DatasetDefinition {\n /** Unique across plugins: `<plugin id>/<name>`. */\n id: string\n /** What this server holds now. Called once per round, and after each `apply`. */\n list: () => Promise<DatasetEntry[]>\n /** Take over a peer's entry. Throwing leaves it to be tried again next round. */\n apply: (entry: IncomingEntry) => Promise<void>\n /**\n * A peer deleted the entry. Return false to keep it here: it is then\n * offered back to the peers as a change of this server's.\n */\n remove: (key: string) => Promise<boolean>\n /** Checked on every key a peer sends, before `apply` or `remove` sees it. */\n isValidKey?: (key: string) => boolean\n}\n\nexport interface DatasetHandle {\n /** Something changed here: look sooner than the next round. */\n changed: () => void\n unregister: () => void\n}\n\nexport interface PeerInfo {\n id: string\n name: string\n url: string\n state: 'waiting-approval' | 'paired' | 'needs-pairing'\n lastSeen?: number\n lastSync?: number\n lastError?: string\n /** The peer is set to be the boat's master, and answered within the last rounds. */\n master?: boolean\n /** A paired peer answered within the last rounds. */\n online?: boolean\n /** The peer's Signal K server version, once it said. */\n signalk?: string\n /** The peer's Multihelm version, once it said. */\n multihelm?: string\n}\n\n/**\n * `master`: this server is the boat's master. `member`: another server is,\n * or none is. The master is set by hand on one server; when several are set,\n * the one with the smallest server id is the master.\n */\nexport type Role = 'master' | 'member'\n\nexport interface MasterRouteHandle {\n unregister: () => void\n}\n\nexport interface MasterResponse {\n status: number\n /** The response headers that matter to a reader: type, length, caching. */\n headers: Record<string, string>\n body: Buffer\n}\n\nexport interface MultihelmApi {\n registerDataset: (definition: DatasetDefinition) => DatasetHandle\n peers: () => PeerInfo[]\n /** This server's id among the boat's servers. */\n serverId: () => string\n role: () => Role\n /** The peer that is the master; null when this server is the master or there is none. */\n master: () => PeerInfo | null\n /**\n * Calls `cb` whenever this server's role or the master changes; returns a\n * function that stops the calls. A master-mode plugin starts its work when\n * its server becomes the master and stops it when it no longer is.\n */\n onRoleChanged: (cb: (role: Role, master: PeerInfo | null) => void) => () => void\n /**\n * Lets this server serve the master's GET requests under `prefix` (a path\n * ending in `/`, e.g. `/signalk/v1/api/resources/charts/`) at\n * `masterPath(...)`, to anyone who may read on this server; the prefix\n * without its `/` is served too, where a collection is listed. Admin and\n * access routes are refused.\n */\n registerMasterRoute: (prefix: string) => MasterRouteHandle\n /** Where this server serves the master's `path`, e.g. for a tile URL handed to a browser. */\n masterPath: (path: string) => string\n /** Reads the master's `path`, under a registered prefix; rejects when there is no master. */\n fetchMaster: (path: string) => Promise<MasterResponse>\n}\n\nexport type MultihelmProperty = { apiVersion: typeof API_VERSION } & Partial<MultihelmApi>\n","/**\n * HTTP client for a Multihelm peer: its routes, and the Signal K\n * device access request that pairs with it.\n *\n * Peers are other Signal K servers on the boat's network, addressed by the\n * URL the user confirmed. An HTTPS peer is trusted the way Node trusts any\n * server or, when no CA that Node knows vouches for it, by the certificate it\n * presented when it was paired (see `locatePeer()`).\n */\n\nimport { X509Certificate } from 'node:crypto'\nimport fs from 'node:fs'\nimport http from 'node:http'\nimport https from 'node:https'\nimport net from 'node:net'\nimport { pipeline } from 'node:stream/promises'\nimport tls from 'node:tls'\n\nexport const ROUTE_PREFIX = '/plugins/signalk-multihelm'\nconst REQUEST_TIMEOUT_MS = 30_000\n\n/**\n * What Node calls a chain whose issuer it does not trust, the one failure a\n * certificate kept from pairing stands in for. Expiry and a name it was not\n * issued for are not among them: pinning must not paper over those.\n */\nexport const UNTRUSTED_ISSUER: ReadonlySet<string> = new Set([\n 'DEPTH_ZERO_SELF_SIGNED_CERT',\n 'SELF_SIGNED_CERT_IN_CHAIN',\n 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',\n 'UNABLE_TO_GET_ISSUER_CERT',\n 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY'\n])\n\n/** Where a peer is, and how to trust it over HTTPS. */\nexport interface PeerAddress {\n url: string\n /**\n * PEM of the certificate the peer's chain must lead to, taken when it was\n * paired; absent when Node trusts the peer by itself, or over HTTP.\n */\n ca?: string\n}\n\nexport interface Hello {\n serverId: string\n name: string\n protocol: number\n datasets: string[]\n /** This server is set to be the boat's master. */\n master: boolean\n /** The Signal K server's version; older Multihelm versions leave it out. */\n signalk?: string\n /** Multihelm's version; older Multihelm versions leave it out. */\n multihelm?: string\n}\n\n/**\n * The server asking for a peer's `hello`, sent along so the peer can list\n * the servers paired with it. Older peers ignore it.\n */\nexport interface HelloFrom {\n serverId: string\n name: string\n /** It is set to be the boat's master; a peer that knew otherwise asks again at once. */\n master?: boolean\n signalk?: string\n multihelm?: string\n}\n\nfunction helloQuery(from: HelloFrom | undefined): string {\n if (!from) {\n return ''\n }\n const query = new URLSearchParams({ from: from.serverId, name: from.name })\n if (from.master !== undefined) {\n query.set('master', from.master ? '1' : '0')\n }\n if (from.signalk) {\n query.set('signalk', from.signalk)\n }\n if (from.multihelm) {\n query.set('multihelm', from.multihelm)\n }\n return `?${query.toString()}`\n}\n\nfunction optionalText(value: unknown): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined\n}\n\nexport interface Manifest {\n cursor: number\n entries: unknown[]\n}\n\ninterface RawResponse {\n status: number\n stream: http.IncomingMessage\n}\n\nexport class PeerHttpError extends Error {\n constructor(\n readonly status: number,\n message: string\n ) {\n super(message)\n }\n}\n\n/** How to check the certificate of `target`, an HTTPS URL, trusted by `ca` when it is set. */\nexport function tlsOptions(target: URL, ca: string | undefined): https.RequestOptions {\n if (ca) {\n return {\n ca,\n // Trusted by this very certificate, whatever names it was issued for:\n // Signal K's own is issued for `localhost`, and a boat's IPs change.\n checkServerIdentity: () => undefined,\n // It is the leaf or an intermediate when a server leaves the rest of its chain out.\n allowPartialTrustChain: true\n }\n }\n // This server itself, reached over loopback, may well have a self-signed certificate.\n return target.hostname === '127.0.0.1' ? { rejectUnauthorized: false } : {}\n}\n\nfunction send(\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n url: string,\n options: {\n token?: string\n body?: unknown\n headers?: Record<string, string>\n ca?: string | undefined\n } = {}\n): Promise<RawResponse> {\n const headers: Record<string, string> = { ...options.headers }\n if (options.token) {\n headers.Authorization = `Bearer ${options.token}`\n }\n let payload: string | undefined\n if (options.body !== undefined) {\n payload = JSON.stringify(options.body)\n headers['Content-Type'] = 'application/json'\n }\n const target = new URL(url)\n const request = target.protocol === 'https:' ? https.request : http.request\n return new Promise((resolve, reject) => {\n const req = request(\n target,\n { method, headers, timeout: REQUEST_TIMEOUT_MS, ...tlsOptions(target, options.ca) },\n (res) => {\n resolve({ status: res.statusCode ?? 0, stream: res })\n }\n )\n req.on('timeout', () =>\n req.destroy(new Error(`timeout after ${String(REQUEST_TIMEOUT_MS)} ms`))\n )\n req.on('error', reject)\n if (payload !== undefined) {\n req.write(payload)\n }\n req.end()\n })\n}\n\nasync function readBody(res: RawResponse): Promise<string> {\n const chunks: Buffer[] = []\n for await (const chunk of res.stream) {\n chunks.push(chunk as Buffer)\n }\n return Buffer.concat(chunks).toString('utf-8')\n}\n\nasync function getJson(url: string, token?: string, ca?: string): Promise<unknown> {\n const res = await send('GET', url, { token, ca })\n const text = await readBody(res)\n if (res.status < 200 || res.status >= 300) {\n throw new PeerHttpError(res.status, `HTTP ${String(res.status)} from ${url}`)\n }\n return JSON.parse(text) as unknown\n}\n\n/** `host:port` or a URL, reduced to `http(s)://host:port`; null when it is neither. */\nexport function normalizePeerUrl(input: string): string | null {\n let url: URL\n try {\n url = new URL(input.includes('://') ? input : `http://${input}`)\n } catch {\n return null\n }\n if ((url.protocol !== 'http:' && url.protocol !== 'https:') || url.username || url.password) {\n return null\n }\n return `${url.protocol}//${url.host}`\n}\n\n/**\n * Where and how to reach the server at `url`, a normalized address, worked\n * out when pairing with it. An HTTP port that redirects to HTTPS on the same\n * host, as Signal K's does once SSL is on, is followed, and an address that\n * speaks HTTPS only is taken as HTTPS. An HTTPS server that no CA Node knows\n * vouches for is trusted from then on by the top certificate of the chain it\n * presents: the CA when signalk-ssl issued its certificate, the certificate\n * itself when Signal K made it.\n */\nexport async function locatePeer(url: string): Promise<PeerAddress> {\n const typed = new URL(url)\n const target = typed.protocol === 'https:' ? typed : await httpsTarget(typed)\n if (!target) {\n return { url }\n }\n const secureUrl = `https://${target.host}`\n const ca = await untrustedAnchor(target)\n return ca === undefined ? { url: secureUrl } : { url: secureUrl, ca }\n}\n\n/** Where HTTP `target` is to be reached over HTTPS instead; null when it is not. */\nasync function httpsTarget(target: URL): Promise<URL | null> {\n let res: RawResponse\n try {\n res = await send('GET', `${target.origin}/signalk`)\n } catch (error) {\n // A Signal K server's SSL port, typed without `https://`, hangs up on plain HTTP.\n if ((error as { code?: unknown }).code === 'ECONNRESET') {\n const same = new URL(`https://${target.hostname}:${target.port || '80'}`)\n if (await speaksTls(same)) {\n return same\n }\n }\n throw error\n }\n res.stream.resume()\n const location = res.status >= 300 && res.status < 400 ? res.stream.headers.location : undefined\n if (location === undefined) {\n return null\n }\n const next = new URL(location, target)\n return next.protocol === 'https:' && next.hostname === target.hostname\n ? new URL(`https://${next.host}`)\n : null\n}\n\nfunction connectTls(target: URL): Promise<tls.TLSSocket> {\n const host = target.hostname.replace(/^\\[(.*)\\]$/, '$1')\n return new Promise((resolve, reject) => {\n const socket = tls.connect(\n {\n host,\n port: Number(target.port || 443),\n ...(net.isIP(host) === 0 ? { servername: host } : {}),\n // Checked by the caller, which needs the certificate either way.\n rejectUnauthorized: false,\n timeout: REQUEST_TIMEOUT_MS\n },\n () => {\n resolve(socket)\n }\n )\n socket.on('timeout', () => {\n socket.destroy(new Error(`timeout after ${String(REQUEST_TIMEOUT_MS)} ms`))\n })\n socket.on('error', reject)\n })\n}\n\nasync function speaksTls(target: URL): Promise<boolean> {\n try {\n ;(await connectTls(target)).end()\n return true\n } catch {\n return false\n }\n}\n\n/**\n * The top certificate of the chain `target` presents, as PEM, when Node\n * refuses the chain for its issuer alone; undefined otherwise.\n */\nasync function untrustedAnchor(target: URL): Promise<string | undefined> {\n const socket = await connectTls(target)\n try {\n // Node sets it to the error's code, though it is typed as the error.\n const reason = String(socket.authorizationError)\n if (socket.authorized || !UNTRUSTED_ISSUER.has(reason)) {\n return undefined\n }\n let top = socket.getPeerCertificate(true)\n // Node links a self-signed certificate to itself; the bound guards against any other loop.\n for (let depth = 0; depth < 10; depth++) {\n const issuer = top.issuerCertificate as tls.DetailedPeerCertificate | undefined\n if (!issuer || issuer.fingerprint256 === top.fingerprint256) {\n break\n }\n top = issuer\n }\n return new X509Certificate(top.raw).toString()\n } finally {\n socket.end()\n }\n}\n\nexport async function fetchHello(\n peer: PeerAddress,\n token?: string,\n from?: HelloFrom\n): Promise<Hello> {\n const body = (await getJson(\n `${peer.url}${ROUTE_PREFIX}/hello${helloQuery(from)}`,\n token,\n peer.ca\n )) as Partial<Hello>\n if (typeof body.serverId !== 'string' || typeof body.protocol !== 'number') {\n throw new Error(`${peer.url} did not answer as a Multihelm peer`)\n }\n const hello: Hello = {\n serverId: body.serverId,\n name: typeof body.name === 'string' ? body.name : peer.url,\n protocol: body.protocol,\n datasets: Array.isArray(body.datasets)\n ? body.datasets.filter((d): d is string => typeof d === 'string')\n : [],\n master: (body as { master?: unknown }).master === true\n }\n const signalk = optionalText(body.signalk)\n const multihelm = optionalText(body.multihelm)\n return {\n ...hello,\n ...(signalk ? { signalk } : {}),\n ...(multihelm ? { multihelm } : {})\n }\n}\n\nexport async function fetchVesselSettings(peer: PeerAddress, token: string): Promise<unknown> {\n return getJson(`${peer.url}${ROUTE_PREFIX}/vessel-settings`, token, peer.ca)\n}\n\n/** A request to a Signal K server's own REST API; throws on any status but 2xx. */\nexport async function callServer(\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n url: string,\n token: string,\n body?: unknown\n): Promise<unknown> {\n const res = await send(method, url, { token, body })\n const text = await readBody(res)\n if (res.status < 200 || res.status >= 300) {\n throw new PeerHttpError(res.status, `HTTP ${String(res.status)} from ${method} ${url}`)\n }\n try {\n return JSON.parse(text) as unknown\n } catch {\n return text\n }\n}\n\n/** A request to a paired peer's REST API, trusted as when it was paired; throws on any status but 2xx. */\nexport async function callPeer(\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n peer: PeerAddress,\n path: string,\n token: string,\n body?: unknown\n): Promise<unknown> {\n const url = `${peer.url}${path}`\n const res = await send(method, url, { token, body, ca: peer.ca })\n const text = await readBody(res)\n if (res.status < 200 || res.status >= 300) {\n throw new PeerHttpError(res.status, `HTTP ${String(res.status)} from ${method} ${url}`)\n }\n try {\n return JSON.parse(text) as unknown\n } catch {\n return text\n }\n}\n\n/** A page of a peer's dataset changes; its entries are checked by the caller. */\nexport async function fetchManifest(\n peer: PeerAddress,\n token: string,\n dataset: string,\n since: number\n): Promise<Manifest> {\n const body = (await getJson(\n `${peer.url}${ROUTE_PREFIX}/manifest?dataset=${encodeURIComponent(dataset)}&since=${String(since)}`,\n token,\n peer.ca\n )) as Partial<Manifest>\n if (typeof body.cursor !== 'number' || !Array.isArray(body.entries)) {\n throw new Error(`${peer.url} sent a malformed manifest`)\n }\n return { cursor: body.cursor, entries: body.entries }\n}\n\n/** Download one file of a peer's entry into `dest`, resuming from what `dest` holds. */\nexport function downloadFile(\n peer: PeerAddress,\n token: string,\n file: { dataset: string; key: string; name: string },\n dest: string\n): Promise<void> {\n const query =\n `file?dataset=${encodeURIComponent(file.dataset)}` +\n `&key=${encodeURIComponent(file.key)}&file=${encodeURIComponent(file.name)}`\n return download(peer, token, query, `${file.key}/${file.name}`, dest)\n}\n\nasync function download(\n peer: PeerAddress,\n token: string,\n query: string,\n label: string,\n dest: string\n): Promise<void> {\n let offset = 0\n try {\n offset = fs.statSync(dest).size\n } catch {\n // Nothing to resume.\n }\n const url = `${peer.url}${ROUTE_PREFIX}/${query}`\n const res = await send('GET', url, {\n token,\n headers: offset > 0 ? { Range: `bytes=${String(offset)}-` } : {},\n ca: peer.ca\n })\n if (res.status === 206) {\n await pipeline(res.stream, fs.createWriteStream(dest, { flags: 'a' }))\n return\n }\n if (res.status === 200) {\n await pipeline(res.stream, fs.createWriteStream(dest))\n return\n }\n res.stream.resume()\n throw new PeerHttpError(res.status, `HTTP ${String(res.status)} for ${label}`)\n}\n\nexport type AccessRequestResult =\n | { kind: 'no-security' }\n | { kind: 'pending'; href: string }\n | { kind: 'approved'; token: string }\n | { kind: 'denied' }\n | { kind: 'error'; message: string }\n\n/** Ask the peer for a device token, readonly unless said otherwise. */\nexport async function requestAccess(\n peer: PeerAddress,\n clientId: string,\n description: string,\n permissions: 'readonly' | 'readwrite' | 'admin' = 'readonly'\n): Promise<AccessRequestResult> {\n const res = await send('POST', `${peer.url}/signalk/v1/access/requests`, {\n body: { clientId, description, permissions },\n ca: peer.ca\n })\n const text = await readBody(res)\n if (res.status === 404) {\n return { kind: 'no-security' }\n }\n if (res.status === 403) {\n return { kind: 'error', message: 'the peer does not accept device access requests' }\n }\n if (res.status !== 200 && res.status !== 202) {\n return { kind: 'error', message: `HTTP ${String(res.status)} from the access request` }\n }\n return interpretReply(JSON.parse(text) as unknown)\n}\n\n/** Follow up an access request that is waiting for approval. */\nexport async function pollAccess(peer: PeerAddress, href: string): Promise<AccessRequestResult> {\n const url = href.startsWith('/') ? `${peer.url}${href}` : href\n if (!url.startsWith(`${peer.url}/`)) {\n return { kind: 'error', message: 'the access request points to another server' }\n }\n try {\n return interpretReply(await getJson(url, undefined, peer.ca))\n } catch (error) {\n if (error instanceof PeerHttpError && error.status === 404) {\n return { kind: 'denied' }\n }\n throw error\n }\n}\n\nfunction interpretReply(raw: unknown): AccessRequestResult {\n const reply = raw as {\n state?: string\n href?: string\n accessRequest?: { permission?: string; token?: string }\n }\n if (reply.state === 'PENDING' && typeof reply.href === 'string') {\n return { kind: 'pending', href: reply.href }\n }\n if (reply.state === 'COMPLETED') {\n const token = reply.accessRequest?.token\n return token ? { kind: 'approved', token } : { kind: 'denied' }\n }\n return { kind: 'error', message: 'unexpected access request reply' }\n}\n","/**\n * Alarms are matched by path: each server gives its alarms ids of its own,\n * and stations on one NMEA 2000 bus raise the same alarm themselves.\n */\n\nimport { isDeepStrictEqual } from 'node:util'\n\nimport type {\n AlarmProperties,\n AlarmRaiseOptions,\n AlarmUpdateOptions,\n ALARM_STATE,\n NotificationId,\n NotificationsApi,\n Path,\n Value\n} from '@signalk/server-api'\n\nimport type { MasterControlAccess, MasterOfBoat } from './master-control.js'\nimport { PeerHttpError, callPeer } from './peer-client.js'\n\nexport const NOTIFICATIONS_PATH = '/signalk/v2/api/notifications'\nexport const ALARMS_POLL_MS = 1_000\n/** In the data of an alarm shown for the master: the master's server id, and its id for the alarm. */\nexport const FROM_MASTER = 'multihelmMaster'\nexport const MASTER_ALARM = 'multihelmMasterAlarm'\n\nexport interface LocalNotifications {\n list: () => Record<string, AlarmProperties>\n raise: (options: AlarmRaiseOptions) => NotificationId\n update: (id: NotificationId, options: AlarmUpdateOptions) => void\n clear: (id: NotificationId) => void\n silence: (id: NotificationId) => void\n acknowledge: (id: NotificationId) => void\n}\n\n/**\n * The server's Notifications API, while the server manages notifications:\n * older servers lack it, and with management off it still raises alarms but\n * can no longer clear, silence or acknowledge them.\n */\nexport function managedNotifications(api: unknown): LocalNotifications | null {\n const notifications = api as Partial<LocalNotifications & NotificationsApi> | undefined\n if (typeof notifications?.list !== 'function' || typeof notifications.getId !== 'function') {\n return null\n }\n try {\n notifications.getId('signalk-multihelm-probe' as NotificationId)\n } catch {\n return null\n }\n return notifications as LocalNotifications\n}\n\nexport interface AlarmsHost {\n /** The master to follow; null when this server is the master or there is none. */\n master: () => MasterOfBoat | null\n control: MasterControlAccess\n notifications: LocalNotifications\n debug: (msg: string) => void\n}\n\nexport interface Alarm {\n id: string\n path: string\n state: ALARM_STATE\n message: string\n data: Record<string, Value>\n silenced: boolean\n acknowledged: boolean\n}\n\nconst ACTIVE = new Set(['alert', 'warn', 'alarm', 'emergency'])\n\nfunction isActive(state: unknown): state is ALARM_STATE {\n return typeof state === 'string' && ACTIVE.has(state)\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nexport function activeAlarms(listing: unknown): Alarm[] {\n if (!isRecord(listing)) {\n return []\n }\n const alarms: Alarm[] = []\n for (const [id, entry] of Object.entries(listing)) {\n if (!isRecord(entry) || typeof entry.path !== 'string' || !isRecord(entry.value)) {\n continue\n }\n const value = entry.value\n const status = isRecord(value.status) ? value.status : {}\n if (!isActive(value.state)) {\n continue\n }\n alarms.push({\n id,\n path: entry.path,\n state: value.state,\n message: typeof value.message === 'string' ? value.message : '',\n data: isRecord(value.data) ? (value.data as Record<string, Value>) : {},\n silenced: status.silenced === true,\n acknowledged: status.acknowledged === true\n })\n }\n return alarms\n}\n\nfunction isMirror(alarm: Alarm): boolean {\n return typeof alarm.data[FROM_MASTER] === 'string'\n}\n\nfunction byPath(alarms: Alarm[]): Map<string, Alarm> {\n const paths = new Map<string, Alarm>()\n for (const alarm of alarms) {\n if (!paths.has(alarm.path)) {\n paths.set(alarm.path, alarm)\n }\n }\n return paths\n}\n\ntype Action = 'silence' | 'acknowledge'\n\n/** Where an alarm here was after the last pass, and for which alarm of which master. */\ninterface Seen {\n masterId: string\n theirId: string\n silenced: boolean\n acknowledged: boolean\n /** Given here, and not yet taken by the master. */\n unsent: Action | null\n}\n\nexport class MasterAlarms {\n private timer: NodeJS.Timeout | null = null\n private running = false\n private stopped = false\n private seen = new Map<string, Seen>()\n\n constructor(private readonly host: AlarmsHost) {}\n\n start(): void {\n this.timer = setInterval(() => {\n void this.sync()\n }, ALARMS_POLL_MS)\n }\n\n stop(): void {\n this.stopped = true\n if (this.timer) {\n clearInterval(this.timer)\n }\n this.timer = null\n this.clearMirrors(() => false)\n }\n\n /** One pass; never rejects. */\n async sync(): Promise<void> {\n if (this.running || this.stopped) {\n return\n }\n this.running = true\n try {\n await this.syncOnce()\n } catch (error) {\n this.host.debug(`Multihelm: the alarms from the master: ${errorText(error)}`)\n } finally {\n this.running = false\n }\n }\n\n private async syncOnce(): Promise<void> {\n const master = this.host.master()\n if (!master) {\n this.clearMirrors(() => false)\n return\n }\n // Before asking, so a new master that does not answer leaves no alarms of the old one sounding.\n this.clearMirrors((mirror) => mirror.data[FROM_MASTER] === master.id)\n const listing: unknown = await callPeer(\n 'GET',\n master.access,\n NOTIFICATIONS_PATH,\n master.access.token\n )\n if (!this.stillFor(master)) {\n return\n }\n // A server that was a member a moment ago may still show another master's alarms.\n const theirs = byPath(activeAlarms(listing).filter((alarm) => !isMirror(alarm)))\n this.clearMirrors(\n (mirror) =>\n mirror.data[FROM_MASTER] === master.id &&\n mirror.data[MASTER_ALARM] === theirs.get(mirror.path)?.id\n )\n const seen = new Map<string, Seen>()\n for (const [path, alarm] of theirs) {\n if (!this.stillFor(master)) {\n return\n }\n try {\n const here = this.alarmHere(path, alarm, master.id)\n seen.set(here.id, await this.keepInStep(master, here, alarm))\n } catch (error) {\n this.host.debug(`Multihelm: the master's alarm ${path}: ${errorText(error)}`)\n }\n }\n this.seen = seen\n }\n\n private stillFor(master: MasterOfBoat): boolean {\n return !this.stopped && this.host.master()?.id === master.id\n }\n\n /**\n * This server's own alarm on the path, or the one shown for the master's.\n * Read again for each alarm, since the server may have raised one of its own while a send waited.\n */\n private alarmHere(path: string, theirs: Alarm, masterId: string): Alarm {\n const here = activeAlarms(this.host.notifications.list()).filter((a) => a.path === path)\n const own = here.find((alarm) => !isMirror(alarm))\n const mirror = here.find(isMirror)\n if (!own) {\n return this.mirrored(mirror, theirs, masterId)\n }\n if (mirror) {\n this.host.notifications.clear(mirror.id as NotificationId)\n }\n return own\n }\n\n private mirrored(mirror: Alarm | undefined, theirs: Alarm, masterId: string): Alarm {\n const notifications = this.host.notifications\n const data = { ...theirs.data, [FROM_MASTER]: masterId, [MASTER_ALARM]: theirs.id }\n const shown = { ...theirs, data, silenced: false, acknowledged: false }\n if (!mirror) {\n const id = notifications.raise({\n state: theirs.state,\n message: theirs.message,\n path: theirs.path as Path,\n data\n })\n return { ...shown, id }\n }\n if (\n mirror.state === theirs.state &&\n mirror.message === theirs.message &&\n isDeepStrictEqual(mirror.data, data)\n ) {\n return mirror\n }\n notifications.update(mirror.id as NotificationId, {\n state: theirs.state,\n message: theirs.message,\n data\n })\n // The server takes a silence and an acknowledgement off an alarm whose state changes.\n return mirror.state === theirs.state\n ? { ...mirror, message: theirs.message, data }\n : { ...shown, id: mirror.id }\n }\n\n private async keepInStep(master: MasterOfBoat, here: Alarm, theirs: Alarm): Promise<Seen> {\n const last = this.seen.get(here.id)\n const before = last?.masterId === master.id && last.theirId === theirs.id ? last : null\n const now: Seen = {\n masterId: master.id,\n theirId: theirs.id,\n silenced: here.silenced,\n acknowledged: here.acknowledged,\n unsent: null\n }\n const id = here.id as NotificationId\n if (theirs.acknowledged && !here.acknowledged) {\n this.host.notifications.acknowledge(id)\n return { ...now, acknowledged: true }\n }\n if (theirs.silenced && !here.silenced && !here.acknowledged) {\n this.host.notifications.silence(id)\n return { ...now, silenced: true }\n }\n if (!before) {\n return now\n }\n const unsent =\n here.acknowledged &&\n !theirs.acknowledged &&\n (!before.acknowledged || before.unsent === 'acknowledge')\n ? 'acknowledge'\n : here.silenced &&\n !theirs.silenced &&\n !theirs.acknowledged &&\n (!before.silenced || before.unsent === 'silence')\n ? 'silence'\n : null\n if (unsent && !(await this.sendToMaster(master, theirs, unsent))) {\n return { ...now, unsent }\n }\n return now\n }\n\n private async sendToMaster(master: MasterOfBoat, alarm: Alarm, action: Action): Promise<boolean> {\n const token = await this.host.control.token(master)\n if (token === null || !this.stillFor(master)) {\n return false\n }\n try {\n await callPeer(\n 'POST',\n master.access,\n `${NOTIFICATIONS_PATH}/${encodeURIComponent(alarm.id)}/${action}`,\n token\n )\n } catch (error) {\n if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) {\n this.host.control.revoked(master.id, token)\n }\n this.host.debug(\n `Multihelm: sending the ${action} of ${alarm.path} to the master: ${errorText(error)}`\n )\n return false\n }\n this.host.debug(`Multihelm: sent the ${action} of ${alarm.path} to the master`)\n return true\n }\n\n private clearMirrors(keep: (mirror: Alarm) => boolean): void {\n const notifications = this.host.notifications\n for (const alarm of activeAlarms(notifications.list())) {\n if (isMirror(alarm) && !keep(alarm)) {\n try {\n notifications.clear(alarm.id as NotificationId)\n } catch (error) {\n this.host.debug(`Multihelm: clearing ${alarm.path}: ${errorText(error)}`)\n }\n }\n }\n }\n}\n","/**\n * On a server that is not the master: the master's autopilot, served by this\n * server's Autopilot API. Multihelm registers itself as the autopilot\n * provider here and sends every command on to the master's Autopilot API, so\n * a chartplotter at any station operates the one autopilot the master drives,\n * and only the master sends to it. Its state is read from the master every\n * second and published here as the provider's update.\n *\n * Reading uses the readonly pairing token; commands need the readwrite\n * device token on the master (`MasterControlAccess`), asked for when the\n * master is first found to have an autopilot.\n */\n\nimport { isDeepStrictEqual } from 'node:util'\n\nimport type {\n AutopilotInfo,\n AutopilotProvider,\n TackGybeDirection,\n Value\n} from '@signalk/server-api'\n\nimport type { MasterControlAccess, MasterOfBoat } from './master-control.js'\nimport { PeerHttpError, callPeer } from './peer-client.js'\n\nexport const AUTOPILOTS_PATH = '/signalk/v2/api/vessels/self/autopilots'\nexport const STATE_POLL_MS = 1_000\nexport const DEVICES_POLL_MS = 10_000\n\nexport interface AutopilotHost {\n control: MasterControlAccess\n /** The master to send to; null when this server is the master or there is none. */\n master: () => MasterOfBoat | null\n /** Whether this server is the master: its own autopilot provider serves, never this one. */\n isMaster: () => boolean\n register: (provider: AutopilotProvider, devices: string[]) => void\n unregister: () => void\n update: (deviceId: string, info: Record<string, Value>) => void\n debug: (msg: string) => void\n error: (msg: string) => void\n}\n\n/** What the server's Autopilot API makes of a provider's rejection: its status and message. */\nexport class AutopilotError extends Error {\n constructor(\n readonly statusCode: number,\n message: string\n ) {\n super(message)\n }\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** The provider answers in the shape the server hands on, so the master's answer passes as it is. */\nfunction asInfo(value: unknown): AutopilotInfo {\n if (!isRecord(value)) {\n throw new AutopilotError(502, 'the master sent no autopilot data')\n }\n return value as unknown as AutopilotInfo\n}\n\nfunction valueOf(answer: unknown): unknown {\n return isRecord(answer) ? answer.value : undefined\n}\n\nexport class MasterAutopilot {\n private registered = false\n /** Counts withdrawals, so a read that outlived one publishes nothing. */\n private withdrawals = 0\n private devices: string[] = []\n private readonly published = new Map<string, Record<string, Value>>()\n private stateTimer: NodeJS.Timeout | null = null\n private devicesTimer: NodeJS.Timeout | null = null\n private polling = false\n private stopped = false\n\n constructor(private readonly host: AutopilotHost) {}\n\n start(): void {\n this.devicesTimer = setInterval(() => {\n this.run(() => this.findDevices())\n }, DEVICES_POLL_MS)\n this.stateTimer = setInterval(() => {\n this.run(() => this.pollState())\n }, STATE_POLL_MS)\n this.run(() => this.findDevices())\n }\n\n stop(): void {\n for (const timer of [this.devicesTimer, this.stateTimer]) {\n if (timer) {\n clearInterval(timer)\n }\n }\n this.devicesTimer = null\n this.stateTimer = null\n this.stopped = true\n this.withdraw()\n }\n\n /**\n * Called when the role changes. On the master its own provider must have\n * the devices, so this one steps aside before that provider starts.\n */\n roleChanged(): void {\n if (this.host.isMaster()) {\n this.withdraw()\n } else {\n this.run(() => this.findDevices())\n }\n }\n\n /** The user has to approve this server's request on the master to send it commands. */\n async findDevices(): Promise<void> {\n if (this.host.isMaster()) {\n this.withdraw()\n return\n }\n const master = this.host.master()\n if (!master) {\n return\n }\n let answer: unknown\n try {\n answer = await callPeer('GET', master.access, AUTOPILOTS_PATH, master.access.token)\n } catch (error) {\n this.host.debug(`Multihelm: the master's autopilots: ${errorText(error)}`)\n return\n }\n const devices = isRecord(answer) ? Object.keys(answer).sort() : []\n if (this.stopped || devices.length === 0 || !this.isCurrent(master)) {\n return\n }\n this.devices = devices\n // Again each time: a device this server's own provider held until it stopped is free now.\n this.host.register(this.provider, devices)\n this.registered = true\n await this.host.control.token(master)\n }\n\n async pollState(): Promise<void> {\n const master = this.host.master()\n if (this.polling || !this.registered || !master) {\n return\n }\n this.polling = true\n const withdrawals = this.withdrawals\n try {\n for (const device of this.devices) {\n let info: AutopilotInfo\n try {\n info = asInfo(await this.read(master, device, ''))\n } catch (error) {\n this.host.debug(\n `Multihelm: the state of the master's autopilot ${device}: ${errorText(error)}`\n )\n continue\n }\n if (withdrawals !== this.withdrawals) {\n return\n }\n const update: Record<string, Value> = {\n state: info.state,\n mode: info.mode,\n target: info.target,\n engaged: info.engaged\n }\n const actions = (info.options as { actions?: unknown } | undefined)?.actions\n if (Array.isArray(actions)) {\n update.actions = actions as Value\n }\n if (!isDeepStrictEqual(this.published.get(device), update)) {\n this.published.set(device, update)\n this.host.update(device, update)\n }\n }\n } finally {\n this.polling = false\n }\n }\n\n private withdraw(): void {\n if (this.registered) {\n this.host.unregister()\n this.registered = false\n this.withdrawals++\n this.published.clear()\n }\n }\n\n private isCurrent(master: MasterOfBoat): boolean {\n return this.host.master()?.id === master.id\n }\n\n private masterOrFail(): MasterOfBoat {\n const master = this.host.isMaster() ? null : this.host.master()\n if (!master) {\n throw new AutopilotError(503, 'no other server is the master now')\n }\n return master\n }\n\n private async read(master: MasterOfBoat, device: string, rest: string): Promise<unknown> {\n try {\n return await callPeer(\n 'GET',\n master.access,\n `${AUTOPILOTS_PATH}/${encodeURIComponent(device)}${rest}`,\n master.access.token\n )\n } catch (error) {\n throw this.asAutopilotError(error)\n }\n }\n\n private async send(\n method: 'POST' | 'PUT' | 'DELETE',\n device: string,\n rest: string,\n body?: unknown\n ): Promise<void> {\n const master = this.masterOrFail()\n const token = await this.host.control.token(master)\n if (token === null) {\n throw new AutopilotError(\n 403,\n this.host.control.denied()\n ? \"the master denied Multihelm's request to steer its autopilot; restart Multihelm to ask again\"\n : `approve Multihelm's request \"${this.host.control.requestId()}\" under Security -> Access Requests on the master to steer from this station`\n )\n }\n try {\n await callPeer(\n method,\n master.access,\n `${AUTOPILOTS_PATH}/${encodeURIComponent(device)}${rest}`,\n token,\n body\n )\n } catch (error) {\n if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) {\n this.host.control.revoked(master.id, token)\n }\n throw this.asAutopilotError(error)\n }\n this.run(() => this.pollState())\n }\n\n private run(work: () => Promise<void>): void {\n work().catch((error: unknown) => {\n this.host.error(`Multihelm: the master's autopilot: ${errorText(error)}`)\n })\n }\n\n private asAutopilotError(error: unknown): AutopilotError {\n if (error instanceof AutopilotError) {\n return error\n }\n const status = error instanceof PeerHttpError ? error.status : 502\n return new AutopilotError(status, `the master's autopilot: ${errorText(error)}`)\n }\n\n private readonly provider: AutopilotProvider = {\n getData: async (device) => asInfo(await this.read(this.masterOrFail(), device, '')),\n getState: async (device) =>\n (valueOf(await this.read(this.masterOrFail(), device, '/state')) as string | null) ?? null,\n getMode: async (device) =>\n (valueOf(await this.read(this.masterOrFail(), device, '/mode')) as string | null) ?? null,\n getTarget: async (device) =>\n (valueOf(await this.read(this.masterOrFail(), device, '/target')) as number | null) ?? null,\n setState: (state, device) => this.send('PUT', device, '/state', { value: state }),\n setMode: (mode, device) => this.send('PUT', device, '/mode', { value: mode }),\n setTarget: (value, device) => this.send('PUT', device, '/target', { value, units: 'rad' }),\n adjustTarget: (value, device) =>\n this.send('PUT', device, '/target/adjust', { value, units: 'rad' }),\n engage: (device) => this.send('POST', device, '/engage'),\n disengage: (device) => this.send('POST', device, '/disengage'),\n courseCurrentPoint: (device) => this.send('POST', device, '/courseCurrentPoint'),\n courseNextPoint: (device) => this.send('POST', device, '/courseNextPoint'),\n tack: (direction: TackGybeDirection, device) => this.send('POST', device, `/tack/${direction}`),\n gybe: (direction: TackGybeDirection, device) => this.send('POST', device, `/gybe/${direction}`),\n // The server maps POST to 0 (dodge on) and DELETE to null (dodge off); a PUT steers by the value.\n dodge: (value, device) =>\n value === null\n ? this.send('DELETE', device, '/dodge')\n : value === 0\n ? this.send('POST', device, '/dodge')\n : this.send('PUT', device, '/dodge', { value, units: 'rad' })\n }\n}\n","/**\n * This server's readwrite device token on the master, for sending it the\n * commands a station gives: the autopilot's, and changes of the course.\n * Asked for once and approved by the user under Security -> Access Requests\n * on the master; a token for one master is no use for another.\n */\n\nimport type { MasterAccess } from './master-proxy.js'\nimport { pollAccess, requestAccess, type AccessRequestResult } from './peer-client.js'\nimport type { ControlAccess, MultihelmStore } from './store.js'\n\nexport interface MasterOfBoat {\n id: string\n access: MasterAccess\n}\n\nexport interface ControlHost {\n store: MultihelmStore\n serverId: string\n /** The id of the master now, whose access is the one kept; null when there is none. */\n currentMaster: () => string | null\n debug: (msg: string) => void\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nexport class MasterControlAccess {\n private control: ControlAccess | null\n /** The access request or poll in flight for each master, shared by everyone waiting for it. */\n private readonly asking = new Map<string, Promise<string | null>>()\n\n constructor(private readonly host: ControlHost) {\n this.control = host.store.loadControlAccess()\n }\n\n requestId(): string {\n return `signalk-multihelm-control-${this.host.serverId}`\n }\n\n /** The request the user has to approve on the master; null on the master itself. */\n waitingForApproval(isMaster: boolean): { masterId: string; request: string } | null {\n return !isMaster && this.control?.state === 'waiting-approval'\n ? { masterId: this.control.masterId, request: this.requestId() }\n : null\n }\n\n /** Whether the master denied it; it is asked for again only after a restart. */\n denied(): boolean {\n return this.control?.state === 'denied'\n }\n\n /** The master refused `token`: it is asked for again, unless a newer one is saved by now. */\n revoked(masterId: string, token: string): void {\n if (this.control?.masterId === masterId && this.control.token === token) {\n this.save(null)\n }\n }\n\n /** The token, empty without security; null until approved. */\n token(master: MasterOfBoat): Promise<string | null> {\n if (this.host.currentMaster() !== master.id) {\n return Promise.resolve(null)\n }\n let token = this.asking.get(master.id)\n if (!token) {\n token = this.ask(master).finally(() => {\n this.asking.delete(master.id)\n })\n this.asking.set(master.id, token)\n }\n return token\n }\n\n private async ask(master: MasterOfBoat): Promise<string | null> {\n if (this.control && this.control.masterId !== master.id) {\n this.save(null)\n }\n if (this.control?.state === 'granted') {\n return this.control.token\n }\n if (this.control?.state === 'denied') {\n return null\n }\n let result: AccessRequestResult\n try {\n result =\n this.control?.state === 'waiting-approval' && this.control.requestHref\n ? await pollAccess(master.access, this.control.requestHref)\n : await requestAccess(\n master.access,\n this.requestId(),\n 'Multihelm: send commands to the master from another station',\n 'readwrite'\n )\n } catch (error) {\n this.host.debug(`Multihelm: access request on the master: ${errorText(error)}`)\n return null\n }\n // The master moved on during the request: its answer must not replace the new master's access.\n if (this.host.currentMaster() !== master.id) {\n return null\n }\n switch (result.kind) {\n case 'no-security':\n this.save({ masterId: master.id, token: '', state: 'granted' })\n return ''\n case 'approved':\n this.save({ masterId: master.id, token: result.token, state: 'granted' })\n return result.token\n case 'pending':\n this.save({\n masterId: master.id,\n token: '',\n requestHref: result.href,\n state: 'waiting-approval'\n })\n return null\n case 'denied':\n // Asked again after a restart, as the user may have denied it by mistake.\n this.host.store.saveControlAccess(null)\n this.control = { masterId: master.id, token: '', state: 'denied' }\n return null\n case 'error':\n this.host.debug(`Multihelm: access request on the master: ${result.message}`)\n return null\n }\n }\n\n private save(access: ControlAccess | null): void {\n this.control = access\n this.host.store.saveControlAccess(access)\n }\n}\n","/**\n * The active destination or route, the same on every server: a server that\n * is not the master takes the master's course over, and a change made here\n * (a destination set at this station, the next point of the route) is sent\n * to the master, which all the others then take over. What is kept in step\n * is the setting itself, never the action that led to it, so two servers\n * that both move on to the next point at an arrival end on the same point.\n *\n * Both servers are read each second through their Course API. This server's\n * course is written with its own admin token, the master's with the control\n * token there. Each server works out the rest of the course (bearings, XTE)\n * from its own position; the start of a leg from the vessel position is\n * where that server was when it took the course over.\n */\n\nimport { isDeepStrictEqual } from 'node:util'\n\nimport type { MasterControlAccess, MasterOfBoat } from './master-control.js'\nimport type { OwnServerAccess } from './own-access.js'\nimport { PeerHttpError, callPeer, callServer } from './peer-client.js'\n\nexport const COURSE_PATH = '/signalk/v2/api/vessels/self/navigation/course'\nexport const COURSE_POLL_MS = 1_000\n\ninterface Position {\n latitude: number\n longitude: number\n}\n\n/** The part of a course the user sets. */\nexport interface CourseSetting {\n route: { href: string; pointIndex: number; reverse: boolean } | null\n /** The destination when no route is active. */\n point: { href: string } | { position: Position } | null\n arrivalCircle: number\n targetArrivalTime: string | null\n}\n\ntype Call = (method: 'GET' | 'PUT' | 'DELETE', path: string, body?: unknown) => Promise<unknown>\n\nexport interface CourseHost {\n /** The master to follow; null when this server is the master or there is none. */\n master: () => MasterOfBoat | null\n control: MasterControlAccess\n own: OwnServerAccess\n /** This server, over loopback: `http(s)://127.0.0.1:<port>`. */\n ownUrl: () => string\n debug: (msg: string) => void\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nfunction asPosition(value: unknown): Position | null {\n return isRecord(value) &&\n typeof value.latitude === 'number' &&\n typeof value.longitude === 'number'\n ? { latitude: value.latitude, longitude: value.longitude }\n : null\n}\n\n/** The setting in a Course API answer; null for an answer that is not one. */\nexport function courseSetting(raw: unknown): CourseSetting | null {\n if (!isRecord(raw)) {\n return null\n }\n const active = raw.activeRoute\n const next = raw.nextPoint\n let route: CourseSetting['route'] = null\n let point: CourseSetting['point'] = null\n if (isRecord(active) && typeof active.href === 'string') {\n route = {\n href: active.href,\n pointIndex: typeof active.pointIndex === 'number' ? active.pointIndex : 0,\n reverse: active.reverse === true\n }\n } else if (isRecord(next)) {\n const position = asPosition(next.position)\n point = typeof next.href === 'string' ? { href: next.href } : position ? { position } : null\n }\n return {\n route,\n point,\n arrivalCircle: typeof raw.arrivalCircle === 'number' ? raw.arrivalCircle : 0,\n targetArrivalTime: typeof raw.targetArrivalTime === 'string' ? raw.targetArrivalTime : null\n }\n}\n\n/** Makes the course `call` reaches, now `from`, into `to`. */\nexport async function writeCourse(\n call: Call,\n from: CourseSetting,\n to: CourseSetting\n): Promise<void> {\n let cleared = false\n if (to.route) {\n if (!isDeepStrictEqual(from.route, to.route)) {\n await call('PUT', '/activeRoute', { ...to.route, arrivalCircle: to.arrivalCircle })\n }\n } else if (to.point) {\n if (from.route || !isDeepStrictEqual(from.point, to.point)) {\n await call('PUT', '/destination', { ...to.point, arrivalCircle: to.arrivalCircle })\n }\n } else if (from.route || from.point) {\n await call('DELETE', '')\n cleared = true\n }\n if (from.arrivalCircle !== to.arrivalCircle) {\n await call('PUT', '/arrivalCircle', { value: to.arrivalCircle })\n }\n // Clearing the course clears its arrival time too.\n if ((cleared ? null : from.targetArrivalTime) !== to.targetArrivalTime) {\n await call('PUT', '/targetArrivalTime', { value: to.targetArrivalTime })\n }\n}\n\n/**\n * Whether `course` lies between `from` and `to`: each part as in one or the\n * other, as after a write from one to the other that stopped part way.\n */\nexport function onTheWay(course: CourseSetting, from: CourseSetting, to: CourseSetting): boolean {\n // Clearing the course clears its arrival time, which is set again after.\n const clearing = !to.route && !to.point\n return (Object.keys(course) as (keyof CourseSetting)[]).every(\n (key) =>\n isDeepStrictEqual(course[key], from[key]) ||\n isDeepStrictEqual(course[key], to[key]) ||\n (key === 'targetArrivalTime' && clearing && course[key] === null)\n )\n}\n\nexport class MasterCourse {\n private timer: NodeJS.Timeout | null = null\n private running = false\n /** The course both servers last agreed on, and the master it was agreed with. */\n private agreed: { masterId: string; course: CourseSetting } | null = null\n /**\n * A course set here whose sending to the master has not completed, and the\n * master's course it was sent over: sent again while the master's course is\n * still on the way from one to the other, and nobody else changed it.\n */\n private sending: { masterId: string; from: CourseSetting; course: CourseSetting } | null = null\n private stopped = false\n\n constructor(private readonly host: CourseHost) {}\n\n start(): void {\n this.timer = setInterval(() => {\n void this.sync()\n }, COURSE_POLL_MS)\n }\n\n stop(): void {\n this.stopped = true\n if (this.timer) {\n clearInterval(this.timer)\n }\n this.timer = null\n }\n\n /** One pass; never rejects. */\n async sync(): Promise<void> {\n if (this.running) {\n return\n }\n this.running = true\n try {\n await this.syncOnce()\n } catch (error) {\n this.host.debug(`Multihelm: the course from the master: ${errorText(error)}`)\n } finally {\n this.running = false\n }\n }\n\n private async syncOnce(): Promise<void> {\n const master = this.host.master()\n if (!master) {\n this.agreed = null\n this.sending = null\n return\n }\n const ownToken = await this.host.own.token()\n if (ownToken === null) {\n return\n }\n const here = this.ownCall(ownToken)\n const refusedHere = (): void => {\n this.host.own.revoked()\n }\n const theirs = await this.readMaster(master)\n const ours = courseSetting(await this.guarded(() => here('GET', ''), refusedHere))\n if (!theirs || !ours || !this.stillFor(master)) {\n return\n }\n const agreed = this.agreed?.masterId === master.id ? this.agreed.course : null\n if (isDeepStrictEqual(ours, theirs)) {\n this.agreed = { masterId: master.id, course: theirs }\n this.sending = null\n return\n }\n const sending =\n this.sending?.masterId === master.id && isDeepStrictEqual(this.sending.course, ours)\n ? this.sending\n : null\n const from = sending\n ? onTheWay(theirs, sending.from, ours)\n ? sending.from\n : null\n : agreed && isDeepStrictEqual(theirs, agreed)\n ? agreed\n : null\n // Changed here alone, or still on its way: the master takes it over. Otherwise the master's course holds.\n if (from) {\n await this.send(master, ours, from, sending !== null)\n return\n }\n this.sending = null\n await this.guarded(() => writeCourse(this.whileFor(master, here), ours, theirs), refusedHere)\n this.agreed = { masterId: master.id, course: theirs }\n this.host.debug(\"Multihelm: took the master's course over\")\n }\n\n /**\n * Sends `ours` to the master, if its course is still `from`, or on the way\n * from `from` to `ours` when an earlier sending stopped part way.\n */\n private async send(\n master: MasterOfBoat,\n ours: CourseSetting,\n from: CourseSetting,\n resending: boolean\n ): Promise<void> {\n const controlToken = await this.host.control.token(master)\n if (controlToken === null) {\n return\n }\n const theirs = await this.readMaster(master)\n const unchanged =\n theirs && (resending ? onTheWay(theirs, from, ours) : isDeepStrictEqual(theirs, from))\n if (!theirs || !unchanged || !this.stillFor(master)) {\n return\n }\n this.sending = { masterId: master.id, from, course: ours }\n await this.guarded(\n () => writeCourse(this.whileFor(master, this.masterCall(master, controlToken)), theirs, ours),\n () => {\n this.host.control.revoked(master.id, controlToken)\n }\n )\n this.sending = null\n this.agreed = { masterId: master.id, course: ours }\n this.host.debug('Multihelm: sent the course set here to the master')\n }\n\n /** `call`, refusing each request once the pass may no longer write for `master`. */\n private whileFor(master: MasterOfBoat, call: Call): Call {\n return (method, path, body) =>\n this.stillFor(master)\n ? call(method, path, body)\n : Promise.reject(new Error('stopped, or the master changed'))\n }\n\n private async readMaster(master: MasterOfBoat): Promise<CourseSetting | null> {\n return courseSetting(await callPeer('GET', master.access, COURSE_PATH, master.access.token))\n }\n\n /** Whether a pass begun for `master` may still write: not stopped, and the master unchanged. */\n private stillFor(master: MasterOfBoat): boolean {\n return !this.stopped && this.host.master()?.id === master.id\n }\n\n private async guarded<T>(work: () => Promise<T>, refused: () => void): Promise<T> {\n try {\n return await work()\n } catch (error) {\n if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) {\n refused()\n }\n throw error\n }\n }\n\n private ownCall(token: string): Call {\n return (method, path, body) =>\n callServer(method, `${this.host.ownUrl()}${COURSE_PATH}${path}`, token, body)\n }\n\n private masterCall(master: MasterOfBoat, token: string): Call {\n return (method, path, body) =>\n callPeer(method, master.access, `${COURSE_PATH}${path}`, token, body)\n }\n}\n","/**\n * Finds the other Signal K servers on the network, to offer them for pairing.\n *\n * Every Signal K server announces its REST API as `_signalk-http._tcp` (or\n * `_signalk-https._tcp`) over mDNS. The server's own discovery turns these\n * into data-connection suggestions only, so Multihelm asks for them itself\n * while it runs. Found servers are only shown; the user pairs with one.\n */\n\nimport os from 'node:os'\n\nimport makeMdns from 'multicast-dns'\nimport type { Answer, TxtAnswer } from 'dns-packet'\n\nimport { normalizePeerUrl } from './peer-client.js'\n\nconst SERVICES = ['_signalk-http._tcp.local', '_signalk-https._tcp.local']\nconst QUERY_INTERVAL_MS = 30_000\n/** A server not heard of for this long is dropped from the list. */\nconst FORGET_AFTER_MS = 3 * 60_000\n\nexport interface DiscoveredServer {\n /** The mDNS instance name, usually the host name. */\n name: string\n url: string\n /** The vessel name from the announcement, when it has one. */\n vessel?: string\n lastSeen: number\n}\n\ninterface Instance {\n service: string\n target?: string\n port?: number\n txt: Record<string, string>\n}\n\nfunction txtRecord(answer: TxtAnswer): Record<string, string> {\n const result: Record<string, string> = {}\n const data = Array.isArray(answer.data) ? answer.data : [answer.data]\n for (const entry of data) {\n const text = typeof entry === 'string' ? entry : Buffer.from(entry).toString('utf-8')\n const eq = text.indexOf('=')\n if (eq > 0) {\n result[text.slice(0, eq)] = text.slice(eq + 1)\n }\n }\n return result\n}\n\nfunction ownAddresses(): Set<string> {\n const result = new Set<string>()\n for (const list of Object.values(os.networkInterfaces())) {\n for (const info of list ?? []) {\n result.add(info.address)\n }\n }\n return result\n}\n\nexport class ServerDiscovery {\n private mdns: ReturnType<typeof makeMdns> | null = null\n private timer: NodeJS.Timeout | null = null\n private readonly instances = new Map<string, Instance>()\n private readonly addresses = new Map<string, string>()\n private readonly found = new Map<string, DiscoveredServer>()\n\n constructor(private readonly ownPort: () => number | undefined) {}\n\n start(): void {\n if (this.mdns) {\n return\n }\n try {\n this.mdns = makeMdns()\n } catch {\n this.mdns = null\n return\n }\n this.mdns.on('response', (response) => {\n this.takeRecords([...response.answers, ...response.additionals])\n })\n this.mdns.on('error', () => {\n // No multicast on this network; the list stays empty and pairing by address still works.\n })\n const query = (): void => {\n this.mdns?.query(SERVICES.map((name) => ({ name, type: 'PTR' as const })))\n }\n query()\n this.timer = setInterval(query, QUERY_INTERVAL_MS)\n }\n\n stop(): void {\n if (this.timer) {\n clearInterval(this.timer)\n this.timer = null\n }\n this.mdns?.destroy()\n this.mdns = null\n }\n\n list(): DiscoveredServer[] {\n const now = Date.now()\n for (const [key, server] of this.found) {\n if (now - server.lastSeen > FORGET_AFTER_MS) {\n this.found.delete(key)\n }\n }\n return [...this.found.values()].sort((a, b) => a.name.localeCompare(b.name))\n }\n\n /** Fold in the records of one mDNS response. */\n takeRecords(records: Answer[]): void {\n for (const record of records) {\n if (record.type === 'PTR' && SERVICES.includes(record.name)) {\n const instance = record.data\n if (!this.instances.has(instance)) {\n this.instances.set(instance, { service: record.name, txt: {} })\n }\n }\n }\n for (const record of records) {\n if (record.type === 'SRV') {\n const instance = this.instances.get(record.name)\n if (instance) {\n const srv = record.data\n instance.target = srv.target\n instance.port = srv.port\n }\n } else if (record.type === 'TXT') {\n const instance = this.instances.get(record.name)\n if (instance) {\n instance.txt = txtRecord(record)\n }\n } else if (record.type === 'A') {\n this.addresses.set(record.name, record.data)\n }\n }\n const own = ownAddresses()\n for (const [instance, info] of this.instances) {\n if (!info.target || info.port === undefined) {\n continue\n }\n const address = this.addresses.get(info.target)\n if (!address) {\n continue\n }\n if (own.has(address) && info.port === this.ownPort()) {\n continue\n }\n const scheme = info.service.startsWith('_signalk-https') ? 'https' : 'http'\n // Spelled as a paired peer's address is, so the two can be matched.\n const url = normalizePeerUrl(`${scheme}://${address}:${String(info.port)}`)\n if (!url) {\n continue\n }\n const server: DiscoveredServer = {\n name: instance.replace(`.${info.service}`, ''),\n url,\n lastSeen: Date.now()\n }\n if (info.txt.vname) {\n server.vessel = info.txt.vname\n }\n this.found.set(url, server)\n }\n }\n}\n","import { Type, type Static } from 'typebox'\n\nexport const ConfigSchema = Type.Object({\n master: Type.Boolean({\n title: \"This server is the boat's master\",\n description:\n 'Set this on one server only. Plugins that run on the master alone run here, and the other servers use them through this one.',\n default: false\n }),\n syncResources: Type.Boolean({\n title: 'Keep routes and waypoints in step',\n description:\n 'Routes, waypoints, regions and notes, kept the same on every server of the boat: a change on one reaches the others, with no master.',\n default: true\n }),\n followVessel: Type.Boolean({\n title: 'Take the vessel data over from the master',\n description:\n \"Name, MMSI, call sign, dimensions and ship type from Server -> Settings. Changes made here are replaced by the master's.\",\n default: true\n }),\n followMetadata: Type.Boolean({\n title: 'Take the path metadata over from the master',\n description:\n \"Display names, units, zones and alarm limits set for paths. Changes made here are replaced by the master's.\",\n default: true\n }),\n followSourcePriorities: Type.Boolean({\n title: 'Take the source priorities over from the master',\n description:\n \"Which source wins for a path, from Data -> Source Priorities. They name sources by connection, so give the NMEA 2000 bus the same connection name on every server. Changes made here are replaced by the master's.\",\n default: true\n }),\n historyFromMaster: Type.Boolean({\n title: \"Answer this server's History API from the master\",\n description:\n \"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.\",\n default: true\n }),\n autopilotFromMaster: Type.Boolean({\n title: \"Operate the master's autopilot from this server\",\n description:\n \"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.\",\n default: true\n }),\n courseFromMaster: Type.Boolean({\n title: 'Keep the course the same as on the master',\n description:\n \"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.\",\n default: true\n }),\n alarmsFromMaster: Type.Boolean({\n title: \"Show the master's alarms here\",\n description:\n '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.',\n default: true\n })\n})\n\n/** The settings as stored; any of them may be missing (see `start()`). */\nexport type Settings = Partial<Static<typeof ConfigSchema>>\n","/**\n * The source priorities the user set under Data -> Source Priorities, in the\n * shape of the server's `/skServer/priorities`: which source wins for a path\n * while it sends, and how long until the next one takes over.\n */\n\nexport interface PriorityGroup {\n id: string\n sources: string[]\n inactive?: boolean\n}\n\nexport interface PriorityEntry {\n sourceRef: string\n timeout: number\n}\n\nexport interface SourcePriorities {\n groups: PriorityGroup[]\n /** Signal K path -> its sources, best first. */\n overrides: Record<string, PriorityEntry[]>\n defaults: { fallbackMs?: number }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isText(value: unknown): value is string {\n return typeof value === 'string' && value !== ''\n}\n\nfunction group(value: unknown): PriorityGroup | null {\n if (\n !isRecord(value) ||\n !isText(value.id) ||\n !Array.isArray(value.sources) ||\n !(value.sources as unknown[]).every(isText) ||\n (value.inactive !== undefined && typeof value.inactive !== 'boolean')\n ) {\n return null\n }\n const sources = value.sources as string[]\n return value.inactive === undefined\n ? { id: value.id, sources }\n : { id: value.id, sources, inactive: value.inactive }\n}\n\n/** The server takes a timeout as an integer or a string of one, and keeps a number. */\nfunction entry(value: unknown): PriorityEntry | null {\n if (!isRecord(value) || !isText(value.sourceRef)) {\n return null\n }\n const timeout =\n typeof value.timeout === 'string' && /^-?\\d+$/.test(value.timeout)\n ? Number(value.timeout)\n : value.timeout\n return typeof timeout === 'number' && Number.isInteger(timeout)\n ? { sourceRef: value.sourceRef, timeout }\n : null\n}\n\nfunction allOrNull<T>(items: unknown[], parse: (item: unknown) => T | null): T[] | null {\n const parsed = items.map(parse)\n return parsed.every((item) => item !== null) ? parsed : null\n}\n\n/**\n * Null unless every part has the shape above: a priorities list cut short\n * would replace a server's whole set with less than the master meant.\n */\nexport function parseSourcePriorities(raw: unknown): SourcePriorities | null {\n if (!isRecord(raw) || !Array.isArray(raw.groups) || !isRecord(raw.overrides)) {\n return null\n }\n const groups = allOrNull(raw.groups as unknown[], group)\n const overrides: Record<string, PriorityEntry[]> = {}\n for (const [path, list] of Object.entries(raw.overrides)) {\n const entries = Array.isArray(list) ? allOrNull(list as unknown[], entry) : null\n if (!entries) {\n return null\n }\n overrides[path] = entries\n }\n const defaults = raw.defaults ?? {}\n if (!groups || !isRecord(defaults)) {\n return null\n }\n const { fallbackMs } = defaults\n if (fallbackMs === undefined) {\n return { groups, overrides, defaults: {} }\n }\n return typeof fallbackMs === 'number' && fallbackMs > 0 && Number.isFinite(fallbackMs)\n ? { groups, overrides, defaults: { fallbackMs } }\n : null\n}\n\n/** What this server holds in its settings, read the way `/skServer/priorities` answers. */\nexport function sourcePrioritiesFromSettings(settings: {\n priorityGroups?: unknown\n priorityOverrides?: unknown\n priorityDefaults?: unknown\n}): SourcePriorities | null {\n return parseSourcePriorities({\n groups: settings.priorityGroups ?? [],\n overrides: settings.priorityOverrides ?? {},\n defaults: settings.priorityDefaults ?? {}\n })\n}\n","/**\n * What the user set for this vessel on the server: the vessel data from\n * Server -> Settings and the metadata set for paths (display names, units,\n * zones). The server keeps both as its base deltas, sent again at every\n * start; they are the self vessel's part of those deltas.\n */\n\nimport { parseSourcePriorities, type SourcePriorities } from './source-priorities.js'\n\n/** The fields of the server's `/skServer/vessel` that follow the master. */\nexport interface VesselData {\n name?: string\n mmsi?: string\n uuid?: string\n draft?: number\n length?: number\n beam?: number\n height?: number\n aisShipType?: number\n callsignVhf?: string\n}\n\nexport const VESSEL_FIELDS = [\n 'name',\n 'mmsi',\n 'uuid',\n 'draft',\n 'length',\n 'beam',\n 'height',\n 'aisShipType',\n 'callsignVhf'\n] as const satisfies readonly (keyof VesselData)[]\n\nexport interface VesselSettings {\n vessel: VesselData\n /** Signal K path -> its metadata. */\n meta: Record<string, unknown>\n /** Absent from a server that does not send them, such as an older Multihelm. */\n priorities?: SourcePriorities\n}\n\nconst SELF = 'vessels.self'\n\n/** A path whose metadata can be read and written: dot-separated segments, none empty. */\nexport function isMetaPath(path: string): boolean {\n return /^[A-Za-z0-9_:-]+(\\.[A-Za-z0-9_:-]+)*$/.test(path)\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction pathValues(list: unknown): { path: string; value: unknown }[] {\n if (!Array.isArray(list)) {\n return []\n }\n return (list as unknown[]).flatMap((pv) =>\n isRecord(pv) && typeof pv.path === 'string' ? [{ path: pv.path, value: pv.value }] : []\n )\n}\n\nfunction text(value: unknown): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined\n}\n\nfunction num(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\nfunction field(value: unknown, key: string): unknown {\n return isRecord(value) ? value[key] : undefined\n}\n\nfunction vesselData(values: Map<string, unknown>): VesselData {\n const length = values.get('design.length')\n const data: VesselData = {\n name: text(values.get('name')),\n mmsi: text(values.get('mmsi')),\n uuid: text(values.get('uuid')),\n draft: num(field(values.get('design.draft'), 'maximum')),\n length: num(length) ?? num(field(length, 'overall')),\n beam: num(values.get('design.beam')),\n height: num(values.get('design.airHeight')),\n aisShipType: num(field(values.get('design.aisShipType'), 'id')),\n callsignVhf: text(field(values.get('communication'), 'callsignVhf'))\n }\n return Object.fromEntries(Object.entries(data).filter(([, v]) => v !== undefined))\n}\n\nexport function vesselSettingsFromDeltas(deltas: unknown): VesselSettings {\n const values = new Map<string, unknown>()\n const meta: Record<string, unknown> = {}\n if (Array.isArray(deltas)) {\n for (const delta of deltas as unknown[]) {\n if (!isRecord(delta) || delta.context !== SELF || !Array.isArray(delta.updates)) {\n continue\n }\n for (const update of delta.updates as unknown[]) {\n if (!isRecord(update)) {\n continue\n }\n for (const { path, value } of pathValues(update.values)) {\n if (path === '' && isRecord(value)) {\n for (const [k, v] of Object.entries(value)) {\n values.set(k, v)\n }\n } else if (path !== '') {\n values.set(path, value)\n }\n }\n for (const { path, value } of pathValues(update.meta)) {\n if (isMetaPath(path)) {\n meta[path] = value\n }\n }\n }\n }\n }\n return { vessel: vesselData(values), meta }\n}\n\n/** A peer's answer, kept to the shape above; anything else is dropped. */\nexport function parseVesselSettings(raw: unknown): VesselSettings | null {\n if (!isRecord(raw) || !isRecord(raw.vessel) || !isRecord(raw.meta)) {\n return null\n }\n const v = raw.vessel\n const vessel: VesselData = {}\n for (const key of ['name', 'mmsi', 'uuid', 'callsignVhf'] as const) {\n const t = text(v[key])\n if (t !== undefined) {\n vessel[key] = t\n }\n }\n for (const key of ['draft', 'length', 'beam', 'height', 'aisShipType'] as const) {\n const n = num(v[key])\n if (n !== undefined) {\n vessel[key] = n\n }\n }\n const meta: Record<string, unknown> = {}\n for (const [path, value] of Object.entries(raw.meta)) {\n if (isMetaPath(path) && isRecord(value)) {\n meta[path] = value\n }\n }\n const priorities = parseSourcePriorities(raw.priorities)\n return priorities ? { vessel, meta, priorities } : { vessel, meta }\n}\n","/**\n * On a server that is not the master: takes the vessel data, path metadata\n * and source priorities over from the master. They are read from the\n * master with the pairing token and written here through this server's own\n * REST API, the way its settings pages write them, so they survive a\n * restart, with this server's admin device token on itself. Metadata of a path the\n * master has none for stays as it is, unless it was the master's before.\n */\n\nimport { isDeepStrictEqual } from 'node:util'\n\nimport type { MasterAccess } from './master-proxy.js'\nimport type { OwnServerAccess } from './own-access.js'\nimport { PeerHttpError, callServer, fetchVesselSettings } from './peer-client.js'\nimport type { SourcePriorities } from './source-priorities.js'\nimport type { MultihelmStore } from './store.js'\nimport {\n VESSEL_FIELDS,\n parseVesselSettings,\n type VesselData,\n type VesselSettings\n} from './vessel-settings.js'\n\nexport interface FollowHost {\n store: MultihelmStore\n access: OwnServerAccess\n /** This server, over loopback: `http(s)://127.0.0.1:<port>`. */\n ownUrl: () => string\n /** What this server holds now; null when the server does not expose it. */\n localSettings: () => VesselSettings | null\n /** The master to follow, or null when this server is the master or there is none. */\n master: () => MasterAccess | null\n followVessel: boolean\n followMeta: boolean\n followPriorities: boolean\n debug: (msg: string) => void\n error: (msg: string) => void\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/** A master where none are set yet would wipe the ones a server kept from before Multihelm. */\nfunction hasPriorities(priorities: SourcePriorities): boolean {\n return priorities.groups.length > 0 || Object.keys(priorities.overrides).length > 0\n}\n\n/**\n * What was last written here and what this server kept of it, seen a round\n * later. A server may keep a value differently from how it was written (a\n * base delta file with the same path twice keeps the older one in force), so\n * a value is not written again until the master's or this server's changes.\n */\nclass WrittenValues {\n private readonly written = new Map<string, { target: unknown; kept?: { value: unknown } }>()\n\n /** Whether `target` is to be written over `local`. */\n due(key: string, target: unknown, local: unknown): boolean {\n if (isDeepStrictEqual(target, local)) {\n this.written.delete(key)\n return false\n }\n const last = this.written.get(key)\n if (last && isDeepStrictEqual(last.target, target)) {\n if (!last.kept) {\n last.kept = { value: local }\n return false\n }\n if (isDeepStrictEqual(last.kept.value, local)) {\n return false\n }\n }\n return true\n }\n\n wrote(key: string, target: unknown): void {\n this.written.set(key, { target })\n }\n\n /** What is not looked at in a round may have changed meanwhile, so it is forgotten. */\n keepOnly(keys: ReadonlySet<string>): void {\n for (const key of this.written.keys()) {\n if (!keys.has(key)) {\n this.written.delete(key)\n }\n }\n }\n}\n\nfunction metaUrl(base: string, path: string): string {\n const segments = path.split('.').map((s) => encodeURIComponent(s))\n return `${base}/signalk/v1/api/vessels/self/${segments.join('/')}/meta`\n}\n\nexport class MasterFollower {\n private readonly prioritiesWritten = new WrittenValues()\n private readonly metaWritten = new WrittenValues()\n /**\n * The paths whose metadata is the master's: all it has, and the ones it\n * had until they are gone here too.\n */\n private followedMeta: Set<string>\n /** The list as last saved; a failed save is tried again the next round. */\n private followedMetaSaved: string\n\n constructor(private readonly host: FollowHost) {\n const followed = host.store.loadFollowedMeta()\n this.followedMeta = new Set(followed)\n this.followedMetaSaved = JSON.stringify(followed.sort())\n }\n\n async run(): Promise<void> {\n const { followVessel, followMeta, followPriorities } = this.host\n const master = this.host.master()\n const local = this.host.localSettings()\n if ((!followVessel && !followMeta && !followPriorities) || !master || !local) {\n return\n }\n let remote: VesselSettings | null\n try {\n remote = parseVesselSettings(await fetchVesselSettings(master, master.token))\n } catch (error) {\n this.host.debug(`Multihelm: vessel settings from the master: ${errorText(error)}`)\n return\n }\n if (!remote) {\n return\n }\n const vesselChanged =\n followVessel && VESSEL_FIELDS.some((k) => remote.vessel[k] !== local.vessel[k])\n if (followMeta) {\n this.followedMeta = new Set([\n ...Object.keys(remote.meta),\n ...[...this.followedMeta].filter((p) => local.meta[p] !== undefined)\n ])\n this.metaWritten.keepOnly(this.followedMeta)\n this.saveFollowedMeta()\n }\n const metaChanged = followMeta\n ? [...this.followedMeta].filter((p) => this.metaWritten.due(p, remote.meta[p], local.meta[p]))\n : []\n const priorities = followPriorities\n ? this.prioritiesToWrite(remote.priorities, local.priorities)\n : null\n if (!vesselChanged && metaChanged.length === 0 && !priorities) {\n return\n }\n const token = await this.host.access.token()\n if (token === null) {\n return\n }\n const base = this.host.ownUrl()\n try {\n if (vesselChanged) {\n await this.writeVessel(base, token, remote.vessel)\n }\n for (const path of metaChanged) {\n const value = remote.meta[path]\n await (value === undefined\n ? callServer('DELETE', metaUrl(base, path), token)\n : callServer('PUT', metaUrl(base, path), token, { value }))\n this.metaWritten.wrote(path, value)\n }\n if (priorities) {\n await callServer('PUT', `${base}/skServer/priorities`, token, priorities)\n this.prioritiesWritten.wrote('', priorities)\n }\n } catch (error) {\n if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) {\n this.host.access.revoked()\n }\n this.host.error(`Multihelm: taking over the master's vessel settings: ${errorText(error)}`)\n }\n if (followMeta) {\n this.saveFollowedMeta()\n }\n }\n\n private saveFollowedMeta(): void {\n const paths = [...this.followedMeta].sort()\n const text = JSON.stringify(paths)\n if (text === this.followedMetaSaved) {\n return\n }\n try {\n this.host.store.saveFollowedMeta(paths)\n this.followedMetaSaved = text\n } catch (error) {\n this.host.error(`Multihelm: saving the paths that follow the master: ${errorText(error)}`)\n }\n }\n\n private prioritiesToWrite(\n remote: SourcePriorities | undefined,\n local: SourcePriorities | undefined\n ): SourcePriorities | null {\n if (!remote || !hasPriorities(remote) || !local) {\n return null\n }\n return this.prioritiesWritten.due('', remote, local) ? remote : null\n }\n\n /** The vessel route writes every field, so the ones that stay here are sent back as they are. */\n private async writeVessel(base: string, token: string, vessel: VesselData): Promise<void> {\n const current = await callServer('GET', `${base}/skServer/vessel`, token)\n const body: Record<string, unknown> =\n typeof current === 'object' && current !== null ? { ...current } : {}\n for (const key of VESSEL_FIELDS) {\n body[key] = vessel[key]\n }\n await callServer('PUT', `${base}/skServer/vessel`, token, body)\n }\n}\n","/**\n * Plugins that run on the boat's master only, such as an autopilot provider\n * that must not send from more than one server. The list is the same on\n * every server, kept in step as a dataset with no master, so a server that\n * becomes the master already knows it. Each server switches those plugins\n * on or off through its own REST API, as the admin UI does, so the state\n * survives a restart and the admin UI shows it.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nimport type { DatasetDefinition, DatasetEntry, IncomingEntry } from './api.js'\nimport type { OwnServerAccess } from './own-access.js'\nimport { PeerHttpError, callServer } from './peer-client.js'\n\nexport const SETTINGS_DATASET = 'signalk-multihelm/settings'\nexport const MASTER_PLUGINS_KEY = 'master-plugins'\nconst FILE = 'plugins.json'\nconst PLUGIN_ID = /^[\\w.@-]{1,100}$/\nconst MAX_PLUGINS = 100\n\nexport function parsePluginIds(raw: unknown): string[] | null {\n if (!Array.isArray(raw) || raw.length > MAX_PLUGINS) {\n return null\n }\n const ids: string[] = []\n for (const id of raw) {\n if (typeof id !== 'string' || !PLUGIN_ID.test(id)) {\n return null\n }\n ids.push(id)\n }\n return [...new Set(ids)].sort()\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/** The list, kept in a file of its own under `dir`, since a dataset entry is made of files. */\nexport class MasterPluginList {\n private readonly file: string\n private current: string[]\n /** Writes one after the other, so two cannot share the temporary file or publish out of order. */\n private writes: Promise<unknown> = Promise.resolve()\n\n constructor(\n dir: string,\n private readonly onChange: () => void\n ) {\n this.file = path.join(dir, FILE)\n this.current = this.read()\n }\n\n ids(): string[] {\n return this.current\n }\n\n set(ids: string[]): Promise<void> {\n return this.queued(() => this.write(ids))\n }\n\n readonly dataset: DatasetDefinition = {\n id: SETTINGS_DATASET,\n isValidKey: (key) => key === MASTER_PLUGINS_KEY,\n\n list: async (): Promise<DatasetEntry[]> => {\n let stat: fs.Stats\n try {\n stat = await fs.promises.stat(this.file)\n } catch {\n return []\n }\n return [\n {\n key: MASTER_PLUGINS_KEY,\n meta: null,\n files: [{ name: FILE, path: this.file, size: stat.size, mtimeMs: stat.mtimeMs }]\n }\n ]\n },\n\n apply: async (entry: IncomingEntry): Promise<void> => {\n const file = entry.files.find((f) => f.name === FILE)\n if (!file || entry.files.length !== 1) {\n throw new Error(`the plugin list has one file, ${String(entry.files.length)} came`)\n }\n const ids = parsePluginIds(JSON.parse(await fs.promises.readFile(file.path, 'utf8')))\n if (!ids) {\n throw new Error('not a list of plugin ids')\n }\n await this.queued(() => this.write(ids))\n },\n\n remove: async (): Promise<boolean> => {\n await this.queued(async () => {\n await fs.promises.rm(this.file, { force: true })\n this.changed([])\n })\n return true\n }\n }\n\n private queued(work: () => Promise<void>): Promise<void> {\n const result = this.writes.then(work)\n this.writes = result.catch(() => undefined)\n return result\n }\n\n private read(): string[] {\n try {\n return parsePluginIds(JSON.parse(fs.readFileSync(this.file, 'utf8'))) ?? []\n } catch {\n return []\n }\n }\n\n private async write(ids: string[]): Promise<void> {\n const sorted = parsePluginIds(ids)\n if (!sorted) {\n throw new Error('not a list of plugin ids')\n }\n const text = JSON.stringify(sorted)\n let had: string | null = null\n try {\n had = await fs.promises.readFile(this.file, 'utf8')\n } catch {\n // Not written yet.\n }\n if (had !== text) {\n await fs.promises.mkdir(path.dirname(this.file), { recursive: true })\n const tmp = `${this.file}.part`\n await fs.promises.writeFile(tmp, text)\n await fs.promises.rename(tmp, this.file)\n }\n this.changed(sorted)\n }\n\n private changed(ids: string[]): void {\n const before = JSON.stringify(this.current)\n this.current = ids\n if (JSON.stringify(ids) !== before) {\n this.onChange()\n }\n }\n}\n\nexport interface SwitchHost {\n ids: () => string[]\n /** true: run them on this server; false: stop them here; null: leave them as they are. */\n wanted: () => boolean | null\n access: OwnServerAccess\n /** This server, over loopback: `http(s)://127.0.0.1:<port>`. */\n ownUrl: () => string\n /** Multihelm itself, which is never switched. */\n selfId: string\n debug: (msg: string) => void\n error: (msg: string) => void\n}\n\nfunction pluginUrl(base: string, id: string, rest = ''): string {\n return `${base}/plugins/${encodeURIComponent(id)}${rest}`\n}\n\n/** Switches the listed plugins on this server to what its role wants; one run at a time. */\nexport class MasterOnlyPlugins {\n private running = false\n private again = false\n\n constructor(private readonly host: SwitchHost) {}\n\n apply(): void {\n if (this.running) {\n this.again = true\n return\n }\n this.running = true\n void this.applyOnce()\n .catch((error: unknown) => {\n this.host.error(\n `Multihelm: switching the plugins that run on the master: ${errorText(error)}`\n )\n })\n .finally(() => {\n this.running = false\n if (this.again) {\n this.again = false\n this.apply()\n }\n })\n }\n\n async applyOnce(): Promise<void> {\n const wanted = this.host.wanted()\n const ids = this.host.ids().filter((id) => id !== this.host.selfId)\n if (wanted === null || ids.length === 0) {\n return\n }\n const token = await this.host.access.token()\n if (token === null) {\n return\n }\n const base = this.host.ownUrl()\n for (const id of ids) {\n try {\n const state = await callServer('GET', pluginUrl(base, id), token)\n if ((state as { enabled?: unknown } | null)?.enabled === wanted) {\n continue\n }\n const options = await callServer('GET', pluginUrl(base, id, '/config'), token)\n // The role or the list may have moved during the requests; the next pass follows them.\n if (this.host.wanted() !== wanted) {\n return\n }\n if (!this.host.ids().includes(id)) {\n continue\n }\n const body =\n typeof options === 'object' && options !== null && !Array.isArray(options)\n ? { ...options, enabled: wanted }\n : { enabled: wanted }\n await callServer('POST', pluginUrl(base, id, '/config'), token, body)\n this.host.debug(\n `Multihelm: ${wanted ? 'started' : 'stopped'} ${id}, which runs on the master only`\n )\n } catch (error) {\n if (error instanceof PeerHttpError && error.status === 404) {\n this.host.debug(`Multihelm: ${id}, set to run on the master only, is not installed here`)\n continue\n }\n if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) {\n this.host.access.revoked()\n this.host.error(`Multihelm: this server refused its own admin token: ${errorText(error)}`)\n return\n }\n this.host.error(\n `Multihelm: cannot ${wanted ? 'start' : 'stop'} ${id}, which runs on the master only: ${errorText(error)}`\n )\n }\n }\n }\n}\n","/**\n * On a server that is not the master, answers this server's History API\n * from the master's, so the history is kept once on the boat. It registers\n * as a history provider only while the master has one itself.\n */\n\nimport type {\n ContextsRequest,\n ContextsResponse,\n HistoryProvider,\n PathSpec,\n PathsRequest,\n PathsResponse,\n ValuesRequest,\n ValuesResponse\n} from '@signalk/server-api/history'\n\nimport type { MasterResponse, MasterRouteHandle } from './api.js'\n\nexport const HISTORY_PREFIX = '/signalk/v2/api/history/'\nconst HTTP_OK = 200\nconst HTTP_NOT_FOUND = 404\n\nexport interface MasterHistoryHost {\n registerMasterRoute: (prefix: string) => MasterRouteHandle\n fetchMaster: (path: string) => Promise<MasterResponse>\n /** This server is a member and another server is the master. */\n hasMaster: () => boolean\n register: (provider: HistoryProvider) => void\n unregister: () => void\n debug: (msg: string) => void\n}\n\ntype RangeRequest = ContextsRequest & { context?: string }\n\nfunction rangeParams(request: RangeRequest): URLSearchParams {\n const params = new URLSearchParams()\n if (request.from !== undefined) {\n params.set('from', request.from.toString())\n }\n if (request.to !== undefined) {\n params.set('to', request.to.toString())\n }\n if (request.duration !== undefined) {\n params.set('duration', request.duration.toString())\n }\n if (request.context !== undefined) {\n params.set('context', request.context)\n }\n return params\n}\n\nexport function pathExpression(spec: PathSpec): string {\n const parameters = spec.parameter.map((p) => `:${p}`).join('')\n const source = spec.sourceRef ? `|${spec.sourceRef}` : ''\n return `${spec.path}:${spec.aggregate}${parameters}${source}`\n}\n\nexport function valuesQuery(request: ValuesRequest): string {\n const params = rangeParams(request)\n params.set('paths', request.pathSpecs.map(pathExpression).join(','))\n if (request.resolution !== undefined) {\n params.set('resolution', String(request.resolution))\n }\n if (request.sourcePolicy !== undefined) {\n params.set('sourcePolicy', request.sourcePolicy)\n }\n return params.toString()\n}\n\n/** Before Signal K 2.32.0 a plugin cannot withdraw its history provider, so it must not register one. */\nexport function canWithdrawHistoryProvider(app: object): boolean {\n return (\n typeof (app as { unregisterHistoryApiProvider?: unknown }).unregisterHistoryApiProvider ===\n 'function'\n )\n}\n\nexport class MasterHistory {\n private registered = false\n /** Only the latest check may act on its answer; stop() outdates every check in flight. */\n private latestCheck = 0\n private route: MasterRouteHandle | null = null\n private readonly provider: HistoryProvider = {\n getValues: (request: ValuesRequest) =>\n this.read<ValuesResponse>(`values?${valuesQuery(request)}`),\n getPaths: (request: PathsRequest) =>\n this.read<PathsResponse>(`paths?${rangeParams(request).toString()}`),\n getContexts: (request: ContextsRequest) =>\n this.read<ContextsResponse>(`contexts?${rangeParams(request).toString()}`)\n }\n\n constructor(private readonly host: MasterHistoryHost) {}\n\n /** Registers while the master has a history provider, and withdraws otherwise. */\n async check(): Promise<void> {\n const thisCheck = ++this.latestCheck\n if (!this.host.hasMaster()) {\n this.withdraw()\n return\n }\n this.route ??= this.host.registerMasterRoute(HISTORY_PREFIX)\n let providers: unknown\n try {\n providers = await this.masterProviders()\n } catch (error) {\n // A master that answers again soon keeps serving the history meanwhile.\n this.host.debug(\n `Multihelm: cannot ask the master for its history providers: ${error instanceof Error ? error.message : String(error)}`\n )\n return\n }\n if (thisCheck !== this.latestCheck) {\n return\n }\n const masterHasHistory =\n typeof providers === 'object' && providers !== null && Object.keys(providers).length > 0\n if (masterHasHistory && this.host.hasMaster()) {\n if (!this.registered) {\n this.host.register(this.provider)\n this.registered = true\n this.host.debug(\"Multihelm: serving the master's history\")\n }\n } else {\n this.withdraw()\n }\n }\n\n stop(): void {\n this.latestCheck++\n this.withdraw()\n this.route?.unregister()\n this.route = null\n }\n\n private withdraw(): void {\n if (this.registered) {\n this.host.unregister()\n this.registered = false\n this.host.debug(\"Multihelm: no longer serving the master's history\")\n }\n }\n\n /** A master without the History API has no providers; any other failure says nothing. */\n private async masterProviders(): Promise<unknown> {\n const answer = await this.host.fetchMaster(`${HISTORY_PREFIX}_providers`)\n if (answer.status === HTTP_NOT_FOUND) {\n return {}\n }\n if (answer.status !== HTTP_OK) {\n throw new Error(`HTTP ${String(answer.status)}`)\n }\n return JSON.parse(answer.body.toString('utf-8')) as unknown\n }\n\n private async read<T>(query: string): Promise<T> {\n const answer = await this.host.fetchMaster(`${HISTORY_PREFIX}${query}`)\n if (answer.status !== HTTP_OK) {\n throw new Error(`the master's History API answered HTTP ${String(answer.status)}`)\n }\n return JSON.parse(answer.body.toString('utf-8')) as T\n }\n}\n","/**\n * Serves what the boat's master provides at this server's own\n * `/plugins/signalk-multihelm/master/<path>`, so a browser at this station\n * talks to its own server only: no token for the master, no CORS, no mixed\n * content. Only paths under a prefix a plugin registered are forwarded,\n * always to the paired master and with its readonly pairing token; the\n * caller's credentials stay here.\n */\n\nimport http from 'node:http'\nimport https from 'node:https'\n\nimport type { MasterResponse, MasterRouteHandle } from './api.js'\nimport { ROUTE_PREFIX, tlsOptions, type PeerAddress } from './peer-client.js'\n\nexport const MASTER_ROUTE = '/master'\nconst REQUEST_TIMEOUT_MS = 30_000\n/** Largest body `fetch` reads into memory; the route itself streams. */\nconst MAX_FETCH_BYTES = 16 * 1024 * 1024\n\nconst SAFE_PATH = /^\\/[A-Za-z0-9\\-._~!$&'()*+,;=:@%/]*$/\n/** Encoded `.`, `/`, `\\` and NUL, which could turn into a traversal after decoding. */\nconst ENCODED_SEPARATOR = /%(2e|2f|5c|00)/i\nconst FORBIDDEN_PREFIXES = [\n '/admin',\n '/skServer',\n '/signalk/v1/access',\n '/signalk/v1/auth',\n `${ROUTE_PREFIX}/`\n]\n\nconst FORWARDED_REQUEST_HEADERS = [\n 'accept',\n 'accept-encoding',\n 'if-none-match',\n 'if-modified-since',\n 'range'\n]\nconst FORWARDED_RESPONSE_HEADERS = [\n 'accept-ranges',\n 'cache-control',\n 'content-encoding',\n 'content-length',\n 'content-range',\n 'content-type',\n 'etag',\n 'expires',\n 'last-modified',\n 'vary'\n]\n\nexport interface MasterAccess extends PeerAddress {\n /** Empty when the master runs without security. */\n token: string\n}\n\nexport class MasterProxyError extends Error {\n constructor(\n readonly status: number,\n message: string\n ) {\n super(message)\n }\n}\n\nexport function isSafePath(path: string): boolean {\n if (!SAFE_PATH.test(path) || path.includes('//') || ENCODED_SEPARATOR.test(path)) {\n return false\n }\n return path\n .split('/')\n .slice(1)\n .every((segment) => segment !== '.' && segment !== '..')\n}\n\nexport function isValidPrefix(prefix: string): boolean {\n return (\n prefix.length > 1 &&\n prefix.endsWith('/') &&\n isSafePath(prefix) &&\n // Express and Signal K match routes regardless of case.\n !FORBIDDEN_PREFIXES.some((forbidden) =>\n prefix.toLowerCase().startsWith(forbidden.toLowerCase())\n )\n )\n}\n\nfunction headersFrom(source: http.IncomingHttpHeaders, names: string[]): Record<string, string> {\n const headers: Record<string, string> = {}\n for (const name of names) {\n const value = source[name]\n if (typeof value === 'string') {\n headers[name] = value\n }\n }\n return headers\n}\n\nexport class MasterProxy {\n private readonly prefixes = new Map<symbol, string>()\n private readonly agents = {\n http: new http.Agent({ keepAlive: true }),\n https: new https.Agent({ keepAlive: true })\n }\n\n constructor(private readonly master: () => MasterAccess | null) {}\n\n register(prefix: string): MasterRouteHandle {\n if (!isValidPrefix(prefix)) {\n throw new Error(`not a path prefix Multihelm forwards to the master: ${prefix}`)\n }\n const id = Symbol(prefix)\n this.prefixes.set(id, prefix)\n return {\n unregister: () => {\n this.prefixes.delete(id)\n }\n }\n }\n\n /** The path and query of `target` when it may be forwarded, else null. */\n allowed(target: string): string | null {\n const queryAt = target.indexOf('?')\n const path = queryAt === -1 ? target : target.slice(0, queryAt)\n if (!isSafePath(path)) {\n return null\n }\n for (const prefix of this.prefixes.values()) {\n // A collection is listed at the prefix without its slash.\n if (path.startsWith(prefix) || path === prefix.slice(0, -1)) {\n return target\n }\n }\n return null\n }\n\n /** Forwards a GET that arrived at `<route>/master<target>` and streams the answer back. */\n forward(target: string, req: http.IncomingMessage, res: http.ServerResponse): void {\n let upstream: http.ClientRequest\n try {\n upstream = this.request(target, headersFrom(req.headers, FORWARDED_REQUEST_HEADERS))\n } catch (error) {\n const status = error instanceof MasterProxyError ? error.status : 500\n res.statusCode = status\n res.setHeader('Content-Type', 'application/json')\n res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }))\n return\n }\n upstream.on('response', (answer) => {\n res.writeHead(\n answer.statusCode ?? 502,\n headersFrom(answer.headers, FORWARDED_RESPONSE_HEADERS)\n )\n answer.on('error', (error) => {\n res.destroy(error)\n })\n answer.pipe(res)\n })\n upstream.on('error', (error) => {\n if (res.headersSent) {\n res.destroy(error)\n return\n }\n res.statusCode = error.message.startsWith('timeout') ? 504 : 502\n res.setHeader('Content-Type', 'application/json')\n res.end(JSON.stringify({ error: `the master did not answer: ${error.message}` }))\n })\n res.on('close', () => {\n if (!res.writableFinished) {\n upstream.destroy()\n }\n })\n upstream.end()\n }\n\n /** Reads a path under a registered prefix from the master, for plugins on this server. */\n fetch(target: string): Promise<MasterResponse> {\n return new Promise((resolve, reject) => {\n const upstream = this.request(target, {})\n upstream.on('response', (answer) => {\n const chunks: Buffer[] = []\n let size = 0\n answer.on('data', (chunk: Buffer) => {\n size += chunk.length\n if (size > MAX_FETCH_BYTES) {\n upstream.destroy(new Error(`answer larger than ${String(MAX_FETCH_BYTES)} bytes`))\n return\n }\n chunks.push(chunk)\n })\n answer.on('end', () => {\n resolve({\n status: answer.statusCode ?? 0,\n headers: headersFrom(answer.headers, FORWARDED_RESPONSE_HEADERS),\n body: Buffer.concat(chunks)\n })\n })\n answer.on('error', reject)\n })\n upstream.on('error', reject)\n upstream.end()\n })\n }\n\n stop(): void {\n this.prefixes.clear()\n this.agents.http.destroy()\n this.agents.https.destroy()\n }\n\n private request(target: string, headers: Record<string, string>): http.ClientRequest {\n const allowed = this.allowed(target)\n if (allowed === null) {\n throw new MasterProxyError(404, 'no plugin forwards this path to the master')\n }\n const master = this.master()\n if (!master) {\n throw new MasterProxyError(503, 'no other server is the master now')\n }\n const url = new URL(`${master.url}${allowed}`)\n const secure = url.protocol === 'https:'\n const request = secure ? https.request : http.request\n const upstream = request(url, {\n method: 'GET',\n headers: master.token ? { ...headers, Authorization: `Bearer ${master.token}` } : headers,\n agent: secure ? this.agents.https : this.agents.http,\n timeout: REQUEST_TIMEOUT_MS,\n // Unlike the peer client, never lenient with a loopback master: it holds the pairing token.\n ...(secure && master.ca !== undefined ? tlsOptions(url, master.ca) : {})\n })\n upstream.on('timeout', () => {\n upstream.destroy(new Error(`timeout after ${String(REQUEST_TIMEOUT_MS)} ms`))\n })\n return upstream\n }\n}\n","/**\n * One dataset's library: the entries this server holds, with the version\n * every server agrees on without a master.\n *\n * Each entry carries a counter and the server that last changed it. A local\n * change takes the counter one past the entry's current one, so a change\n * made after seeing a peer's version wins over it. Two servers changing the\n * same entry without seeing each other's change tie on the counter; the\n * higher server id wins, so every server picks the same one without\n * comparing clocks.\n */\n\nimport crypto from 'node:crypto'\n\nexport interface Version {\n counter: number\n /** The server id that made this version. */\n origin: string\n}\n\n/** A file of an entry as peers see it. */\nexport interface FileInfo {\n name: string\n size: number\n sha256: string\n}\n\n/** A file of an entry as this server holds it. */\nexport interface LocalFile {\n name: string\n size: number\n mtimeMs: number\n sha256?: string\n}\n\nexport interface Entry {\n key: string\n meta: unknown\n files: LocalFile[]\n /** Of `meta` and each file's name, size and time on this server; notices local changes. */\n fingerprint: string\n version: Version\n /** Set when the entry was deleted; it is kept as a tombstone. */\n deletedAt?: number\n /**\n * A peer's entry the dataset did not take (it lists nothing under the\n * key afterwards). Not a deletion: no tombstone is made for it.\n */\n declined?: boolean\n /** Local change sequence, for `manifest?since=`. */\n seq: number\n}\n\nexport interface RemoteEntry {\n key: string\n meta: unknown\n files: FileInfo[]\n version: Version\n deletedAt?: number\n}\n\nexport interface Library {\n seq: number\n entries: Record<string, Entry>\n}\n\nexport const TOMBSTONE_RETENTION_MS = 30 * 24 * 60 * 60 * 1000\n\n/** A file written less than this long ago may still be growing, so its entry waits. */\nexport const SETTLE_MS = 30_000\n\nconst FILE_NAME = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,127}$/\nconst SHA256 = /^[0-9a-f]{64}$/\n\n/** Positive when `a` wins over `b`, negative when `b` wins, 0 when equal. */\nexport function compareVersions(a: Version, b: Version): number {\n if (a.counter !== b.counter) {\n return a.counter - b.counter\n }\n if (a.origin === b.origin) {\n return 0\n }\n return a.origin > b.origin ? 1 : -1\n}\n\nexport function emptyLibrary(): Library {\n return { seq: 0, entries: {} }\n}\n\nexport function fingerprint(meta: unknown, files: readonly LocalFile[]): string {\n const canonical = JSON.stringify({\n meta: meta ?? null,\n files: [...files]\n .sort((a, b) => a.name.localeCompare(b.name))\n .map((f) => [f.name, f.size, f.mtimeMs])\n })\n return crypto.createHash('sha256').update(canonical).digest('hex')\n}\n\nexport function isValidFileName(name: string): boolean {\n return FILE_NAME.test(name) && !name.includes('..')\n}\n\n/** The shape checks every entry a peer sends must pass before anything else looks at it. */\nexport function isWellFormedRemote(raw: unknown): raw is RemoteEntry {\n if (typeof raw !== 'object' || raw === null) {\n return false\n }\n const entry = raw as Partial<RemoteEntry>\n if (\n typeof entry.key !== 'string' ||\n entry.key.length === 0 ||\n entry.key.length > 512 ||\n entry.key.includes('\\0') ||\n typeof entry.version?.counter !== 'number' ||\n !Number.isInteger(entry.version.counter) ||\n entry.version.counter < 1 ||\n typeof entry.version.origin !== 'string' ||\n !Array.isArray(entry.files)\n ) {\n return false\n }\n if (entry.deletedAt !== undefined && typeof entry.deletedAt !== 'number') {\n return false\n }\n const names = new Set<string>()\n for (const file of entry.files as unknown[]) {\n const f = file as Partial<FileInfo>\n if (\n typeof f.name !== 'string' ||\n !isValidFileName(f.name) ||\n names.has(f.name) ||\n typeof f.size !== 'number' ||\n !Number.isInteger(f.size) ||\n f.size < 0 ||\n typeof f.sha256 !== 'string' ||\n !SHA256.test(f.sha256)\n ) {\n return false\n }\n names.add(f.name)\n }\n return true\n}\n\n/** One entry as the dataset lists it now. */\nexport interface ListedEntry {\n key: string\n meta: unknown\n files: { name: string; size: number; mtimeMs: number }[]\n}\n\nexport interface ScanResult {\n /** Keys whose entry changed and needs its files hashed. */\n changed: string[]\n}\n\n/**\n * Bring the library up to date with what the dataset lists: new or changed\n * entries get a new local version (once their files have settled), entries\n * gone become tombstones, tombstones past retention are dropped.\n */\nexport function applyListing(\n library: Library,\n listed: readonly ListedEntry[],\n serverId: string,\n now: number\n): ScanResult {\n const changed: string[] = []\n const seen = new Set<string>()\n for (const item of listed) {\n seen.add(item.key)\n const prev = library.entries[item.key]\n const files: LocalFile[] = item.files.map((f) => ({\n name: f.name,\n size: f.size,\n mtimeMs: f.mtimeMs\n }))\n const print = fingerprint(item.meta, files)\n if (prev && prev.deletedAt === undefined && prev.fingerprint === print) {\n if (prev.declined) {\n delete prev.declined\n }\n continue\n }\n // A change of meta alone goes out at once; only a file may still be growing.\n const changedFiles = files.filter(\n (f) =>\n !prev?.files.some((o) => o.name === f.name && o.size === f.size && o.mtimeMs === f.mtimeMs)\n )\n if (changedFiles.some((f) => now - f.mtimeMs < SETTLE_MS)) {\n continue\n }\n // Keep the hashes of files that did not change.\n for (const file of files) {\n const old = prev?.files.find(\n (f) => f.name === file.name && f.size === file.size && f.mtimeMs === file.mtimeMs\n )\n if (old?.sha256 !== undefined) {\n file.sha256 = old.sha256\n }\n }\n library.seq++\n library.entries[item.key] = {\n key: item.key,\n meta: item.meta,\n files,\n fingerprint: print,\n version: { counter: (prev?.version.counter ?? 0) + 1, origin: serverId },\n seq: library.seq\n }\n changed.push(item.key)\n }\n for (const entry of Object.values(library.entries)) {\n if (seen.has(entry.key) || entry.declined) {\n continue\n }\n if (entry.deletedAt === undefined) {\n library.seq++\n library.entries[entry.key] = {\n key: entry.key,\n meta: null,\n files: [],\n fingerprint: '',\n version: { counter: entry.version.counter + 1, origin: serverId },\n deletedAt: now,\n seq: library.seq\n }\n } else if (now - entry.deletedAt > TOMBSTONE_RETENTION_MS) {\n Reflect.deleteProperty(library.entries, entry.key)\n }\n }\n return { changed }\n}\n\nfunction isOfferable(entry: Entry): boolean {\n return entry.deletedAt !== undefined || entry.files.every((f) => f.sha256 !== undefined)\n}\n\nexport function toRemote(entry: Entry): RemoteEntry {\n const remote: RemoteEntry = {\n key: entry.key,\n meta: entry.meta,\n files: entry.files.map((f) => ({ name: f.name, size: f.size, sha256: f.sha256 ?? '' })),\n version: entry.version\n }\n if (entry.deletedAt !== undefined) {\n remote.deletedAt = entry.deletedAt\n }\n return remote\n}\n\n/** Entries changed after `since`. One not hashed yet stops the page, so the cursor never skips it. */\nexport function manifestSince(\n library: Library,\n since: number\n): { cursor: number; entries: RemoteEntry[] } {\n let cursor = since\n const entries: RemoteEntry[] = []\n for (const entry of Object.values(library.entries).sort((a, b) => a.seq - b.seq)) {\n if (entry.seq <= since || entry.declined) {\n if (entry.seq > cursor) {\n cursor = entry.seq\n }\n continue\n }\n if (!isOfferable(entry)) {\n break\n }\n cursor = entry.seq\n entries.push(toRemote(entry))\n }\n return { cursor, entries }\n}\n\n/** Take over a peer's version, with what this server holds for it now (null: nothing). */\nexport function recordRemote(\n library: Library,\n remote: RemoteEntry,\n local: ListedEntry | null\n): void {\n library.seq++\n const files: LocalFile[] = local\n ? local.files.map((f) => {\n const file: LocalFile = { name: f.name, size: f.size, mtimeMs: f.mtimeMs }\n const sha256 = remote.files.find((r) => r.name === f.name && r.size === f.size)?.sha256\n if (sha256 !== undefined) {\n file.sha256 = sha256\n }\n return file\n })\n : []\n const entry: Entry = {\n key: remote.key,\n meta: local ? local.meta : remote.meta,\n files,\n fingerprint: local ? fingerprint(local.meta, files) : '',\n version: remote.version,\n seq: library.seq\n }\n if (remote.deletedAt !== undefined) {\n entry.deletedAt = remote.deletedAt\n } else if (!local) {\n entry.declined = true\n }\n library.entries[remote.key] = entry\n}\n","/**\n * Membership and dataset replication between the Signal K servers of a boat.\n *\n * Every server keeps a full copy of each registered dataset. Each round it\n * lists its own datasets, then asks every paired peer for the entries that\n * changed there and takes over those whose version wins over its own (see\n * `library.ts`). Replication has no master: any server may change or delete an\n * entry and the others follow, also a server that was off at the time.\n *\n * All work is serialized: a round, a pairing step and a registration never\n * run at the same time, so each library is changed by one of them at a time.\n */\n\nimport crypto from 'node:crypto'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { pipeline } from 'node:stream/promises'\n\nimport type {\n DatasetDefinition,\n DatasetEntry,\n DatasetHandle,\n IncomingEntry,\n PeerInfo,\n Role\n} from './api.js'\nimport {\n applyListing,\n compareVersions,\n isWellFormedRemote,\n manifestSince,\n recordRemote,\n type Library,\n type ListedEntry,\n type RemoteEntry\n} from './library.js'\nimport type { MasterAccess } from './master-proxy.js'\nimport {\n PeerHttpError,\n UNTRUSTED_ISSUER,\n downloadFile,\n fetchHello,\n fetchManifest,\n locatePeer,\n normalizePeerUrl,\n pollAccess,\n requestAccess,\n type AccessRequestResult,\n type Hello,\n type HelloFrom\n} from './peer-client.js'\nimport type { PairedByInfo } from './status.js'\nimport type { MultihelmStore, PairedServer, Peer } from './store.js'\n\nexport const PROTOCOL = 1\nexport const ROUND_INTERVAL_MS = 60_000\n/**\n * Paired peers are asked whether they are set to be the master this often,\n * on a timer of its own, so a long round of transfers does not hold it up.\n */\nexport const MASTER_CHECK_INTERVAL_MS = 30_000\n/**\n * A peer set to be the master counts as the master while it answered this\n * recently, so a few missed answers do not move the role.\n */\nexport const MASTER_STALE_MS = 5 * MASTER_CHECK_INTERVAL_MS\n/** Every peer asks every 30 s, so a sighting is saved only now and then. */\nconst PAIRED_BY_SAVE_MS = 10 * 60_000\n/** Without security anyone may ask, so writes of that list are gathered, never one per request. */\nconst PAIRED_BY_FLUSH_MS = 10_000\n/** Without security anyone may ask for `hello`; the list stays small. */\nconst MAX_PAIRED_BY = 32\n/** A pairing request waiting for approval is followed this often, so an approval shows at once. */\nexport const PAIRING_POLL_MS = 5_000\n/** Free space kept beyond an incoming file, as a fraction of its size. */\nconst FREE_SPACE_MARGIN = 0.05\n\nexport interface MultihelmHost {\n serverName: () => string\n /** The user set this server to be the boat's master. */\n isMaster: () => boolean\n /** What this server runs, for the peers to show. */\n versions?: () => { signalk?: string; multihelm?: string }\n debug: (msg: string) => void\n error: (msg: string) => void\n}\n\ninterface Dataset {\n definition: DatasetDefinition\n library: Library\n /** The last listing, for serving files: key → entry. */\n listed: Map<string, DatasetEntry>\n}\n\nexport async function hashFile(file: string): Promise<string> {\n const hash = crypto.createHash('sha256')\n await pipeline(fs.createReadStream(file), hash)\n return hash.digest('hex')\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/** What Node calls a certificate chain that does not lead to a certificate it trusts. */\nconst UNTRUSTED_CERTIFICATE = new Set([\n ...UNTRUSTED_ISSUER,\n 'CERT_SIGNATURE_FAILURE',\n 'CERT_UNTRUSTED',\n 'CERT_REJECTED'\n])\n\nfunction errorCode(error: unknown): unknown {\n return (error as { code?: unknown } | null)?.code\n}\n\nfunction isRedirect(error: unknown): boolean {\n return error instanceof PeerHttpError && error.status >= 300 && error.status < 400\n}\n\n/** Pairing the peer again mends it: its certificate changed, or it went over to HTTPS. */\nfunction needsPairingAgain(error: unknown): boolean {\n const code = errorCode(error)\n return isRedirect(error) || (typeof code === 'string' && UNTRUSTED_CERTIFICATE.has(code))\n}\n\n/** `error` in words when it is about the peer's certificate or a redirect; null otherwise. */\nfunction connectionText(error: unknown): string | null {\n if (isRedirect(error)) {\n return 'it redirects to another address, likely its HTTPS one; pair it again'\n }\n const code = errorCode(error)\n if (typeof code !== 'string') {\n return null\n }\n if (UNTRUSTED_CERTIFICATE.has(code)) {\n return 'its certificate is not the one it had when paired; pair it again if it was changed on purpose'\n }\n if (code === 'ERR_TLS_CERT_ALTNAME_INVALID') {\n return 'its certificate is issued for another name; pair it by that name'\n }\n if (code === 'CERT_HAS_EXPIRED') {\n return 'its certificate has expired'\n }\n return null\n}\n\n/** Said without the address, which the panel shows anyway. */\nfunction helloErrorText(error: unknown): string {\n if (!(error instanceof PeerHttpError)) {\n return connectionText(error) ?? errorText(error)\n }\n switch (error.status) {\n case 404:\n return 'Multihelm is not running there'\n case 401:\n case 403:\n return 'access was revoked on the peer'\n default:\n return connectionText(error) ?? `HTTP ${String(error.status)}`\n }\n}\n\nfunction toListed(entry: DatasetEntry): ListedEntry {\n return {\n key: entry.key,\n meta: entry.meta,\n files: entry.files.map((f) => ({ name: f.name, size: f.size, mtimeMs: f.mtimeMs }))\n }\n}\n\nexport class Multihelm {\n private peers: Peer[]\n private readonly datasets = new Map<string, Dataset>()\n private queue: Promise<unknown> = Promise.resolve()\n private timer: NodeJS.Timeout | null = null\n private soon: NodeJS.Timeout | null = null\n /** Rounds run on their own between start and stop. */\n private started = false\n /** Set by stop: work under way ends at the next step. */\n private stopped = false\n /** Peer URL → when it last answered as set to be the master. */\n private readonly masterSeen = new Map<string, number>()\n /** Peer URL → its last `hello`, and when. */\n private readonly answers = new Map<string, { at: number; hello: Hello }>()\n /** Peer URL → why its last `hello` failed. */\n private readonly helloErrors = new Map<string, string>()\n /** Server id → a server that asks this one for its `hello`. */\n private readonly pairedBy: Map<string, PairedServer>\n private pairedBySavedAt = 0\n private pairedByTimer: NodeJS.Timeout | null = null\n private readonly roleListeners = new Set<(role: Role, master: PeerInfo | null) => void>()\n private readonly statusListeners = new Set<() => void>()\n /** What the role listeners were last told: role and master id. */\n private announcedRole = ''\n /** What the status listeners were last told: role, master id and conflict. */\n private announcedStatus = ''\n private masterTimer: NodeJS.Timeout | null = null\n private checkingMasters = false\n private checkMastersAgain = false\n /** Whether the paired peers were asked once since the start, so the role is known. */\n private mastersChecked = false\n private pairingTimer: NodeJS.Timeout | null = null\n private pollingPairings = false\n readonly serverId: string\n\n constructor(\n private readonly store: MultihelmStore,\n private readonly host: MultihelmHost\n ) {\n this.peers = store.loadPeers()\n this.serverId = store.serverId()\n this.pairedBy = new Map(store.loadPairedBy().map((s) => [s.id, s]))\n }\n\n start(): void {\n this.started = true\n this.stopped = false\n const tick = (): void => {\n void this.runRound().finally(() => {\n if (!this.stopped) {\n this.timer = setTimeout(tick, ROUND_INTERVAL_MS)\n }\n })\n }\n this.timer = setTimeout(tick, 0)\n void this.checkMasters()\n this.masterTimer = setInterval(() => {\n void this.checkMasters()\n }, MASTER_CHECK_INTERVAL_MS)\n this.pairingTimer = setInterval(() => {\n this.pollPairings().catch((error: unknown) => {\n this.host.error(`Multihelm: following a pairing request: ${errorText(error)}`)\n })\n }, PAIRING_POLL_MS)\n }\n\n stop(): void {\n this.started = false\n this.stopped = true\n for (const timer of [this.timer, this.soon]) {\n if (timer) {\n clearTimeout(timer)\n }\n }\n this.timer = null\n this.soon = null\n for (const timer of [this.masterTimer, this.pairingTimer]) {\n if (timer) {\n clearInterval(timer)\n }\n }\n this.masterTimer = null\n this.pairingTimer = null\n if (this.pairedByTimer) {\n clearTimeout(this.pairedByTimer)\n this.pairedByTimer = null\n this.savePairedBy()\n }\n }\n\n /**\n * Asks every paired peer whether it is set to be the master. Runs outside\n * the work queue and touches nothing but what it keeps of the answers, so it neither waits\n * for a round nor races one.\n */\n async checkMasters(): Promise<void> {\n if (this.stopped) {\n return\n }\n if (this.checkingMasters) {\n this.checkMastersAgain = true\n return\n }\n this.checkingMasters = true\n try {\n await Promise.all(\n this.peers\n .filter((p) => p.state === 'paired' && p.id !== '')\n .map(async (peer) => {\n const { url, ca } = peer\n // Unpaired or stopped meanwhile, or paired again at another address or by another certificate.\n const current = (): boolean =>\n !this.stopped && this.peers.includes(peer) && peer.url === url && peer.ca === ca\n let hello\n try {\n hello = await fetchHello(peer, peer.token, this.helloFrom())\n } catch (error) {\n if (current()) {\n this.helloErrors.set(url, helloErrorText(error))\n }\n return // It counts until its last answer is stale.\n }\n // Or another server at that address now.\n if (!current() || hello.serverId !== peer.id) {\n return\n }\n this.answered(url, hello)\n if (hello.master) {\n this.masterSeen.set(url, Date.now())\n } else {\n this.masterSeen.delete(url)\n }\n })\n )\n } finally {\n this.checkingMasters = false\n }\n // stop() may have run during the awaits above.\n if (this.stopped as boolean) {\n return\n }\n this.mastersChecked = true\n this.announceRole()\n if (this.checkMastersAgain) {\n this.checkMastersAgain = false\n await this.checkMasters()\n }\n }\n\n /** Whether the role is known: the paired peers were asked since the start. */\n roleKnown(): boolean {\n return this.mastersChecked\n }\n\n /**\n * Follows up the pairing requests waiting for approval, between rounds. At\n * most one waits in the queue, so a long round does not pile them up.\n */\n async pollPairings(): Promise<void> {\n const waiting = (): Peer[] => this.peers.filter((p) => p.state === 'waiting-approval')\n if (this.pollingPairings || this.stopped || waiting().length === 0) {\n return\n }\n this.pollingPairings = true\n try {\n await this.serialize(async () => {\n let paired = false\n for (const peer of waiting()) {\n if (this.stopped) {\n break\n }\n await this.pollPairingLocked(peer)\n paired ||= peer.state === 'paired'\n }\n this.store.savePeers(this.peers)\n this.announceRole()\n if (paired) {\n this.changedSoon()\n }\n })\n } finally {\n this.pollingPairings = false\n }\n }\n\n /** Run `task` after every task queued before it. */\n private serialize<T>(task: () => Promise<T>): Promise<T> {\n const run = this.queue.then(task, task)\n this.queue = run.catch(() => undefined)\n return run\n }\n\n // --- datasets -------------------------------------------------------\n\n registerDataset(definition: DatasetDefinition): DatasetHandle {\n if (this.datasets.has(definition.id)) {\n throw new Error(`dataset ${definition.id} is already registered`)\n }\n this.datasets.set(definition.id, {\n definition,\n library: this.store.loadLibrary(definition.id),\n listed: new Map()\n })\n this.changedSoon()\n return {\n changed: () => {\n this.changedSoon()\n },\n unregister: () => {\n if (this.datasets.get(definition.id)?.definition === definition) {\n this.datasets.delete(definition.id)\n }\n }\n }\n }\n\n datasetIds(): string[] {\n return [...this.datasets.keys()].sort()\n }\n\n /** A round a few seconds from now, so a burst of changes makes one round. */\n private changedSoon(): void {\n if (!this.started || this.soon) {\n return\n }\n this.soon = setTimeout(() => {\n this.soon = null\n void this.runRound()\n }, 2_000)\n }\n\n /** One listing of every dataset, then one round with every paired peer. */\n runRound(): Promise<void> {\n return this.serialize(async () => {\n for (const dataset of this.datasets.values()) {\n await this.listLocked(dataset)\n }\n for (const peer of this.peers) {\n if (this.stopped) {\n break\n }\n await this.pollPairingLocked(peer)\n if (peer.state === 'paired') {\n await this.helloLocked(peer)\n }\n if (peer.state === 'paired') {\n await this.syncPeerLocked(peer)\n }\n }\n this.store.savePeers(this.peers)\n this.announceRole()\n })\n }\n\n // --- master role ----------------------------------------------------\n\n /** The servers set to be the master that count now, this one included, smallest id first. */\n private masterCandidates(): { id: string; peer: Peer | null }[] {\n const now = Date.now()\n const candidates: { id: string; peer: Peer | null }[] = []\n if (this.host.isMaster()) {\n candidates.push({ id: this.serverId, peer: null })\n }\n for (const peer of this.peers) {\n const seen = this.masterSeen.get(peer.url)\n if (\n peer.state === 'paired' &&\n peer.id !== '' &&\n seen !== undefined &&\n now - seen <= MASTER_STALE_MS\n ) {\n candidates.push({ id: peer.id, peer })\n }\n }\n return candidates.sort((x, y) => (x.id < y.id ? -1 : x.id > y.id ? 1 : 0))\n }\n\n role(): Role {\n return this.masterCandidates()[0]?.peer === null ? 'master' : 'member'\n }\n\n master(): PeerInfo | null {\n const peer = this.masterCandidates()[0]?.peer\n return peer ? this.infoOf(peer) : null\n }\n\n /** Where to reach the master, with the pairing token; null when this server is it or there is none. */\n masterAccess(): MasterAccess | null {\n const peer = this.masterCandidates()[0]?.peer\n if (!peer) {\n return null\n }\n return peer.ca === undefined\n ? { url: peer.url, token: peer.token }\n : { url: peer.url, token: peer.token, ca: peer.ca }\n }\n\n /** More than one server is set to be the master: the user should set one only. */\n masterConflict(): boolean {\n return this.masterCandidates().length > 1\n }\n\n /** Calls `cb` whenever the role, the master or `masterConflict()` changes. */\n onStatusChanged(cb: () => void): () => void {\n this.statusListeners.add(cb)\n return () => {\n this.statusListeners.delete(cb)\n }\n }\n\n onRoleChanged(cb: (role: Role, master: PeerInfo | null) => void): () => void {\n this.roleListeners.add(cb)\n return () => {\n this.roleListeners.delete(cb)\n }\n }\n\n private announceRole(): void {\n const role = this.role()\n const master = this.master()\n const now = `${role}:${master?.id ?? ''}`\n const status = `${now}:${String(this.masterConflict())}`\n if (now !== this.announcedRole) {\n this.announcedRole = now\n for (const cb of this.roleListeners) {\n try {\n cb(role, master)\n } catch (error) {\n this.host.error(`Multihelm: a role listener failed: ${errorText(error)}`)\n }\n }\n }\n if (status !== this.announcedStatus) {\n this.announcedStatus = status\n for (const cb of this.statusListeners) {\n try {\n cb()\n } catch (error) {\n this.host.error(`Multihelm: a status listener failed: ${errorText(error)}`)\n }\n }\n }\n }\n\n private async listLocked(dataset: Dataset): Promise<void> {\n const id = dataset.definition.id\n let listed: DatasetEntry[]\n try {\n listed = await dataset.definition.list()\n } catch (error) {\n this.host.error(`Multihelm: listing ${id} failed: ${errorText(error)}`)\n return\n }\n dataset.listed = new Map(listed.map((e) => [e.key, e]))\n const { changed } = applyListing(\n dataset.library,\n listed.map(toListed),\n this.serverId,\n Date.now()\n )\n for (const key of changed) {\n const entry = dataset.library.entries[key]\n const local = dataset.listed.get(key)\n if (!entry || !local) {\n continue\n }\n for (const file of entry.files) {\n if (this.stopped) {\n break\n }\n const source = local.files.find((f) => f.name === file.name)\n if (!source || file.sha256 !== undefined) {\n continue\n }\n try {\n file.sha256 = await hashFile(source.path)\n } catch (error) {\n this.host.debug(`Multihelm: cannot hash ${source.path}: ${errorText(error)}`)\n }\n }\n }\n // Hashes stay unknown for entries whose files could not be read: those are held back.\n this.store.saveLibrary(id, dataset.library)\n }\n\n // --- serving --------------------------------------------------------\n\n hello(): Hello {\n return {\n serverId: this.serverId,\n name: this.host.serverName(),\n protocol: PROTOCOL,\n datasets: this.datasetIds(),\n master: this.host.isMaster(),\n ...this.versions()\n }\n }\n\n private versions(): { signalk?: string; multihelm?: string } {\n const { signalk, multihelm } = this.host.versions?.() ?? {}\n return { ...(signalk ? { signalk } : {}), ...(multihelm ? { multihelm } : {}) }\n }\n\n private helloFrom(): HelloFrom {\n return {\n serverId: this.serverId,\n name: this.host.serverName(),\n master: this.host.isMaster(),\n ...this.versions()\n }\n }\n\n private answered(url: string, hello: Hello): void {\n this.answers.set(url, { at: Date.now(), hello })\n this.helloErrors.delete(url)\n }\n\n /**\n * Notes a server that asked for this one's `hello`. Its last sighting is\n * saved with any change to what it is, and otherwise once in a while.\n */\n sawPairedServer(from: HelloFrom): void {\n if (from.serverId === this.serverId) {\n return\n }\n const now = Date.now()\n const known = this.pairedBy.get(from.serverId)\n const server: PairedServer = {\n id: from.serverId,\n name: from.name,\n ...(from.signalk ? { signalk: from.signalk } : {}),\n ...(from.multihelm ? { multihelm: from.multihelm } : {}),\n lastSeen: now\n }\n this.pairedBy.set(server.id, server)\n if (this.pairedBy.size > MAX_PAIRED_BY) {\n const oldest = [...this.pairedBy.values()].sort((x, y) => x.lastSeen - y.lastSeen)[0]\n if (oldest) {\n this.pairedBy.delete(oldest.id)\n }\n }\n const changed =\n !known ||\n known.name !== server.name ||\n known.signalk !== server.signalk ||\n known.multihelm !== server.multihelm\n if (changed || now - this.pairedBySavedAt >= PAIRED_BY_SAVE_MS) {\n this.savePairedBySoon()\n }\n // A server that became or stopped being the master says so at once, so the role moves in seconds.\n const peer = this.peers.find((p) => p.state === 'paired' && p.id === from.serverId)\n if (peer && from.master !== undefined && this.masterSeen.has(peer.url) !== from.master) {\n void this.checkMasters()\n }\n }\n\n /** The servers paired with this one, by name. */\n pairedByInfo(): PairedByInfo[] {\n const now = Date.now()\n return [...this.pairedBy.values()]\n .sort((x, y) => x.name.localeCompare(y.name))\n .map((s) => ({ ...s, online: now - s.lastSeen <= MASTER_STALE_MS }))\n }\n\n /** Drops a server from that list; it comes back when it asks again. */\n forgetPairedBy(id: string): boolean {\n const removed = this.pairedBy.delete(id)\n if (removed) {\n this.savePairedBy()\n }\n return removed\n }\n\n private savePairedBySoon(): void {\n if (this.pairedByTimer) {\n return\n }\n this.pairedByTimer = setTimeout(() => {\n this.pairedByTimer = null\n this.savePairedBy()\n }, PAIRED_BY_FLUSH_MS)\n this.pairedByTimer.unref()\n }\n\n private savePairedBy(): void {\n this.pairedBySavedAt = Date.now()\n try {\n this.store.savePairedBy([...this.pairedBy.values()])\n } catch (error) {\n this.host.error(`Multihelm: saving the servers paired with this one: ${errorText(error)}`)\n }\n }\n\n manifest(datasetId: string, since: number): { cursor: number; entries: RemoteEntry[] } | null {\n const dataset = this.datasets.get(datasetId)\n return dataset ? manifestSince(dataset.library, since) : null\n }\n\n /** Absolute path of a file this server offers, or null. */\n servableFile(datasetId: string, key: string, name: string): string | null {\n const dataset = this.datasets.get(datasetId)\n const entry = dataset?.library.entries[key]\n if (!dataset || !entry || entry.deletedAt !== undefined) {\n return null\n }\n const file = entry.files.find((f) => f.name === name)\n const local = dataset.listed.get(key)?.files.find((f) => f.name === name)\n if (!file?.sha256 || !local || local.size !== file.size || local.mtimeMs !== file.mtimeMs) {\n return null\n }\n return local.path\n }\n\n // --- pulling --------------------------------------------------------\n\n /** Errors with one dataset are cleared by that dataset's next sync. */\n private isDatasetError(text: string): boolean {\n return [...this.datasets.keys()].some((id) => text.startsWith(`${id}:`))\n }\n\n private async syncPeerLocked(peer: Peer): Promise<void> {\n try {\n for (const dataset of this.datasets.values()) {\n if (this.stopped) {\n return\n }\n await this.syncDatasetLocked(peer, dataset)\n }\n peer.lastSync = Date.now()\n if (peer.lastError !== undefined && !this.isDatasetError(peer.lastError)) {\n delete peer.lastError\n }\n } catch (error) {\n if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) {\n peer.state = 'needs-pairing'\n peer.lastError = 'access was revoked on the peer'\n } else {\n if (needsPairingAgain(error)) {\n peer.state = 'needs-pairing'\n }\n peer.lastError = connectionText(error) ?? errorText(error)\n }\n this.host.debug(`Multihelm: ${peer.name}: ${peer.lastError}`)\n }\n }\n\n private async syncDatasetLocked(peer: Peer, dataset: Dataset): Promise<void> {\n const id = dataset.definition.id\n let manifest\n try {\n manifest = await fetchManifest(peer, peer.token, id, peer.cursors[id] ?? 0)\n } catch (error) {\n if (error instanceof PeerHttpError && error.status === 404) {\n if (peer.lastError?.startsWith(`${id}:`)) {\n delete peer.lastError\n }\n return // The peer does not have this dataset.\n }\n throw error\n }\n try {\n for (const raw of manifest.entries) {\n if (this.stopped) {\n return\n }\n // Stop at the first entry that fails, so the cursor never skips it.\n if (!(await this.applyRemote(peer, dataset, raw))) {\n return\n }\n }\n peer.cursors[id] = manifest.cursor\n if (peer.lastError?.startsWith(`${id}:`)) {\n delete peer.lastError\n }\n } finally {\n this.store.saveLibrary(id, dataset.library)\n }\n }\n\n /** Apply one entry of a peer's manifest; false when it failed and is tried again. */\n private async applyRemote(peer: Peer, dataset: Dataset, raw: unknown): Promise<boolean> {\n const { definition, library } = dataset\n if (!isWellFormedRemote(raw) || (definition.isValidKey && !definition.isValidKey(raw.key))) {\n this.host.debug(`Multihelm: ignoring a malformed ${definition.id} entry from ${peer.name}`)\n return true\n }\n const remote = raw\n const local = library.entries[remote.key]\n if (local && compareVersions(remote.version, local.version) <= 0) {\n return true\n }\n const fail = (error: unknown): false => {\n peer.lastError = `${definition.id}: ${remote.key}: ${errorText(error)}`\n this.host.debug(`Multihelm: ${peer.lastError}`)\n return false\n }\n\n if (remote.deletedAt !== undefined) {\n if (!local || local.deletedAt !== undefined || local.declined) {\n recordRemote(library, remote, null)\n return true\n }\n try {\n if (await definition.remove(remote.key)) {\n recordRemote(library, remote, null)\n } else {\n // Kept here: offer it back as this server's change.\n library.seq++\n library.entries[remote.key] = {\n ...local,\n version: { counter: remote.version.counter + 1, origin: this.serverId },\n seq: library.seq\n }\n }\n return true\n } catch (error) {\n return fail(error)\n }\n }\n\n try {\n const incoming = await this.fetchFiles(peer, dataset, remote)\n if (!incoming) {\n return false\n }\n await definition.apply(incoming)\n await this.cleanIncoming(definition.id, incoming)\n const after = (await definition.list()).find((e) => e.key === remote.key)\n if (after) {\n dataset.listed.set(after.key, after)\n }\n recordRemote(library, remote, after ? toListed(after) : null)\n return true\n } catch (error) {\n return fail(error)\n }\n }\n\n /** The peer's entry with every file verified on this server's disk, or null on failure. */\n private async fetchFiles(\n peer: Peer,\n dataset: Dataset,\n remote: RemoteEntry\n ): Promise<IncomingEntry | null> {\n const id = dataset.definition.id\n const mine = dataset.library.entries[remote.key]\n const listed = dataset.listed.get(remote.key)\n const incomingDir = this.store.incomingDir(id)\n await fs.promises.mkdir(incomingDir, { recursive: true })\n const files: IncomingEntry['files'] = []\n for (const file of remote.files) {\n const have = mine?.files.find(\n (f) => f.name === file.name && f.sha256 === file.sha256 && f.size === file.size\n )\n const own = have ? listed?.files.find((f) => f.name === file.name) : undefined\n if (own && own.size === file.size) {\n files.push({\n name: file.name,\n path: own.path,\n size: file.size,\n sha256: file.sha256,\n unchanged: true\n })\n continue\n }\n const dest = path.join(incomingDir, file.sha256)\n const already = await fs.promises.stat(dest).then(\n (s) => s.size,\n () => 0\n )\n if (already > file.size) {\n await fs.promises.rm(dest, { force: true })\n }\n if (already !== file.size) {\n const free = await fs.promises.statfs(incomingDir)\n if (free.bavail * free.bsize < (file.size - already) * (1 + FREE_SPACE_MARGIN)) {\n peer.lastError = `${id}: not enough free space for ${remote.key}`\n return null\n }\n this.host.debug(`Multihelm: fetching ${id} ${remote.key} ${file.name} from ${peer.name}`)\n await downloadFile(\n peer,\n peer.token,\n { dataset: id, key: remote.key, name: file.name },\n dest\n )\n }\n const size = (await fs.promises.stat(dest)).size\n if (size !== file.size || (await hashFile(dest)) !== file.sha256) {\n await fs.promises.rm(dest, { force: true })\n peer.lastError = `${id}: ${remote.key} arrived damaged; it is fetched again`\n return null\n }\n files.push({\n name: file.name,\n path: dest,\n size: file.size,\n sha256: file.sha256,\n unchanged: false\n })\n }\n return { key: remote.key, meta: remote.meta, files }\n }\n\n /** Files the dataset copied rather than moved are left in the work folder; remove them. */\n private async cleanIncoming(datasetId: string, entry: IncomingEntry): Promise<void> {\n const dir = this.store.incomingDir(datasetId)\n for (const file of entry.files) {\n if (!file.unchanged && path.dirname(file.path) === dir) {\n await fs.promises.rm(file.path, { force: true })\n }\n }\n }\n\n // --- peers ----------------------------------------------------------\n\n peerInfo(): PeerInfo[] {\n return this.peers.map((p) => this.infoOf(p))\n }\n\n private infoOf(p: Peer): PeerInfo {\n const info: PeerInfo = { id: p.id, name: p.name, url: p.url, state: p.state }\n if (p.lastSeen !== undefined) {\n info.lastSeen = p.lastSeen\n }\n if (p.lastSync !== undefined) {\n info.lastSync = p.lastSync\n }\n if (p.lastError !== undefined) {\n info.lastError = p.lastError\n }\n const now = Date.now()\n const answer = this.answers.get(p.url)\n if (answer) {\n info.lastSeen = Math.max(info.lastSeen ?? 0, answer.at)\n if (answer.hello.signalk) {\n info.signalk = answer.hello.signalk\n }\n if (answer.hello.multihelm) {\n info.multihelm = answer.hello.multihelm\n }\n }\n const helloError = this.helloErrors.get(p.url)\n if (helloError !== undefined && p.state === 'paired') {\n info.lastError = helloError\n }\n if (p.state === 'paired') {\n info.online = info.lastSeen !== undefined && now - info.lastSeen <= MASTER_STALE_MS\n }\n const seen = this.masterSeen.get(p.url)\n if (seen !== undefined && now - seen <= MASTER_STALE_MS) {\n info.master = true\n }\n return info\n }\n\n /**\n * Pair with the server at `input`: without security it is paired at once,\n * otherwise a readonly device access request waits for approval there.\n */\n pair(input: string): Promise<PeerInfo> {\n return this.serialize(async () => {\n const typed = normalizePeerUrl(input)\n if (!typed) {\n throw new Error('not a server address')\n }\n const address = await locatePeer(typed)\n const url = address.url\n // Asked before anything of a pairing changes, so one that works stays as it is if asking fails.\n const result = await requestAccess(\n address,\n `signalk-multihelm-${this.serverId}-${crypto.randomUUID().slice(0, 8)}`,\n `Multihelm on ${this.host.serverName()}`\n )\n // Or paired over HTTP before the server went over to HTTPS.\n let peer = this.peers.find((p) => p.url === url) ?? this.peers.find((p) => p.url === typed)\n if (peer && result.kind === 'error') {\n throw new Error(result.message)\n }\n if (peer && peer.url !== url) {\n this.forgetAnswers(peer.url)\n peer.url = url\n }\n if (!peer) {\n peer = { id: '', name: url, url, token: '', state: 'needs-pairing', cursors: {} }\n this.peers.push(peer)\n }\n if (address.ca === undefined) {\n delete peer.ca\n } else {\n peer.ca = address.ca\n }\n this.applyAccessResult(peer, result)\n if (peer.state === 'paired') {\n await this.helloLocked(peer)\n }\n this.store.savePeers(this.peers)\n const info = this.peerInfo().find((p) => p.url === url)\n if (!info) {\n throw new Error('peer vanished')\n }\n if (peer.state === 'paired') {\n this.changedSoon()\n }\n return info\n })\n }\n\n unpair(url: string): Promise<boolean> {\n return this.serialize(() => {\n const before = this.peers.length\n this.peers = this.peers.filter((p) => p.url !== url)\n this.forgetAnswers(url)\n this.store.savePeers(this.peers)\n this.announceRole()\n return Promise.resolve(this.peers.length !== before)\n })\n }\n\n private forgetAnswers(url: string): void {\n this.masterSeen.delete(url)\n this.answers.delete(url)\n this.helloErrors.delete(url)\n }\n\n private applyAccessResult(peer: Peer, result: AccessRequestResult): void {\n switch (result.kind) {\n case 'no-security':\n peer.token = ''\n peer.state = 'paired'\n delete peer.requestHref\n break\n case 'approved':\n peer.token = result.token\n peer.state = 'paired'\n delete peer.requestHref\n delete peer.lastError\n break\n case 'pending':\n peer.requestHref = result.href\n peer.state = 'waiting-approval'\n break\n case 'denied':\n peer.state = 'needs-pairing'\n delete peer.requestHref\n peer.lastError = 'the access request was denied'\n break\n case 'error':\n peer.state = 'needs-pairing'\n peer.lastError = result.message\n break\n }\n }\n\n private async pollPairingLocked(peer: Peer): Promise<void> {\n if (peer.state !== 'waiting-approval' || !peer.requestHref) {\n return\n }\n try {\n this.applyAccessResult(peer, await pollAccess(peer, peer.requestHref))\n // applyAccessResult changed the state; read it afresh.\n if ((peer.state as Peer['state']) === 'paired') {\n await this.helloLocked(peer)\n }\n } catch (error) {\n peer.lastError = errorText(error)\n }\n }\n\n private async helloLocked(peer: Peer): Promise<void> {\n try {\n const hello = await fetchHello(peer, peer.token, this.helloFrom())\n if (hello.serverId === this.serverId) {\n peer.state = 'needs-pairing'\n peer.lastError = 'this is this server itself'\n return\n }\n peer.id = hello.serverId\n peer.name = hello.name\n peer.lastSeen = Date.now()\n this.answered(peer.url, hello)\n if (hello.master) {\n this.masterSeen.set(peer.url, peer.lastSeen)\n } else {\n this.masterSeen.delete(peer.url)\n }\n } catch (error) {\n this.helloErrors.set(peer.url, helloErrorText(error))\n if (needsPairingAgain(error)) {\n peer.state = 'needs-pairing'\n peer.lastError = connectionText(error) ?? errorText(error)\n }\n }\n }\n}\n","/**\n * Routes under `/plugins/signalk-multihelm/`.\n *\n * Peers read `hello`, `manifest`, `file` and `vessel-settings` with the readonly device token\n * they got when pairing, so those are registered with readonly access\n * (`router.access`, signalk-server 2.31 and later). Without it plugin routes\n * are admin-only, a readonly token cannot reach them, and `status` says\n * Multihelm is unavailable. `master/…` serves the master's answers to anyone\n * who may read here. Pairing and the status page stay admin-only.\n */\n\nimport type { IRouter, Request, Response } from 'express'\n\nimport type { DiscoveredServer } from './discovery.js'\nimport { parsePluginIds, type MasterPluginList } from './master-plugins.js'\nimport { MASTER_ROUTE, type MasterProxy } from './master-proxy.js'\nimport type { Multihelm } from './multihelm.js'\nimport type { HelloFrom } from './peer-client.js'\nimport type { OwnAccessState, Status } from './status.js'\nimport type { VesselSettings } from './vessel-settings.js'\n\ntype Handler = (req: Request, res: Response) => void | Promise<void>\n\ninterface AccessScopedRouter {\n get: (path: string, handler: Handler) => AccessScopedRouter\n}\n\ntype RouterWithAccess = IRouter & {\n access?: (level: 'readonly' | 'readwrite' | 'admin') => AccessScopedRouter\n}\n\nconst MAX_URL_LENGTH = 300\n\nfunction queryString(req: Request, name: string): string {\n const value = (req.query as Record<string, unknown>)[name]\n return typeof value === 'string' ? value : ''\n}\n\nconst SERVER_ID = /^[\\w-]{1,64}$/\nconst VERSION = /^[\\w.+-]{1,32}$/\n\n/** The server asking, when it said; what does not fit is left out. */\nfunction helloFrom(req: Request): HelloFrom | null {\n const serverId = queryString(req, 'from')\n const name = queryString(req, 'name').trim().slice(0, 100)\n if (!SERVER_ID.test(serverId) || name === '') {\n return null\n }\n const signalk = queryString(req, 'signalk')\n const multihelm = queryString(req, 'multihelm')\n const master = queryString(req, 'master')\n return {\n serverId,\n name,\n ...(master === '1' || master === '0' ? { master: master === '1' } : {}),\n ...(VERSION.test(signalk) ? { signalk } : {}),\n ...(VERSION.test(multihelm) ? { multihelm } : {})\n }\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nexport function registerRoutes(\n router: IRouter,\n multihelm: () => Multihelm | null,\n discovered: () => DiscoveredServer[],\n vesselSettings: () => VesselSettings | null = () => null,\n masterProxy: () => MasterProxy | null = () => null,\n ownAccess: () => OwnAccessState = () => null,\n masterPlugins: () => MasterPluginList | null = () => null,\n controlAccess: () => Status['controlAccess'] = () => null\n): void {\n const scoped = (router as RouterWithAccess).access\n const available = typeof scoped === 'function'\n const readonly: AccessScopedRouter = available\n ? scoped.call(router, 'readonly')\n : {\n get(path, handler) {\n router.get(path, handler)\n return this\n }\n }\n\n const running =\n (handler: (mh: Multihelm, req: Request, res: Response) => void | Promise<void>) =>\n async (req: Request, res: Response): Promise<void> => {\n const mh = multihelm()\n if (!mh) {\n res.status(503).json({ error: 'Multihelm is not running' })\n return\n }\n try {\n await handler(mh, req, res)\n } catch (error) {\n res.status(500).json({ error: errorText(error) })\n }\n }\n\n readonly.get(\n '/hello',\n running((mh, req, res) => {\n const from = helloFrom(req)\n if (from) {\n mh.sawPairedServer(from)\n }\n res.json(mh.hello())\n })\n )\n\n readonly.get(\n '/vessel-settings',\n running((_mh, _req, res) => {\n const settings = vesselSettings()\n if (!settings) {\n res.status(501).json({ error: 'this server does not expose its vessel settings' })\n return\n }\n res.json(settings)\n })\n )\n\n readonly.get(\n '/manifest',\n running((mh, req, res) => {\n const since = Number(queryString(req, 'since') || '0')\n if (!Number.isInteger(since) || since < 0) {\n res.status(400).json({ error: 'since must be a non-negative integer' })\n return\n }\n const manifest = mh.manifest(queryString(req, 'dataset'), since)\n if (!manifest) {\n res.status(404).json({ error: 'no such dataset' })\n return\n }\n res.json(manifest)\n })\n )\n\n readonly.get(\n '/file',\n running((mh, req, res) => {\n const file = mh.servableFile(\n queryString(req, 'dataset'),\n queryString(req, 'key'),\n queryString(req, 'file')\n )\n if (!file) {\n res.status(404).json({ error: 'no such file' })\n return\n }\n // Only files the dataset lists get here; the server's data dir sits under `.signalk`.\n res.sendFile(file, { acceptRanges: true, dotfiles: 'allow' })\n })\n )\n\n const forwardToMaster: Handler = (req, res) => {\n const proxy = masterProxy()\n if (!proxy) {\n res.status(503).json({ error: 'Multihelm is not running' })\n return\n }\n proxy.forward(req.url.slice(MASTER_ROUTE.length), req, res)\n }\n // The master's answer goes to whoever may read here; this server's own security decides who that is.\n // Express 4, which signalk-server runs, and Express 5 spell a wildcard differently.\n try {\n readonly.get(`${MASTER_ROUTE}/*`, forwardToMaster)\n } catch {\n readonly.get(`${MASTER_ROUTE}/*path`, forwardToMaster)\n }\n\n router.get('/status', (_req: Request, res: Response) => {\n const mh = multihelm()\n const status: Status = {\n available,\n running: mh !== null,\n serverId: mh?.serverId ?? null,\n name: mh?.hello().name ?? '',\n role: mh?.role() ?? null,\n master: mh?.master() ?? null,\n masterConflict: mh?.masterConflict() ?? false,\n datasets: mh?.datasetIds() ?? [],\n peers: mh?.peerInfo() ?? [],\n pairedBy: mh?.pairedByInfo() ?? [],\n discovered: mh ? discovered() : [],\n ownAccess: mh ? ownAccess() : null,\n masterPlugins: masterPlugins()?.ids() ?? [],\n controlAccess: mh ? controlAccess() : null\n }\n res.json(status)\n })\n\n router.post(\n '/peers',\n running(async (mh, req, res) => {\n const url = (req.body as { url?: unknown } | undefined)?.url\n if (typeof url !== 'string' || url.length === 0 || url.length > MAX_URL_LENGTH) {\n res.status(400).json({ error: 'url is required' })\n return\n }\n try {\n res.json(await mh.pair(url))\n } catch (error) {\n res.status(400).json({ error: errorText(error) })\n }\n })\n )\n\n router.delete(\n '/peers',\n running(async (mh, req, res) => {\n const url = queryString(req, 'url')\n res.status((await mh.unpair(url)) ? 200 : 404).json({ removed: url })\n })\n )\n\n router.delete(\n '/paired-by',\n running((mh, req, res) => {\n const id = queryString(req, 'id')\n res.status(mh.forgetPairedBy(id) ? 200 : 404).json({ removed: id })\n })\n )\n\n router.put('/master-plugins', async (req: Request, res: Response) => {\n const list = masterPlugins()\n if (!list) {\n res.status(503).json({ error: 'Multihelm is not running' })\n return\n }\n const ids = parsePluginIds((req.body as { plugins?: unknown } | undefined)?.plugins)\n if (!ids) {\n res.status(400).json({ error: 'plugins must be a list of plugin ids' })\n return\n }\n try {\n await list.set(ids)\n res.json({ plugins: list.ids() })\n } catch (error) {\n res.status(500).json({ error: errorText(error) })\n }\n })\n\n router.post(\n '/run',\n running((mh, _req, res) => {\n void mh.runRound()\n res.status(202).json({ started: true })\n })\n )\n}\n","/**\n * The `resources` dataset: the routes, waypoints, regions and notes of this\n * server, one entry per resource keyed `<type>/<id>`, kept in step between\n * the boat's servers with no master. They are read and written through the\n * server's Resources API, so every provider is covered and every change\n * reaches the clients as a delta. Each resource is mirrored as a JSON file\n * in the data dir, because a dataset entry is made of files.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nimport type { DatasetDefinition, DatasetEntry, IncomingEntry } from './api.js'\n\nexport const RESOURCES_DATASET = 'signalk-multihelm/resources'\nexport const RESOURCE_TYPES = ['routes', 'waypoints', 'regions', 'notes'] as const\nexport type ResourceType = (typeof RESOURCE_TYPES)[number]\n\nconst FILE = 'resource.json'\n/** What the server's Resources API requires of an id for these types. */\nconst RESOURCE_ID =\n /^[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}$/\n/** Added by the provider on every read, not part of the resource. */\nconst READ_ONLY_FIELDS = new Set(['timestamp', '$source'])\nconst STORED_CHECKS = 20\nconst STORED_CHECK_MS = 100\nconst DELETE_CONFIRM_MS = 2000\n\nexport interface ResourcesHost {\n list: (type: ResourceType) => Promise<Record<string, unknown>>\n set: (type: ResourceType, id: string, resource: Record<string, unknown>) => Promise<void>\n delete: (type: ResourceType, id: string) => Promise<void>\n /** Where the mirror files live. */\n mirrorDir: string\n debug: (msg: string) => void\n error: (msg: string) => void\n}\n\n/** Plugins reach the Resources API in process; a server without it has nothing to keep in step. */\nexport function hasResourcesApi(app: object): boolean {\n const api = (app as { resourcesApi?: { setResource?: unknown } }).resourcesApi\n return typeof api?.setResource === 'function'\n}\n\nfunction isResourceType(type: string): type is ResourceType {\n return (RESOURCE_TYPES as readonly string[]).includes(type)\n}\n\nexport function isResourceKey(key: string): boolean {\n const [type, id, ...rest] = key.split('/')\n return (\n rest.length === 0 && type !== undefined && isResourceType(type) && RESOURCE_ID.test(id ?? '')\n )\n}\n\n/** The resource a `resources.<type>.<id>` delta path names, or null. */\nexport function resourceOfPath(deltaPath: string): { type: ResourceType; id: string } | null {\n const [root, type, id, ...rest] = deltaPath.split('.')\n return root === 'resources' &&\n rest.length === 0 &&\n type !== undefined &&\n isResourceType(type) &&\n RESOURCE_ID.test(id ?? '')\n ? { type, id: id ?? '' }\n : null\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Sorted keys, so the same resource always gives the same file and nothing churns. */\nfunction canonical(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(canonical)\n }\n if (isRecord(value)) {\n return Object.fromEntries(\n Object.keys(value)\n .sort()\n .map((k) => [k, canonical(value[k])])\n )\n }\n return value\n}\n\nexport function resourceText(resource: Record<string, unknown>): string {\n const stored = Object.fromEntries(\n Object.entries(resource).filter(([k]) => !READ_ONLY_FIELDS.has(k))\n )\n return JSON.stringify(canonical(stored))\n}\n\nfunction splitKey(key: string): { type: ResourceType; id: string } {\n const [type, id] = key.split('/') as [ResourceType, string]\n return { type, id }\n}\n\nconst sleep = (ms: number): Promise<void> =>\n new Promise((resolve) => {\n setTimeout(resolve, ms)\n })\n\nexport interface ResourcesDataset {\n dataset: DatasetDefinition\n /** The server announced a deletion with a null value on `resources.<type>.<id>`. */\n deleted: (type: ResourceType, id: string) => Promise<void>\n /** The server announced a stored value on `resources.<type>.<id>`. */\n written: (type: ResourceType, id: string) => void\n}\n\nexport function resourcesDataset(host: ResourcesHost): ResourcesDataset {\n const mirrorPath = (type: ResourceType, id: string): string =>\n path.join(host.mirrorDir, type, `${id}.json`)\n\n async function mirrored(type: ResourceType): Promise<Map<string, string>> {\n const found = new Map<string, string>()\n let names: string[]\n try {\n names = await fs.promises.readdir(path.join(host.mirrorDir, type))\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return found\n }\n throw error\n }\n for (const name of names) {\n const id = name.replace(/\\.json$/, '')\n if (name.endsWith('.json') && RESOURCE_ID.test(id)) {\n found.set(id, await fs.promises.readFile(path.join(host.mirrorDir, type, name), 'utf8'))\n }\n }\n return found\n }\n\n /** Rewrites a mirror file only when its resource changed, so its time stays what was hashed. */\n async function mirror(type: ResourceType, id: string, text: string, had?: string): Promise<void> {\n if (had !== text) {\n const file = mirrorPath(type, id)\n await fs.promises.mkdir(path.dirname(file), { recursive: true })\n const tmp = `${file}.part`\n await fs.promises.writeFile(tmp, text)\n await fs.promises.rename(tmp, file)\n }\n pendingRemovals.delete(`${type}/${id}`)\n }\n\n /**\n * The resources of one type, added to and updated from the server's\n * listing but never shortened by it: the Resources API leaves a failing\n * provider out of its answer, so a resource missing from it may still be\n * there. Deletions come from the server's deltas instead (`deleted`).\n */\n async function current(type: ResourceType): Promise<Map<string, string>> {\n const readAt = deletions\n const known = await mirrored(type)\n let listed: Record<string, unknown>\n try {\n listed = await host.list(type)\n } catch (error) {\n host.debug(\n `Multihelm: cannot list the ${type}: ${error instanceof Error ? error.message : String(error)}`\n )\n return known\n }\n for (const [id, resource] of Object.entries(listed)) {\n if (!RESOURCE_ID.test(id) || !isRecord(resource)) {\n continue\n }\n const key = `${type}/${id}`\n if (deletedHere.has(key) || (deletedAt.get(key) ?? 0) > readAt) {\n known.delete(id)\n continue\n }\n const text = resourceText(resource)\n await mirror(type, id, text, known.get(id))\n known.set(id, text)\n }\n return known\n }\n\n /**\n * Deleted on this server and not written again since: a listing read\n * before the deletion must not bring them back.\n */\n const deletedHere = new Set<string>()\n /** When each was last deleted, counted in deletions: a listing read before then is stale for it. */\n const deletedAt = new Map<string, number>()\n let deletions = 0\n const awaitingDeletion = new Map<string, () => void>()\n /** Deleted on the server, but their mirror files could not be removed yet. */\n const pendingRemovals = new Set<string>()\n\n /** Mirror files are written and removed one after the other, so a deletion cannot race a rewrite. */\n let mirrorWork: Promise<unknown> = Promise.resolve()\n function exclusive<T>(work: () => Promise<T>): Promise<T> {\n const result = mirrorWork.then(work)\n mirrorWork = result.catch(() => undefined)\n return result\n }\n\n async function removeMirror(key: string): Promise<void> {\n const { type, id } = splitKey(key)\n try {\n await fs.promises.rm(mirrorPath(type, id), { force: true })\n pendingRemovals.delete(key)\n } catch (error) {\n pendingRemovals.add(key)\n host.error(\n `Multihelm: cannot remove the copy of ${key}, trying again: ${error instanceof Error ? error.message : String(error)}`\n )\n }\n }\n\n /** The Resources API answers before the provider has written: wait until it has. */\n async function whenStored(\n type: ResourceType,\n id: string,\n text: string,\n wanted: () => boolean\n ): Promise<void> {\n for (let check = 0; check < STORED_CHECKS && wanted(); check++) {\n const resource = (await host.list(type))[id]\n if (isRecord(resource) && resourceText(resource) === text) {\n return\n }\n await sleep(STORED_CHECK_MS)\n }\n if (!wanted()) {\n return\n }\n throw new Error(`the server did not store ${type}/${id}`)\n }\n\n /** Only the server's delta says a deletion was stored; a listing that lacks the resource may just be failing. */\n function whenDeleted(key: string): Promise<void> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n awaitingDeletion.delete(key)\n reject(new Error(`the server did not delete ${key}`))\n }, DELETE_CONFIRM_MS)\n awaitingDeletion.set(key, () => {\n clearTimeout(timer)\n resolve()\n })\n })\n }\n\n async function deleted(type: ResourceType, id: string): Promise<void> {\n const key = `${type}/${id}`\n deletedHere.add(key)\n deletedAt.set(key, ++deletions)\n await exclusive(() => removeMirror(key))\n awaitingDeletion.get(key)?.()\n awaitingDeletion.delete(key)\n }\n\n const dataset: DatasetDefinition = {\n id: RESOURCES_DATASET,\n isValidKey: isResourceKey,\n\n list: async (): Promise<DatasetEntry[]> => {\n const entries: DatasetEntry[] = []\n for (const key of [...pendingRemovals]) {\n await exclusive(async () => {\n if (pendingRemovals.has(key)) {\n await removeMirror(key)\n }\n })\n }\n for (const type of RESOURCE_TYPES) {\n for (const id of (await exclusive(() => current(type))).keys()) {\n if (pendingRemovals.has(`${type}/${id}`)) {\n continue\n }\n const file = mirrorPath(type, id)\n const stat = await fs.promises.stat(file)\n entries.push({\n key: `${type}/${id}`,\n meta: null,\n files: [{ name: FILE, path: file, size: stat.size, mtimeMs: stat.mtimeMs }]\n })\n }\n }\n return entries\n },\n\n apply: async (entry: IncomingEntry): Promise<void> => {\n const file = entry.files.find((f) => f.name === FILE)\n if (!file || entry.files.length !== 1) {\n throw new Error(`a resource has one file, ${entry.key} has ${String(entry.files.length)}`)\n }\n const { type, id } = splitKey(entry.key)\n const resource: unknown = JSON.parse(await fs.promises.readFile(file.path, 'utf8'))\n if (!isRecord(resource)) {\n throw new Error(`${entry.key} is not a resource`)\n }\n const text = resourceText(resource)\n deletedHere.delete(entry.key)\n const setAt = deletions\n const notDeletedSince = (): boolean => (deletedAt.get(entry.key) ?? 0) <= setAt\n await host.set(type, id, resource)\n await whenStored(type, id, text, notDeletedSince)\n await exclusive(async () => {\n if (notDeletedSince()) {\n await mirror(type, id, text)\n }\n })\n },\n\n /**\n * A delete the server refuses is taken as done: it cannot say whether\n * the resource is already gone or its provider failed, and should it\n * still be there, the next listing offers it to the peers again. A\n * failure can bring a deleted route back, but never lose one.\n */\n remove: async (key: string): Promise<boolean> => {\n const { type, id } = splitKey(key)\n const confirmed = whenDeleted(key)\n try {\n await host.delete(type, id)\n } catch (error) {\n awaitingDeletion.get(key)?.()\n host.debug(\n `Multihelm: the server refused to delete ${key}: ${error instanceof Error ? error.message : String(error)}`\n )\n await exclusive(() => removeMirror(key))\n return true\n }\n await confirmed\n return true\n }\n }\n\n function written(type: ResourceType, id: string): void {\n deletedHere.delete(`${type}/${id}`)\n }\n\n return { dataset, deleted, written }\n}\n","/**\n * This server's admin device token on itself, for writing what follows the\n * master through the server's own REST API: vessel settings, and which\n * plugins run. Asked for once; until the user approves it nothing is written.\n */\n\nimport { pollAccess, requestAccess, type AccessRequestResult } from './peer-client.js'\nimport type { MultihelmStore, OwnAccess } from './store.js'\n\nexport interface OwnAccessHost {\n store: MultihelmStore\n serverId: string\n /** This server, over loopback: `http(s)://127.0.0.1:<port>`. */\n ownUrl: () => string\n debug: (msg: string) => void\n}\n\nexport class OwnServerAccess {\n private access: OwnAccess\n /** One request or poll at a time, shared by everyone waiting for the token. */\n private asking: Promise<string | null> | null = null\n\n constructor(private readonly host: OwnAccessHost) {\n this.access = host.store.loadOwnAccess()\n }\n\n /** Whether the user has to approve this server's own access request. */\n waitingForApproval(): boolean {\n return this.access.state === 'waiting-approval'\n }\n\n /** The identifier of the access request on this server, as Security -> Access Requests lists it. */\n requestId(): string {\n return `signalk-multihelm-self-${this.host.serverId}`\n }\n\n /** Whether the user denied it; it is asked for again only after a restart. */\n denied(): boolean {\n return this.access.state === 'denied'\n }\n\n /** The server refused the token: it is asked for again. */\n revoked(): void {\n this.save({ token: '', state: 'none' })\n }\n\n /** The token, empty without security; null while there is none to use. */\n token(): Promise<string | null> {\n if (this.access.state === 'granted') {\n return Promise.resolve(this.access.token)\n }\n if (this.access.state === 'denied') {\n return Promise.resolve(null)\n }\n this.asking ??= this.ask().finally(() => {\n this.asking = null\n })\n return this.asking\n }\n\n private async ask(): Promise<string | null> {\n const base = this.host.ownUrl()\n let result: AccessRequestResult\n try {\n result =\n this.access.state === 'waiting-approval' && this.access.requestHref\n ? await pollAccess({ url: base }, this.access.requestHref)\n : await requestAccess(\n { url: base },\n this.requestId(),\n 'Multihelm: write the settings that follow the master on this server',\n 'admin'\n )\n } catch (error) {\n this.host.debug(\n `Multihelm: access request on this server: ${error instanceof Error ? error.message : String(error)}`\n )\n return null\n }\n switch (result.kind) {\n case 'no-security':\n this.save({ token: '', state: 'granted' })\n return ''\n case 'approved':\n this.save({ token: result.token, state: 'granted' })\n return result.token\n case 'pending':\n this.save({ token: '', requestHref: result.href, state: 'waiting-approval' })\n return null\n case 'denied':\n this.host.store.saveOwnAccess({ token: '', state: 'none' })\n this.access = { token: '', state: 'denied' }\n return null\n case 'error':\n this.host.debug(`Multihelm: access request on this server: ${result.message}`)\n return null\n }\n }\n\n private save(access: OwnAccess): void {\n this.access = access\n this.host.store.saveOwnAccess(access)\n }\n}\n","/**\n * Multihelm state on disk, in the plugin's data dir: this server's id, its\n * paired peers and one library per dataset. Peers hold access tokens, so\n * their file is readable by the server's user only.\n */\n\nimport crypto from 'node:crypto'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { Type, type Static } from 'typebox'\nimport { Value } from 'typebox/value'\n\nimport { emptyLibrary, type Library } from './library.js'\n\nexport const PeerSchema = Type.Object({\n /** The peer's server id, from its `hello`; empty until it answered once. */\n id: Type.String(),\n name: Type.String(),\n /** Base URL of the peer's Signal K server, e.g. `http://192.168.1.20:3000`. */\n url: Type.String(),\n /** PEM of the certificate its HTTPS chain must lead to; see `PeerAddress`. */\n ca: Type.Optional(Type.String()),\n /** Readonly device token; empty when the peer runs without security. */\n token: Type.String(),\n /** Set while an access request waits for approval on the peer. */\n requestHref: Type.Optional(Type.String()),\n state: Type.Union([\n Type.Literal('waiting-approval'),\n Type.Literal('paired'),\n Type.Literal('needs-pairing')\n ]),\n /** Per dataset, the peer's change sequence this server has applied up to. */\n cursors: Type.Record(Type.String(), Type.Integer({ minimum: 0 })),\n lastSeen: Type.Optional(Type.Number()),\n lastSync: Type.Optional(Type.Number()),\n lastError: Type.Optional(Type.String())\n})\n\nexport type Peer = Static<typeof PeerSchema>\n\nconst PeersFileSchema = Type.Array(PeerSchema)\n\n/** This server's admin device token on itself, for writing what follows the master. */\nexport const OwnAccessSchema = Type.Object({\n token: Type.String(),\n requestHref: Type.Optional(Type.String()),\n state: Type.Union([\n Type.Literal('none'),\n Type.Literal('waiting-approval'),\n Type.Literal('granted'),\n Type.Literal('denied')\n ])\n})\n\nexport type OwnAccess = Static<typeof OwnAccessSchema>\n\n/** A readwrite device token on the master, for sending it commands such as the autopilot's. */\nexport const ControlAccessSchema = Type.Object({\n /** The master's server id: a token for one master is no use for another. */\n masterId: Type.String(),\n token: Type.String(),\n requestHref: Type.Optional(Type.String()),\n state: Type.Union([\n Type.Literal('waiting-approval'),\n Type.Literal('granted'),\n Type.Literal('denied')\n ])\n})\n\nexport type ControlAccess = Static<typeof ControlAccessSchema>\n\nconst PathsFileSchema = Type.Array(Type.String())\n\n/** A server that asked this one for its `hello`, which a server does while paired with it. */\nexport const PairedServerSchema = Type.Object({\n id: Type.String(),\n name: Type.String(),\n signalk: Type.Optional(Type.String()),\n multihelm: Type.Optional(Type.String()),\n lastSeen: Type.Number()\n})\n\nexport type PairedServer = Static<typeof PairedServerSchema>\n\nconst PairedServersFileSchema = Type.Array(PairedServerSchema)\n\nconst LibraryFileSchema = Type.Object({\n seq: Type.Integer({ minimum: 0 }),\n entries: Type.Record(Type.String(), Type.Any())\n})\n\nfunction writeAtomic(file: string, data: string, mode?: number): void {\n const tmp = `${file}.${String(process.pid)}.tmp`\n fs.writeFileSync(tmp, data, mode === undefined ? undefined : { mode })\n fs.renameSync(tmp, file)\n}\n\nfunction readJson(file: string): unknown {\n try {\n return JSON.parse(fs.readFileSync(file, 'utf-8')) as unknown\n } catch {\n return undefined\n }\n}\n\nexport class MultihelmStore {\n readonly dir: string\n\n constructor(dataDir: string) {\n this.dir = dataDir\n fs.mkdirSync(path.join(dataDir, 'datasets'), { recursive: true })\n }\n\n /** Where a peer's files for `dataset` wait until they are verified and applied. */\n incomingDir(dataset: string): string {\n return path.join(this.dir, 'incoming', encodeURIComponent(dataset))\n }\n\n private libraryFile(dataset: string): string {\n return path.join(this.dir, 'datasets', `${encodeURIComponent(dataset)}.json`)\n }\n\n loadLibrary(dataset: string): Library {\n const raw = readJson(this.libraryFile(dataset))\n return Value.Check(LibraryFileSchema, raw) ? raw : emptyLibrary()\n }\n\n saveLibrary(dataset: string, library: Library): void {\n writeAtomic(this.libraryFile(dataset), JSON.stringify(library))\n }\n\n loadPeers(): Peer[] {\n const raw = readJson(path.join(this.dir, 'peers.json'))\n return Value.Check(PeersFileSchema, raw) ? raw : []\n }\n\n savePeers(peers: readonly Peer[]): void {\n writeAtomic(path.join(this.dir, 'peers.json'), JSON.stringify(peers, null, 2), 0o600)\n }\n\n loadOwnAccess(): OwnAccess {\n const raw = readJson(path.join(this.dir, 'own-access.json'))\n return Value.Check(OwnAccessSchema, raw) ? raw : { token: '', state: 'none' }\n }\n\n saveOwnAccess(access: OwnAccess): void {\n writeAtomic(path.join(this.dir, 'own-access.json'), JSON.stringify(access), 0o600)\n }\n\n loadControlAccess(): ControlAccess | null {\n const raw = readJson(path.join(this.dir, 'control-access.json'))\n return Value.Check(ControlAccessSchema, raw) ? raw : null\n }\n\n saveControlAccess(access: ControlAccess | null): void {\n const file = path.join(this.dir, 'control-access.json')\n if (access === null) {\n fs.rmSync(file, { force: true })\n return\n }\n writeAtomic(file, JSON.stringify(access), 0o600)\n }\n\n /** The paths whose metadata this server takes over from the master. */\n loadFollowedMeta(): string[] {\n const raw = readJson(path.join(this.dir, 'followed-meta.json'))\n return Value.Check(PathsFileSchema, raw) ? raw : []\n }\n\n saveFollowedMeta(paths: readonly string[]): void {\n writeAtomic(path.join(this.dir, 'followed-meta.json'), JSON.stringify(paths))\n }\n\n loadPairedBy(): PairedServer[] {\n const raw = readJson(path.join(this.dir, 'paired-by.json'))\n return Value.Check(PairedServersFileSchema, raw) ? raw : []\n }\n\n savePairedBy(servers: readonly PairedServer[]): void {\n writeAtomic(path.join(this.dir, 'paired-by.json'), JSON.stringify(servers))\n }\n\n /** A random id made once per installation: every server of a boat shares its vessel id. */\n serverId(): string {\n const file = path.join(this.dir, 'server-id')\n try {\n const id = fs.readFileSync(file, 'utf-8').trim()\n if (id) {\n return id\n }\n } catch {\n // First start.\n }\n const id = crypto.randomUUID()\n writeAtomic(file, id)\n return id\n }\n}\n","import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nimport type {\n Context,\n Path,\n Plugin,\n ServerAPI,\n SubscribeCallback,\n SubscribeMessage,\n Unsubscribes\n} from '@signalk/server-api'\n\nimport {\n API_VERSION,\n PROPERTY_NAME,\n type MultihelmProperty,\n type PeerInfo,\n type Role\n} from './api.js'\nimport { MasterAlarms, managedNotifications } from './alarms-from-master.js'\nimport { MasterAutopilot } from './autopilot-from-master.js'\nimport { MasterControlAccess } from './master-control.js'\nimport { MasterCourse } from './course-from-master.js'\nimport { ServerDiscovery } from './discovery.js'\nimport { ConfigSchema } from './config.js'\nimport { MasterFollower } from './follow-master.js'\nimport { MasterOnlyPlugins, MasterPluginList } from './master-plugins.js'\nimport { MasterHistory, canWithdrawHistoryProvider } from './history-from-master.js'\nimport { MASTER_ROUTE, MasterProxy } from './master-proxy.js'\nimport { Multihelm, ROUND_INTERVAL_MS } from './multihelm.js'\nimport { ROUTE_PREFIX } from './peer-client.js'\nimport { registerRoutes } from './routes.js'\nimport type { OwnAccessState } from './status.js'\nimport { hasResourcesApi, resourceOfPath, resourcesDataset } from './resources-dataset.js'\nimport { OwnServerAccess } from './own-access.js'\nimport { MultihelmStore } from './store.js'\nimport { sourcePrioritiesFromSettings } from './source-priorities.js'\nimport { vesselSettingsFromDeltas, type VesselSettings } from './vessel-settings.js'\n\nconst PLUGIN_ID = 'signalk-multihelm'\n\n/** The bundle and the sources both sit one folder below `package.json`. */\nfunction multihelmVersion(): string | undefined {\n try {\n const file = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'package.json')\n const { version } = JSON.parse(fs.readFileSync(file, 'utf-8')) as { version?: unknown }\n return typeof version === 'string' ? version : undefined\n } catch {\n return undefined\n }\n}\n\ntype Config = {\n master?: unknown\n syncResources?: unknown\n followVessel?: unknown\n followMetadata?: unknown\n followSourcePriorities?: unknown\n historyFromMaster?: unknown\n autopilotFromMaster?: unknown\n courseFromMaster?: unknown\n alarmsFromMaster?: unknown\n}\n\nconst APPROVE_HINT =\n \"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\"\n\nconst DENIED_HINT =\n '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'\n\nfunction statusText(role: Role, master: PeerInfo | null, conflict: boolean): string {\n if (conflict) {\n return `${role === 'master' ? 'Master' : `Member, master: ${master?.name ?? '?'}`}. More than one server is set to be the master: set one only`\n }\n if (role === 'master') {\n return \"Master of the boat's servers\"\n }\n return master ? `Member, master: ${master.name}` : 'Member, no master found'\n}\n\n/** The parts of the server the typed API leaves out. */\ntype Host = ServerAPI & {\n config?: {\n version?: string\n getExternalPort?: () => number\n baseDeltaEditor?: { deltas?: unknown }\n settings?: {\n ssl?: boolean\n port?: number\n sslport?: number\n priorityGroups?: unknown\n priorityOverrides?: unknown\n priorityDefaults?: unknown\n }\n }\n}\n\n/** Registering is plugin API; withdrawing before the plugin stops is reached on the server's own autopilot API. */\nfunction autopilotWithdrawal(app: ServerAPI): (() => void) | null {\n const api = (app as { autopilotApi?: { unRegister?: unknown } }).autopilotApi\n const unRegister = api?.unRegister\n if (typeof app.registerAutopilotProvider !== 'function' || typeof unRegister !== 'function') {\n return null\n }\n return () => {\n unRegister.call(api, PLUGIN_ID)\n }\n}\n\n/** The server takes the source policy of a plugin's subscription as an argument, not from the command. */\ninterface SourcePolicySubscriptions {\n subscribe: (\n command: SubscribeMessage,\n unsubscribes: Unsubscribes,\n errorCallback: (err: unknown) => void,\n callback: SubscribeCallback,\n user: string | undefined,\n sourcePolicy: 'all'\n ) => void\n}\n\nexport default function (app: ServerAPI): Plugin {\n const host = app as Host\n let multihelm: Multihelm | null = null\n let discovery: ServerDiscovery | null = null\n let masterProxy: MasterProxy | null = null\n let stopRoleStatus: (() => void) | null = null\n let stopFollowing: (() => void) | null = null\n let ownAccess: OwnServerAccess | null = null\n let masterPluginList: MasterPluginList | null = null\n let masterControl: MasterControlAccess | null = null\n\n function localVesselSettings(): VesselSettings | null {\n const deltas = host.config?.baseDeltaEditor?.deltas\n if (deltas === undefined) {\n return null\n }\n const settings = vesselSettingsFromDeltas(deltas)\n const priorities = host.config?.settings\n ? sourcePrioritiesFromSettings(host.config.settings)\n : null\n return priorities ? { ...settings, priorities } : settings\n }\n\n /** The port this server listens on, as the server itself works it out. */\n function ownUrl(): string {\n const settings = host.config?.settings\n if (settings?.ssl) {\n return `https://127.0.0.1:${String(Number(process.env.SSLPORT) || settings.sslport || 3443)}`\n }\n return `http://127.0.0.1:${String(Number(process.env.PORT) || settings?.port || 3000)}`\n }\n\n function ownAccessState(): OwnAccessState {\n if (ownAccess?.waitingForApproval()) {\n return { state: 'waiting-approval', request: ownAccess.requestId() }\n }\n return ownAccess?.denied() ? { state: 'denied' } : null\n }\n\n /** Deletions are learnt from the server's deltas: only they show that one was stored. */\n function syncResources(mh: Multihelm): () => void {\n const sync = resourcesDataset({\n list: (type) => app.resourcesApi.listResources(type, {}),\n set: (type, id, resource) => app.resourcesApi.setResource(type, id, resource),\n delete: (type, id) => app.resourcesApi.deleteResource(type, id),\n mirrorDir: path.join(app.getDataDirPath(), 'resources'),\n debug: (msg) => {\n app.debug(msg)\n },\n error: (msg) => {\n app.error(msg)\n }\n })\n const handle = mh.registerDataset(sync.dataset)\n const unsubscribes: Unsubscribes = []\n ;(app.subscriptionmanager as SourcePolicySubscriptions).subscribe(\n {\n context: 'vessels.self' as Context,\n subscribe: [{ path: 'resources.*' as Path, policy: 'instant' }]\n },\n unsubscribes,\n (error) => {\n app.error(`Multihelm: following resource deletions: ${String(error)}`)\n },\n (delta) => {\n for (const update of delta.updates) {\n for (const { path: valuePath, value } of 'values' in update ? update.values : []) {\n const resource = resourceOfPath(valuePath)\n if (resource && value !== null) {\n sync.written(resource.type, resource.id)\n } else if (resource) {\n sync.deleted(resource.type, resource.id).then(\n () => {\n handle.changed()\n },\n (error: unknown) => {\n app.error(\n `Multihelm: cannot follow the deletion of ${resource.type}/${resource.id}: ${error instanceof Error ? error.message : String(error)}`\n )\n }\n )\n }\n }\n }\n },\n undefined,\n 'all'\n )\n return () => {\n for (const unsubscribe of unsubscribes) {\n unsubscribe()\n }\n handle.unregister()\n }\n }\n\n function publish(value: MultihelmProperty): void {\n app.emitPropertyValue(PROPERTY_NAME, value)\n }\n\n return {\n id: PLUGIN_ID,\n name: 'Multihelm',\n description:\n \"Keeps the Signal K servers of one boat in step, and knows which one is the boat's master\",\n schema: () => ConfigSchema,\n\n start(config: object) {\n // Schema defaults are not applied at runtime: a never configured plugin gets {}.\n const settings = config as Config\n const isMaster = settings.master === true\n const store = new MultihelmStore(app.getDataDirPath())\n const mh = new Multihelm(store, {\n serverName: () => os.hostname(),\n isMaster: () => isMaster,\n versions: () => ({ signalk: host.config?.version, multihelm: multihelmVersion() }),\n debug: (msg) => {\n app.debug(msg)\n },\n error: (msg) => {\n app.error(msg)\n }\n })\n multihelm = mh\n const proxy = new MasterProxy(() => mh.masterAccess())\n masterProxy = proxy\n discovery = new ServerDiscovery(() => host.config?.getExternalPort?.())\n discovery.start()\n mh.start()\n const stopResources =\n settings.syncResources !== false && hasResourcesApi(app) ? syncResources(mh) : null\n publish({\n apiVersion: API_VERSION,\n registerDataset: (definition) => mh.registerDataset(definition),\n peers: () => mh.peerInfo(),\n serverId: () => mh.serverId,\n role: () => mh.role(),\n master: () => mh.master(),\n onRoleChanged: (cb) => mh.onRoleChanged(cb),\n registerMasterRoute: (prefix) => proxy.register(prefix),\n masterPath: (target) => `${ROUTE_PREFIX}${MASTER_ROUTE}${target}`,\n fetchMaster: (target) => proxy.fetch(target)\n })\n const access = new OwnServerAccess({\n store,\n serverId: mh.serverId,\n ownUrl,\n debug: (msg) => {\n app.debug(msg)\n }\n })\n ownAccess = access\n const masterPlugins = new MasterOnlyPlugins({\n ids: () => pluginList.ids(),\n // Nothing is switched before the role is known, nor on a server with no master to defer to.\n wanted: () =>\n !mh.roleKnown() ? null : mh.role() === 'master' ? true : mh.master() ? false : null,\n access,\n ownUrl,\n selfId: PLUGIN_ID,\n debug: (msg) => {\n app.debug(msg)\n },\n error: (msg) => {\n app.error(msg)\n }\n })\n const pluginList = new MasterPluginList(\n path.join(app.getDataDirPath(), 'master-plugins'),\n () => {\n masterPlugins.apply()\n settingsHandle.changed()\n }\n )\n const settingsHandle = mh.registerDataset(pluginList.dataset)\n masterPluginList = pluginList\n const pluginsTimer = setInterval(() => {\n masterPlugins.apply()\n }, ROUND_INTERVAL_MS)\n const stopRolePlugins = mh.onRoleChanged(() => {\n masterPlugins.apply()\n })\n const follower = new MasterFollower({\n store,\n access,\n ownUrl,\n localSettings: localVesselSettings,\n master: () => mh.masterAccess(),\n followVessel: settings.followVessel !== false,\n followMeta: settings.followMetadata !== false,\n followPriorities: settings.followSourcePriorities !== false,\n debug: (msg) => {\n app.debug(msg)\n },\n error: (msg) => {\n app.error(msg)\n }\n })\n const showRole = (): void => {\n const text = statusText(mh.role(), mh.master(), mh.masterConflict())\n if (access.waitingForApproval()) {\n app.setPluginStatus(`${text}; ${APPROVE_HINT}`)\n } else if (access.denied()) {\n app.setPluginStatus(`${text}; ${DENIED_HINT}`)\n } else {\n app.setPluginStatus(text)\n }\n }\n let following = false\n const follow = (): void => {\n if (following) {\n return\n }\n following = true\n void follower\n .run()\n .catch((error: unknown) => {\n app.error(\n `Multihelm: taking over the master's vessel settings: ${error instanceof Error ? error.message : String(error)}`\n )\n })\n .finally(() => {\n following = false\n showRole()\n })\n }\n const followTimer = setInterval(follow, ROUND_INTERVAL_MS)\n const stopRoleFollow = mh.onRoleChanged(follow)\n const history =\n settings.historyFromMaster !== false && canWithdrawHistoryProvider(app)\n ? new MasterHistory({\n registerMasterRoute: (prefix) => proxy.register(prefix),\n fetchMaster: (target) => proxy.fetch(target),\n hasMaster: () => mh.masterAccess() !== null,\n register: (provider) => {\n app.registerHistoryApiProvider(provider)\n },\n unregister: () => {\n app.unregisterHistoryApiProvider()\n },\n debug: (msg) => {\n app.debug(msg)\n }\n })\n : null\n const checkHistory = (): void => {\n history?.check().catch((error: unknown) => {\n app.error(\n `Multihelm: serving the master's history: ${error instanceof Error ? error.message : String(error)}`\n )\n })\n }\n const control = new MasterControlAccess({\n store,\n serverId: mh.serverId,\n currentMaster: () => (mh.role() === 'master' ? null : (mh.master()?.id ?? null)),\n debug: (msg) => {\n app.debug(msg)\n }\n })\n masterControl = control\n const withdrawAutopilot = autopilotWithdrawal(app)\n const autopilot =\n settings.autopilotFromMaster !== false && withdrawAutopilot\n ? new MasterAutopilot({\n control,\n master: () => {\n const access = mh.masterAccess()\n const master = mh.master()\n return access && master ? { id: master.id, access } : null\n },\n isMaster: () => mh.role() === 'master',\n register: (provider, devices) => {\n app.registerAutopilotProvider(provider, devices)\n },\n unregister: withdrawAutopilot,\n update: (device, info) => {\n app.autopilotUpdate(device, info)\n },\n debug: (msg) => {\n app.debug(msg)\n },\n error: (msg) => {\n app.error(msg)\n }\n })\n : null\n autopilot?.start()\n const course =\n settings.courseFromMaster !== false\n ? new MasterCourse({\n master: () => {\n const masterAccess = mh.masterAccess()\n const master = mh.role() === 'master' ? null : mh.master()\n return masterAccess && master ? { id: master.id, access: masterAccess } : null\n },\n control,\n own: access,\n ownUrl,\n debug: (msg) => {\n app.debug(msg)\n }\n })\n : null\n course?.start()\n const notifications = managedNotifications(app.notifications)\n const alarms =\n settings.alarmsFromMaster !== false && notifications\n ? new MasterAlarms({\n master: () => {\n const masterAccess = mh.masterAccess()\n const master = mh.role() === 'master' ? null : mh.master()\n return masterAccess && master ? { id: master.id, access: masterAccess } : null\n },\n control,\n notifications,\n debug: (msg) => {\n app.debug(msg)\n }\n })\n : null\n alarms?.start()\n const stopRoleAutopilot = mh.onRoleChanged(() => {\n autopilot?.roleChanged()\n })\n const historyTimer = setInterval(checkHistory, ROUND_INTERVAL_MS)\n const stopRoleHistory = mh.onRoleChanged(checkHistory)\n checkHistory()\n stopFollowing = () => {\n clearInterval(pluginsTimer)\n stopRolePlugins()\n settingsHandle.unregister()\n stopRoleAutopilot()\n autopilot?.stop()\n course?.stop()\n alarms?.stop()\n clearInterval(followTimer)\n stopRoleFollow()\n clearInterval(historyTimer)\n stopRoleHistory()\n history?.stop()\n stopResources?.()\n }\n stopRoleStatus = mh.onStatusChanged(showRole)\n showRole()\n },\n\n stop() {\n stopFollowing?.()\n stopFollowing = null\n ownAccess = null\n masterPluginList = null\n masterControl = null\n stopRoleStatus?.()\n stopRoleStatus = null\n if (multihelm) {\n publish({ apiVersion: API_VERSION })\n }\n multihelm?.stop()\n multihelm = null\n masterProxy?.stop()\n masterProxy = null\n discovery?.stop()\n discovery = null\n },\n\n registerWithRouter(router) {\n registerRoutes(\n router,\n () => multihelm,\n () => discovery?.list() ?? [],\n localVesselSettings,\n () => masterProxy,\n ownAccessState,\n () => masterPluginList,\n () => masterControl?.waitingForApproval(multihelm?.role() === 'master') ?? null\n )\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAYA,IAAa,gBAAgB;;;;;;;;;;;ACM7B,IAAa,eAAe;AAC5B,IAAMA,uBAAqB;;;;;;AAO3B,IAAa,mCAAwC,IAAI,IAAI;CAC3D;CACA;CACA;CACA;CACA;AACF,CAAC;AAsCD,SAAS,WAA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