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/CHANGELOG.md CHANGED
@@ -42,6 +42,13 @@ Local Nofax `0.2.x` behavior is unchanged by these removals.
42
42
  - The capability-path form is normalized to `/mcp` before MCP protocol handling.
43
43
  - Remote read operations perform no external messaging/provider calls; only explicit `nofax_notify` invokes ntfy.
44
44
 
45
+ ## 0.2.51 - 2026-11-24
46
+
47
+ ### Security and reliability
48
+
49
+ - Includes accumulated credential-redaction, approval-label visibility, request-timestamp, and notification cancellation fixes from the local 0.2.x development line.
50
+ - Adds a local desktop extension manifest, privacy notice, and installation/verification guide. The MCPB does not install hooks or alter permission policy.
51
+
45
52
  ## 0.2.49 - 2026-10-30
46
53
 
47
54
  ### Security
package/PRIVACY.md ADDED
@@ -0,0 +1,25 @@
1
+ # Nofax local MCP privacy notice
2
+
3
+ Last updated: November 24, 2026
4
+
5
+ This notice applies to the local Nofax CLI, stdio MCP server, and desktop extension. The optional separately self-deployed Worker is described in [the remote MCP documentation](docs/remote-mcp.md) and [the security policy](SECURITY.md).
6
+
7
+ ## Data processed
8
+
9
+ Nofax processes notification titles and messages, requested choices, request identifiers, and the responses needed for the specific interaction you initiate. It does not provide a Nofax-hosted account service or intentionally send telemetry to the project maintainer. Only send content that you are authorized to disclose; never send passwords, private keys, authentication codes, or confidential prompts to a public notification service.
10
+
11
+ ## Notification provider
12
+
13
+ The configured ntfy server receives notification content, topic identifiers, and response messages needed to deliver or poll the request. The default is https://ntfy.sh, operated independently under its [privacy policy](https://docs.ntfy.sh/privacy/). Its public service may cache messages and process network metadata; the default service is not end-to-end encrypted. A random topic is a bearer capability, not encryption. For sensitive use, choose a trusted authenticated or self-hosted HTTPS transport and consult that operator's policies. Optional publishing credentials are supplied by the user, are not saved in config.json, and must remain secret. An explicitly invoked iOS refinement shortcut can process your refinement text and the one-time response URL on your device.
14
+
15
+ ## Local storage and deletion
16
+
17
+ By default, Nofax keeps its configuration and durable request records under ~/.nofax (or NOFAX_HOME if you configure it). Records contain request metadata, response-topic capabilities, permitted decisions, timestamps, and terminal decisions or refinement text where applicable. The MCP-facing inspection tools omit secret response topics. The configuration and records remain on your computer until you remove them; protect the directory with your operating system's account permissions. After resolving or explicitly abandoning outstanding requests, you can remove the relevant records or configuration yourself. Deleting local records does not delete notification-provider caches or MCP-client transcripts. Do not interpret deletion, transport failure, timeout or silence as approval.
18
+
19
+ ## Desktop and host permissions
20
+
21
+ The desktop bundle launches only the local MCP server. It installs no approval hooks, does not change host permissions, and must not be used to override Claude, operating-system or organizational authorization controls. Your MCP host and notification client may separately retain inputs and outputs under their own policies.
22
+
23
+ ## Contact
24
+
25
+ For privacy or support questions, use info@tomiseregi.si or the [issue tracker](https://github.com/AKzar1el/nofax/issues). Never post secrets in a public issue; follow [SECURITY.md](SECURITY.md) for security reports.
package/README.md CHANGED
@@ -61,6 +61,14 @@ nofax init
61
61
 
62
62
  Nofax creates `~/.nofax/config.json` and generates a high-entropy notification topic. With the default transport, subscribe to the displayed topic in the ntfy mobile app.
63
63
 
64
+ To check local setup without contacting ntfy or exposing the private topic,
65
+ run `nofax doctor`. It reports whether the saved configuration is valid,
66
+ missing, invalid, or requires legacy topic rotation. Exit code `0` means
67
+ **local configuration only** is valid; `1` means it needs attention. Its JSON
68
+ output never includes the topic or private server URL. A successful local
69
+ check does **not** prove the phone receives notifications or that anyone has
70
+ approved a request; use the next step to test delivery explicitly.
71
+
64
72
  ### 3. Test
65
73
 
66
74
  ```bash
@@ -121,6 +129,8 @@ policy instead. See Microsoft's [PowerShell execution policy reference](https://
121
129
 
122
130
  ## MCP
123
131
 
132
+ For Claude Desktop, see the [desktop extension setup and verification guide](docs/desktop-extension.md) and the [local privacy notice](PRIVACY.md).
133
+
124
134
  Start the local stdio MCP server:
125
135
 
126
136
  ```bash
@@ -247,7 +257,7 @@ Current Gemini CLI builds expose a synchronous `BeforeTool` hook that can allow
247
257
  "name": "nofax-approval",
248
258
  "type": "command",
249
259
  "command": "nofax hook gemini",
250
- "timeout": 305000
260
+ "timeout": 330000
251
261
  }
252
262
  ]
253
263
  }
@@ -270,7 +280,7 @@ Current Gemini CLI builds expose a synchronous `BeforeTool` hook that can allow
270
280
 
271
281
  `BeforeTool` waits for an explicit Nofax Allow/Deny result. A Nofax timeout or transport failure returns Gemini's `ask` decision, forcing the native interactive confirmation instead of allowing an auto-approval policy to treat the missing Nofax decision as permission. The `Notification` hook remains advisory and is forwarded only as a phone notification.
272
282
 
273
- Adjust the matcher to the tools you want Nofax to gate. Keep the hook timeout longer than Nofax's configured approval timeout (`timeoutSeconds`, 300 seconds by default).
283
+ Adjust the matcher to the tools you want Nofax to gate. Gemini's hook `timeout` is in milliseconds and must cover more than the configured human-decision window: Nofax can spend up to 15 seconds publishing the request, 300 seconds waiting for a decision by default (`timeoutSeconds`), and another 5 seconds on best-effort confirmation. The example allows 330 seconds, including 10 seconds of startup/scheduling headroom. If you increase `timeoutSeconds`, increase the Gemini hook timeout by the same amount; otherwise Gemini may terminate the hook before Nofax finishes. A missing decision still falls back to native confirmation, never automatic approval.
274
284
 
275
285
  ### Pi (native MCP support)
276
286
 
@@ -407,12 +417,34 @@ Override the home directory with `NOFAX_HOME`:
407
417
  NOFAX_HOME=/path/to/nofax-home nofax config
408
418
  ```
409
419
 
420
+ `nofax config` masks the notification topic by default because the topic grants
421
+ access to notification content and may be captured in terminal or agent logs.
422
+ Use `nofax config --show-topic` only when you deliberately need to view or copy
423
+ the topic locally, and keep that output private. A legacy repeated topic is
424
+ always shown as `[ROTATION_REQUIRED]`, even with `--show-topic`.
425
+ The initial `nofax init` and explicit `nofax init --force` setup outputs still
426
+ print the subscription URL needed to connect your phone.
427
+
410
428
  Use another ntfy-compatible server with:
411
429
 
412
430
  ```bash
413
431
  nofax init --server https://ntfy.example.com --force
414
432
  ```
415
433
 
434
+ Running `nofax init` again without options reuses the existing configuration
435
+ without printing the saved notification topic. Use `nofax config --show-topic`
436
+ privately if you need to resubscribe an existing phone.
437
+ When a configuration already exists, supplying `--server`, `--topic`, or
438
+ `--timeout` requires `--force`; otherwise Nofax stops instead of silently
439
+ ignoring the requested change. `--force` rotates the phone topic while keeping
440
+ the existing valid server and timeout unless you override them. If the saved
441
+ configuration is invalid, `--force` can recover the phone topic and use safe
442
+ defaults for invalid timeout settings. If the saved server is malformed or the
443
+ saved file is unreadable, oversized, or has an unsupported version, provide an
444
+ explicit `--server URL` with `--force`: Nofax refuses to silently switch a
445
+ possibly private endpoint to public `ntfy.sh`. Confirm the new displayed
446
+ subscription in your ntfy app after each rotation.
447
+
416
448
  Notification content and one-time response-topic callbacks can carry sensitive
417
449
  capabilities. Custom servers require HTTPS; HTTP is supported only for local
418
450
  development on `localhost`, IPv4 loopback (`127.0.0.0/8`) or `[::1]`.
@@ -0,0 +1,18 @@
1
+ # Claude Desktop extension
2
+
3
+ The local MCPB distribution contains the released Node.js MCP server and its locked production dependencies. It installs no agent hooks and does not override Claude or OS permissions. It is separate from the optional self-hosted Worker.
4
+
5
+ ## Setup
6
+
7
+ 1. Install the matching `.mcpb` asset from the [GitHub Releases](https://github.com/AKzar1el/nofax/releases) page using your desktop client's local extension installation flow. Review the declared tools.
8
+ 2. Configure your own notification transport using the [Nofax quick start](../README.md#quick-start). If you have no existing Nofax configuration, run `npx -y nofax@0.2.51 init` in a terminal and subscribe your own ntfy app to the topic shown locally. Treat that topic as a secret. Use your trusted HTTPS ntfy server for sensitive use. No Nofax account is required.
9
+ 3. Use the following examples with synthetic or non-sensitive content and your own recipient/topic:
10
+ - "Send a Nofax notification titled Test with the message Desktop extension check."
11
+ - "Ask me whether to proceed with a harmless draft preview via Nofax; wait for my actual decision."
12
+ - "List my pending Nofax requests without sending anything."
13
+
14
+ An unresolved request is never authorization. Nofax does not bypass the client's own confirmation requirements. See [privacy](../PRIVACY.md) and [security](../SECURITY.md).
15
+
16
+ ## Build from the released source
17
+
18
+ Use the release tag, verify its version and install the lockfile with `npm ci --omit=dev --ignore-scripts`. Use `npm pack` to obtain the distribution files, extract them to a new staging directory, include the tagged manifest, privacy documentation, production dependencies, and lockfile, and run `npx --yes @anthropic-ai/mcpb@2.1.2 validate manifest.json` and `npx --yes @anthropic-ai/mcpb@2.1.2 pack . nofax-0.2.51.mcpb`. Never include configuration, local request state, credentials, or hooks. Independently extract the bundle and test `node bin/nofax.mjs mcp` over stdio with a disposable Nofax home and loopback notification fixture before publishing.
package/manifest.json ADDED
@@ -0,0 +1,81 @@
1
+ {
2
+ "manifest_version": "0.3",
3
+ "name": "nofax",
4
+ "display_name": "Nofax - Human Approval and Notifications",
5
+ "version": "0.2.51",
6
+ "description": "Local human-in-the-loop notifications, approval requests, choices, and refinement via a configured ntfy transport.",
7
+ "long_description": "Nofax runs locally over MCP and sends explicitly requested notifications through your configured ntfy service. Interactive requests remain pending until a matching terminal response is received. It does not replace Claude or operating-system permission controls and installs no hooks. Configure Nofax first using the documented CLI quick start. Public ntfy is not end-to-end encrypted; avoid sensitive material and use a trusted transport. Local request state stays in your Nofax home directory.",
8
+ "author": {
9
+ "name": "AKzar1el",
10
+ "url": "https://github.com/AKzar1el"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/AKzar1el/nofax"
15
+ },
16
+ "homepage": "https://github.com/AKzar1el/nofax",
17
+ "documentation": "https://github.com/AKzar1el/nofax#readme",
18
+ "support": "https://github.com/AKzar1el/nofax/issues",
19
+ "license": "MIT",
20
+ "privacy_policies": [
21
+ "https://github.com/AKzar1el/nofax/blob/main/PRIVACY.md",
22
+ "https://docs.ntfy.sh/privacy/"
23
+ ],
24
+ "server": {
25
+ "type": "node",
26
+ "entry_point": "bin/nofax.mjs",
27
+ "mcp_config": {
28
+ "command": "node",
29
+ "args": [
30
+ "${__dirname}/bin/nofax.mjs",
31
+ "mcp"
32
+ ]
33
+ }
34
+ },
35
+ "tools": [
36
+ {
37
+ "name": "nofax_notify",
38
+ "description": "Send a one-way phone notification. This tool is informational and does not create a human-response wait. Notification transport success never counts as approval."
39
+ },
40
+ {
41
+ "name": "nofax_request_approval",
42
+ "description": "Send Allow/Deny to the phone and return a durable pending requestId. IMPORTANT: after this tool returns pending, call nofax_wait_for_response and repeat while it remains pending. Never continue the guarded action without a terminal Allow response. Set allowRefine when the human should also be able to send refinement text."
43
+ },
44
+ {
45
+ "name": "nofax_request_choice",
46
+ "description": "Send up to three explicit options to the phone and return a durable pending requestId. IMPORTANT: call nofax_wait_for_response and repeat while pending; do not choose on the human's behalf."
47
+ },
48
+ {
49
+ "name": "nofax_request_refinement",
50
+ "description": "Ask the human for free-text refinement through the configured Nofax Refine iOS Shortcut. Use this when free-text edits are needed; use nofax_request_approval for Allow/Deny or nofax_request_choice for predefined options. Returns a durable pending requestId; call nofax_wait_for_response and repeat while pending."
51
+ },
52
+ {
53
+ "name": "nofax_wait_for_response",
54
+ "description": "Long-poll a durable Nofax request for up to 240 seconds. If the result is pending, you MUST call this tool again with the same requestId. Repeat indefinitely until a terminal response is returned or the user explicitly changes/cancels the goal. Do not continue the guarded action while pending."
55
+ },
56
+ {
57
+ "name": "nofax_get_request",
58
+ "description": "Inspect safe metadata and terminal state for one known durable requestId without waiting. Use nofax_wait_for_response when the caller must wait for a human decision, or nofax_list_pending to recover requestIds after interruption. Secret response topics are never returned."
59
+ },
60
+ {
61
+ "name": "nofax_list_pending",
62
+ "description": "List a bounded set of unresolved Nofax request handles for recovery after client or conversation interruption. Secret response topics are never returned."
63
+ }
64
+ ],
65
+ "keywords": [
66
+ "human-in-the-loop",
67
+ "notifications",
68
+ "approvals",
69
+ "ntfy",
70
+ "developer-tools"
71
+ ],
72
+ "compatibility": {
73
+ "platforms": [
74
+ "win32",
75
+ "darwin"
76
+ ],
77
+ "runtimes": {
78
+ "node": ">=20.0.0"
79
+ }
80
+ }
81
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nofax",
3
- "version": "0.2.50",
3
+ "version": "0.2.51",
4
4
  "mcpName": "io.github.AKzar1el/nofax",
5
5
  "description": "Human-in-the-loop approvals and notifications for AI coding agents via CLI, MCP, and agent hooks.",
6
6
  "type": "module",
@@ -20,7 +20,10 @@
20
20
  "CHANGELOG.md",
21
21
  "CONTRIBUTING.md",
22
22
  "docs/architecture.md",
23
- "docs/remote-mcp.md"
23
+ "docs/remote-mcp.md",
24
+ "manifest.json",
25
+ "PRIVACY.md",
26
+ "docs/desktop-extension.md"
24
27
  ],
25
28
  "scripts": {
26
29
  "test": "node --test test/*.test.mjs",
package/src/cli.mjs CHANGED
@@ -5,19 +5,37 @@ import { listPendingRequests } from './requests.mjs';
5
5
  import { handleClaudePermissionRequest } from './adapters/claude.mjs';
6
6
  import { handleCodexPermissionRequest } from './adapters/codex.mjs';
7
7
  import { handleGeminiHook } from './adapters/gemini.mjs';
8
+ import { redactDiagnosticSecrets } from './protocol.mjs';
8
9
 
9
- 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 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\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`;
10
11
 
11
12
  const PACKAGE_JSON_URL = new URL('../package.json', import.meta.url);
12
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;
13
17
 
14
18
  function safeDiagnostic(error) {
15
19
  // Untrusted transport errors may contain line controls or invisible marks
16
- // that disguise decision words. Render both explicitly in terminal logs.
17
- return String(error?.message ?? error).replace(
18
- /[\x00-\x1f\x7f-\x9f\u00ad\u034f\u061c\u115f-\u1160\u180e\u200b-\u200f\u2028-\u202e\u2060-\u206f\u2800\u3164\ufe0e-\ufe0f\ufeff\uffa0]/gu,
19
- (character) => '\\u' + character.codePointAt(0).toString(16).padStart(4, '0')
20
- );
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('');
21
39
  }
22
40
 
23
41
  async function readPackageVersion() {
@@ -33,11 +51,20 @@ function parseArgs(args, allowedFlags = []) {
33
51
  const positionals = [];
34
52
  for (let index = 0; index < args.length; index += 1) {
35
53
  const value = args[index];
54
+ if (value === '--') {
55
+ positionals.push(...args.slice(index + 1));
56
+ break;
57
+ }
36
58
  if (value === '--force') {
37
59
  if (!allowedFlags.includes(value)) throw new Error(`NOFAX_UNKNOWN_FLAG:${value}`);
38
60
  flags.force = true;
39
61
  continue;
40
62
  }
63
+ if (value === '--show-topic') {
64
+ if (!allowedFlags.includes(value)) throw new Error(`NOFAX_UNKNOWN_FLAG:${value}`);
65
+ flags.showTopic = true;
66
+ continue;
67
+ }
41
68
  if (['--title', '--server', '--topic', '--timeout', '--limit'].includes(value)) {
42
69
  if (!allowedFlags.includes(value)) throw new Error(`NOFAX_UNKNOWN_FLAG:${value}`);
43
70
  const next = args[index + 1];
@@ -46,14 +73,16 @@ function parseArgs(args, allowedFlags = []) {
46
73
  index += 1;
47
74
  continue;
48
75
  }
49
- 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');
50
79
  positionals.push(value);
51
80
  }
52
81
  return { flags, positionals };
53
82
  }
54
83
 
55
84
  function rejectUnexpectedArgs(positionals) {
56
- if (positionals.length > 0) throw new Error(`NOFAX_UNEXPECTED_ARGUMENT:${positionals[0]}`);
85
+ if (positionals.length > 0) throw new Error('NOFAX_UNEXPECTED_ARGUMENT');
57
86
  }
58
87
 
59
88
  async function readStdin(stdinText, stdinStream = process.stdin) {
@@ -146,7 +175,7 @@ async function runHook(adapter, deps) {
146
175
  onError
147
176
  });
148
177
  } else {
149
- throw new Error(`NOFAX_HOOK_UNSUPPORTED:${adapter}`);
178
+ throw new Error('NOFAX_HOOK_UNSUPPORTED');
150
179
  }
151
180
 
152
181
  if (output === null) {
@@ -187,11 +216,17 @@ export async function runCli(args, overrides = {}) {
187
216
 
188
217
  try {
189
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
+ }
190
223
  deps.stdout.write(HELP);
191
224
  return 0;
192
225
  }
193
226
 
194
227
  if (args[0] === '--version' || args[0] === '-v') {
228
+ const { positionals } = parseArgs(args.slice(1));
229
+ rejectUnexpectedArgs(positionals);
195
230
  deps.stdout.write(`${await readPackageVersion()}\n`);
196
231
  return 0;
197
232
  }
@@ -201,34 +236,72 @@ export async function runCli(args, overrides = {}) {
201
236
  const { flags, positionals } = parseArgs(args.slice(1), ['--server', '--topic', '--timeout', '--force']);
202
237
  rejectUnexpectedArgs(positionals);
203
238
  const timeoutSeconds = flags.timeout === undefined ? undefined : Number(flags.timeout);
239
+ let created = false;
204
240
  const config = await deps.initConfigImpl({
205
241
  env: deps.env,
206
242
  ...(flags.server === undefined ? {} : { server: flags.server }),
207
243
  ...(flags.topic === undefined ? {} : { topic: flags.topic }),
208
244
  ...(timeoutSeconds === undefined ? {} : { timeoutSeconds }),
209
- 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; }
210
249
  });
211
250
  if (isLegacyRepeatedTopic(config?.topic)) {
212
251
  throw new Error('NOFAX_LEGACY_TOPIC_ROTATION_REQUIRED: run nofax init --force');
213
252
  }
214
- deps.stdout.write('Nofax ready.\n');
215
- deps.stdout.write(`Subscribe your ntfy app to: ${config.server}/${config.topic}\n`);
216
- deps.stdout.write('Then run: nofax test\n');
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
+ }
217
261
  return 0;
218
262
  }
219
263
 
220
264
  if (command === 'config') {
221
- rejectUnexpectedArgs(args.slice(1));
265
+ const { flags, positionals } = parseArgs(args.slice(1), ['--show-topic']);
266
+ rejectUnexpectedArgs(positionals);
222
267
  const config = await rawLoadConfig({ env: deps.env });
223
268
  if (isLegacyRepeatedTopic(config?.topic)) {
224
269
  deps.stderr.write('nofax: legacy topic requires rotation; run nofax init --force.\n');
225
270
  deps.stdout.write(`${JSON.stringify({ ...config, topic: '[ROTATION_REQUIRED]' }, null, 2)}\n`);
226
271
  } else {
227
- deps.stdout.write(`${JSON.stringify(config, null, 2)}\n`);
272
+ deps.stdout.write(`${JSON.stringify(flags.showTopic ? config : { ...config, topic: '[REDACTED]' }, null, 2)}\n`);
228
273
  }
229
274
  return 0;
230
275
  }
231
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
+
232
305
  if (command === 'pending') {
233
306
  const { flags, positionals } = parseArgs(args.slice(1), ['--limit']);
234
307
  rejectUnexpectedArgs(positionals);
@@ -332,7 +405,7 @@ export async function runCli(args, overrides = {}) {
332
405
  }
333
406
  }
334
407
 
335
- throw new Error(`NOFAX_UNKNOWN_COMMAND:${command}`);
408
+ throw new Error('NOFAX_UNKNOWN_COMMAND');
336
409
  } catch (error) {
337
410
  deps.stderr.write(`nofax: ${safeDiagnostic(error)}\n`);
338
411
  return 1;
package/src/config.mjs CHANGED
@@ -7,6 +7,17 @@ import { createPhoneTopic } from './protocol.mjs';
7
7
  export const DEFAULT_SERVER = 'https://ntfy.sh';
8
8
  export const DEFAULT_TIMEOUT_SECONDS = 300;
9
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
+ ]);
10
21
 
11
22
  async function readConfigJson(path) {
12
23
  const file = await open(path, 'r');
@@ -132,21 +143,59 @@ export async function loadConfig({ home, env } = {}) {
132
143
  }
133
144
  }
134
145
 
135
- 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 } = {}) {
136
147
  const root = resolveNofaxHome({ home, env });
148
+ let savedConfig;
137
149
  if (!force) {
138
150
  try {
139
- 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;
140
156
  } catch (error) {
141
157
  if (error.message !== 'NOFAX_NOT_INITIALIZED') throw error;
142
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
+ }
143
192
  }
144
193
 
145
194
  const config = validateConfig({
146
195
  version: 1,
147
- server,
196
+ server: server ?? savedConfig?.server ?? DEFAULT_SERVER,
148
197
  topic: topic ?? createPhoneTopic(),
149
- timeoutSeconds
198
+ timeoutSeconds: timeoutSeconds ?? savedConfig?.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS
150
199
  });
151
200
  await mkdir(root, { recursive: true, mode: 0o700 });
152
201
  const path = join(root, 'config.json');
@@ -179,6 +228,9 @@ export async function initConfig({ home, env, server = DEFAULT_SERVER, topic, ti
179
228
  await link(temporaryPath, path);
180
229
  } catch (error) {
181
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
+ }
182
234
  return await loadConfig({ home: root });
183
235
  }
184
236
  }
@@ -191,5 +243,8 @@ export async function initConfig({ home, env, server = DEFAULT_SERVER, topic, ti
191
243
  }
192
244
  }
193
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?.();
194
249
  return config;
195
250
  }
@@ -122,7 +122,7 @@ export function buildMcpServer({ handlers = createMcpToolHandlers() } = {}) {
122
122
  title: z.string().min(1).max(120).optional().describe('Optional choice prompt title shown to the human; defaults to "Nofax choice".'),
123
123
  message: z.string().min(1).max(2200).describe('Question or decision context shown to the human.'),
124
124
  options: z.array(z.union([
125
- 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.'),
126
126
  z.object({
127
127
  value: z.string().min(1).max(80).describe('Choice value returned as the terminal human decision.'),
128
128
  label: z.string().min(1).max(32).describe('Short human-facing label displayed for this choice.')
package/src/mcp-tools.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import { loadConfig, validateTopic } from './config.mjs';
2
2
  import {
3
3
  createRemoteRequest,
4
+ normalizeOptions,
4
5
  pollRemoteResponse,
5
6
  sendNotification,
6
7
  sendResponseConfirmation
@@ -117,34 +118,10 @@ function validateWaitSeconds(value) {
117
118
  return seconds;
118
119
  }
119
120
 
120
- function boundChoiceLabel(label) {
121
- const end = safeSliceEnd(label, Math.min(label.length, 32));
122
- return label.slice(0, end);
123
- }
124
-
125
121
  function validateChoiceOptions(options) {
126
122
  if (!Array.isArray(options) || options.length < 1 || options.length > 3) throw new Error('NOFAX_CHOICE_LIMIT');
127
- const normalized = options.map((option) => {
128
- if (typeof option === 'string') {
129
- const value = option.trim();
130
- if (!value || value.length > 80 || !value.isWellFormed()) throw new Error('NOFAX_CHOICE_INVALID');
131
- return { value, label: boundChoiceLabel(value) };
132
- }
133
- if (!option || typeof option.value !== 'string' || typeof option.label !== 'string') throw new Error('NOFAX_CHOICE_INVALID');
134
- const value = option.value.trim();
135
- const label = option.label.trim();
136
- if (!value || !label || value.length > 80 || !value.isWellFormed() || !label.isWellFormed()) {
137
- throw new Error('NOFAX_CHOICE_INVALID');
138
- }
139
- return { value, label: boundChoiceLabel(label) };
140
- });
141
- if (new Set(normalized.map((option) => option.value)).size !== normalized.length) {
142
- throw new Error('NOFAX_CHOICE_DUPLICATE');
143
- }
144
- if (new Set(normalized.map((option) => option.label)).size !== normalized.length) {
145
- throw new Error('NOFAX_CHOICE_DUPLICATE');
146
- }
147
- return normalized;
123
+ // Prevalidate the same rendered labels that ntfy will show on the phone.
124
+ return normalizeOptions(options);
148
125
  }
149
126
 
150
127
  export function createMcpToolHandlers(overrides = {}) {