nofax 0.2.48 → 0.2.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/PRIVACY.md +25 -0
- package/README.md +99 -3
- package/docs/desktop-extension.md +18 -0
- package/docs/remote-mcp.md +55 -0
- package/manifest.json +81 -0
- package/package.json +5 -2
- package/src/adapters/claude.mjs +2 -2
- package/src/adapters/codex.mjs +2 -2
- package/src/adapters/gemini.mjs +3 -3
- package/src/cli.mjs +197 -26
- package/src/config.mjs +174 -15
- package/src/mcp-server.mjs +6 -2
- package/src/mcp-tools.mjs +41 -40
- package/src/ntfy.mjs +387 -53
- package/src/protocol.mjs +852 -24
- package/src/requests.mjs +122 -38
package/src/ntfy.mjs
CHANGED
|
@@ -1,27 +1,154 @@
|
|
|
1
1
|
import { createRequestId, createResponseTopic, parseResponseMessage } from './protocol.mjs';
|
|
2
|
+
import { normalizeServer, validateTopic } from './config.mjs';
|
|
2
3
|
|
|
3
4
|
const MAX_TITLE = 120;
|
|
4
5
|
const MAX_MESSAGE = 2200;
|
|
5
6
|
const MAX_NTFY_MESSAGE_BYTES = 4096;
|
|
7
|
+
const MAX_NTFY_POLL_RESPONSE_BYTES = 1_048_576;
|
|
6
8
|
const DEFAULT_REFINE_SHORTCUT = 'Nofax Refine';
|
|
7
9
|
const POLL_TIMEOUT = Symbol('NOFAX_POLL_TIMEOUT');
|
|
8
10
|
const PUBLISH_TIMEOUT = Symbol('NOFAX_PUBLISH_TIMEOUT');
|
|
11
|
+
const PUBLISH_CANCELLED = Symbol('NOFAX_PUBLISH_CANCELLED');
|
|
9
12
|
const DEFAULT_PUBLISH_TIMEOUT_MS = 15_000;
|
|
10
|
-
|
|
11
|
-
const
|
|
13
|
+
const MAX_TIMER_TIMEOUT_MS = 2_147_483_647;
|
|
14
|
+
const actionGraphemeSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
|
|
15
|
+
const RGI_EMOJI_TAG_FLAGS = new Set(['gbeng', 'gbsct', 'gbwls']);
|
|
16
|
+
// ntfy rejects invalid, unauthorized, oversized, and rate-limited requests
|
|
17
|
+
// before accepting the message. These must not leave orphan approvals.
|
|
18
|
+
const NOT_APPLIED_PUBLISH_STATUSES = new Set([400, 401, 403, 413, 429]);
|
|
19
|
+
|
|
20
|
+
function visibleNotificationText(value) {
|
|
21
|
+
// Never let untrusted notification text visually alter its own display.
|
|
22
|
+
// Keep genuine emoji flags and ideographic variation sequences, but expose
|
|
23
|
+
// supplementary invisible selectors or tags hidden in ordinary words.
|
|
24
|
+
if (typeof value !== 'string') return value;
|
|
25
|
+
const characters = [...value];
|
|
26
|
+
let characterIndex = 0;
|
|
27
|
+
return [...actionGraphemeSegmenter.segment(value)].map(({ segment }) => {
|
|
28
|
+
const graphemeCharacters = [...segment];
|
|
29
|
+
const tagCode = emojiTagCode(segment);
|
|
30
|
+
const visible = tagCode === null
|
|
31
|
+
? graphemeCharacters.map((character, index) => {
|
|
32
|
+
const previous = characters[characterIndex + index - 1] ?? '';
|
|
33
|
+
if (/[\u{e0001}\u{e0020}-\u{e007f}]/u.test(character) ||
|
|
34
|
+
(/[\u{e0100}-\u{e01ef}]/u.test(character) && !/\p{Unified_Ideograph}/u.test(previous))) {
|
|
35
|
+
return '\\u{' + character.codePointAt(0).toString(16) + '}';
|
|
36
|
+
}
|
|
37
|
+
return visibleNotificationCharacter(character, characters, characterIndex + index);
|
|
38
|
+
}).join('')
|
|
39
|
+
: RGI_EMOJI_TAG_FLAGS.has(tagCode) ? segment : '\u{1f3f4}[tag:' + tagCode + ']';
|
|
40
|
+
characterIndex += graphemeCharacters.length;
|
|
41
|
+
return visible;
|
|
42
|
+
}).join('');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function visibleNotificationTitle(value) {
|
|
46
|
+
const visible = visibleNotificationText(value);
|
|
47
|
+
// Titles are single-line; a raw newline could impersonate notification body text.
|
|
48
|
+
return typeof visible === 'string' ? visible.replace(/\n/g, '\\u000a') : visible;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function visibleNotificationCharacter(character, characters, index) {
|
|
52
|
+
if (character === '\ufe0e' || character === '\ufe0f') {
|
|
53
|
+
// Keep genuine emoji presentation and keycap sequences, not invisible
|
|
54
|
+
// variation selectors inserted into ordinary approval words.
|
|
55
|
+
let previous = index - 1;
|
|
56
|
+
while (previous >= 0 && /\p{Emoji_Modifier}/u.test(characters[previous])) previous--;
|
|
57
|
+
if (/\p{Extended_Pictographic}/u.test(characters[previous] ?? '') ||
|
|
58
|
+
(character === '\ufe0f' && /^[0-9#*]$/.test(characters[index - 1] ?? '') &&
|
|
59
|
+
characters[index + 1] === '\u20e3')) return character;
|
|
60
|
+
return `\\u${character.codePointAt(0).toString(16).padStart(4, '0')}`;
|
|
61
|
+
}
|
|
62
|
+
// Preserve genuine emoji ZWJ sequences, including skin-tone modifiers, but
|
|
63
|
+
// expose joiners hidden inside decision words rather than disguising choices.
|
|
64
|
+
if (character === '\u200c' || character === '\u200d') {
|
|
65
|
+
let before = index - 1;
|
|
66
|
+
while (before >= 0 && /[\ufe0e\ufe0f\p{Emoji_Modifier}]/u.test(characters[before])) before--;
|
|
67
|
+
if (character === '\u200d' &&
|
|
68
|
+
/\p{Extended_Pictographic}/u.test(characters[before] ?? '') &&
|
|
69
|
+
/\p{Extended_Pictographic}/u.test(characters[index + 1] ?? '')) {
|
|
70
|
+
return character;
|
|
71
|
+
}
|
|
72
|
+
return `\\u${character.codePointAt(0).toString(16).padStart(4, '0')}`;
|
|
73
|
+
}
|
|
74
|
+
// Blank Hangul/Braille fillers can disguise approval words.
|
|
75
|
+
return character.replace(/[\x00-\x09\x0b-\x1f\x7f-\x9f\u00ad\u034f\u061c\u115f-\u1160\u180e\u200b\u200e-\u200f\u2028-\u202e\u2060-\u206f\u2800\u3164\uffa0\ufff9-\ufffb\ufeff]/gu,
|
|
76
|
+
(control) => `\\u${control.codePointAt(0).toString(16).padStart(4, '0')}`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function visibleActionCharacter(character, characters, index) {
|
|
80
|
+
if (character === '\n') return '\\u000a';
|
|
81
|
+
// Expose invisible supplementary variation selectors in approval words too.
|
|
82
|
+
if (character === '\u{e0001}' ||
|
|
83
|
+
/[\u{e0020}-\u{e007f}\u{e0100}-\u{e01ef}]/u.test(character)) {
|
|
84
|
+
return `\\u{${character.codePointAt(0).toString(16)}}`;
|
|
85
|
+
}
|
|
86
|
+
// Unusual Unicode spaces can make distinct phone choices look identical.
|
|
87
|
+
// Keep ordinary ASCII word spacing; only expose the ambiguous variants.
|
|
88
|
+
if (character !== ' ' && /\p{Space_Separator}/u.test(character)) {
|
|
89
|
+
return `\\u${character.codePointAt(0).toString(16).padStart(4, '0')}`;
|
|
90
|
+
}
|
|
91
|
+
return visibleNotificationCharacter(character, characters, index);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function emojiTagCode(segment) {
|
|
95
|
+
const match = /^\u{1f3f4}([\u{e0061}-\u{e007a}]+)\u{e007f}$/u.exec(segment);
|
|
96
|
+
return match === null ? null : [...match[1]].map((tag) =>
|
|
97
|
+
String.fromCodePoint(tag.codePointAt(0) - 0xe0000)).join('');
|
|
98
|
+
}
|
|
12
99
|
|
|
13
100
|
function safeSliceEnd(text, end) {
|
|
14
|
-
|
|
15
|
-
|
|
101
|
+
// A code-unit boundary can split a joined emoji or combining sequence.
|
|
102
|
+
for (const { segment, index } of actionGraphemeSegmenter.segment(text)) {
|
|
103
|
+
if (index + segment.length > end) return index;
|
|
104
|
+
}
|
|
105
|
+
return text.length;
|
|
16
106
|
}
|
|
17
107
|
|
|
18
108
|
function boundChoiceLabel(value) {
|
|
19
|
-
|
|
109
|
+
const segments = [];
|
|
110
|
+
let renderedLength = 0;
|
|
111
|
+
let visibleContent = 0;
|
|
112
|
+
const characters = [...value];
|
|
113
|
+
let characterIndex = 0;
|
|
114
|
+
for (const { segment } of actionGraphemeSegmenter.segment(value)) {
|
|
115
|
+
// Action labels are single-line and must not hide/reorder the human's choices.
|
|
116
|
+
// Clip by whole graphemes so a joined emoji or flag cannot become a
|
|
117
|
+
// misleading partial symbol. Preserve atomic visible control escapes too.
|
|
118
|
+
const graphemeCharacters = [...segment];
|
|
119
|
+
// Only registered RGI tag flags have a reliable emoji presentation.
|
|
120
|
+
// Other complete tag sequences look like plain black flags on many phones;
|
|
121
|
+
// show their code visibly rather than silently hiding a decision label.
|
|
122
|
+
const tagCode = emojiTagCode(segment);
|
|
123
|
+
const visible = tagCode === null
|
|
124
|
+
? graphemeCharacters.map((character, index) =>
|
|
125
|
+
visibleActionCharacter(character, characters, characterIndex + index)).join('')
|
|
126
|
+
: RGI_EMOJI_TAG_FLAGS.has(tagCode) ? segment : `\u{1f3f4}[tag:${tagCode}]`;
|
|
127
|
+
characterIndex += graphemeCharacters.length;
|
|
128
|
+
if (renderedLength + visible.length > 32) {
|
|
129
|
+
// An explicit marker prevents a clipped action from looking complete.
|
|
130
|
+
while (renderedLength > 31) {
|
|
131
|
+
const removed = segments.pop();
|
|
132
|
+
renderedLength -= removed.text.length;
|
|
133
|
+
if (removed.hasContent) visibleContent -= 1;
|
|
134
|
+
}
|
|
135
|
+
segments.push({ text: '…', hasContent: false });
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
const hasContent = /[\p{L}\p{N}\p{P}\p{S}]/u.test(segment);
|
|
139
|
+
segments.push({ text: visible, hasContent });
|
|
140
|
+
renderedLength += visible.length;
|
|
141
|
+
if (hasContent) visibleContent += 1;
|
|
142
|
+
}
|
|
143
|
+
if (!visibleContent) throw new Error('NOFAX_CHOICE_INVALID');
|
|
144
|
+
return segments.map((segment) => segment.text).join('');
|
|
20
145
|
}
|
|
21
146
|
|
|
22
147
|
function boundText(value, max, name) {
|
|
23
148
|
if (typeof value !== 'string' || value.trim().length === 0) throw new Error(`NOFAX_${name}_REQUIRED`);
|
|
24
149
|
const text = value.trim();
|
|
150
|
+
// JSON serialization substitutes lone surrogates, changing what the human sees.
|
|
151
|
+
if (!text.isWellFormed()) throw new Error(`NOFAX_${name}_INVALID_UTF8`);
|
|
25
152
|
if (text.length <= max) return text;
|
|
26
153
|
const end = safeSliceEnd(text, max - 14);
|
|
27
154
|
return `${text.slice(0, end)}…[truncated]`;
|
|
@@ -35,11 +162,11 @@ function boundMessageText(value) {
|
|
|
35
162
|
const maxContentBytes = MAX_NTFY_MESSAGE_BYTES - Buffer.byteLength(marker, 'utf8');
|
|
36
163
|
let bytes = 0;
|
|
37
164
|
let end = 0;
|
|
38
|
-
for (const
|
|
39
|
-
const
|
|
40
|
-
if (bytes +
|
|
41
|
-
bytes +=
|
|
42
|
-
end +=
|
|
165
|
+
for (const { segment } of actionGraphemeSegmenter.segment(text)) {
|
|
166
|
+
const segmentBytes = Buffer.byteLength(segment, 'utf8');
|
|
167
|
+
if (bytes + segmentBytes > maxContentBytes) break;
|
|
168
|
+
bytes += segmentBytes;
|
|
169
|
+
end += segment.length;
|
|
43
170
|
}
|
|
44
171
|
return `${text.slice(0, end)}${marker}`;
|
|
45
172
|
}
|
|
@@ -82,7 +209,10 @@ function refineAction({ shortcutName, server, responseTopic, requestId }) {
|
|
|
82
209
|
}
|
|
83
210
|
|
|
84
211
|
async function ensureOk(response, code) {
|
|
85
|
-
if (!response?.ok)
|
|
212
|
+
if (!response?.ok) {
|
|
213
|
+
releaseResponseBody(response);
|
|
214
|
+
throw new Error(`${code}_${response?.status ?? 'NETWORK'}`);
|
|
215
|
+
}
|
|
86
216
|
return response;
|
|
87
217
|
}
|
|
88
218
|
|
|
@@ -92,45 +222,132 @@ function publishError(message, deliveryState) {
|
|
|
92
222
|
return error;
|
|
93
223
|
}
|
|
94
224
|
|
|
95
|
-
|
|
225
|
+
function validateTimeoutMs(value, errorCode) {
|
|
226
|
+
// Node timers clamp nonpositive, fractional and overflowing delays; do not
|
|
227
|
+
// publish an approval that could then immediately time out.
|
|
228
|
+
if (!Number.isSafeInteger(value) || value < 1 || value > MAX_TIMER_TIMEOUT_MS) {
|
|
229
|
+
throw new Error(errorCode);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// The optional ntfy publishing token is process-local, not stored in config.json.
|
|
234
|
+
// Never attach it to approval action URLs or response-topic polling requests.
|
|
235
|
+
function publishAuthorization(config, token) {
|
|
236
|
+
if (token === undefined) return null;
|
|
237
|
+
if (typeof token !== 'string' || token.length < 8 || token.length > 1024 ||
|
|
238
|
+
!/^[A-Za-z0-9_./+~=-]+$/.test(token)) {
|
|
239
|
+
throw new Error('NOFAX_NTFY_AUTH_TOKEN_INVALID');
|
|
240
|
+
}
|
|
241
|
+
let server;
|
|
242
|
+
try {
|
|
243
|
+
server = new URL(config.server);
|
|
244
|
+
} catch {
|
|
245
|
+
throw new Error('NOFAX_NTFY_AUTH_SERVER_INVALID');
|
|
246
|
+
}
|
|
247
|
+
if (server.protocol !== 'https:' || server.username || server.password) {
|
|
248
|
+
throw new Error('NOFAX_NTFY_AUTH_REQUIRES_HTTPS');
|
|
249
|
+
}
|
|
250
|
+
return `Bearer ${token}`;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function releaseResponseBody(response) {
|
|
254
|
+
try {
|
|
255
|
+
// Start disposal without allowing a slow cleanup to delay an approval result.
|
|
256
|
+
void Promise.resolve(response?.body?.cancel()).catch(() => {});
|
|
257
|
+
} catch {
|
|
258
|
+
// Response cleanup must not change the notification's delivery classification.
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export async function sendNotification({ config, title, message, actions, priority = 4, tags = ['bell'], signal, fetchImpl = fetch, timeoutMs, authToken = process.env.NOFAX_NTFY_TOKEN }) {
|
|
263
|
+
const server = normalizeServer(config.server);
|
|
264
|
+
const topic = validateTopic(config.topic);
|
|
265
|
+
const authorization = publishAuthorization(config, authToken);
|
|
96
266
|
const payload = {
|
|
97
|
-
topic
|
|
98
|
-
title: boundText(title, MAX_TITLE, 'TITLE'),
|
|
99
|
-
message: boundMessageText(message),
|
|
267
|
+
topic,
|
|
268
|
+
title: boundText(visibleNotificationTitle(title), MAX_TITLE, 'TITLE'),
|
|
269
|
+
message: boundMessageText(visibleNotificationText(message)),
|
|
100
270
|
priority,
|
|
101
271
|
tags
|
|
102
272
|
};
|
|
103
273
|
if (actions?.length) payload.actions = actions;
|
|
104
274
|
|
|
105
|
-
//
|
|
106
|
-
//
|
|
107
|
-
const ownsTimeout = signal
|
|
108
|
-
|
|
109
|
-
|
|
275
|
+
// Approval and confirmation callers manage their own deadline when they pass
|
|
276
|
+
// only a signal. An explicit timeout must still bound a direct caller's POST.
|
|
277
|
+
const ownsTimeout = signal == null || timeoutMs !== undefined;
|
|
278
|
+
const deadlineMs = timeoutMs === undefined ? DEFAULT_PUBLISH_TIMEOUT_MS : timeoutMs;
|
|
279
|
+
if (ownsTimeout) validateTimeoutMs(deadlineMs, 'NOFAX_PUBLISH_TIMEOUT_INVALID');
|
|
280
|
+
// An already-cancelled caller cannot authorize even attempting publication.
|
|
281
|
+
if (signal?.aborted) {
|
|
282
|
+
throw publishError('NOFAX_NTFY_PUBLISH_NETWORK', 'not_applied');
|
|
110
283
|
}
|
|
111
284
|
const controller = ownsTimeout ? new AbortController() : null;
|
|
112
285
|
let timeoutId;
|
|
286
|
+
let resolveDeadline;
|
|
287
|
+
let resolveCallerCancellation;
|
|
288
|
+
const callerCancellation = signal == null ? null : new Promise((resolve) => {
|
|
289
|
+
resolveCallerCancellation = resolve;
|
|
290
|
+
});
|
|
113
291
|
const timeout = controller === null ? null : new Promise((resolve) => {
|
|
292
|
+
resolveDeadline = resolve;
|
|
114
293
|
timeoutId = setTimeout(() => {
|
|
115
294
|
resolve(PUBLISH_TIMEOUT);
|
|
116
295
|
controller.abort();
|
|
117
|
-
},
|
|
296
|
+
}, deadlineMs);
|
|
118
297
|
});
|
|
298
|
+
const forwardAbort = signal != null ? () => {
|
|
299
|
+
controller?.abort();
|
|
300
|
+
// A custom fetch can ignore abort: caller cancellation still settles promptly.
|
|
301
|
+
resolveCallerCancellation(PUBLISH_CANCELLED);
|
|
302
|
+
} : null;
|
|
119
303
|
let response;
|
|
304
|
+
let request;
|
|
305
|
+
let cancelledBeforeFetch = false;
|
|
120
306
|
try {
|
|
121
|
-
|
|
307
|
+
if (forwardAbort !== null) {
|
|
308
|
+
if (signal.aborted) forwardAbort();
|
|
309
|
+
else signal.addEventListener('abort', forwardAbort, { once: true });
|
|
310
|
+
}
|
|
311
|
+
// A signal may abort synchronously while its listener is being installed.
|
|
312
|
+
if (signal?.aborted) {
|
|
313
|
+
cancelledBeforeFetch = true;
|
|
314
|
+
throw publishError('NOFAX_NTFY_PUBLISH_NETWORK', 'not_applied');
|
|
315
|
+
}
|
|
316
|
+
request = fetchImpl(`${server}/`, {
|
|
122
317
|
method: 'POST',
|
|
123
|
-
headers: {
|
|
318
|
+
headers: {
|
|
319
|
+
'content-type': 'application/json',
|
|
320
|
+
...(authorization === null ? {} : { authorization })
|
|
321
|
+
},
|
|
124
322
|
body: JSON.stringify(payload),
|
|
323
|
+
// Do not forward notification content or response-topic actions to a redirect target.
|
|
324
|
+
redirect: 'error',
|
|
125
325
|
signal: controller === null ? signal : controller.signal
|
|
126
326
|
});
|
|
127
|
-
|
|
327
|
+
const inFlight = [request];
|
|
328
|
+
if (timeout !== null) inFlight.push(timeout);
|
|
329
|
+
if (callerCancellation !== null) inFlight.unshift(callerCancellation);
|
|
330
|
+
response = inFlight.length === 1 ? await request : await Promise.race(inFlight);
|
|
128
331
|
} catch (error) {
|
|
129
|
-
|
|
332
|
+
if (cancelledBeforeFetch) throw error;
|
|
333
|
+
// Even anonymous transport errors may echo the topic, message or callback
|
|
334
|
+
// URL. These are approval capabilities, so never forward provider prose.
|
|
335
|
+
throw publishError('NOFAX_NTFY_PUBLISH_NETWORK', 'ambiguous');
|
|
130
336
|
} finally {
|
|
131
337
|
if (timeoutId !== undefined) clearTimeout(timeoutId);
|
|
338
|
+
if (forwardAbort !== null) signal.removeEventListener('abort', forwardAbort);
|
|
132
339
|
}
|
|
133
|
-
if (response === PUBLISH_TIMEOUT
|
|
340
|
+
if (response === PUBLISH_TIMEOUT || response === PUBLISH_CANCELLED || signal?.aborted) {
|
|
341
|
+
// Some fetch implementations ignore abort and return a body after cancellation or timeout.
|
|
342
|
+
if (response === PUBLISH_TIMEOUT || response === PUBLISH_CANCELLED) {
|
|
343
|
+
void Promise.resolve(request).then(releaseResponseBody, () => {});
|
|
344
|
+
} else {
|
|
345
|
+
releaseResponseBody(response);
|
|
346
|
+
}
|
|
347
|
+
throw publishError(response === PUBLISH_TIMEOUT
|
|
348
|
+
? 'NOFAX_NTFY_PUBLISH_TIMEOUT' : 'NOFAX_NTFY_PUBLISH_NETWORK', 'ambiguous');
|
|
349
|
+
}
|
|
350
|
+
releaseResponseBody(response);
|
|
134
351
|
if (!response?.ok) {
|
|
135
352
|
const status = response?.status ?? 'NETWORK';
|
|
136
353
|
const deliveryState = NOT_APPLIED_PUBLISH_STATUSES.has(status) ? 'not_applied' : 'ambiguous';
|
|
@@ -138,22 +355,42 @@ export async function sendNotification({ config, title, message, actions, priori
|
|
|
138
355
|
}
|
|
139
356
|
}
|
|
140
357
|
|
|
141
|
-
function normalizeOptions(options) {
|
|
358
|
+
export function normalizeOptions(options) {
|
|
142
359
|
if (!Array.isArray(options) || options.length > 3) throw new Error('NOFAX_CHOICE_LIMIT');
|
|
143
360
|
const normalized = options.map((option) => {
|
|
144
361
|
if (typeof option === 'string') {
|
|
145
362
|
const value = option.trim();
|
|
146
|
-
if (!value || value.length > 80) throw new Error('NOFAX_CHOICE_INVALID');
|
|
363
|
+
if (!value || value.length > 80 || !value.isWellFormed()) throw new Error('NOFAX_CHOICE_INVALID');
|
|
147
364
|
return { value, label: boundChoiceLabel(value) };
|
|
148
365
|
}
|
|
149
366
|
if (!option || typeof option.value !== 'string' || typeof option.label !== 'string') throw new Error('NOFAX_CHOICE_INVALID');
|
|
150
367
|
const value = option.value.trim();
|
|
151
368
|
const label = option.label.trim();
|
|
152
|
-
if (!value || !label || value.length > 80)
|
|
369
|
+
if (!value || !label || value.length > 80 || !value.isWellFormed() || !label.isWellFormed()) {
|
|
370
|
+
throw new Error('NOFAX_CHOICE_INVALID');
|
|
371
|
+
}
|
|
153
372
|
return { value, label: boundChoiceLabel(label) };
|
|
154
373
|
});
|
|
155
374
|
if (new Set(normalized.map((option) => option.value)).size !== normalized.length) throw new Error('NOFAX_CHOICE_DUPLICATE');
|
|
156
|
-
|
|
375
|
+
// Phones without Unicode tag support render distinct subdivision flags as
|
|
376
|
+
// identical black flags. Compare that fallback as well as NFKC, while
|
|
377
|
+
// preserving the actual action labels and exact decision values.
|
|
378
|
+
const displayKey = (label, originalOption) => {
|
|
379
|
+
let displayLabel = label;
|
|
380
|
+
const sourceLabel = typeof originalOption === 'string' ? originalOption.trim() : originalOption.label.trim();
|
|
381
|
+
// Only fold generated tag captions to a black flag, not literal visible
|
|
382
|
+
// captions supplied by the caller, which remain distinct phone choices.
|
|
383
|
+
for (const { segment } of actionGraphemeSegmenter.segment(sourceLabel)) {
|
|
384
|
+
const code = emojiTagCode(segment);
|
|
385
|
+
if (code !== null && !RGI_EMOJI_TAG_FLAGS.has(code)) {
|
|
386
|
+
displayLabel = displayLabel.replace(`\u{1f3f4}[tag:${code}]`, '\u{1f3f4}');
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
return displayLabel.normalize('NFKC').replace(/[\u{e0020}-\u{e007f}]/gu, '');
|
|
390
|
+
};
|
|
391
|
+
if (new Set(normalized.map((option, index) => displayKey(option.label, options[index]))).size !== normalized.length) {
|
|
392
|
+
throw new Error('NOFAX_CHOICE_DUPLICATE');
|
|
393
|
+
}
|
|
157
394
|
return normalized;
|
|
158
395
|
}
|
|
159
396
|
|
|
@@ -166,11 +403,16 @@ export async function createRemoteRequest({
|
|
|
166
403
|
shortcutName = config.refineShortcutName ?? DEFAULT_REFINE_SHORTCUT,
|
|
167
404
|
beforePublish = async () => {},
|
|
168
405
|
publishTimeoutMs = DEFAULT_PUBLISH_TIMEOUT_MS,
|
|
169
|
-
fetchImpl = fetch
|
|
406
|
+
fetchImpl = fetch,
|
|
407
|
+
authToken = process.env.NOFAX_NTFY_TOKEN
|
|
170
408
|
}) {
|
|
409
|
+
const server = normalizeServer(config.server);
|
|
410
|
+
validateTopic(config.topic);
|
|
171
411
|
const normalized = normalizeOptions(options);
|
|
172
412
|
if (includeRefine && normalized.some((option) => option.value === 'refine')) throw new Error('NOFAX_CHOICE_DUPLICATE');
|
|
173
|
-
if (includeRefine && normalized.some((option) => option.label === 'Refine'))
|
|
413
|
+
if (includeRefine && normalized.some((option) => option.label.normalize('NFKC') === 'Refine')) {
|
|
414
|
+
throw new Error('NOFAX_CHOICE_DUPLICATE');
|
|
415
|
+
}
|
|
174
416
|
const totalActions = normalized.length + (includeRefine ? 1 : 0);
|
|
175
417
|
if (totalActions < 1 || totalActions > 3) throw new Error('NOFAX_CHOICE_LIMIT');
|
|
176
418
|
|
|
@@ -181,26 +423,31 @@ export async function createRemoteRequest({
|
|
|
181
423
|
|
|
182
424
|
if (includeRefine && normalized.length === 2) {
|
|
183
425
|
const [first, second] = normalized;
|
|
184
|
-
actions.push(httpAction({ label: first.label, server
|
|
426
|
+
actions.push(httpAction({ label: first.label, server, responseTopic, requestId, decision: first.value }));
|
|
185
427
|
allowed.push(first.value);
|
|
186
|
-
actions.push(refineAction({ shortcutName, server
|
|
428
|
+
actions.push(refineAction({ shortcutName, server, responseTopic, requestId }));
|
|
187
429
|
allowed.push('refine');
|
|
188
|
-
actions.push(httpAction({ label: second.label, server
|
|
430
|
+
actions.push(httpAction({ label: second.label, server, responseTopic, requestId, decision: second.value }));
|
|
189
431
|
allowed.push(second.value);
|
|
190
432
|
} else {
|
|
191
433
|
for (const option of normalized) {
|
|
192
|
-
actions.push(httpAction({ label: option.label, server
|
|
434
|
+
actions.push(httpAction({ label: option.label, server, responseTopic, requestId, decision: option.value }));
|
|
193
435
|
allowed.push(option.value);
|
|
194
436
|
}
|
|
195
437
|
if (includeRefine) {
|
|
196
|
-
actions.push(refineAction({ shortcutName, server
|
|
438
|
+
actions.push(refineAction({ shortcutName, server, responseTopic, requestId }));
|
|
197
439
|
allowed.push('refine');
|
|
198
440
|
}
|
|
199
441
|
}
|
|
200
442
|
|
|
201
443
|
const remote = { requestId, responseTopic, allowed };
|
|
444
|
+
// Validate synchronously before the persistence callback can record a pending request.
|
|
445
|
+
boundText(title, MAX_TITLE, 'TITLE');
|
|
446
|
+
boundMessageText(message);
|
|
447
|
+
validateTimeoutMs(publishTimeoutMs, 'NOFAX_PUBLISH_TIMEOUT_INVALID');
|
|
448
|
+
// Reject invalid/cleartext credential use before persisting a pending approval.
|
|
449
|
+
publishAuthorization(config, authToken);
|
|
202
450
|
await beforePublish(remote);
|
|
203
|
-
if (!Number.isFinite(publishTimeoutMs) || publishTimeoutMs <= 0) throw new Error('NOFAX_PUBLISH_TIMEOUT_INVALID');
|
|
204
451
|
const controller = new AbortController();
|
|
205
452
|
let timeoutId;
|
|
206
453
|
const timeout = new Promise((resolve) => {
|
|
@@ -211,7 +458,7 @@ export async function createRemoteRequest({
|
|
|
211
458
|
});
|
|
212
459
|
try {
|
|
213
460
|
const delivered = await Promise.race([
|
|
214
|
-
sendNotification({ config, title, message, actions, signal: controller.signal, fetchImpl }),
|
|
461
|
+
sendNotification({ config, title, message, actions, signal: controller.signal, fetchImpl, authToken }),
|
|
215
462
|
timeout
|
|
216
463
|
]);
|
|
217
464
|
// A timed-out POST may have reached ntfy. Never discard persisted pending state.
|
|
@@ -238,7 +485,56 @@ function parseNtfyPoll(text, requestId, allowed, kind) {
|
|
|
238
485
|
return null;
|
|
239
486
|
}
|
|
240
487
|
|
|
488
|
+
async function readPollText(response, signal) {
|
|
489
|
+
// Response.text() hides its reader, making cancellation impossible if a
|
|
490
|
+
// transport ignores abort while the response body remains open.
|
|
491
|
+
// A streamless response can only be size-checked after text() has completed.
|
|
492
|
+
if (typeof response.body?.getReader !== 'function') {
|
|
493
|
+
const text = await response.text();
|
|
494
|
+
if (Buffer.byteLength(text, 'utf8') > MAX_NTFY_POLL_RESPONSE_BYTES) {
|
|
495
|
+
throw new Error('NOFAX_NTFY_POLL_BODY_TOO_LARGE');
|
|
496
|
+
}
|
|
497
|
+
return text;
|
|
498
|
+
}
|
|
499
|
+
const reader = response.body.getReader();
|
|
500
|
+
const cancel = () => {
|
|
501
|
+
try {
|
|
502
|
+
void Promise.resolve(reader.cancel()).catch(() => {});
|
|
503
|
+
} catch {
|
|
504
|
+
// Timeout cleanup must not turn an unanswered request into a decision.
|
|
505
|
+
}
|
|
506
|
+
};
|
|
507
|
+
signal?.addEventListener('abort', cancel, { once: true });
|
|
508
|
+
if (signal?.aborted) cancel();
|
|
509
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
510
|
+
let text = '';
|
|
511
|
+
let totalBytes = 0;
|
|
512
|
+
try {
|
|
513
|
+
while (true) {
|
|
514
|
+
const { done, value } = await reader.read();
|
|
515
|
+
if (done) return text + decoder.decode();
|
|
516
|
+
// Bound raw transport bytes before decoding or parsing untrusted NDJSON.
|
|
517
|
+
if (!ArrayBuffer.isView(value) || value.byteLength > MAX_NTFY_POLL_RESPONSE_BYTES - totalBytes) {
|
|
518
|
+
cancel();
|
|
519
|
+
throw new Error('NOFAX_NTFY_POLL_BODY_TOO_LARGE');
|
|
520
|
+
}
|
|
521
|
+
totalBytes += value.byteLength;
|
|
522
|
+
text += decoder.decode(value, { stream: true });
|
|
523
|
+
}
|
|
524
|
+
} finally {
|
|
525
|
+
signal?.removeEventListener('abort', cancel);
|
|
526
|
+
reader.releaseLock();
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
241
530
|
export async function pollRemoteResponse({ config, responseTopic, requestId, allowed, kind, timeoutMs, fetchImpl = fetch }) {
|
|
531
|
+
const server = normalizeServer(config.server);
|
|
532
|
+
// MCP callers pass fractional remaining milliseconds; reject only invalid
|
|
533
|
+
// or overflowing delays that Node timers would silently clamp.
|
|
534
|
+
if (timeoutMs !== undefined &&
|
|
535
|
+
(!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMER_TIMEOUT_MS)) {
|
|
536
|
+
throw new Error('NOFAX_NTFY_POLL_TIMEOUT_INVALID');
|
|
537
|
+
}
|
|
242
538
|
let timeoutId;
|
|
243
539
|
const controller = timeoutMs === undefined ? null : new AbortController();
|
|
244
540
|
const timeout = controller === null
|
|
@@ -251,29 +547,42 @@ export async function pollRemoteResponse({ config, responseTopic, requestId, all
|
|
|
251
547
|
});
|
|
252
548
|
try {
|
|
253
549
|
let response;
|
|
550
|
+
let request;
|
|
254
551
|
try {
|
|
255
|
-
|
|
552
|
+
request = fetchImpl(`${server}/${responseTopic}/json?poll=1&since=all`, {
|
|
256
553
|
method: 'GET',
|
|
257
554
|
headers: { accept: 'application/x-ndjson' },
|
|
555
|
+
// The response topic itself is a capability; never disclose it via redirects.
|
|
556
|
+
redirect: 'error',
|
|
258
557
|
...(controller === null ? {} : { signal: controller.signal })
|
|
259
558
|
});
|
|
260
559
|
response = timeout === null ? await request : await Promise.race([request, timeout]);
|
|
261
|
-
} catch
|
|
560
|
+
} catch {
|
|
262
561
|
if (controller?.signal.aborted) return null;
|
|
263
|
-
|
|
562
|
+
// Transport errors can include the request URL, including the private
|
|
563
|
+
// response topic that grants access to a human decision. Do not expose it
|
|
564
|
+
// through MCP error text, CLI diagnostics, or logs.
|
|
565
|
+
throw new Error('NOFAX_NTFY_POLL_NETWORK');
|
|
566
|
+
}
|
|
567
|
+
if (response === POLL_TIMEOUT) {
|
|
568
|
+
// A transport ignoring abort may still return a readable body after the deadline.
|
|
569
|
+
void Promise.resolve(request).then(releaseResponseBody, () => {});
|
|
570
|
+
return null;
|
|
264
571
|
}
|
|
265
|
-
if (response === POLL_TIMEOUT) return null;
|
|
266
572
|
await ensureOk(response, 'NOFAX_NTFY_POLL');
|
|
267
573
|
|
|
268
574
|
let text;
|
|
269
575
|
try {
|
|
270
|
-
const body = response
|
|
576
|
+
const body = readPollText(response, controller?.signal);
|
|
271
577
|
text = timeout === null ? await body : await Promise.race([body, timeout]);
|
|
272
|
-
} catch
|
|
578
|
+
} catch {
|
|
273
579
|
if (controller?.signal.aborted) return null;
|
|
274
|
-
|
|
580
|
+
// A stream-reader failure may also include the private polling URL.
|
|
581
|
+
throw new Error('NOFAX_NTFY_POLL_NETWORK');
|
|
275
582
|
}
|
|
276
|
-
|
|
583
|
+
// Cancellation can finish a partial read just before the timeout promise.
|
|
584
|
+
// Never parse that partial body as a human decision after the deadline.
|
|
585
|
+
if (text === POLL_TIMEOUT || controller?.signal.aborted) return null;
|
|
277
586
|
return parseNtfyPoll(text, requestId, allowed, kind);
|
|
278
587
|
} finally {
|
|
279
588
|
if (timeoutId !== undefined) clearTimeout(timeoutId);
|
|
@@ -281,6 +590,8 @@ export async function pollRemoteResponse({ config, responseTopic, requestId, all
|
|
|
281
590
|
}
|
|
282
591
|
|
|
283
592
|
export async function sendResponseConfirmation({ config, response, kind, title = 'Nofax', timeoutMs = 5000, fetchImpl = fetch }) {
|
|
593
|
+
// Reject timer overflow and zero/fractional delays before any phone side effect.
|
|
594
|
+
validateTimeoutMs(timeoutMs, 'NOFAX_CONFIRMATION_TIMEOUT_INVALID');
|
|
284
595
|
let confirmationTitle = 'Response received';
|
|
285
596
|
let tag = 'white_check_mark';
|
|
286
597
|
if (kind === 'choice') confirmationTitle = 'Choice received';
|
|
@@ -328,11 +639,19 @@ export async function waitRemoteResponse({
|
|
|
328
639
|
pollIntervalMs = 1000,
|
|
329
640
|
fetchImpl = fetch,
|
|
330
641
|
nowImpl = Date.now,
|
|
642
|
+
elapsedNowImpl,
|
|
331
643
|
sleepImpl = sleep
|
|
332
644
|
}) {
|
|
333
|
-
|
|
645
|
+
// This is also exported for direct callers, which bypass requestDecision's
|
|
646
|
+
// deadline validation. Reject zero/overflow intervals before any polling.
|
|
647
|
+
validateTimeoutMs(timeoutMs, 'NOFAX_DECISION_TIMEOUT_INVALID');
|
|
648
|
+
validateTimeoutMs(pollIntervalMs, 'NOFAX_POLL_INTERVAL_INVALID');
|
|
649
|
+
// Wall-clock corrections must not extend an unattended human approval wait.
|
|
650
|
+
// Preserve injected virtual clocks used by existing integration callers.
|
|
651
|
+
const elapsedClock = elapsedNowImpl ?? (nowImpl === Date.now ? () => performance.now() : nowImpl);
|
|
652
|
+
const deadline = elapsedClock() + timeoutMs;
|
|
334
653
|
while (true) {
|
|
335
|
-
const remainingBeforePoll = deadline -
|
|
654
|
+
const remainingBeforePoll = deadline - elapsedClock();
|
|
336
655
|
if (remainingBeforePoll <= 0) break;
|
|
337
656
|
const response = await pollRemoteResponse({
|
|
338
657
|
config,
|
|
@@ -343,8 +662,9 @@ export async function waitRemoteResponse({
|
|
|
343
662
|
timeoutMs: remainingBeforePoll,
|
|
344
663
|
fetchImpl
|
|
345
664
|
});
|
|
346
|
-
|
|
347
|
-
|
|
665
|
+
// A poll arriving at or after the deadline cannot grant human approval.
|
|
666
|
+
if (response !== null && elapsedClock() < deadline) return response;
|
|
667
|
+
const remaining = deadline - elapsedClock();
|
|
348
668
|
if (remaining <= 0) break;
|
|
349
669
|
await sleepImpl(Math.min(pollIntervalMs, remaining));
|
|
350
670
|
}
|
|
@@ -365,6 +685,10 @@ async function requestDecision({
|
|
|
365
685
|
nowImpl = Date.now,
|
|
366
686
|
sleepImpl = sleep
|
|
367
687
|
}) {
|
|
688
|
+
// Validate the decision window before createRemoteRequest persists or sends.
|
|
689
|
+
validateTimeoutMs(timeoutMs, 'NOFAX_DECISION_TIMEOUT_INVALID');
|
|
690
|
+
// Reject invalid polling before persisting or publishing a remote request.
|
|
691
|
+
validateTimeoutMs(pollIntervalMs, 'NOFAX_POLL_INTERVAL_INVALID');
|
|
368
692
|
const remote = await createRemoteRequest({ config, title, message, options, includeRefine, publishTimeoutMs, fetchImpl });
|
|
369
693
|
const response = await waitRemoteResponse({
|
|
370
694
|
config,
|
|
@@ -379,8 +703,18 @@ async function requestDecision({
|
|
|
379
703
|
if (response === null) {
|
|
380
704
|
return { decision: 'timeout', requestId: remote.requestId, responseTopic: remote.responseTopic };
|
|
381
705
|
}
|
|
382
|
-
|
|
383
|
-
|
|
706
|
+
let confirmationDelivered = false;
|
|
707
|
+
try {
|
|
708
|
+
confirmationDelivered = await sendResponseConfirmation({ config, response, kind, title, fetchImpl });
|
|
709
|
+
} catch {
|
|
710
|
+
// A best-effort receipt must never erase the actual human decision.
|
|
711
|
+
}
|
|
712
|
+
return {
|
|
713
|
+
...response,
|
|
714
|
+
requestId: remote.requestId,
|
|
715
|
+
responseTopic: remote.responseTopic,
|
|
716
|
+
...(confirmationDelivered ? {} : { confirmationStatus: 'failed' })
|
|
717
|
+
};
|
|
384
718
|
}
|
|
385
719
|
|
|
386
720
|
export async function requestApproval(options) {
|