nofax 0.2.48 → 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/CHANGELOG.md CHANGED
@@ -42,6 +42,12 @@ 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.49 - 2026-10-30
46
+
47
+ ### Security
48
+
49
+ - Redact Azure Blob Storage SAS sig query signatures from agent approval summaries; synthetic regression covers both message and tool input without expanding human consent.
50
+
45
51
  ## 0.2.48 - 2026-10-30
46
52
 
47
53
  ### Security
package/README.md CHANGED
@@ -67,6 +67,12 @@ Nofax creates `~/.nofax/config.json` and generates a high-entropy notification t
67
67
  nofax test
68
68
  ```
69
69
 
70
+ To inspect local outstanding approval requests without sending a notification or
71
+ granting a decision, run `nofax pending` (or `nofax pending --limit 10`). It
72
+ prints only request IDs, kinds, statuses, and creation times as JSON; it does
73
+ not print request prompts or the ntfy subscription topic. This is a read-only
74
+ local diagnostic, not an approval interface.
75
+
70
76
  ### 4. Use it
71
77
 
72
78
  ```bash
@@ -89,8 +95,30 @@ or:
89
95
 
90
96
  If the request is still pending, times out, disconnects, or hits a transport error, Nofax never converts that condition into approval.
91
97
 
98
+ For scripts using `nofax approve`, exit status `0` means explicit **allow**, `2` means explicit **deny**, `3` means **timeout**, and `1` means an error or unrecognized decision. The terminal JSON `decision` remains unchanged. Never treat a denied request as successful based solely on receipt of a response.
99
+
92
100
  **ntfy client compatibility:** On iOS, the ntfy app may leave an HTTP action notification visible after you tap Allow or Deny, even when the action requests `clear: true` ([upstream ntfy issue #1728](https://github.com/binwiederhier/ntfy/issues/1728)). A still-visible notification does not prove whether Nofax recorded a decision: rely on Nofax's terminal `allow`/`deny` response or pending/timeout state, not on whether the notification disappears. If you use the ntfy web app instead of the mobile app, HTTP action buttons in notifications are supported in Chrome, Edge, and Opera but not Firefox or Safari; cross-origin callbacks also need the target server to allow CORS ([ntfy web-app support](https://docs.ntfy.sh/subscribe/web/)).
93
101
 
102
+ ### Windows PowerShell with restricted script execution
103
+
104
+ If PowerShell reports that `npm.ps1` or `npx.ps1` cannot be loaded because
105
+ scripts are disabled, invoke npm's Windows `.cmd` launchers explicitly.
106
+ The usual global install creates a `nofax.cmd` launcher too:
107
+
108
+ ```powershell
109
+ npm.cmd install --global nofax
110
+ nofax.cmd init
111
+ nofax.cmd test
112
+ ```
113
+
114
+ For a one-off local MCP launch without a global Nofax installation, use
115
+ `npx.cmd -y nofax mcp` (the final `mcp` argument is required). An MCP client
116
+ that launches `npx` through PowerShell can set its command to `npx.cmd` with
117
+ arguments `["-y", "nofax", "mcp"]`. These are executable launchers, not a
118
+ request to disable or bypass your organization's PowerShell execution policy.
119
+ If executable launches themselves are restricted, follow your administrator's
120
+ policy instead. See Microsoft's [PowerShell execution policy reference](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_execution_policies).
121
+
94
122
  ## MCP
95
123
 
96
124
  Start the local stdio MCP server:
@@ -137,7 +165,7 @@ VS Code can register Nofax in its user-profile MCP configuration. Open the Comma
137
165
 
138
166
  Merge the `nofax` entry with any existing servers rather than replacing them. Review VS Code's normal server-trust prompt before starting it; MCP registration does not install separate permission hooks.
139
167
 
140
- For other stdio MCP clients, set the command to `npx` with arguments `["-y", "nofax", "mcp"]`. The final `mcp` argument is required: running `npx -y nofax` without it prints the CLI usage and exits instead of starting a server. Complete the Quick start configuration before using notification or approval tools.
168
+ For other stdio MCP clients, set the command to `npx` with arguments `["-y", "nofax", "mcp"]`. The final `mcp` argument is required: running `npx -y nofax` without it prints the CLI usage and exits instead of starting a server. On Windows, use `npx.cmd` when a PowerShell script-execution policy prevents the `.ps1` shim from running. Complete the Quick start configuration before using notification or approval tools.
141
169
 
142
170
  Local MCP exposes:
143
171
 
@@ -296,6 +324,14 @@ It exposes exactly three tools:
296
324
  - `nofax_get_request` — read one safe request projection;
297
325
  - `nofax_list_pending` — read unresolved, unexpired request projections.
298
326
 
327
+ **Fresh deployments have no requests to inspect.** These two inspection tools
328
+ read only historical records already stored in that Worker's Durable Object,
329
+ such as rows preserved from earlier experimental builds. `nofax_notify` does
330
+ not create a request record, and local Nofax approvals are not synchronized
331
+ with the remote Worker. On a new Worker, `nofax_list_pending` therefore
332
+ returns an empty list and `nofax_get_request` reports not found until a
333
+ historical row exists. Use the local CLI/stdio MCP for actual phone approvals.
334
+
299
335
  Deploy from `worker/`:
300
336
 
301
337
  ```bash
@@ -377,6 +413,34 @@ Use another ntfy-compatible server with:
377
413
  nofax init --server https://ntfy.example.com --force
378
414
  ```
379
415
 
416
+ Notification content and one-time response-topic callbacks can carry sensitive
417
+ capabilities. Custom servers require HTTPS; HTTP is supported only for local
418
+ development on `localhost`, IPv4 loopback (`127.0.0.0/8`) or `[::1]`.
419
+ Previously configured non-loopback HTTP endpoints must be moved to HTTPS
420
+ before notifications or approval polling will work. This is not an approval
421
+ fallback: transport failures always remain pending, denied or timed out.
422
+
423
+ ### Optional authenticated ntfy publishing
424
+
425
+ If your ntfy server requires an access token to publish to the phone's topic,
426
+ set `NOFAX_NTFY_TOKEN` in the environment of the **local NoFax process**
427
+ (CLI, MCP server, or agent hook). Use an ntfy access token with the minimum
428
+ necessary publish permission. NoFax adds `Authorization: Bearer` only to
429
+ notification publication requests. See [ntfy access tokens](https://docs.ntfy.sh/publish/#access-tokens).
430
+
431
+ Authenticated publishing requires an HTTPS ntfy server; invalid credentials
432
+ or HTTP transport fail before publishing or persisting a new pending approval.
433
+ Do **not** put the token in `config.json`, Git, command arguments or logs.
434
+ `nofax config` does not print the environment token.
435
+
436
+ This does **not** authenticate the phone's HTTP action callbacks or the
437
+ temporary response-topic polling endpoint. Keep response-topic callbacks
438
+ reachable using the standard NoFax workflow; server-wide access rules that
439
+ block these callbacks will cause approval to remain pending or time out,
440
+ **never** auto-approve. Configure the ntfy phone app separately for access
441
+ to the protected notification topic. The remote Cloudflare Worker is not
442
+ configured by this local-only setting.
443
+
380
444
  ## Development
381
445
 
382
446
  Local package:
@@ -69,6 +69,9 @@ Input:
69
69
  ```
70
70
 
71
71
  It retrieves the safe public projection for one existing durable request.
72
+ On a new remote deployment without earlier persisted experimental records,
73
+ request IDs are not present and the tool reports not found. Local Nofax
74
+ request IDs do not become available here automatically.
72
75
 
73
76
  The response may include:
74
77
 
@@ -94,6 +97,9 @@ Optional input:
94
97
  It lists a bounded set of unresolved, unexpired request projections. The limit is 1-100.
95
98
 
96
99
  The query is observational only. It filters expired rows but does not delete them or perform lazy cleanup as a side effect of the read.
100
+ For a fresh remote Worker deployment, the expected result is an empty list;
101
+ `nofax_notify` does not populate this list, and local CLI/stdio approvals are
102
+ not synchronized into the Worker's Durable Object.
97
103
 
98
104
  ## Remote side-effect boundary
99
105
 
@@ -153,6 +159,31 @@ Generate a high-entropy secret outside the repository. For example:
153
159
  node -e "console.log(require('node:crypto').randomBytes(32).toString('base64url'))"
154
160
  ```
155
161
 
162
+ The Worker rejects obviously weak or malformed remote keys: after trimming, the
163
+ key must have 32–128 URL-safe ASCII characters (`A-Z`, `a-z`, `0-9`, `_`,
164
+ `-`) and at least eight distinct characters. These checks **cannot prove
165
+ entropy**. Use cryptographic randomness as above; do not use memorable tokens,
166
+ repeated patterns, or values copied from example configurations.
167
+
168
+ Generate a separate random ntfy topic (32 URL-safe characters from 24 random
169
+ bytes) on your own machine:
170
+
171
+ ```bash
172
+ node -e "console.log(require('node:crypto').randomBytes(24).toString('base64url'))"
173
+ ```
174
+
175
+ The Worker requires the ntfy topic to contain 24–64 URL-safe ASCII characters
176
+ and at least eight distinct characters. It rejects path separators, dots and
177
+ query characters rather than publishing to an unexpected topic. The topic is
178
+ a bearer-like secret; neither length nor character checks establish secrecy.
179
+
180
+ **Existing deployment migration:** Before updating the Worker, check that
181
+ your current `NOFAX_REMOTE_KEY` and `NTFY_TOPIC` meet these requirements.
182
+ Rotate weak values using `wrangler secret put`, and update MCP client
183
+ credentials and ntfy subscriptions as needed. A weak remote key now causes
184
+ MCP authentication to fail closed (401/404); a weak topic blocks publication.
185
+ No migration, secret rotation, or deployment is automatic.
186
+
156
187
  ### 2. Store the secret and deploy
157
188
 
158
189
  From `worker/`:
@@ -168,6 +199,30 @@ npm run deploy
168
199
 
169
200
  `NTFY_TOPIC` is a bearer-like capability and should be stored as a Worker secret. The publisher defaults to `https://ntfy.sh` unless `NTFY_SERVER` is configured.
170
201
 
202
+ `NTFY_SERVER` must be an **HTTPS origin only** (for example,
203
+ `https://ntfy.example`), without userinfo, paths other than `/`, query strings
204
+ or fragments. Cleartext `http://` is deliberately rejected for remote Worker
205
+ publishing. Before upgrading a deployment that uses a custom ntfy server,
206
+ configure a trusted HTTPS endpoint with a valid certificate; otherwise
207
+ notifications will fail closed. Do not embed credentials in the server URL.
208
+
209
+ ### Optional authenticated ntfy publishing
210
+
211
+ For an ntfy topic requiring an access token, configure the **separate** Worker
212
+ secret from the `worker/` directory:
213
+
214
+ ```bash
215
+ npx wrangler secret put NOFAX_NTFY_TOKEN
216
+ ```
217
+
218
+ The Worker uses `Authorization: Bearer <NOFAX_NTFY_TOKEN>` only when publishing
219
+ to the configured HTTPS ntfy origin. This is not `NOFAX_REMOTE_KEY`, an MCP
220
+ credential, an approval response, or an option to read phone decisions.
221
+ Do not put the token in the server URL, topic, client configuration, source,
222
+ logs, or versioned Wrangler settings. Unset it for unprotected topics.
223
+ Invalid configured tokens fail before sending, and redirects are never
224
+ followed. No credential provisioning, rotation or Worker deployment is automatic.
225
+
171
226
  Do not place the remote key in `wrangler.jsonc`, source files, `.env`, `.dev.vars`, screenshots, or issue text.
172
227
 
173
228
  ### Public ntfy quota caveat
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nofax",
3
- "version": "0.2.48",
3
+ "version": "0.2.50",
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",
@@ -1,4 +1,4 @@
1
- import { buildAgentSummary } from '../protocol.mjs';
1
+ import { buildAgentSummary, redactAndBound } from '../protocol.mjs';
2
2
  import { requestApproval } from '../ntfy.mjs';
3
3
 
4
4
  function assertClaudePermissionRequest(input) {
@@ -15,7 +15,7 @@ export async function handleClaudePermissionRequest(input, {
15
15
  try {
16
16
  const result = await requestApprovalImpl({
17
17
  config,
18
- title: `Claude Code needs approval: ${input.tool_name}`,
18
+ title: `Claude Code needs approval: ${redactAndBound(input.tool_name)}`,
19
19
  message: buildAgentSummary({
20
20
  source: 'Claude Code',
21
21
  toolName: input.tool_name,
@@ -1,4 +1,4 @@
1
- import { buildAgentSummary } from '../protocol.mjs';
1
+ import { buildAgentSummary, redactAndBound } from '../protocol.mjs';
2
2
  import { requestApproval } from '../ntfy.mjs';
3
3
 
4
4
  function assertCodexPermissionRequest(input) {
@@ -15,7 +15,7 @@ export async function handleCodexPermissionRequest(input, {
15
15
  try {
16
16
  const result = await requestApprovalImpl({
17
17
  config,
18
- title: `Codex needs approval: ${input.tool_name}`,
18
+ title: `Codex needs approval: ${redactAndBound(input.tool_name)}`,
19
19
  message: buildAgentSummary({
20
20
  source: 'Codex',
21
21
  toolName: input.tool_name,
@@ -1,4 +1,4 @@
1
- import { buildAgentSummary } from '../protocol.mjs';
1
+ import { buildAgentSummary, redactAndBound } from '../protocol.mjs';
2
2
  import { requestApproval, sendNotification } from '../ntfy.mjs';
3
3
 
4
4
  export async function handleGeminiNotification(input, {
@@ -11,7 +11,7 @@ export async function handleGeminiNotification(input, {
11
11
  : 'Notification';
12
12
  await sendNotificationImpl({
13
13
  config,
14
- title: `Gemini CLI: ${type}`,
14
+ title: `Gemini CLI: ${redactAndBound(type)}`,
15
15
  message: buildAgentSummary({
16
16
  source: 'Gemini CLI',
17
17
  message: typeof input.message === 'string' ? input.message : 'Gemini CLI needs attention.',
@@ -42,7 +42,7 @@ export async function handleGeminiHook(input, {
42
42
  try {
43
43
  const result = await requestApprovalImpl({
44
44
  config,
45
- title: `Gemini CLI needs approval: ${input.tool_name}`,
45
+ title: `Gemini CLI needs approval: ${redactAndBound(input.tool_name)}`,
46
46
  message: buildAgentSummary({
47
47
  source: 'Gemini CLI',
48
48
  toolName: input.tool_name,
package/src/cli.mjs CHANGED
@@ -1,13 +1,24 @@
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';
7
8
 
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`;
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`;
9
10
 
10
11
  const PACKAGE_JSON_URL = new URL('../package.json', import.meta.url);
12
+ const MAX_HOOK_STDIN_BYTES = 1024 * 1024;
13
+
14
+ function safeDiagnostic(error) {
15
+ // 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
+ );
21
+ }
11
22
 
12
23
  async function readPackageVersion() {
13
24
  const metadata = JSON.parse(await readFile(PACKAGE_JSON_URL, 'utf8'));
@@ -27,7 +38,7 @@ function parseArgs(args, allowedFlags = []) {
27
38
  flags.force = true;
28
39
  continue;
29
40
  }
30
- if (['--title', '--server', '--topic', '--timeout'].includes(value)) {
41
+ if (['--title', '--server', '--topic', '--timeout', '--limit'].includes(value)) {
31
42
  if (!allowedFlags.includes(value)) throw new Error(`NOFAX_UNKNOWN_FLAG:${value}`);
32
43
  const next = args[index + 1];
33
44
  if (next === undefined || next.startsWith('--')) throw new Error(`NOFAX_FLAG_VALUE:${value}`);
@@ -45,11 +56,57 @@ function rejectUnexpectedArgs(positionals) {
45
56
  if (positionals.length > 0) throw new Error(`NOFAX_UNEXPECTED_ARGUMENT:${positionals[0]}`);
46
57
  }
47
58
 
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;
59
+ async function readStdin(stdinText, stdinStream = process.stdin) {
60
+ if (stdinText !== undefined) {
61
+ if (Buffer.byteLength(stdinText, 'utf8') > MAX_HOOK_STDIN_BYTES) {
62
+ throw new Error('NOFAX_HOOK_INPUT_TOO_LARGE');
63
+ }
64
+ // Match stream validation: malformed JavaScript text must never be
65
+ // normalized before a human sees the command requiring approval.
66
+ if (typeof stdinText === 'string' && !stdinText.isWellFormed()) {
67
+ throw new Error('NOFAX_HOOK_INVALID_UTF8');
68
+ }
69
+ return stdinText;
70
+ }
71
+
72
+ const chunks = [];
73
+ let totalBytes = 0;
74
+ let pendingHighSurrogate = '';
75
+ const append = (bytes) => {
76
+ totalBytes += bytes.length;
77
+ if (totalBytes > MAX_HOOK_STDIN_BYTES) {
78
+ throw new Error('NOFAX_HOOK_INPUT_TOO_LARGE');
79
+ }
80
+ chunks.push(bytes);
81
+ };
82
+ for await (const chunk of stdinStream) {
83
+ if (typeof chunk === 'string') {
84
+ // A custom text stream may split a UTF-16 surrogate pair between yields.
85
+ // Encode the pair together rather than replacing each half with U+FFFD.
86
+ const text = pendingHighSurrogate + chunk;
87
+ const last = text.charCodeAt(text.length - 1);
88
+ const hasHighSurrogate = last >= 0xD800 && last <= 0xDBFF;
89
+ pendingHighSurrogate = hasHighSurrogate ? text.slice(-1) : '';
90
+ const completeText = hasHighSurrogate ? text.slice(0, -1) : text;
91
+ if (!completeText.isWellFormed()) throw new Error('NOFAX_HOOK_INVALID_UTF8');
92
+ append(Buffer.from(completeText));
93
+ } else {
94
+ if (pendingHighSurrogate) {
95
+ throw new Error('NOFAX_HOOK_INVALID_UTF8');
96
+ }
97
+ append(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
98
+ }
99
+ }
100
+ if (pendingHighSurrogate) throw new Error('NOFAX_HOOK_INVALID_UTF8');
101
+ try {
102
+ // Replacement characters would make the command shown for human approval
103
+ // differ from the bytes supplied by the hook. Reject malformed input.
104
+ // Preserve the previous BOM behavior: JSON.parse must reject a leading BOM.
105
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
106
+ .decode(Buffer.concat(chunks, totalBytes));
107
+ } catch {
108
+ throw new Error('NOFAX_HOOK_INVALID_UTF8');
109
+ }
53
110
  }
54
111
 
55
112
  function writeJson(stream, value) {
@@ -57,14 +114,14 @@ function writeJson(stream, value) {
57
114
  }
58
115
 
59
116
  async function runHook(adapter, deps) {
60
- const inputText = await readStdin(deps.stdinText);
117
+ const inputText = await readStdin(deps.stdinText, deps.stdinStream);
61
118
  let input;
62
119
  try {
63
120
  input = JSON.parse(inputText);
64
121
  } catch {
65
122
  throw new Error('NOFAX_HOOK_INVALID_JSON');
66
123
  }
67
- const onError = (error) => deps.stderr.write(`nofax: ${error.message}\n`);
124
+ const onError = (error) => deps.stderr.write(`nofax: ${safeDiagnostic(error)}\n`);
68
125
  let config;
69
126
  try {
70
127
  config = await deps.loadConfigImpl({ env: deps.env });
@@ -104,6 +161,7 @@ export async function runCli(args, overrides = {}) {
104
161
  const deps = {
105
162
  env: overrides.env ?? process.env,
106
163
  stdinText: overrides.stdinText,
164
+ stdinStream: overrides.stdinStream ?? process.stdin,
107
165
  stdout: overrides.stdout ?? process.stdout,
108
166
  stderr: overrides.stderr ?? process.stderr,
109
167
  initConfigImpl: overrides.initConfigImpl ?? initConfig,
@@ -111,11 +169,21 @@ export async function runCli(args, overrides = {}) {
111
169
  requestApprovalImpl: overrides.requestApprovalImpl ?? requestApproval,
112
170
  requestRefinementImpl: overrides.requestRefinementImpl ?? requestRefinement,
113
171
  sendNotificationImpl: overrides.sendNotificationImpl ?? sendNotification,
172
+ listPendingRequestsImpl: overrides.listPendingRequestsImpl ?? listPendingRequests,
114
173
  runMcpServerImpl: overrides.runMcpServerImpl ?? (async () => {
115
174
  const { runMcpServer } = await import('./mcp-server.mjs');
116
175
  await runMcpServer();
117
176
  })
118
177
  };
178
+ const rawLoadConfig = deps.loadConfigImpl;
179
+ deps.loadConfigImpl = async (...options) => {
180
+ const config = await rawLoadConfig(...options);
181
+ // Do not let old guessable topics reach notification or approval handlers.
182
+ if (isLegacyRepeatedTopic(config?.topic)) {
183
+ throw new Error('NOFAX_LEGACY_TOPIC_ROTATION_REQUIRED: run nofax init --force');
184
+ }
185
+ return config;
186
+ };
119
187
 
120
188
  try {
121
189
  if (args.length === 0 || args[0] === '--help' || args[0] === '-h' || args[0] === 'help') {
@@ -140,6 +208,9 @@ export async function runCli(args, overrides = {}) {
140
208
  ...(timeoutSeconds === undefined ? {} : { timeoutSeconds }),
141
209
  force: flags.force === true
142
210
  });
211
+ if (isLegacyRepeatedTopic(config?.topic)) {
212
+ throw new Error('NOFAX_LEGACY_TOPIC_ROTATION_REQUIRED: run nofax init --force');
213
+ }
143
214
  deps.stdout.write('Nofax ready.\n');
144
215
  deps.stdout.write(`Subscribe your ntfy app to: ${config.server}/${config.topic}\n`);
145
216
  deps.stdout.write('Then run: nofax test\n');
@@ -148,11 +219,30 @@ export async function runCli(args, overrides = {}) {
148
219
 
149
220
  if (command === 'config') {
150
221
  rejectUnexpectedArgs(args.slice(1));
151
- const config = await deps.loadConfigImpl({ env: deps.env });
152
- deps.stdout.write(`${JSON.stringify(config, null, 2)}\n`);
222
+ const config = await rawLoadConfig({ env: deps.env });
223
+ if (isLegacyRepeatedTopic(config?.topic)) {
224
+ deps.stderr.write('nofax: legacy topic requires rotation; run nofax init --force.\n');
225
+ deps.stdout.write(`${JSON.stringify({ ...config, topic: '[ROTATION_REQUIRED]' }, null, 2)}\n`);
226
+ } else {
227
+ deps.stdout.write(`${JSON.stringify(config, null, 2)}\n`);
228
+ }
153
229
  return 0;
154
230
  }
155
231
 
232
+ if (command === 'pending') {
233
+ const { flags, positionals } = parseArgs(args.slice(1), ['--limit']);
234
+ rejectUnexpectedArgs(positionals);
235
+ const limit = flags.limit === undefined ? 20 : Number(flags.limit);
236
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) {
237
+ throw new Error('NOFAX_REQUEST_LIMIT_INVALID');
238
+ }
239
+ const requests = await deps.listPendingRequestsImpl({ env: deps.env, limit });
240
+ // Local diagnostics expose request metadata only, never prompts or decisions.
241
+ deps.stdout.write(`${JSON.stringify({ requests: requests.map(({ requestId, kind, status, createdAt }) => ({
242
+ requestId, kind, status, createdAt
243
+ })) })}\n`);
244
+ return 0;
245
+ }
156
246
  if (command === 'test') {
157
247
  rejectUnexpectedArgs(args.slice(1));
158
248
  const config = await deps.loadConfigImpl({ env: deps.env });
@@ -188,7 +278,10 @@ export async function runCli(args, overrides = {}) {
188
278
  message: positionals.join(' ')
189
279
  });
190
280
  writeJson(deps.stdout, { decision: result.decision });
191
- return result.decision === 'timeout' ? 3 : 0;
281
+ // Shell callers must not mistake a denied or invalid decision for approval.
282
+ if (result.decision === 'allow') return 0;
283
+ if (result.decision === 'deny') return 2;
284
+ return result.decision === 'timeout' ? 3 : 1;
192
285
  }
193
286
 
194
287
  if (command === 'refine') {
@@ -204,7 +297,12 @@ export async function runCli(args, overrides = {}) {
204
297
  decision: result.decision,
205
298
  ...(result.text === undefined ? {} : { text: result.text })
206
299
  });
207
- return result.decision === 'timeout' ? 3 : 0;
300
+ // A zero exit code must mean an actual, nonempty human refinement.
301
+ if (result.decision === 'refine') {
302
+ return typeof result.text === 'string' && result.text.trim() ? 0 : 1;
303
+ }
304
+ if (result.decision === 'deny') return 2;
305
+ return result.decision === 'timeout' ? 3 : 1;
208
306
  }
209
307
 
210
308
  if (command === 'mcp') {
@@ -221,12 +319,12 @@ export async function runCli(args, overrides = {}) {
221
319
  return await runHook(adapter, deps);
222
320
  } catch (error) {
223
321
  if (adapter === 'gemini') {
224
- deps.stderr.write(`nofax: ${error.message}\n`);
322
+ deps.stderr.write(`nofax: ${safeDiagnostic(error)}\n`);
225
323
  writeJson(deps.stdout, { decision: 'ask' });
226
324
  return 0;
227
325
  }
228
326
  if (adapter === 'claude' || adapter === 'codex') {
229
- deps.stderr.write(`nofax: ${error.message}\n`);
327
+ deps.stderr.write(`nofax: ${safeDiagnostic(error)}\n`);
230
328
  deps.stderr.write('nofax: no remote decision; continuing with native approval.\n');
231
329
  return 0;
232
330
  }
@@ -236,7 +334,7 @@ export async function runCli(args, overrides = {}) {
236
334
 
237
335
  throw new Error(`NOFAX_UNKNOWN_COMMAND:${command}`);
238
336
  } catch (error) {
239
- deps.stderr.write(`nofax: ${error.message}\n`);
337
+ deps.stderr.write(`nofax: ${safeDiagnostic(error)}\n`);
240
338
  return 1;
241
339
  }
242
340
  }