@sailingnaturali/signalk-ntfy-relay 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +56 -0
  3. package/index.js +204 -0
  4. package/package.json +36 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bryan Clark
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,56 @@
1
+ # @sailingnaturali/signalk-ntfy-relay
2
+
3
+ Relay [Signal K](https://signalk.org) notifications (alarms) to an
4
+ [ntfy](https://ntfy.sh) topic — so a man-overboard, depth/wind/battery alarm, or
5
+ any other notification reaches your phone, independent of any chartplotter or
6
+ shoreside server.
7
+
8
+ **Zero runtime dependencies.** Notifications are read in-process via the Signal K
9
+ subscription manager; ntfy is reached with Node's built-in `https`.
10
+
11
+ ## How it works
12
+
13
+ - Subscribes to `notifications.*` and **edge-triggers**: it pushes once when an
14
+ alarm becomes active, not repeatedly while it persists.
15
+ - Forwards notifications at or above a configurable severity (`warn` by default).
16
+ - Maps Signal K severity to ntfy **priority** and **tags**:
17
+
18
+ | Signal K state | ntfy priority | tag |
19
+ |----------------|---------------|-----|
20
+ | `emergency` | 5 (max) | 🆘 `sos` |
21
+ | `alarm` | 4 (high) | 🚨 `rotating_light` |
22
+ | `warn` | 3 (default) | âš ī¸ `warning` |
23
+ | `alert` | 2 (low) | â„šī¸ `information_source` |
24
+ | cleared (`normal`) | 1 (min) | ✅ `white_check_mark` |
25
+
26
+ - Appends the vessel position to the message when known.
27
+
28
+ ## Configuration
29
+
30
+ | Setting | Default | Notes |
31
+ |---------|---------|-------|
32
+ | `server` | `https://ntfy.sh` | Set to your self-hosted ntfy server |
33
+ | `topic` | *(required)* | The ntfy topic to publish to |
34
+ | `token` | *(empty)* | `Authorization: Bearer` token (self-hosted/ACL) |
35
+ | `minState` | `warn` | Minimum severity to forward |
36
+ | `notifyOnClear` | `true` | Also send a message when an alarm resolves |
37
+ | `includePosition` | `true` | Append `lat, lon` to the message |
38
+
39
+ ## Setup
40
+
41
+ 1. Install from the Signal K app store (category: Notifications), or drop this
42
+ folder into the server's `node_modules`.
43
+ 2. Pick a hard-to-guess topic (anyone who knows a public-server topic can read it),
44
+ e.g. `naturali-alarms-7f3a`.
45
+ 3. Install the ntfy app on your phone and subscribe to that topic.
46
+ 4. Configure the plugin with the topic and enable it.
47
+
48
+ Test it by raising a notification, e.g. a man-overboard via the Signal K v2 API:
49
+
50
+ ```bash
51
+ curl -X POST http://localhost:3000/signalk/v2/api/notifications/mob
52
+ ```
53
+
54
+ ## License
55
+
56
+ MIT
package/index.js ADDED
@@ -0,0 +1,204 @@
1
+ /*
2
+ * signalk-ntfy-relay — relay SignalK notifications to ntfy.
3
+ *
4
+ * Watches notifications.* in-process, edge-triggers on state change, and POSTs
5
+ * active alarms (>= a configurable severity) to an ntfy topic via Node's
6
+ * built-in https/http. Zero runtime dependencies, so it mounts read-only.
7
+ *
8
+ * The factory takes an optional second arg `deps` so tests can inject a fake
9
+ * `send`; SignalK calls it with just (app), using the real network sender.
10
+ */
11
+ const SEVERITY = { nominal: 0, normal: 1, alert: 2, warn: 3, alarm: 4, emergency: 5 };
12
+ const INACTIVE = new Set(['nominal', 'normal']);
13
+
14
+ function rank(state) {
15
+ return state in SEVERITY ? SEVERITY[state] : -1;
16
+ }
17
+ function isActive(state) {
18
+ return state != null && !INACTIVE.has(state);
19
+ }
20
+ function shouldForward(state, minState) {
21
+ return isActive(state) && rank(state) >= rank(minState);
22
+ }
23
+
24
+ const PRIORITY = { emergency: '5', alarm: '4', warn: '3', alert: '2' };
25
+ const TAGS = {
26
+ emergency: 'sos',
27
+ alarm: 'rotating_light',
28
+ warn: 'warning',
29
+ alert: 'information_source',
30
+ };
31
+
32
+ // Inactive (cleared) states get the min-priority "resolved" treatment.
33
+ function priorityFor(state) {
34
+ return isActive(state) ? (PRIORITY[state] || '3') : '1';
35
+ }
36
+ function tagsFor(state) {
37
+ return isActive(state) ? (TAGS[state] || 'warning') : 'white_check_mark';
38
+ }
39
+
40
+ // Compose the ntfy HTTP request (pure — no I/O). Returns {url, headers, body}.
41
+ function buildRequest(n, position, options) {
42
+ const base = (options.server || 'https://ntfy.sh').replace(/\/+$/, '');
43
+ // Encode the topic so a stray space/slash can't break the path or smuggle in
44
+ // extra path segments (ntfy topics are [A-Za-z0-9_-], but be defensive).
45
+ const url = `${base}/${encodeURIComponent(options.topic)}`;
46
+ const headers = {
47
+ 'Content-Type': 'text/plain; charset=utf-8',
48
+ Title: `${String(n.state).toUpperCase()}: ${n.path}`,
49
+ Priority: priorityFor(n.state),
50
+ Tags: tagsFor(n.state),
51
+ };
52
+ if (options.token) headers.Authorization = `Bearer ${options.token}`;
53
+ let body = n.message || n.path;
54
+ if (
55
+ options.includePosition !== false &&
56
+ position &&
57
+ typeof position.latitude === 'number' &&
58
+ typeof position.longitude === 'number'
59
+ ) {
60
+ body += `\n@ ${position.latitude.toFixed(5)}, ${position.longitude.toFixed(5)}`;
61
+ }
62
+ return { url, headers, body };
63
+ }
64
+
65
+ const https = require('https');
66
+ const http = require('http');
67
+ const { URL } = require('url');
68
+
69
+ // The only I/O boundary. Fire-and-forget POST to ntfy; never throws — any
70
+ // failure is logged via app.error so one bad push can't stall other alarms.
71
+ function defaultSend({ url, headers, body }, app) {
72
+ try {
73
+ const u = new URL(url);
74
+ const lib = u.protocol === 'http:' ? http : https;
75
+ const req = lib.request(u, { method: 'POST', headers }, (res) => {
76
+ res.resume(); // drain
77
+ if (res.statusCode >= 300) app.error(`ntfy responded ${res.statusCode}`);
78
+ });
79
+ req.on('error', (e) => app.error(`ntfy post failed: ${e.message}`));
80
+ req.setTimeout(5000, () => req.destroy(new Error('ntfy timeout')));
81
+ req.write(body);
82
+ req.end();
83
+ } catch (e) {
84
+ app.error(`ntfy send error: ${e.message}`);
85
+ }
86
+ }
87
+
88
+ module.exports = function (app, deps) {
89
+ const send = (deps && deps.send) || defaultSend;
90
+ const plugin = {
91
+ id: 'signalk-ntfy-relay',
92
+ name: 'ntfy notification relay',
93
+ description: 'Relay SignalK notifications (alarms) to an ntfy topic.',
94
+ };
95
+
96
+ plugin.schema = {
97
+ type: 'object',
98
+ required: ['topic'],
99
+ properties: {
100
+ server: {
101
+ type: 'string',
102
+ title: 'ntfy server base URL',
103
+ default: 'https://ntfy.sh',
104
+ },
105
+ topic: {
106
+ type: 'string',
107
+ title: 'ntfy topic to publish alarms to',
108
+ },
109
+ token: {
110
+ type: 'string',
111
+ title: 'Access token (optional, for self-hosted/ACL servers)',
112
+ default: '',
113
+ },
114
+ minState: {
115
+ type: 'string',
116
+ title: 'Minimum severity to forward',
117
+ enum: ['alert', 'warn', 'alarm', 'emergency'],
118
+ default: 'warn',
119
+ },
120
+ notifyOnClear: {
121
+ type: 'boolean',
122
+ title: 'Send a message when an alarm clears',
123
+ default: true,
124
+ },
125
+ includePosition: {
126
+ type: 'boolean',
127
+ title: 'Append vessel position to the message',
128
+ default: true,
129
+ },
130
+ },
131
+ };
132
+
133
+ let unsubscribes = [];
134
+ let lastState = new Map();
135
+
136
+ function position() {
137
+ const node = app.getSelfPath('navigation.position');
138
+ if (node == null) return undefined;
139
+ const v = typeof node === 'object' && 'value' in node ? node.value : node;
140
+ return v && typeof v.latitude === 'number' ? v : undefined;
141
+ }
142
+
143
+ function onDelta(delta, options) {
144
+ (delta.updates || []).forEach((u) =>
145
+ (u.values || []).forEach((v) => {
146
+ if (!v.path || !v.path.startsWith('notifications.')) return;
147
+ const state = v.value && v.value.state;
148
+ const path = v.path.slice('notifications.'.length);
149
+ const prev = lastState.get(path);
150
+ if (state === prev) return; // edge-trigger: only act on change
151
+ lastState.set(path, state);
152
+ const min = options.minState || 'warn';
153
+ const message = (v.value && v.value.message) || undefined;
154
+ if (shouldForward(state, min)) {
155
+ send(buildRequest({ path, state, message }, position(), options), app);
156
+ } else if (
157
+ !isActive(state) &&
158
+ isActive(prev) &&
159
+ options.notifyOnClear !== false
160
+ ) {
161
+ send(
162
+ buildRequest({ path, state: state || 'normal', message }, position(), options),
163
+ app
164
+ );
165
+ }
166
+ })
167
+ );
168
+ }
169
+
170
+ plugin.start = function (options) {
171
+ options = options || {};
172
+ lastState = new Map();
173
+ if (!options.topic) {
174
+ app.error('signalk-ntfy-relay: no ntfy topic configured — idling');
175
+ return;
176
+ }
177
+ app.subscriptionmanager.subscribe(
178
+ {
179
+ context: 'vessels.self',
180
+ subscribe: [{ path: 'notifications.*', policy: 'instant' }],
181
+ },
182
+ unsubscribes,
183
+ (err) => app.error(err),
184
+ (delta) => {
185
+ try {
186
+ onDelta(delta, options);
187
+ } catch (e) {
188
+ app.error(`signalk-ntfy-relay: ${e.message}`);
189
+ }
190
+ }
191
+ );
192
+ };
193
+
194
+ plugin.stop = function () {
195
+ unsubscribes.forEach((f) => f());
196
+ unsubscribes = [];
197
+ lastState = new Map();
198
+ };
199
+
200
+ return plugin;
201
+ };
202
+
203
+ // Pure helpers, hung off the factory for unit tests.
204
+ module.exports._internal = { rank, isActive, shouldForward, priorityFor, tagsFor, buildRequest };
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@sailingnaturali/signalk-ntfy-relay",
3
+ "version": "0.1.0",
4
+ "description": "Relay SignalK notifications (alarms) to an ntfy topic — zero dependencies, edge-triggered, severity-aware.",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "node --test"
8
+ },
9
+ "keywords": [
10
+ "signalk-node-server-plugin",
11
+ "signalk-category-notifications",
12
+ "ntfy",
13
+ "notifications",
14
+ "alarm",
15
+ "marine"
16
+ ],
17
+ "author": "Bryan Clark",
18
+ "license": "MIT",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/sailingnaturali/signalk-ntfy-relay.git"
22
+ },
23
+ "homepage": "https://github.com/sailingnaturali/signalk-ntfy-relay#readme",
24
+ "bugs": {
25
+ "url": "https://github.com/sailingnaturali/signalk-ntfy-relay/issues"
26
+ },
27
+ "files": [
28
+ "index.js"
29
+ ],
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "engines": {
34
+ "node": ">=18"
35
+ }
36
+ }