nofax 0.2.47 → 0.2.50

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
@@ -1,14 +1,57 @@
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');
9
11
  const DEFAULT_PUBLISH_TIMEOUT_MS = 15_000;
10
- // ntfy rejects validation and rate-limit responses before accepting the publish.
11
- const NOT_APPLIED_PUBLISH_STATUSES = new Set([400, 429]);
12
+ const MAX_TIMER_TIMEOUT_MS = 2_147_483_647;
13
+ // ntfy rejects invalid, unauthorized, oversized, and rate-limited requests
14
+ // before accepting the message. These must not leave orphan approvals.
15
+ const NOT_APPLIED_PUBLISH_STATUSES = new Set([400, 401, 403, 413, 429]);
16
+
17
+ function visibleNotificationText(value) {
18
+ // 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;
25
+ }
26
+
27
+ function visibleNotificationTitle(value) {
28
+ const visible = visibleNotificationText(value);
29
+ // Titles are single-line; a raw newline could impersonate notification body text.
30
+ return typeof visible === 'string' ? visible.replace(/\n/g, '\\u000a') : visible;
31
+ }
32
+
33
+ function visibleNotificationCharacter(character, characters, index) {
34
+ // Preserve genuine emoji ZWJ sequences, including skin-tone modifiers, but
35
+ // expose joiners hidden inside decision words rather than disguising choices.
36
+ if (character === '\u200c' || character === '\u200d') {
37
+ let before = index - 1;
38
+ while (before >= 0 && /[\ufe0e\ufe0f\p{Emoji_Modifier}]/u.test(characters[before])) before--;
39
+ if (character === '\u200d' &&
40
+ /\p{Extended_Pictographic}/u.test(characters[before] ?? '') &&
41
+ /\p{Extended_Pictographic}/u.test(characters[index + 1] ?? '')) {
42
+ return character;
43
+ }
44
+ return `\\u${character.codePointAt(0).toString(16).padStart(4, '0')}`;
45
+ }
46
+ // 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,
48
+ (control) => `\\u${control.codePointAt(0).toString(16).padStart(4, '0')}`);
49
+ }
50
+
51
+ function visibleActionCharacter(character, characters, index) {
52
+ if (character === '\n') return '\\u000a';
53
+ return visibleNotificationCharacter(character, characters, index);
54
+ }
12
55
 
13
56
  function safeSliceEnd(text, end) {
14
57
  const previous = text.charCodeAt(end - 1);
@@ -16,12 +59,26 @@ function safeSliceEnd(text, end) {
16
59
  }
17
60
 
18
61
  function boundChoiceLabel(value) {
19
- return value.slice(0, safeSliceEnd(value, 32));
62
+ let label = '';
63
+ let visibleContent = false;
64
+ const characters = [...value];
65
+ for (const [index, character] of characters.entries()) {
66
+ // 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;
72
+ }
73
+ if (!visibleContent) throw new Error('NOFAX_CHOICE_INVALID');
74
+ return label;
20
75
  }
21
76
 
22
77
  function boundText(value, max, name) {
23
78
  if (typeof value !== 'string' || value.trim().length === 0) throw new Error(`NOFAX_${name}_REQUIRED`);
24
79
  const text = value.trim();
80
+ // JSON serialization substitutes lone surrogates, changing what the human sees.
81
+ if (!text.isWellFormed()) throw new Error(`NOFAX_${name}_INVALID_UTF8`);
25
82
  if (text.length <= max) return text;
26
83
  const end = safeSliceEnd(text, max - 14);
27
84
  return `${text.slice(0, end)}…[truncated]`;
@@ -82,7 +139,10 @@ function refineAction({ shortcutName, server, responseTopic, requestId }) {
82
139
  }
83
140
 
84
141
  async function ensureOk(response, code) {
85
- if (!response?.ok) throw new Error(`${code}_${response?.status ?? 'NETWORK'}`);
142
+ if (!response?.ok) {
143
+ releaseResponseBody(response);
144
+ throw new Error(`${code}_${response?.status ?? 'NETWORK'}`);
145
+ }
86
146
  return response;
87
147
  }
88
148
 
@@ -92,45 +152,103 @@ function publishError(message, deliveryState) {
92
152
  return error;
93
153
  }
94
154
 
95
- export async function sendNotification({ config, title, message, actions, priority = 4, tags = ['bell'], signal, fetchImpl = fetch, timeoutMs = DEFAULT_PUBLISH_TIMEOUT_MS }) {
155
+ function validateTimeoutMs(value, errorCode) {
156
+ // Node timers clamp nonpositive, fractional and overflowing delays; do not
157
+ // publish an approval that could then immediately time out.
158
+ if (!Number.isSafeInteger(value) || value < 1 || value > MAX_TIMER_TIMEOUT_MS) {
159
+ throw new Error(errorCode);
160
+ }
161
+ }
162
+
163
+ // The optional ntfy publishing token is process-local, not stored in config.json.
164
+ // Never attach it to approval action URLs or response-topic polling requests.
165
+ function publishAuthorization(config, token) {
166
+ if (token === undefined) return null;
167
+ if (typeof token !== 'string' || token.length < 8 || token.length > 1024 ||
168
+ !/^[A-Za-z0-9_./+~=-]+$/.test(token)) {
169
+ throw new Error('NOFAX_NTFY_AUTH_TOKEN_INVALID');
170
+ }
171
+ let server;
172
+ try {
173
+ server = new URL(config.server);
174
+ } catch {
175
+ throw new Error('NOFAX_NTFY_AUTH_SERVER_INVALID');
176
+ }
177
+ if (server.protocol !== 'https:' || server.username || server.password) {
178
+ throw new Error('NOFAX_NTFY_AUTH_REQUIRES_HTTPS');
179
+ }
180
+ return `Bearer ${token}`;
181
+ }
182
+
183
+ function releaseResponseBody(response) {
184
+ try {
185
+ // Start disposal without allowing a slow cleanup to delay an approval result.
186
+ void Promise.resolve(response?.body?.cancel()).catch(() => {});
187
+ } catch {
188
+ // Response cleanup must not change the notification's delivery classification.
189
+ }
190
+ }
191
+
192
+ export async function sendNotification({ config, title, message, actions, priority = 4, tags = ['bell'], signal, fetchImpl = fetch, timeoutMs, authToken = process.env.NOFAX_NTFY_TOKEN }) {
193
+ const server = normalizeServer(config.server);
194
+ const topic = validateTopic(config.topic);
195
+ const authorization = publishAuthorization(config, authToken);
96
196
  const payload = {
97
- topic: config.topic,
98
- title: boundText(title, MAX_TITLE, 'TITLE'),
99
- message: boundMessageText(message),
197
+ topic,
198
+ title: boundText(visibleNotificationTitle(title), MAX_TITLE, 'TITLE'),
199
+ message: boundMessageText(visibleNotificationText(message)),
100
200
  priority,
101
201
  tags
102
202
  };
103
203
  if (actions?.length) payload.actions = actions;
104
204
 
105
- // Caller-managed approval publication and confirmation already have a deadline.
106
- // A direct notification needs its own bounded transport when no signal is supplied.
107
- const ownsTimeout = signal === undefined;
108
- if (ownsTimeout && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) {
109
- throw new Error('NOFAX_PUBLISH_TIMEOUT_INVALID');
110
- }
205
+ // Approval and confirmation callers manage their own deadline when they pass
206
+ // only a signal. An explicit timeout must still bound a direct caller's POST.
207
+ const ownsTimeout = signal == null || timeoutMs !== undefined;
208
+ const deadlineMs = timeoutMs === undefined ? DEFAULT_PUBLISH_TIMEOUT_MS : timeoutMs;
209
+ if (ownsTimeout) validateTimeoutMs(deadlineMs, 'NOFAX_PUBLISH_TIMEOUT_INVALID');
111
210
  const controller = ownsTimeout ? new AbortController() : null;
211
+ const forwardAbort = controller !== null && signal != null ? () => controller.abort() : null;
112
212
  let timeoutId;
113
213
  const timeout = controller === null ? null : new Promise((resolve) => {
114
214
  timeoutId = setTimeout(() => {
115
215
  resolve(PUBLISH_TIMEOUT);
116
216
  controller.abort();
117
- }, timeoutMs);
217
+ }, deadlineMs);
118
218
  });
119
219
  let response;
220
+ let request;
120
221
  try {
121
- const request = fetchImpl(`${config.server}/`, {
222
+ if (forwardAbort !== null) {
223
+ if (signal.aborted) forwardAbort();
224
+ else signal.addEventListener('abort', forwardAbort, { once: true });
225
+ }
226
+ request = fetchImpl(`${server}/`, {
122
227
  method: 'POST',
123
- headers: { 'content-type': 'application/json' },
228
+ headers: {
229
+ 'content-type': 'application/json',
230
+ ...(authorization === null ? {} : { authorization })
231
+ },
124
232
  body: JSON.stringify(payload),
233
+ // Do not forward notification content or response-topic actions to a redirect target.
234
+ redirect: 'error',
125
235
  signal: controller === null ? signal : controller.signal
126
236
  });
127
237
  response = timeout === null ? await request : await Promise.race([request, timeout]);
128
- } catch (error) {
129
- throw publishError(`NOFAX_NTFY_PUBLISH_NETWORK: ${error?.message ?? String(error)}`, 'ambiguous');
238
+ } catch {
239
+ // Even anonymous transport errors may echo the topic, message or callback
240
+ // URL. These are approval capabilities, so never forward provider prose.
241
+ throw publishError('NOFAX_NTFY_PUBLISH_NETWORK', 'ambiguous');
130
242
  } finally {
131
243
  if (timeoutId !== undefined) clearTimeout(timeoutId);
244
+ if (forwardAbort !== null) signal.removeEventListener('abort', forwardAbort);
132
245
  }
133
- if (response === PUBLISH_TIMEOUT) throw publishError('NOFAX_NTFY_PUBLISH_TIMEOUT', 'ambiguous');
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');
250
+ }
251
+ releaseResponseBody(response);
134
252
  if (!response?.ok) {
135
253
  const status = response?.status ?? 'NETWORK';
136
254
  const deliveryState = NOT_APPLIED_PUBLISH_STATUSES.has(status) ? 'not_applied' : 'ambiguous';
@@ -143,13 +261,15 @@ function normalizeOptions(options) {
143
261
  const normalized = options.map((option) => {
144
262
  if (typeof option === 'string') {
145
263
  const value = option.trim();
146
- if (!value || value.length > 80) throw new Error('NOFAX_CHOICE_INVALID');
264
+ if (!value || value.length > 80 || !value.isWellFormed()) throw new Error('NOFAX_CHOICE_INVALID');
147
265
  return { value, label: boundChoiceLabel(value) };
148
266
  }
149
267
  if (!option || typeof option.value !== 'string' || typeof option.label !== 'string') throw new Error('NOFAX_CHOICE_INVALID');
150
268
  const value = option.value.trim();
151
269
  const label = option.label.trim();
152
- if (!value || !label || value.length > 80) throw new Error('NOFAX_CHOICE_INVALID');
270
+ if (!value || !label || value.length > 80 || !value.isWellFormed() || !label.isWellFormed()) {
271
+ throw new Error('NOFAX_CHOICE_INVALID');
272
+ }
153
273
  return { value, label: boundChoiceLabel(label) };
154
274
  });
155
275
  if (new Set(normalized.map((option) => option.value)).size !== normalized.length) throw new Error('NOFAX_CHOICE_DUPLICATE');
@@ -166,8 +286,11 @@ export async function createRemoteRequest({
166
286
  shortcutName = config.refineShortcutName ?? DEFAULT_REFINE_SHORTCUT,
167
287
  beforePublish = async () => {},
168
288
  publishTimeoutMs = DEFAULT_PUBLISH_TIMEOUT_MS,
169
- fetchImpl = fetch
289
+ fetchImpl = fetch,
290
+ authToken = process.env.NOFAX_NTFY_TOKEN
170
291
  }) {
292
+ const server = normalizeServer(config.server);
293
+ validateTopic(config.topic);
171
294
  const normalized = normalizeOptions(options);
172
295
  if (includeRefine && normalized.some((option) => option.value === 'refine')) throw new Error('NOFAX_CHOICE_DUPLICATE');
173
296
  if (includeRefine && normalized.some((option) => option.label === 'Refine')) throw new Error('NOFAX_CHOICE_DUPLICATE');
@@ -181,26 +304,31 @@ export async function createRemoteRequest({
181
304
 
182
305
  if (includeRefine && normalized.length === 2) {
183
306
  const [first, second] = normalized;
184
- actions.push(httpAction({ label: first.label, server: config.server, responseTopic, requestId, decision: first.value }));
307
+ actions.push(httpAction({ label: first.label, server, responseTopic, requestId, decision: first.value }));
185
308
  allowed.push(first.value);
186
- actions.push(refineAction({ shortcutName, server: config.server, responseTopic, requestId }));
309
+ actions.push(refineAction({ shortcutName, server, responseTopic, requestId }));
187
310
  allowed.push('refine');
188
- actions.push(httpAction({ label: second.label, server: config.server, responseTopic, requestId, decision: second.value }));
311
+ actions.push(httpAction({ label: second.label, server, responseTopic, requestId, decision: second.value }));
189
312
  allowed.push(second.value);
190
313
  } else {
191
314
  for (const option of normalized) {
192
- actions.push(httpAction({ label: option.label, server: config.server, responseTopic, requestId, decision: option.value }));
315
+ actions.push(httpAction({ label: option.label, server, responseTopic, requestId, decision: option.value }));
193
316
  allowed.push(option.value);
194
317
  }
195
318
  if (includeRefine) {
196
- actions.push(refineAction({ shortcutName, server: config.server, responseTopic, requestId }));
319
+ actions.push(refineAction({ shortcutName, server, responseTopic, requestId }));
197
320
  allowed.push('refine');
198
321
  }
199
322
  }
200
323
 
201
324
  const remote = { requestId, responseTopic, allowed };
325
+ // Validate synchronously before the persistence callback can record a pending request.
326
+ boundText(title, MAX_TITLE, 'TITLE');
327
+ boundMessageText(message);
328
+ validateTimeoutMs(publishTimeoutMs, 'NOFAX_PUBLISH_TIMEOUT_INVALID');
329
+ // Reject invalid/cleartext credential use before persisting a pending approval.
330
+ publishAuthorization(config, authToken);
202
331
  await beforePublish(remote);
203
- if (!Number.isFinite(publishTimeoutMs) || publishTimeoutMs <= 0) throw new Error('NOFAX_PUBLISH_TIMEOUT_INVALID');
204
332
  const controller = new AbortController();
205
333
  let timeoutId;
206
334
  const timeout = new Promise((resolve) => {
@@ -211,7 +339,7 @@ export async function createRemoteRequest({
211
339
  });
212
340
  try {
213
341
  const delivered = await Promise.race([
214
- sendNotification({ config, title, message, actions, signal: controller.signal, fetchImpl }),
342
+ sendNotification({ config, title, message, actions, signal: controller.signal, fetchImpl, authToken }),
215
343
  timeout
216
344
  ]);
217
345
  // A timed-out POST may have reached ntfy. Never discard persisted pending state.
@@ -238,7 +366,56 @@ function parseNtfyPoll(text, requestId, allowed, kind) {
238
366
  return null;
239
367
  }
240
368
 
369
+ async function readPollText(response, signal) {
370
+ // Response.text() hides its reader, making cancellation impossible if a
371
+ // transport ignores abort while the response body remains open.
372
+ // A streamless response can only be size-checked after text() has completed.
373
+ if (typeof response.body?.getReader !== 'function') {
374
+ const text = await response.text();
375
+ if (Buffer.byteLength(text, 'utf8') > MAX_NTFY_POLL_RESPONSE_BYTES) {
376
+ throw new Error('NOFAX_NTFY_POLL_BODY_TOO_LARGE');
377
+ }
378
+ return text;
379
+ }
380
+ const reader = response.body.getReader();
381
+ const cancel = () => {
382
+ try {
383
+ void Promise.resolve(reader.cancel()).catch(() => {});
384
+ } catch {
385
+ // Timeout cleanup must not turn an unanswered request into a decision.
386
+ }
387
+ };
388
+ signal?.addEventListener('abort', cancel, { once: true });
389
+ if (signal?.aborted) cancel();
390
+ const decoder = new TextDecoder('utf-8', { fatal: true });
391
+ let text = '';
392
+ let totalBytes = 0;
393
+ try {
394
+ while (true) {
395
+ const { done, value } = await reader.read();
396
+ if (done) return text + decoder.decode();
397
+ // Bound raw transport bytes before decoding or parsing untrusted NDJSON.
398
+ if (!ArrayBuffer.isView(value) || value.byteLength > MAX_NTFY_POLL_RESPONSE_BYTES - totalBytes) {
399
+ cancel();
400
+ throw new Error('NOFAX_NTFY_POLL_BODY_TOO_LARGE');
401
+ }
402
+ totalBytes += value.byteLength;
403
+ text += decoder.decode(value, { stream: true });
404
+ }
405
+ } finally {
406
+ signal?.removeEventListener('abort', cancel);
407
+ reader.releaseLock();
408
+ }
409
+ }
410
+
241
411
  export async function pollRemoteResponse({ config, responseTopic, requestId, allowed, kind, timeoutMs, fetchImpl = fetch }) {
412
+ const server = normalizeServer(config.server);
413
+ // MCP callers pass fractional remaining milliseconds; reject only invalid
414
+ // or overflowing delays that Node timers would silently clamp.
415
+ if (timeoutMs !== undefined &&
416
+ (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMER_TIMEOUT_MS)) {
417
+ throw new Error('NOFAX_NTFY_POLL_TIMEOUT_INVALID');
418
+ }
242
419
  let timeoutId;
243
420
  const controller = timeoutMs === undefined ? null : new AbortController();
244
421
  const timeout = controller === null
@@ -251,29 +428,42 @@ export async function pollRemoteResponse({ config, responseTopic, requestId, all
251
428
  });
252
429
  try {
253
430
  let response;
431
+ let request;
254
432
  try {
255
- const request = fetchImpl(`${config.server}/${responseTopic}/json?poll=1&since=all`, {
433
+ request = fetchImpl(`${server}/${responseTopic}/json?poll=1&since=all`, {
256
434
  method: 'GET',
257
435
  headers: { accept: 'application/x-ndjson' },
436
+ // The response topic itself is a capability; never disclose it via redirects.
437
+ redirect: 'error',
258
438
  ...(controller === null ? {} : { signal: controller.signal })
259
439
  });
260
440
  response = timeout === null ? await request : await Promise.race([request, timeout]);
261
- } catch (error) {
441
+ } catch {
262
442
  if (controller?.signal.aborted) return null;
263
- throw new Error(`NOFAX_NTFY_POLL_NETWORK: ${error?.message ?? String(error)}`);
443
+ // Transport errors can include the request URL, including the private
444
+ // response topic that grants access to a human decision. Do not expose it
445
+ // through MCP error text, CLI diagnostics, or logs.
446
+ throw new Error('NOFAX_NTFY_POLL_NETWORK');
447
+ }
448
+ if (response === POLL_TIMEOUT) {
449
+ // A transport ignoring abort may still return a readable body after the deadline.
450
+ void Promise.resolve(request).then(releaseResponseBody, () => {});
451
+ return null;
264
452
  }
265
- if (response === POLL_TIMEOUT) return null;
266
453
  await ensureOk(response, 'NOFAX_NTFY_POLL');
267
454
 
268
455
  let text;
269
456
  try {
270
- const body = response.text();
457
+ const body = readPollText(response, controller?.signal);
271
458
  text = timeout === null ? await body : await Promise.race([body, timeout]);
272
- } catch (error) {
459
+ } catch {
273
460
  if (controller?.signal.aborted) return null;
274
- throw error;
461
+ // A stream-reader failure may also include the private polling URL.
462
+ throw new Error('NOFAX_NTFY_POLL_NETWORK');
275
463
  }
276
- if (text === POLL_TIMEOUT) return null;
464
+ // Cancellation can finish a partial read just before the timeout promise.
465
+ // Never parse that partial body as a human decision after the deadline.
466
+ if (text === POLL_TIMEOUT || controller?.signal.aborted) return null;
277
467
  return parseNtfyPoll(text, requestId, allowed, kind);
278
468
  } finally {
279
469
  if (timeoutId !== undefined) clearTimeout(timeoutId);
@@ -281,6 +471,8 @@ export async function pollRemoteResponse({ config, responseTopic, requestId, all
281
471
  }
282
472
 
283
473
  export async function sendResponseConfirmation({ config, response, kind, title = 'Nofax', timeoutMs = 5000, fetchImpl = fetch }) {
474
+ // Reject timer overflow and zero/fractional delays before any phone side effect.
475
+ validateTimeoutMs(timeoutMs, 'NOFAX_CONFIRMATION_TIMEOUT_INVALID');
284
476
  let confirmationTitle = 'Response received';
285
477
  let tag = 'white_check_mark';
286
478
  if (kind === 'choice') confirmationTitle = 'Choice received';
@@ -328,11 +520,19 @@ export async function waitRemoteResponse({
328
520
  pollIntervalMs = 1000,
329
521
  fetchImpl = fetch,
330
522
  nowImpl = Date.now,
523
+ elapsedNowImpl,
331
524
  sleepImpl = sleep
332
525
  }) {
333
- const deadline = nowImpl() + timeoutMs;
526
+ // This is also exported for direct callers, which bypass requestDecision's
527
+ // deadline validation. Reject zero/overflow intervals before any polling.
528
+ validateTimeoutMs(timeoutMs, 'NOFAX_DECISION_TIMEOUT_INVALID');
529
+ validateTimeoutMs(pollIntervalMs, 'NOFAX_POLL_INTERVAL_INVALID');
530
+ // Wall-clock corrections must not extend an unattended human approval wait.
531
+ // Preserve injected virtual clocks used by existing integration callers.
532
+ const elapsedClock = elapsedNowImpl ?? (nowImpl === Date.now ? () => performance.now() : nowImpl);
533
+ const deadline = elapsedClock() + timeoutMs;
334
534
  while (true) {
335
- const remainingBeforePoll = deadline - nowImpl();
535
+ const remainingBeforePoll = deadline - elapsedClock();
336
536
  if (remainingBeforePoll <= 0) break;
337
537
  const response = await pollRemoteResponse({
338
538
  config,
@@ -343,8 +543,9 @@ export async function waitRemoteResponse({
343
543
  timeoutMs: remainingBeforePoll,
344
544
  fetchImpl
345
545
  });
346
- if (response !== null) return response;
347
- const remaining = deadline - nowImpl();
546
+ // A poll arriving at or after the deadline cannot grant human approval.
547
+ if (response !== null && elapsedClock() < deadline) return response;
548
+ const remaining = deadline - elapsedClock();
348
549
  if (remaining <= 0) break;
349
550
  await sleepImpl(Math.min(pollIntervalMs, remaining));
350
551
  }
@@ -365,6 +566,10 @@ async function requestDecision({
365
566
  nowImpl = Date.now,
366
567
  sleepImpl = sleep
367
568
  }) {
569
+ // Validate the decision window before createRemoteRequest persists or sends.
570
+ validateTimeoutMs(timeoutMs, 'NOFAX_DECISION_TIMEOUT_INVALID');
571
+ // Reject invalid polling before persisting or publishing a remote request.
572
+ validateTimeoutMs(pollIntervalMs, 'NOFAX_POLL_INTERVAL_INVALID');
368
573
  const remote = await createRemoteRequest({ config, title, message, options, includeRefine, publishTimeoutMs, fetchImpl });
369
574
  const response = await waitRemoteResponse({
370
575
  config,
@@ -379,8 +584,18 @@ async function requestDecision({
379
584
  if (response === null) {
380
585
  return { decision: 'timeout', requestId: remote.requestId, responseTopic: remote.responseTopic };
381
586
  }
382
- await sendResponseConfirmation({ config, response, kind, title, fetchImpl });
383
- return { ...response, requestId: remote.requestId, responseTopic: remote.responseTopic };
587
+ let confirmationDelivered = false;
588
+ try {
589
+ confirmationDelivered = await sendResponseConfirmation({ config, response, kind, title, fetchImpl });
590
+ } catch {
591
+ // A best-effort receipt must never erase the actual human decision.
592
+ }
593
+ return {
594
+ ...response,
595
+ requestId: remote.requestId,
596
+ responseTopic: remote.responseTopic,
597
+ ...(confirmationDelivered ? {} : { confirmationStatus: 'failed' })
598
+ };
384
599
  }
385
600
 
386
601
  export async function requestApproval(options) {