nofax 0.2.50 → 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/src/ntfy.mjs CHANGED
@@ -8,20 +8,38 @@ const MAX_NTFY_POLL_RESPONSE_BYTES = 1_048_576;
8
8
  const DEFAULT_REFINE_SHORTCUT = 'Nofax Refine';
9
9
  const POLL_TIMEOUT = Symbol('NOFAX_POLL_TIMEOUT');
10
10
  const PUBLISH_TIMEOUT = Symbol('NOFAX_PUBLISH_TIMEOUT');
11
+ const PUBLISH_CANCELLED = Symbol('NOFAX_PUBLISH_CANCELLED');
11
12
  const DEFAULT_PUBLISH_TIMEOUT_MS = 15_000;
12
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']);
13
16
  // ntfy rejects invalid, unauthorized, oversized, and rate-limited requests
14
17
  // before accepting the message. These must not leave orphan approvals.
15
18
  const NOT_APPLIED_PUBLISH_STATUSES = new Set([400, 401, 403, 413, 429]);
16
19
 
17
20
  function visibleNotificationText(value) {
18
21
  // Never let untrusted notification text visually alter its own display.
19
- // Keep ordinary line breaks and genuine emoji joiners, but expose invisible
20
- // separators embedded in words that can disguise decision labels.
21
- return typeof value === 'string'
22
- ? [...value].map((character, index, characters) =>
23
- visibleNotificationCharacter(character, characters, index)).join('')
24
- : value;
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('');
25
43
  }
26
44
 
27
45
  function visibleNotificationTitle(value) {
@@ -31,6 +49,16 @@ function visibleNotificationTitle(value) {
31
49
  }
32
50
 
33
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
+ }
34
62
  // Preserve genuine emoji ZWJ sequences, including skin-tone modifiers, but
35
63
  // expose joiners hidden inside decision words rather than disguising choices.
36
64
  if (character === '\u200c' || character === '\u200d') {
@@ -44,34 +72,76 @@ function visibleNotificationCharacter(character, characters, index) {
44
72
  return `\\u${character.codePointAt(0).toString(16).padStart(4, '0')}`;
45
73
  }
46
74
  // Blank Hangul/Braille fillers can disguise approval words.
47
- return character.replace(/[\x00-\x09\x0b-\x1f\x7f-\x9f\u00ad\u034f\u061c\u115f-\u1160\u180e\u200b\u200e-\u200f\u2028-\u202e\u2060-\u2064\u2066-\u2069\u2800\u3164\uffa0\ufeff]/gu,
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,
48
76
  (control) => `\\u${control.codePointAt(0).toString(16).padStart(4, '0')}`);
49
77
  }
50
78
 
51
79
  function visibleActionCharacter(character, characters, index) {
52
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
+ }
53
91
  return visibleNotificationCharacter(character, characters, index);
54
92
  }
55
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
+ }
99
+
56
100
  function safeSliceEnd(text, end) {
57
- const previous = text.charCodeAt(end - 1);
58
- return previous >= 0xD800 && previous <= 0xDBFF ? end - 1 : end;
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;
59
106
  }
60
107
 
61
108
  function boundChoiceLabel(value) {
62
- let label = '';
63
- let visibleContent = false;
109
+ const segments = [];
110
+ let renderedLength = 0;
111
+ let visibleContent = 0;
64
112
  const characters = [...value];
65
- for (const [index, character] of characters.entries()) {
113
+ let characterIndex = 0;
114
+ for (const { segment } of actionGraphemeSegmenter.segment(value)) {
66
115
  // Action labels are single-line and must not hide/reorder the human's choices.
67
- // Keep each visible escape or Unicode code point intact at the 32-unit limit.
68
- const visible = visibleActionCharacter(character, characters, index);
69
- if (label.length + visible.length > 32) break;
70
- label += visible;
71
- if (/[\p{L}\p{N}\p{P}\p{S}]/u.test(character)) visibleContent = true;
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;
72
142
  }
73
143
  if (!visibleContent) throw new Error('NOFAX_CHOICE_INVALID');
74
- return label;
144
+ return segments.map((segment) => segment.text).join('');
75
145
  }
76
146
 
77
147
  function boundText(value, max, name) {
@@ -92,11 +162,11 @@ function boundMessageText(value) {
92
162
  const maxContentBytes = MAX_NTFY_MESSAGE_BYTES - Buffer.byteLength(marker, 'utf8');
93
163
  let bytes = 0;
94
164
  let end = 0;
95
- for (const character of text) {
96
- const characterBytes = Buffer.byteLength(character, 'utf8');
97
- if (bytes + characterBytes > maxContentBytes) break;
98
- bytes += characterBytes;
99
- end += character.length;
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;
100
170
  }
101
171
  return `${text.slice(0, end)}${marker}`;
102
172
  }
@@ -207,22 +277,42 @@ export async function sendNotification({ config, title, message, actions, priori
207
277
  const ownsTimeout = signal == null || timeoutMs !== undefined;
208
278
  const deadlineMs = timeoutMs === undefined ? DEFAULT_PUBLISH_TIMEOUT_MS : timeoutMs;
209
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');
283
+ }
210
284
  const controller = ownsTimeout ? new AbortController() : null;
211
- const forwardAbort = controller !== null && signal != null ? () => controller.abort() : null;
212
285
  let timeoutId;
286
+ let resolveDeadline;
287
+ let resolveCallerCancellation;
288
+ const callerCancellation = signal == null ? null : new Promise((resolve) => {
289
+ resolveCallerCancellation = resolve;
290
+ });
213
291
  const timeout = controller === null ? null : new Promise((resolve) => {
292
+ resolveDeadline = resolve;
214
293
  timeoutId = setTimeout(() => {
215
294
  resolve(PUBLISH_TIMEOUT);
216
295
  controller.abort();
217
296
  }, deadlineMs);
218
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;
219
303
  let response;
220
304
  let request;
305
+ let cancelledBeforeFetch = false;
221
306
  try {
222
307
  if (forwardAbort !== null) {
223
308
  if (signal.aborted) forwardAbort();
224
309
  else signal.addEventListener('abort', forwardAbort, { once: true });
225
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
+ }
226
316
  request = fetchImpl(`${server}/`, {
227
317
  method: 'POST',
228
318
  headers: {
@@ -234,8 +324,12 @@ export async function sendNotification({ config, title, message, actions, priori
234
324
  redirect: 'error',
235
325
  signal: controller === null ? signal : controller.signal
236
326
  });
237
- response = timeout === null ? await request : await Promise.race([request, timeout]);
238
- } catch {
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);
331
+ } catch (error) {
332
+ if (cancelledBeforeFetch) throw error;
239
333
  // Even anonymous transport errors may echo the topic, message or callback
240
334
  // URL. These are approval capabilities, so never forward provider prose.
241
335
  throw publishError('NOFAX_NTFY_PUBLISH_NETWORK', 'ambiguous');
@@ -243,10 +337,15 @@ export async function sendNotification({ config, title, message, actions, priori
243
337
  if (timeoutId !== undefined) clearTimeout(timeoutId);
244
338
  if (forwardAbort !== null) signal.removeEventListener('abort', forwardAbort);
245
339
  }
246
- if (response === PUBLISH_TIMEOUT) {
247
- // Some fetch implementations ignore abort and return a body after the deadline.
248
- void Promise.resolve(request).then(releaseResponseBody, () => {});
249
- throw publishError('NOFAX_NTFY_PUBLISH_TIMEOUT', 'ambiguous');
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');
250
349
  }
251
350
  releaseResponseBody(response);
252
351
  if (!response?.ok) {
@@ -256,7 +355,7 @@ export async function sendNotification({ config, title, message, actions, priori
256
355
  }
257
356
  }
258
357
 
259
- function normalizeOptions(options) {
358
+ export function normalizeOptions(options) {
260
359
  if (!Array.isArray(options) || options.length > 3) throw new Error('NOFAX_CHOICE_LIMIT');
261
360
  const normalized = options.map((option) => {
262
361
  if (typeof option === 'string') {
@@ -273,7 +372,25 @@ function normalizeOptions(options) {
273
372
  return { value, label: boundChoiceLabel(label) };
274
373
  });
275
374
  if (new Set(normalized.map((option) => option.value)).size !== normalized.length) throw new Error('NOFAX_CHOICE_DUPLICATE');
276
- if (new Set(normalized.map((option) => option.label)).size !== normalized.length) throw new Error('NOFAX_CHOICE_DUPLICATE');
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
+ }
277
394
  return normalized;
278
395
  }
279
396
 
@@ -293,7 +410,9 @@ export async function createRemoteRequest({
293
410
  validateTopic(config.topic);
294
411
  const normalized = normalizeOptions(options);
295
412
  if (includeRefine && normalized.some((option) => option.value === 'refine')) throw new Error('NOFAX_CHOICE_DUPLICATE');
296
- if (includeRefine && normalized.some((option) => option.label === 'Refine')) throw new Error('NOFAX_CHOICE_DUPLICATE');
413
+ if (includeRefine && normalized.some((option) => option.label.normalize('NFKC') === 'Refine')) {
414
+ throw new Error('NOFAX_CHOICE_DUPLICATE');
415
+ }
297
416
  const totalActions = normalized.length + (includeRefine ? 1 : 0);
298
417
  if (totalActions < 1 || totalActions > 3) throw new Error('NOFAX_CHOICE_LIMIT');
299
418