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/config.mjs CHANGED
@@ -1,10 +1,37 @@
1
- import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';
1
+ import { chmod, link, mkdir, open, rename, unlink } from 'node:fs/promises';
2
+ import { randomUUID } from 'node:crypto';
2
3
  import { homedir } from 'node:os';
3
4
  import { isAbsolute, join, resolve } from 'node:path';
4
5
  import { createPhoneTopic } from './protocol.mjs';
5
6
 
6
7
  export const DEFAULT_SERVER = 'https://ntfy.sh';
7
8
  export const DEFAULT_TIMEOUT_SECONDS = 300;
9
+ const MAX_CONFIG_BYTES = 64 * 1024;
10
+
11
+ async function readConfigJson(path) {
12
+ const file = await open(path, 'r');
13
+ try {
14
+ const buffer = Buffer.allocUnsafe(MAX_CONFIG_BYTES + 1);
15
+ let length = 0;
16
+ while (length < buffer.length) {
17
+ const { bytesRead } = await file.read(buffer, length, buffer.length - length, null);
18
+ if (bytesRead === 0) break;
19
+ length += bytesRead;
20
+ }
21
+ if (length > MAX_CONFIG_BYTES) throw new Error('NOFAX_CONFIG_TOO_LARGE');
22
+ let json;
23
+ try {
24
+ // TextDecoder strips a leading UTF-8 BOM but rejects malformed byte
25
+ // sequences instead of silently replacing them in a security config.
26
+ json = new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, length));
27
+ } catch {
28
+ throw new Error('NOFAX_CONFIG_INVALID_UTF8');
29
+ }
30
+ return JSON.parse(json);
31
+ } finally {
32
+ await file.close();
33
+ }
34
+ }
8
35
 
9
36
  export function resolveNofaxHome({ home, env = process.env } = {}) {
10
37
  const configured = home ?? env.NOFAX_HOME;
@@ -17,6 +44,11 @@ export function resolveNofaxHome({ home, env = process.env } = {}) {
17
44
  }
18
45
 
19
46
  export function normalizeServer(input) {
47
+ // URL parsing silently strips embedded CR/LF/TAB, which could disguise the
48
+ // actual destination for notification capabilities and approval callbacks.
49
+ if (typeof input === 'string' && /[\x00-\x1f\x7f]/.test(input)) {
50
+ throw new Error('NOFAX_SERVER_INVALID');
51
+ }
20
52
  let url;
21
53
  try {
22
54
  url = new URL(input);
@@ -26,11 +58,41 @@ export function normalizeServer(input) {
26
58
  if (url.protocol !== 'https:' && url.protocol !== 'http:') throw new Error('NOFAX_SERVER_PROTOCOL');
27
59
  if (url.username || url.password) throw new Error('NOFAX_SERVER_CREDENTIALS');
28
60
  if ((url.pathname && url.pathname !== '/') || url.search || url.hash) throw new Error('NOFAX_SERVER_PATH');
61
+ if (url.protocol === 'http:' &&
62
+ url.hostname !== 'localhost' &&
63
+ url.hostname !== '[::1]' &&
64
+ !/^127\.(?:\d+\.){2}\d+$/.test(url.hostname)) {
65
+ // Notifications and approval callback URLs contain capabilities; only
66
+ // explicit loopback development endpoints may use cleartext transport.
67
+ throw new Error('NOFAX_SERVER_INSECURE_HTTP');
68
+ }
29
69
  return `${url.protocol}//${url.host}`;
30
70
  }
31
71
 
32
- function validateTopic(topic) {
33
- if (typeof topic !== 'string' || topic.length < 24 || topic.length > 64 || !/^[A-Za-z0-9_-]+$/.test(topic)) {
72
+ function hasRepeatedTopicPattern(topic) {
73
+ // Eight distinct characters can still be one short, easily guessed motif.
74
+ for (let length = 1; length <= Math.floor(topic.length / 2); length += 1) {
75
+ if (topic.length % length === 0 && topic === topic.slice(0, length).repeat(topic.length / length)) {
76
+ return true;
77
+ }
78
+ }
79
+ return false;
80
+ }
81
+
82
+ function hasValidTopicShape(topic) {
83
+ return typeof topic === 'string' && topic.length >= 24 && topic.length <= 64 &&
84
+ /^[A-Za-z0-9_-]+$/.test(topic) && new Set(topic).size >= 8;
85
+ }
86
+
87
+ export function isLegacyRepeatedTopic(topic) {
88
+ // Only persisted topics matching the former character/length rules qualify.
89
+ return hasValidTopicShape(topic) && hasRepeatedTopicPattern(topic);
90
+ }
91
+
92
+ export function validateTopic(topic) {
93
+ // The phone topic grants access to notification content and embedded response
94
+ // actions. Reject obviously guessable values, as the remote Worker does.
95
+ if (!hasValidTopicShape(topic) || hasRepeatedTopicPattern(topic)) {
34
96
  throw new Error('NOFAX_TOPIC_INVALID');
35
97
  }
36
98
  return topic;
@@ -41,21 +103,28 @@ function validateTimeout(value) {
41
103
  return value;
42
104
  }
43
105
 
44
- export function validateConfig(input) {
106
+ function validateConfigInternal(input, allowSavedLegacyTopic) {
45
107
  if (!input || input.version !== 1) throw new Error('NOFAX_CONFIG_VERSION');
46
108
  return {
47
109
  version: 1,
48
110
  server: normalizeServer(input.server),
49
- topic: validateTopic(input.topic),
111
+ topic: allowSavedLegacyTopic && isLegacyRepeatedTopic(input.topic)
112
+ ? input.topic : validateTopic(input.topic),
50
113
  timeoutSeconds: validateTimeout(input.timeoutSeconds)
51
114
  };
52
115
  }
53
116
 
117
+ export function validateConfig(input) {
118
+ return validateConfigInternal(input, false);
119
+ }
120
+
54
121
  export async function loadConfig({ home, env } = {}) {
55
122
  const root = resolveNofaxHome({ home, env });
56
123
  try {
57
- const parsed = JSON.parse(await readFile(join(root, 'config.json'), 'utf8'));
58
- return validateConfig(parsed);
124
+ const parsed = await readConfigJson(join(root, 'config.json'));
125
+ // Read existing repeated topics so users can inspect and rotate them;
126
+ // newly supplied topics and notification transports remain strict.
127
+ return validateConfigInternal(parsed, true);
59
128
  } catch (error) {
60
129
  if (error?.code === 'ENOENT') throw new Error('NOFAX_NOT_INITIALIZED');
61
130
  if (error instanceof SyntaxError) throw new Error('NOFAX_CONFIG_INVALID_JSON');
@@ -81,11 +150,46 @@ export async function initConfig({ home, env, server = DEFAULT_SERVER, topic, ti
81
150
  });
82
151
  await mkdir(root, { recursive: true, mode: 0o700 });
83
152
  const path = join(root, 'config.json');
84
- await writeFile(path, `${JSON.stringify(config, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
153
+ const temporaryPath = join(root, `.config.json.${randomUUID()}.tmp`);
154
+ let temporaryCreated = false;
155
+ let replaced = false;
85
156
  try {
86
- await chmod(path, 0o600);
87
- } catch {
88
- // Windows may not honor POSIX mode bits; the file still lives in the user's profile.
157
+ // Replacing a complete same-directory temp file keeps readers from seeing a
158
+ // truncated config and avoids writing through an existing symlink/hardlink.
159
+ const file = await open(temporaryPath, 'wx', 0o600);
160
+ temporaryCreated = true;
161
+ try {
162
+ await file.writeFile(`${JSON.stringify(config, null, 2)}\n`, 'utf8');
163
+ await file.sync();
164
+ } finally {
165
+ await file.close();
166
+ }
167
+ try {
168
+ await chmod(temporaryPath, 0o600);
169
+ } catch {
170
+ // Windows may not honor POSIX mode bits; the file still lives in the user's profile.
171
+ }
172
+ if (force) {
173
+ await rename(temporaryPath, path);
174
+ replaced = true;
175
+ } else {
176
+ // The first initializer owns the topic. An atomic hardlink claim avoids
177
+ // changing it underneath another process that just read its new config.
178
+ try {
179
+ await link(temporaryPath, path);
180
+ } catch (error) {
181
+ if (error?.code !== 'EEXIST') throw error;
182
+ return await loadConfig({ home: root });
183
+ }
184
+ }
185
+ } finally {
186
+ if (temporaryCreated && !replaced) {
187
+ try {
188
+ await unlink(temporaryPath);
189
+ } catch (error) {
190
+ if (error?.code !== 'ENOENT') throw error;
191
+ }
192
+ }
89
193
  }
90
194
  return config;
91
195
  }
@@ -1,8 +1,11 @@
1
1
  import { McpServer } from '@modelcontextprotocol/server';
2
2
  import { serveStdio } from '@modelcontextprotocol/server/stdio';
3
+ import { readFileSync } from 'node:fs';
3
4
  import * as z from 'zod/v4';
4
5
  import { createMcpToolHandlers } from './mcp-tools.mjs';
5
6
 
7
+ const PACKAGE_VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
8
+
6
9
  export const MCP_TOOL_NAMES = Object.freeze([
7
10
  'nofax_notify',
8
11
  'nofax_request_approval',
@@ -45,6 +48,7 @@ const WAIT_OUTPUT_SCHEMA = z.object({
45
48
  mustWait: z.boolean().optional().describe('Present and true while the request remains pending.'),
46
49
  decision: z.string().min(1).max(80).optional().describe('Terminal human decision when resolved, such as allow, deny, refine, or an explicit choice value.'),
47
50
  text: z.string().min(1).max(2000).optional().describe('Human free-text refinement when the terminal decision is refine.'),
51
+ confirmationStatus: z.literal('failed').optional().describe('Confirmation notification failed after an explicit human decision was durably recorded; this is never itself approval.'),
48
52
  instruction: z.string().min(1).describe('Safety-preserving instruction describing what the caller may do next.')
49
53
  });
50
54
 
@@ -74,7 +78,7 @@ const LIST_PENDING_OUTPUT_SCHEMA = z.object({
74
78
 
75
79
  export function buildMcpServer({ handlers = createMcpToolHandlers() } = {}) {
76
80
  const server = new McpServer(
77
- { name: 'nofax', version: '0.2.46' },
81
+ { name: 'nofax', version: PACKAGE_VERSION },
78
82
  { instructions: SERVER_INSTRUCTIONS }
79
83
  );
80
84
 
package/src/mcp-tools.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { loadConfig } from './config.mjs';
1
+ import { loadConfig, validateTopic } from './config.mjs';
2
2
  import {
3
3
  createRemoteRequest,
4
4
  pollRemoteResponse,
@@ -102,6 +102,8 @@ function safeSliceEnd(text, end) {
102
102
  function validateText(value, name, max = 2200) {
103
103
  if (typeof value !== 'string' || !value.trim()) throw new Error(`NOFAX_${name}_REQUIRED`);
104
104
  const text = value.trim();
105
+ // Replacing an ill-formed code unit could change the request the human sees.
106
+ if (!text.isWellFormed()) throw new Error(`NOFAX_${name}_INVALID_UTF8`);
105
107
  if (text.length <= max) return text;
106
108
  const end = safeSliceEnd(text, max - 14);
107
109
  return `${text.slice(0, end)}…[truncated]`;
@@ -125,13 +127,15 @@ function validateChoiceOptions(options) {
125
127
  const normalized = options.map((option) => {
126
128
  if (typeof option === 'string') {
127
129
  const value = option.trim();
128
- if (!value || value.length > 80) throw new Error('NOFAX_CHOICE_INVALID');
130
+ if (!value || value.length > 80 || !value.isWellFormed()) throw new Error('NOFAX_CHOICE_INVALID');
129
131
  return { value, label: boundChoiceLabel(value) };
130
132
  }
131
133
  if (!option || typeof option.value !== 'string' || typeof option.label !== 'string') throw new Error('NOFAX_CHOICE_INVALID');
132
134
  const value = option.value.trim();
133
135
  const label = option.label.trim();
134
- if (!value || !label || value.length > 80) throw new Error('NOFAX_CHOICE_INVALID');
136
+ if (!value || !label || value.length > 80 || !value.isWellFormed() || !label.isWellFormed()) {
137
+ throw new Error('NOFAX_CHOICE_INVALID');
138
+ }
135
139
  return { value, label: boundChoiceLabel(label) };
136
140
  });
137
141
  if (new Set(normalized.map((option) => option.value)).size !== normalized.length) {
@@ -158,6 +162,9 @@ export function createMcpToolHandlers(overrides = {}) {
158
162
  resolveRequestWithClaimImpl: overrides.resolveRequestWithClaimImpl ?? resolveRequestWithClaim,
159
163
  listPendingRequestsImpl: overrides.listPendingRequestsImpl ?? listPendingRequests,
160
164
  nowImpl: overrides.nowImpl ?? Date.now,
165
+ // Wall-clock adjustments must not extend a human-approval polling window.
166
+ // Existing callers that inject nowImpl for tests keep their virtual clock.
167
+ elapsedNowImpl: overrides.elapsedNowImpl ?? (overrides.nowImpl ?? (() => performance.now())),
161
168
  sleepImpl: overrides.sleepImpl ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)))
162
169
  };
163
170
 
@@ -259,9 +266,12 @@ export function createMcpToolHandlers(overrides = {}) {
259
266
  const current = request.server && request.topic
260
267
  ? { server: request.server, topic: request.topic }
261
268
  : await config();
262
- const deadline = deps.nowImpl() + seconds * 1000;
269
+ // Historical records remain readable, but a weak saved topic must never
270
+ // become a live approval-response transport after topic rules tighten.
271
+ validateTopic(current.topic);
272
+ const deadline = deps.elapsedNowImpl() + seconds * 1000;
263
273
  while (true) {
264
- const remainingBeforePoll = deadline - deps.nowImpl();
274
+ const remainingBeforePoll = deadline - deps.elapsedNowImpl();
265
275
  if (remainingBeforePoll <= 0) break;
266
276
  const response = await deps.pollRemoteResponseImpl({
267
277
  config: current,
@@ -271,29 +281,43 @@ export function createMcpToolHandlers(overrides = {}) {
271
281
  kind: request.kind,
272
282
  timeoutMs: remainingBeforePoll
273
283
  });
274
- if (response !== null) {
284
+ // A poll transport can return after its deadline despite a timeout
285
+ // hint. Do not turn that late result into an accepted human decision.
286
+ if (response !== null && deps.elapsedNowImpl() < deadline) {
287
+ // A wall-clock correction after request creation must not make a
288
+ // genuine terminal decision invalid or erase the human's denial.
289
+ const createdAtMs = Date.parse(request.createdAt);
290
+ const nowMs = deps.nowImpl();
291
+ const resolvedAtMs = Number.isFinite(createdAtMs) ? Math.max(nowMs, createdAtMs) : nowMs;
275
292
  const resolution = await deps.resolveRequestWithClaimImpl({
276
293
  home: deps.home,
277
294
  env: deps.env,
278
295
  requestId: request.requestId,
279
296
  response,
280
- resolvedAt: new Date(deps.nowImpl()).toISOString()
297
+ resolvedAt: new Date(resolvedAtMs).toISOString()
281
298
  });
282
299
  request = resolution.request;
283
- const acceptedResponse = resolution.claimed
284
- && request.decision === response.decision
285
- && (request.text ?? undefined) === (response.text ?? undefined);
300
+ // A new terminal claim is authoritative even when durable storage
301
+ // trims or bounds the human's raw refinement text.
302
+ const acceptedResponse = resolution.claimed && request.decision === response.decision;
303
+ let confirmationStatus;
286
304
  if (acceptedResponse) {
287
- await deps.sendResponseConfirmationImpl({
288
- config: current,
289
- response,
290
- kind: request.kind,
291
- title: request.kind === 'approval' ? 'Approval' : request.kind === 'refinement' ? 'Refinement' : 'Choice'
292
- });
305
+ try {
306
+ const confirmationDelivered = await deps.sendResponseConfirmationImpl({
307
+ config: current,
308
+ response: { ...response, text: request.text },
309
+ kind: request.kind,
310
+ title: request.kind === 'approval' ? 'Approval' : request.kind === 'refinement' ? 'Refinement' : 'Choice'
311
+ });
312
+ if (confirmationDelivered === false) confirmationStatus = 'failed';
313
+ } catch {
314
+ confirmationStatus = 'failed';
315
+ }
293
316
  }
294
- return terminalResult(request);
317
+ const result = terminalResult(request);
318
+ return confirmationStatus ? { ...result, confirmationStatus } : result;
295
319
  }
296
- const remaining = deadline - deps.nowImpl();
320
+ const remaining = deadline - deps.elapsedNowImpl();
297
321
  if (remaining <= 0) break;
298
322
  await deps.sleepImpl(Math.min(1000, remaining));
299
323
  }