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/src/cli.mjs CHANGED
@@ -1,13 +1,42 @@
1
1
  import { readFile } from 'node:fs/promises';
2
- import { initConfig, loadConfig } from './config.mjs';
2
+ import { initConfig, isLegacyRepeatedTopic, loadConfig } from './config.mjs';
3
3
  import { requestApproval, requestRefinement, sendNotification } from './ntfy.mjs';
4
+ import { listPendingRequests } from './requests.mjs';
4
5
  import { handleClaudePermissionRequest } from './adapters/claude.mjs';
5
6
  import { handleCodexPermissionRequest } from './adapters/codex.mjs';
6
7
  import { handleGeminiHook } from './adapters/gemini.mjs';
8
+ import { redactDiagnosticSecrets } from './protocol.mjs';
7
9
 
8
- const HELP = `nofax - remote approvals and notifications for coding agents\n\nUsage:\n nofax --version\n nofax init [--server URL] [--topic TOPIC] [--timeout SECONDS] [--force]\n nofax test\n nofax notify [--title TITLE] MESSAGE...\n nofax approve [--title TITLE] MESSAGE...\n nofax refine [--title TITLE] MESSAGE...\n nofax mcp\n nofax config\n nofax hook claude\n nofax hook codex\n nofax hook gemini\n\nEnvironment:\n NOFAX_HOME Override ~/.nofax\n`;
10
+ const HELP = `nofax - remote approvals and notifications for coding agents\n\nUsage:\n nofax --version\n nofax init [--server URL] [--topic TOPIC] [--timeout SECONDS] [--force]\n nofax doctor\n nofax test\n nofax pending [--limit N]\n nofax notify [--title TITLE] MESSAGE...\n nofax approve [--title TITLE] MESSAGE...\n nofax refine [--title TITLE] MESSAGE...\n nofax mcp\n nofax config [--show-topic]\n nofax hook claude\n nofax hook codex\n nofax hook gemini\n\nEnvironment:\n NOFAX_HOME Override ~/.nofax\n`;
9
11
 
10
12
  const PACKAGE_JSON_URL = new URL('../package.json', import.meta.url);
13
+ const MAX_HOOK_STDIN_BYTES = 1024 * 1024;
14
+ const MAX_DIAGNOSTIC_CHARS = 4096;
15
+ const DIAGNOSTIC_TRUNCATION = '...[truncated]';
16
+ const DIAGNOSTIC_CONTROLS = /[\x00-\x1f\x7f-\x9f\u00ad\u034f\u061c\u115f-\u1160\u180e\u200b-\u200f\u2028-\u202e\u2060-\u206f\u2800\u3164\ufe00-\ufe0f\ufeff\uffa0\u{e0000}-\u{e007f}\u{e0100}-\u{e01ef}]/u;
17
+
18
+ function safeDiagnostic(error) {
19
+ // Untrusted transport errors may contain line controls or invisible marks
20
+ // that disguise decision words or flood logs after escape expansion.
21
+ const chunks = [];
22
+ let length = 0;
23
+ for (const character of redactDiagnosticSecrets(String(error?.message ?? error))) {
24
+ const point = character.codePointAt(0);
25
+ const rendered = DIAGNOSTIC_CONTROLS.test(character)
26
+ ? (point <= 0xffff ? '\\u' + point.toString(16).padStart(4, '0') : '\\u{' + point.toString(16) + '}')
27
+ : character;
28
+ if (length + rendered.length > MAX_DIAGNOSTIC_CHARS) {
29
+ // Back off whole escaped characters; never split a Unicode pair or escape.
30
+ while (length > MAX_DIAGNOSTIC_CHARS - DIAGNOSTIC_TRUNCATION.length) {
31
+ length -= chunks.pop().length;
32
+ }
33
+ return chunks.join('') + DIAGNOSTIC_TRUNCATION;
34
+ }
35
+ chunks.push(rendered);
36
+ length += rendered.length;
37
+ }
38
+ return chunks.join('');
39
+ }
11
40
 
12
41
  async function readPackageVersion() {
13
42
  const metadata = JSON.parse(await readFile(PACKAGE_JSON_URL, 'utf8'));
@@ -22,12 +51,21 @@ function parseArgs(args, allowedFlags = []) {
22
51
  const positionals = [];
23
52
  for (let index = 0; index < args.length; index += 1) {
24
53
  const value = args[index];
54
+ if (value === '--') {
55
+ positionals.push(...args.slice(index + 1));
56
+ break;
57
+ }
25
58
  if (value === '--force') {
26
59
  if (!allowedFlags.includes(value)) throw new Error(`NOFAX_UNKNOWN_FLAG:${value}`);
27
60
  flags.force = true;
28
61
  continue;
29
62
  }
30
- if (['--title', '--server', '--topic', '--timeout'].includes(value)) {
63
+ if (value === '--show-topic') {
64
+ if (!allowedFlags.includes(value)) throw new Error(`NOFAX_UNKNOWN_FLAG:${value}`);
65
+ flags.showTopic = true;
66
+ continue;
67
+ }
68
+ if (['--title', '--server', '--topic', '--timeout', '--limit'].includes(value)) {
31
69
  if (!allowedFlags.includes(value)) throw new Error(`NOFAX_UNKNOWN_FLAG:${value}`);
32
70
  const next = args[index + 1];
33
71
  if (next === undefined || next.startsWith('--')) throw new Error(`NOFAX_FLAG_VALUE:${value}`);
@@ -35,21 +73,69 @@ function parseArgs(args, allowedFlags = []) {
35
73
  index += 1;
36
74
  continue;
37
75
  }
38
- if (value.startsWith('--')) throw new Error(`NOFAX_UNKNOWN_FLAG:${value}`);
76
+ // Unknown arguments may carry credentials (--token=...), so do not echo
77
+ // their caller-controlled text into logs or captured approval output.
78
+ if (value.startsWith('--')) throw new Error('NOFAX_UNKNOWN_FLAG');
39
79
  positionals.push(value);
40
80
  }
41
81
  return { flags, positionals };
42
82
  }
43
83
 
44
84
  function rejectUnexpectedArgs(positionals) {
45
- if (positionals.length > 0) throw new Error(`NOFAX_UNEXPECTED_ARGUMENT:${positionals[0]}`);
85
+ if (positionals.length > 0) throw new Error('NOFAX_UNEXPECTED_ARGUMENT');
46
86
  }
47
87
 
48
- async function readStdin(stdinText) {
49
- if (stdinText !== undefined) return stdinText;
50
- let text = '';
51
- for await (const chunk of process.stdin) text += chunk;
52
- return text;
88
+ async function readStdin(stdinText, stdinStream = process.stdin) {
89
+ if (stdinText !== undefined) {
90
+ if (Buffer.byteLength(stdinText, 'utf8') > MAX_HOOK_STDIN_BYTES) {
91
+ throw new Error('NOFAX_HOOK_INPUT_TOO_LARGE');
92
+ }
93
+ // Match stream validation: malformed JavaScript text must never be
94
+ // normalized before a human sees the command requiring approval.
95
+ if (typeof stdinText === 'string' && !stdinText.isWellFormed()) {
96
+ throw new Error('NOFAX_HOOK_INVALID_UTF8');
97
+ }
98
+ return stdinText;
99
+ }
100
+
101
+ const chunks = [];
102
+ let totalBytes = 0;
103
+ let pendingHighSurrogate = '';
104
+ const append = (bytes) => {
105
+ totalBytes += bytes.length;
106
+ if (totalBytes > MAX_HOOK_STDIN_BYTES) {
107
+ throw new Error('NOFAX_HOOK_INPUT_TOO_LARGE');
108
+ }
109
+ chunks.push(bytes);
110
+ };
111
+ for await (const chunk of stdinStream) {
112
+ if (typeof chunk === 'string') {
113
+ // A custom text stream may split a UTF-16 surrogate pair between yields.
114
+ // Encode the pair together rather than replacing each half with U+FFFD.
115
+ const text = pendingHighSurrogate + chunk;
116
+ const last = text.charCodeAt(text.length - 1);
117
+ const hasHighSurrogate = last >= 0xD800 && last <= 0xDBFF;
118
+ pendingHighSurrogate = hasHighSurrogate ? text.slice(-1) : '';
119
+ const completeText = hasHighSurrogate ? text.slice(0, -1) : text;
120
+ if (!completeText.isWellFormed()) throw new Error('NOFAX_HOOK_INVALID_UTF8');
121
+ append(Buffer.from(completeText));
122
+ } else {
123
+ if (pendingHighSurrogate) {
124
+ throw new Error('NOFAX_HOOK_INVALID_UTF8');
125
+ }
126
+ append(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
127
+ }
128
+ }
129
+ if (pendingHighSurrogate) throw new Error('NOFAX_HOOK_INVALID_UTF8');
130
+ try {
131
+ // Replacement characters would make the command shown for human approval
132
+ // differ from the bytes supplied by the hook. Reject malformed input.
133
+ // Preserve the previous BOM behavior: JSON.parse must reject a leading BOM.
134
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
135
+ .decode(Buffer.concat(chunks, totalBytes));
136
+ } catch {
137
+ throw new Error('NOFAX_HOOK_INVALID_UTF8');
138
+ }
53
139
  }
54
140
 
55
141
  function writeJson(stream, value) {
@@ -57,14 +143,14 @@ function writeJson(stream, value) {
57
143
  }
58
144
 
59
145
  async function runHook(adapter, deps) {
60
- const inputText = await readStdin(deps.stdinText);
146
+ const inputText = await readStdin(deps.stdinText, deps.stdinStream);
61
147
  let input;
62
148
  try {
63
149
  input = JSON.parse(inputText);
64
150
  } catch {
65
151
  throw new Error('NOFAX_HOOK_INVALID_JSON');
66
152
  }
67
- const onError = (error) => deps.stderr.write(`nofax: ${error.message}\n`);
153
+ const onError = (error) => deps.stderr.write(`nofax: ${safeDiagnostic(error)}\n`);
68
154
  let config;
69
155
  try {
70
156
  config = await deps.loadConfigImpl({ env: deps.env });
@@ -89,7 +175,7 @@ async function runHook(adapter, deps) {
89
175
  onError
90
176
  });
91
177
  } else {
92
- throw new Error(`NOFAX_HOOK_UNSUPPORTED:${adapter}`);
178
+ throw new Error('NOFAX_HOOK_UNSUPPORTED');
93
179
  }
94
180
 
95
181
  if (output === null) {
@@ -104,6 +190,7 @@ export async function runCli(args, overrides = {}) {
104
190
  const deps = {
105
191
  env: overrides.env ?? process.env,
106
192
  stdinText: overrides.stdinText,
193
+ stdinStream: overrides.stdinStream ?? process.stdin,
107
194
  stdout: overrides.stdout ?? process.stdout,
108
195
  stderr: overrides.stderr ?? process.stderr,
109
196
  initConfigImpl: overrides.initConfigImpl ?? initConfig,
@@ -111,19 +198,35 @@ export async function runCli(args, overrides = {}) {
111
198
  requestApprovalImpl: overrides.requestApprovalImpl ?? requestApproval,
112
199
  requestRefinementImpl: overrides.requestRefinementImpl ?? requestRefinement,
113
200
  sendNotificationImpl: overrides.sendNotificationImpl ?? sendNotification,
201
+ listPendingRequestsImpl: overrides.listPendingRequestsImpl ?? listPendingRequests,
114
202
  runMcpServerImpl: overrides.runMcpServerImpl ?? (async () => {
115
203
  const { runMcpServer } = await import('./mcp-server.mjs');
116
204
  await runMcpServer();
117
205
  })
118
206
  };
207
+ const rawLoadConfig = deps.loadConfigImpl;
208
+ deps.loadConfigImpl = async (...options) => {
209
+ const config = await rawLoadConfig(...options);
210
+ // Do not let old guessable topics reach notification or approval handlers.
211
+ if (isLegacyRepeatedTopic(config?.topic)) {
212
+ throw new Error('NOFAX_LEGACY_TOPIC_ROTATION_REQUIRED: run nofax init --force');
213
+ }
214
+ return config;
215
+ };
119
216
 
120
217
  try {
121
218
  if (args.length === 0 || args[0] === '--help' || args[0] === '-h' || args[0] === 'help') {
219
+ if (args.length > 0) {
220
+ const { positionals } = parseArgs(args.slice(1));
221
+ rejectUnexpectedArgs(positionals);
222
+ }
122
223
  deps.stdout.write(HELP);
123
224
  return 0;
124
225
  }
125
226
 
126
227
  if (args[0] === '--version' || args[0] === '-v') {
228
+ const { positionals } = parseArgs(args.slice(1));
229
+ rejectUnexpectedArgs(positionals);
127
230
  deps.stdout.write(`${await readPackageVersion()}\n`);
128
231
  return 0;
129
232
  }
@@ -133,26 +236,86 @@ export async function runCli(args, overrides = {}) {
133
236
  const { flags, positionals } = parseArgs(args.slice(1), ['--server', '--topic', '--timeout', '--force']);
134
237
  rejectUnexpectedArgs(positionals);
135
238
  const timeoutSeconds = flags.timeout === undefined ? undefined : Number(flags.timeout);
239
+ let created = false;
136
240
  const config = await deps.initConfigImpl({
137
241
  env: deps.env,
138
242
  ...(flags.server === undefined ? {} : { server: flags.server }),
139
243
  ...(flags.topic === undefined ? {} : { topic: flags.topic }),
140
244
  ...(timeoutSeconds === undefined ? {} : { timeoutSeconds }),
141
- force: flags.force === true
245
+ force: flags.force === true,
246
+ rejectExisting: flags.force !== true &&
247
+ (flags.server !== undefined || flags.topic !== undefined || flags.timeout !== undefined),
248
+ onCreated: () => { created = true; }
142
249
  });
143
- deps.stdout.write('Nofax ready.\n');
144
- deps.stdout.write(`Subscribe your ntfy app to: ${config.server}/${config.topic}\n`);
145
- deps.stdout.write('Then run: nofax test\n');
250
+ if (isLegacyRepeatedTopic(config?.topic)) {
251
+ throw new Error('NOFAX_LEGACY_TOPIC_ROTATION_REQUIRED: run nofax init --force');
252
+ }
253
+ if (created) {
254
+ deps.stdout.write('Nofax ready.\n');
255
+ deps.stdout.write(`Subscribe your ntfy app to: ${config.server}/${config.topic}\n`);
256
+ deps.stdout.write('Then run: nofax test\n');
257
+ } else {
258
+ deps.stdout.write('Nofax ready (already initialized).\n');
259
+ deps.stdout.write('To view your existing subscription topic, run nofax config --show-topic privately.\n');
260
+ }
146
261
  return 0;
147
262
  }
148
263
 
149
264
  if (command === 'config') {
150
- rejectUnexpectedArgs(args.slice(1));
151
- const config = await deps.loadConfigImpl({ env: deps.env });
152
- deps.stdout.write(`${JSON.stringify(config, null, 2)}\n`);
265
+ const { flags, positionals } = parseArgs(args.slice(1), ['--show-topic']);
266
+ rejectUnexpectedArgs(positionals);
267
+ const config = await rawLoadConfig({ env: deps.env });
268
+ if (isLegacyRepeatedTopic(config?.topic)) {
269
+ deps.stderr.write('nofax: legacy topic requires rotation; run nofax init --force.\n');
270
+ deps.stdout.write(`${JSON.stringify({ ...config, topic: '[ROTATION_REQUIRED]' }, null, 2)}\n`);
271
+ } else {
272
+ deps.stdout.write(`${JSON.stringify(flags.showTopic ? config : { ...config, topic: '[REDACTED]' }, null, 2)}\n`);
273
+ }
153
274
  return 0;
154
275
  }
155
276
 
277
+ if (command === 'doctor') {
278
+ rejectUnexpectedArgs(args.slice(1));
279
+ let localConfig;
280
+ let nextStep;
281
+ let errorCode;
282
+ try {
283
+ const config = await rawLoadConfig({ env: deps.env });
284
+ localConfig = isLegacyRepeatedTopic(config.topic) ? 'legacy_topic' : 'valid';
285
+ nextStep = localConfig === 'valid' ? 'nofax test' : 'nofax init --force';
286
+ } catch (error) {
287
+ localConfig = error?.message === 'NOFAX_NOT_INITIALIZED' ? 'not_initialized' : 'invalid';
288
+ nextStep = localConfig === 'not_initialized' ? 'nofax init' : 'review local configuration';
289
+ if (localConfig === 'invalid') {
290
+ // Never echo untrusted filesystem errors, paths, or credential contents.
291
+ errorCode = /^NOFAX_[A-Z0-9_]+$/.test(error?.message ?? '')
292
+ ? error.message : 'NOFAX_CONFIG_UNAVAILABLE';
293
+ }
294
+ }
295
+ writeJson(deps.stdout, {
296
+ localConfig,
297
+ ...(errorCode === undefined ? {} : { errorCode }),
298
+ notificationDelivery: 'not_tested',
299
+ humanApproval: 'not_tested',
300
+ nextStep
301
+ });
302
+ return localConfig === 'valid' ? 0 : 1;
303
+ }
304
+
305
+ if (command === 'pending') {
306
+ const { flags, positionals } = parseArgs(args.slice(1), ['--limit']);
307
+ rejectUnexpectedArgs(positionals);
308
+ const limit = flags.limit === undefined ? 20 : Number(flags.limit);
309
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) {
310
+ throw new Error('NOFAX_REQUEST_LIMIT_INVALID');
311
+ }
312
+ const requests = await deps.listPendingRequestsImpl({ env: deps.env, limit });
313
+ // Local diagnostics expose request metadata only, never prompts or decisions.
314
+ deps.stdout.write(`${JSON.stringify({ requests: requests.map(({ requestId, kind, status, createdAt }) => ({
315
+ requestId, kind, status, createdAt
316
+ })) })}\n`);
317
+ return 0;
318
+ }
156
319
  if (command === 'test') {
157
320
  rejectUnexpectedArgs(args.slice(1));
158
321
  const config = await deps.loadConfigImpl({ env: deps.env });
@@ -188,7 +351,10 @@ export async function runCli(args, overrides = {}) {
188
351
  message: positionals.join(' ')
189
352
  });
190
353
  writeJson(deps.stdout, { decision: result.decision });
191
- return result.decision === 'timeout' ? 3 : 0;
354
+ // Shell callers must not mistake a denied or invalid decision for approval.
355
+ if (result.decision === 'allow') return 0;
356
+ if (result.decision === 'deny') return 2;
357
+ return result.decision === 'timeout' ? 3 : 1;
192
358
  }
193
359
 
194
360
  if (command === 'refine') {
@@ -204,7 +370,12 @@ export async function runCli(args, overrides = {}) {
204
370
  decision: result.decision,
205
371
  ...(result.text === undefined ? {} : { text: result.text })
206
372
  });
207
- return result.decision === 'timeout' ? 3 : 0;
373
+ // A zero exit code must mean an actual, nonempty human refinement.
374
+ if (result.decision === 'refine') {
375
+ return typeof result.text === 'string' && result.text.trim() ? 0 : 1;
376
+ }
377
+ if (result.decision === 'deny') return 2;
378
+ return result.decision === 'timeout' ? 3 : 1;
208
379
  }
209
380
 
210
381
  if (command === 'mcp') {
@@ -221,12 +392,12 @@ export async function runCli(args, overrides = {}) {
221
392
  return await runHook(adapter, deps);
222
393
  } catch (error) {
223
394
  if (adapter === 'gemini') {
224
- deps.stderr.write(`nofax: ${error.message}\n`);
395
+ deps.stderr.write(`nofax: ${safeDiagnostic(error)}\n`);
225
396
  writeJson(deps.stdout, { decision: 'ask' });
226
397
  return 0;
227
398
  }
228
399
  if (adapter === 'claude' || adapter === 'codex') {
229
- deps.stderr.write(`nofax: ${error.message}\n`);
400
+ deps.stderr.write(`nofax: ${safeDiagnostic(error)}\n`);
230
401
  deps.stderr.write('nofax: no remote decision; continuing with native approval.\n');
231
402
  return 0;
232
403
  }
@@ -234,9 +405,9 @@ export async function runCli(args, overrides = {}) {
234
405
  }
235
406
  }
236
407
 
237
- throw new Error(`NOFAX_UNKNOWN_COMMAND:${command}`);
408
+ throw new Error('NOFAX_UNKNOWN_COMMAND');
238
409
  } catch (error) {
239
- deps.stderr.write(`nofax: ${error.message}\n`);
410
+ deps.stderr.write(`nofax: ${safeDiagnostic(error)}\n`);
240
411
  return 1;
241
412
  }
242
413
  }
package/src/config.mjs CHANGED
@@ -1,10 +1,48 @@
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
+ const RECOVERABLE_SAVED_CONFIG_ERRORS = new Set([
11
+ 'NOFAX_NOT_INITIALIZED', 'NOFAX_CONFIG_VERSION', 'NOFAX_CONFIG_INVALID_JSON',
12
+ 'NOFAX_CONFIG_INVALID_UTF8', 'NOFAX_CONFIG_TOO_LARGE',
13
+ 'NOFAX_SERVER_INVALID', 'NOFAX_SERVER_PROTOCOL', 'NOFAX_SERVER_CREDENTIALS',
14
+ 'NOFAX_SERVER_PATH', 'NOFAX_SERVER_INSECURE_HTTP', 'NOFAX_TOPIC_INVALID',
15
+ 'NOFAX_TIMEOUT_INVALID'
16
+ ]);
17
+ const UNREADABLE_SAVED_SERVER_ERRORS = new Set([
18
+ 'NOFAX_CONFIG_VERSION', 'NOFAX_CONFIG_INVALID_JSON',
19
+ 'NOFAX_CONFIG_INVALID_UTF8', 'NOFAX_CONFIG_TOO_LARGE'
20
+ ]);
21
+
22
+ async function readConfigJson(path) {
23
+ const file = await open(path, 'r');
24
+ try {
25
+ const buffer = Buffer.allocUnsafe(MAX_CONFIG_BYTES + 1);
26
+ let length = 0;
27
+ while (length < buffer.length) {
28
+ const { bytesRead } = await file.read(buffer, length, buffer.length - length, null);
29
+ if (bytesRead === 0) break;
30
+ length += bytesRead;
31
+ }
32
+ if (length > MAX_CONFIG_BYTES) throw new Error('NOFAX_CONFIG_TOO_LARGE');
33
+ let json;
34
+ try {
35
+ // TextDecoder strips a leading UTF-8 BOM but rejects malformed byte
36
+ // sequences instead of silently replacing them in a security config.
37
+ json = new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, length));
38
+ } catch {
39
+ throw new Error('NOFAX_CONFIG_INVALID_UTF8');
40
+ }
41
+ return JSON.parse(json);
42
+ } finally {
43
+ await file.close();
44
+ }
45
+ }
8
46
 
9
47
  export function resolveNofaxHome({ home, env = process.env } = {}) {
10
48
  const configured = home ?? env.NOFAX_HOME;
@@ -17,6 +55,11 @@ export function resolveNofaxHome({ home, env = process.env } = {}) {
17
55
  }
18
56
 
19
57
  export function normalizeServer(input) {
58
+ // URL parsing silently strips embedded CR/LF/TAB, which could disguise the
59
+ // actual destination for notification capabilities and approval callbacks.
60
+ if (typeof input === 'string' && /[\x00-\x1f\x7f]/.test(input)) {
61
+ throw new Error('NOFAX_SERVER_INVALID');
62
+ }
20
63
  let url;
21
64
  try {
22
65
  url = new URL(input);
@@ -26,11 +69,41 @@ export function normalizeServer(input) {
26
69
  if (url.protocol !== 'https:' && url.protocol !== 'http:') throw new Error('NOFAX_SERVER_PROTOCOL');
27
70
  if (url.username || url.password) throw new Error('NOFAX_SERVER_CREDENTIALS');
28
71
  if ((url.pathname && url.pathname !== '/') || url.search || url.hash) throw new Error('NOFAX_SERVER_PATH');
72
+ if (url.protocol === 'http:' &&
73
+ url.hostname !== 'localhost' &&
74
+ url.hostname !== '[::1]' &&
75
+ !/^127\.(?:\d+\.){2}\d+$/.test(url.hostname)) {
76
+ // Notifications and approval callback URLs contain capabilities; only
77
+ // explicit loopback development endpoints may use cleartext transport.
78
+ throw new Error('NOFAX_SERVER_INSECURE_HTTP');
79
+ }
29
80
  return `${url.protocol}//${url.host}`;
30
81
  }
31
82
 
32
- function validateTopic(topic) {
33
- if (typeof topic !== 'string' || topic.length < 24 || topic.length > 64 || !/^[A-Za-z0-9_-]+$/.test(topic)) {
83
+ function hasRepeatedTopicPattern(topic) {
84
+ // Eight distinct characters can still be one short, easily guessed motif.
85
+ for (let length = 1; length <= Math.floor(topic.length / 2); length += 1) {
86
+ if (topic.length % length === 0 && topic === topic.slice(0, length).repeat(topic.length / length)) {
87
+ return true;
88
+ }
89
+ }
90
+ return false;
91
+ }
92
+
93
+ function hasValidTopicShape(topic) {
94
+ return typeof topic === 'string' && topic.length >= 24 && topic.length <= 64 &&
95
+ /^[A-Za-z0-9_-]+$/.test(topic) && new Set(topic).size >= 8;
96
+ }
97
+
98
+ export function isLegacyRepeatedTopic(topic) {
99
+ // Only persisted topics matching the former character/length rules qualify.
100
+ return hasValidTopicShape(topic) && hasRepeatedTopicPattern(topic);
101
+ }
102
+
103
+ export function validateTopic(topic) {
104
+ // The phone topic grants access to notification content and embedded response
105
+ // actions. Reject obviously guessable values, as the remote Worker does.
106
+ if (!hasValidTopicShape(topic) || hasRepeatedTopicPattern(topic)) {
34
107
  throw new Error('NOFAX_TOPIC_INVALID');
35
108
  }
36
109
  return topic;
@@ -41,21 +114,28 @@ function validateTimeout(value) {
41
114
  return value;
42
115
  }
43
116
 
44
- export function validateConfig(input) {
117
+ function validateConfigInternal(input, allowSavedLegacyTopic) {
45
118
  if (!input || input.version !== 1) throw new Error('NOFAX_CONFIG_VERSION');
46
119
  return {
47
120
  version: 1,
48
121
  server: normalizeServer(input.server),
49
- topic: validateTopic(input.topic),
122
+ topic: allowSavedLegacyTopic && isLegacyRepeatedTopic(input.topic)
123
+ ? input.topic : validateTopic(input.topic),
50
124
  timeoutSeconds: validateTimeout(input.timeoutSeconds)
51
125
  };
52
126
  }
53
127
 
128
+ export function validateConfig(input) {
129
+ return validateConfigInternal(input, false);
130
+ }
131
+
54
132
  export async function loadConfig({ home, env } = {}) {
55
133
  const root = resolveNofaxHome({ home, env });
56
134
  try {
57
- const parsed = JSON.parse(await readFile(join(root, 'config.json'), 'utf8'));
58
- return validateConfig(parsed);
135
+ const parsed = await readConfigJson(join(root, 'config.json'));
136
+ // Read existing repeated topics so users can inspect and rotate them;
137
+ // newly supplied topics and notification transports remain strict.
138
+ return validateConfigInternal(parsed, true);
59
139
  } catch (error) {
60
140
  if (error?.code === 'ENOENT') throw new Error('NOFAX_NOT_INITIALIZED');
61
141
  if (error instanceof SyntaxError) throw new Error('NOFAX_CONFIG_INVALID_JSON');
@@ -63,29 +143,108 @@ export async function loadConfig({ home, env } = {}) {
63
143
  }
64
144
  }
65
145
 
66
- export async function initConfig({ home, env, server = DEFAULT_SERVER, topic, timeoutSeconds = DEFAULT_TIMEOUT_SECONDS, force = false } = {}) {
146
+ export async function initConfig({ home, env, server, topic, timeoutSeconds, force = false, rejectExisting = false, onCreated } = {}) {
67
147
  const root = resolveNofaxHome({ home, env });
148
+ let savedConfig;
68
149
  if (!force) {
69
150
  try {
70
- return await loadConfig({ home: root });
151
+ const existing = await loadConfig({ home: root });
152
+ if (rejectExisting) {
153
+ throw new Error('NOFAX_INIT_OPTIONS_REQUIRE_FORCE: existing configuration; run nofax init --force to replace it');
154
+ }
155
+ return existing;
71
156
  } catch (error) {
72
157
  if (error.message !== 'NOFAX_NOT_INITIALIZED') throw error;
73
158
  }
159
+ } else {
160
+ try {
161
+ const saved = await readConfigJson(join(root, 'config.json'));
162
+ if (!saved || saved.version !== 1) throw new Error('NOFAX_CONFIG_VERSION');
163
+ // Force always rotates the topic. Recover each transport setting on its
164
+ // own, so one damaged field cannot silently reset another valid field.
165
+ savedConfig = {};
166
+ try {
167
+ savedConfig.server = normalizeServer(saved.server);
168
+ } catch (error) {
169
+ if (!RECOVERABLE_SAVED_CONFIG_ERRORS.has(error?.message)) throw error;
170
+ // Never silently redirect a previously configured private endpoint to
171
+ // the public default. Require an explicit destination for recovery.
172
+ if (server === undefined) {
173
+ throw new Error('NOFAX_SERVER_REQUIRES_EXPLICIT_REPLACEMENT: provide --server URL with --force');
174
+ }
175
+ }
176
+ try {
177
+ savedConfig.timeoutSeconds = validateTimeout(saved.timeoutSeconds);
178
+ } catch (error) {
179
+ if (error?.message !== 'NOFAX_TIMEOUT_INVALID') throw error;
180
+ }
181
+ } catch (error) {
182
+ // Explicit force can repair invalid saved data, but must not hide I/O failures.
183
+ if (error?.code !== 'ENOENT' && !(error instanceof SyntaxError) &&
184
+ !RECOVERABLE_SAVED_CONFIG_ERRORS.has(error?.message)) throw error;
185
+ // If the old file exists but cannot be decoded/validated, its private
186
+ // server cannot be recovered safely. Require a deliberate destination.
187
+ if ((error instanceof SyntaxError || UNREADABLE_SAVED_SERVER_ERRORS.has(error?.message)) &&
188
+ server === undefined) {
189
+ throw new Error('NOFAX_SERVER_REQUIRES_EXPLICIT_REPLACEMENT: provide --server URL with --force');
190
+ }
191
+ }
74
192
  }
75
193
 
76
194
  const config = validateConfig({
77
195
  version: 1,
78
- server,
196
+ server: server ?? savedConfig?.server ?? DEFAULT_SERVER,
79
197
  topic: topic ?? createPhoneTopic(),
80
- timeoutSeconds
198
+ timeoutSeconds: timeoutSeconds ?? savedConfig?.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS
81
199
  });
82
200
  await mkdir(root, { recursive: true, mode: 0o700 });
83
201
  const path = join(root, 'config.json');
84
- await writeFile(path, `${JSON.stringify(config, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
202
+ const temporaryPath = join(root, `.config.json.${randomUUID()}.tmp`);
203
+ let temporaryCreated = false;
204
+ let replaced = false;
85
205
  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.
206
+ // Replacing a complete same-directory temp file keeps readers from seeing a
207
+ // truncated config and avoids writing through an existing symlink/hardlink.
208
+ const file = await open(temporaryPath, 'wx', 0o600);
209
+ temporaryCreated = true;
210
+ try {
211
+ await file.writeFile(`${JSON.stringify(config, null, 2)}\n`, 'utf8');
212
+ await file.sync();
213
+ } finally {
214
+ await file.close();
215
+ }
216
+ try {
217
+ await chmod(temporaryPath, 0o600);
218
+ } catch {
219
+ // Windows may not honor POSIX mode bits; the file still lives in the user's profile.
220
+ }
221
+ if (force) {
222
+ await rename(temporaryPath, path);
223
+ replaced = true;
224
+ } else {
225
+ // The first initializer owns the topic. An atomic hardlink claim avoids
226
+ // changing it underneath another process that just read its new config.
227
+ try {
228
+ await link(temporaryPath, path);
229
+ } catch (error) {
230
+ if (error?.code !== 'EEXIST') throw error;
231
+ if (rejectExisting) {
232
+ throw new Error('NOFAX_INIT_OPTIONS_REQUIRE_FORCE: existing configuration; run nofax init --force to replace it');
233
+ }
234
+ return await loadConfig({ home: root });
235
+ }
236
+ }
237
+ } finally {
238
+ if (temporaryCreated && !replaced) {
239
+ try {
240
+ await unlink(temporaryPath);
241
+ } catch (error) {
242
+ if (error?.code !== 'ENOENT') throw error;
243
+ }
244
+ }
89
245
  }
246
+ // A reused config (including a concurrent initializer's winning write) must
247
+ // not trigger a fresh subscription-capability disclosure in CLI output.
248
+ onCreated?.();
90
249
  return config;
91
250
  }
@@ -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
 
@@ -118,7 +122,7 @@ export function buildMcpServer({ handlers = createMcpToolHandlers() } = {}) {
118
122
  title: z.string().min(1).max(120).optional().describe('Optional choice prompt title shown to the human; defaults to "Nofax choice".'),
119
123
  message: z.string().min(1).max(2200).describe('Question or decision context shown to the human.'),
120
124
  options: z.array(z.union([
121
- z.string().min(1).max(80).describe('String shorthand for a choice value; its first 32 characters are also used as the human-facing label.'),
125
+ z.string().min(1).max(80).describe('String shorthand for a choice value. The decision value remains exact; the phone label is bounded to 32 UTF-16 units using whole graphemes and a visible clipping marker.'),
122
126
  z.object({
123
127
  value: z.string().min(1).max(80).describe('Choice value returned as the terminal human decision.'),
124
128
  label: z.string().min(1).max(32).describe('Short human-facing label displayed for this choice.')