replywizard-whatsapp-mcp 0.6.2 → 0.6.4

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/README.md CHANGED
@@ -42,14 +42,15 @@ lifted into its own repository without touching the extension.
42
42
  | `save_template` | write | Saves a message template to Reply Wizard's Templates. |
43
43
  | `send_message` | send | Puts text in one chat's message box under a bar naming the app and the chat, with Send and Discard. **Sent only if you press Send** within about 45 seconds; otherwise it stays as an ordinary draft. Needs `chatId`, `expectName` (the chat's name exactly as `list_chats` gave it) and `text`. Only to chats where the other person has written, at most 10 an hour and 50 a day, never the same text to many chats, groups only if you allow them. The `replywizard` command line does not offer it. |
44
44
 
45
- **Write tools (0.5.0) are off until you allow them.** They need Reply Wizard 3.5.9 or later and the
46
- switch "Let AI assistants save and draft" on the extension's WhatsApp MCP tab. Until then every call
47
- answers with a sentence saying so and changes nothing. Every attempt, allowed or refused, is listed on
45
+ **Write tools (0.5.0) follow a switch in the extension.** They need Reply Wizard 3.5.9 or later and the
46
+ switch "Let AI assistants save and draft" on the extension's WhatsApp MCP tab, which is on from Reply
47
+ Wizard 3.6.11 (off until you allowed it before that). With it off every call answers with a sentence
48
+ saying so and changes nothing. Every attempt, allowed or refused, is listed on
48
49
  that tab, and none of the three can send a message.
49
50
 
50
51
  **`send_message` (Reply Wizard 3.6.7 or later) has its own switch.** It needs "Let AI assistants save
51
- and draft" and then "Let AI assistants send messages" (both off by default; groups need "Also in group
52
- chats" too). Even with both on, nothing is sent until you press Send on the bar in WhatsApp Web. Out of
52
+ and draft" and then "Let AI assistants send messages" (both on by default from Reply Wizard 3.6.11, off before it; groups need "Also in group
53
+ chats", also on by default from 3.6.11). Even with both on, nothing is sent until you press Send on the bar in WhatsApp Web. Out of
53
54
  the box, Reply Wizard never sends a message.
54
55
 
55
56
  Value tools reuse the extension's existing AI/STT configuration; **your API keys never leave the
@@ -66,7 +67,38 @@ extension** (the hub only sees tool arguments and results).
66
67
  Published to npm as [`replywizard-whatsapp-mcp`](https://www.npmjs.com/package/replywizard-whatsapp-mcp).
67
68
  You don't install anything by hand, your AI client runs it via `npx` (requires Node.js 18+).
68
69
 
69
- ### Claude Desktop
70
+ ### Without Node.js
71
+
72
+ Two ways in that need nothing installed but the AI app (ROADMAP row 19, 2026-11-12):
73
+
74
+ - **Claude Desktop, any plan: the `.mcpb` bundle.** Reply Wizard's WhatsApp MCP tab has an
75
+ **Add to Claude Desktop** button on Windows, macOS and Linux. It downloads
76
+ `https://replywizard.app/download/replywizard.mcpb`; open the file, press **Install** in Claude
77
+ Desktop, then enter the 6 digit pairing code on the WhatsApp MCP tab. Claude Desktop runs the
78
+ bundle in its own built-in Node.js. The bundle is this package, built into one file by
79
+ `npm run build:mcpb` (`dist/replywizard.mcpb`), with the same version as the npm package.
80
+ - **Claude Desktop, VS Code and Claude Code on a paid plan: the relay.** The address
81
+ `https://mcp.replywizard.app/mcp` works as a remote connector. Claude Desktop shares the
82
+ connectors you add on claude.ai; VS Code takes the extension's **Add to VS Code** link under
83
+ "Use from claude.ai and ChatGPT"; Claude Code takes
84
+ `claude mcp add --transport http replywizard https://mcp.replywizard.app/mcp` and signs in from `/mcp`.
85
+
86
+ **How the bundle runs inside Claude Desktop.** Claude Desktop starts a `.mcpb` Node server in an
87
+ Electron utility process (its "built-in Node.js"), where `process.execPath` is the Claude Desktop
88
+ binary and any attempt to start that binary as a child process is refused. So the bundle cannot
89
+ start the usual detached daemon there: it starts the daemon **inside its own process** instead
90
+ (`/healthz` reports `"inProcess": true`, and `entry` names the bundle). That daemon lives as long
91
+ as Claude Desktop keeps the server running and does not idle out. If another daemon (from `npx`)
92
+ already holds port 7870, the bundle uses that one. With "Use built-in Node.js for MCP" turned off
93
+ in Claude Desktop, a system Node runs the bundle and the ordinary detached daemon is started from
94
+ the same file with its `daemon` subcommand.
95
+
96
+ **Building it:** `npm ci && npm run build:mcpb` in `mcp-host/`. The manual workflow
97
+ `build-mcpb.yml` does the same on GitHub, runs the tests, scans the output for key shapes and
98
+ attaches the file to the run. The copy users download is built by `site/stage.sh` when the site is
99
+ deployed, so a site deploy is what publishes a new bundle.
100
+
101
+ ### Claude Desktop with Node.js
70
102
 
71
103
  Add to `claude_desktop_config.json`:
72
104
 
@@ -116,6 +148,8 @@ the entry in the editor's own MCP panel as well.
116
148
 
117
149
  **Staying connected (0.6.1, 0.6.2).** The daemon closes a session that has been quiet for 10 minutes and, with no browser connected, exits after 30. Up to 0.6.0 the connector your AI app launches kept one session for life, so the first request after a quiet spell answered "The Reply Wizard MCP daemon is not reachable" until you restarted the app's MCP server. From 0.6.1 the connector opens a new session, or starts the daemon again, and sends the request once more, with nothing for you to do; the daemon answers an unknown session with HTTP 404, as the MCP specification asks, so apps that connect over HTTP directly start a new session too; the daemon stays up while a paired browser is connected; and a freshly started daemon waits up to 40 seconds for the browser before answering "not connected", inside the request's own time budget. 0.6.2 fixes one case: a reconnect whose first message could not be sent used to end the connector process; it now fails that one request and the next request tries again.
118
150
 
151
+ **Help text (0.6.3).** No change in behaviour: this README and `replywizard --help` now say that the saving, drafting and sending switches are on by default from Reply Wizard 3.6.11, which is live on the Chrome Web Store.
152
+
119
153
  **Budgets (0.6.0).** `transcribe_voice_note` is allowed 160 seconds (voice capture inside the extension takes up to 130), and the host reports its real package version on the handshake and in `replywizard status`.
120
154
 
121
155
  **The bridge names its own version on the handshake** as of 0.3.1, so the extension can tell a
@@ -248,7 +282,9 @@ claude mcp add rw --transport http http://127.0.0.1:7870/mcp --header "Authoriza
248
282
  }
249
283
  ```
250
284
 
251
- > From source: `node /abs/path/mcp-host/src/connector.js` (or `…/daemon.js` to run the daemon directly).
285
+ > From source: `node /abs/path/mcp-host/src/connector.js` (or `node …/src/connector.js daemon`, or
286
+ > `…/daemon.js`, to run the daemon directly). The connector starts the daemon as itself with the
287
+ > `daemon` subcommand, so the same file works unbundled and as the one-file `.mcpb` bundle.
252
288
 
253
289
  ### Environment variables
254
290
 
@@ -258,6 +294,7 @@ claude mcp add rw --transport http http://127.0.0.1:7870/mcp --header "Authoriza
258
294
  | `RW_MCP_HTTP_PORT` | `7870` | Daemon HTTP (client) port. |
259
295
  | `RW_MCP_IDLE_MS` | `1800000` | Daemon exits after this long with no sessions (`0` disables). |
260
296
  | `RW_MCP_STALE_SESSION_MS` | `600000` | Reap sessions silent this long (client crashed without a clean disconnect). |
297
+ | `REPLYWIZARD_EXTENSION_IDS` | unset | Extra extension ids (comma separated) allowed to connect, for a local build with its own id. The Chrome Web Store and Edge Add-ons ids are always allowed; nothing else is, and a client with no `Origin` is refused. |
261
298
 
262
299
  ### Auth token
263
300
 
@@ -320,7 +357,7 @@ client. Printed, the two tell themselves apart.
320
357
 
321
358
  - Binds to `127.0.0.1` only.
322
359
  - No tool runs until the pairing code is confirmed in the extension.
323
- - **Write and send tools are off until you allow them** on the extension's WhatsApp MCP tab. A
360
+ - **Write and send tools follow switches** on the extension's WhatsApp MCP tab (on by default from Reply Wizard 3.6.11; turn any of them off there). A
324
361
  `send_message` call is sent only when you press Send in WhatsApp Web; no tool edits or deletes a
325
362
  message.
326
363
  - Session tokens are stored at `~/.replywizard-mcp/session.json` (mode 600), at most five,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "replywizard-whatsapp-mcp",
3
- "version": "0.6.2",
3
+ "version": "0.6.4",
4
4
  "description": "Local MCP server and command line that expose WhatsApp Web (read + value tools) to AI clients via the Reply Wizard Chrome extension.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -18,7 +18,8 @@
18
18
  ],
19
19
  "scripts": {
20
20
  "start": "node src/index.js",
21
- "test": "node --test"
21
+ "test": "node --test",
22
+ "build:mcpb": "node scripts/build-mcpb.js"
22
23
  },
23
24
  "engines": {
24
25
  "node": ">=18"
@@ -46,5 +47,9 @@
46
47
  "@modelcontextprotocol/sdk": "^1.0.0",
47
48
  "ws": "^8.18.0"
48
49
  },
49
- "license": "PolyForm-Noncommercial-1.0.0"
50
+ "license": "PolyForm-Noncommercial-1.0.0",
51
+ "devDependencies": {
52
+ "@anthropic-ai/mcpb": "2.1.2",
53
+ "esbuild": "0.28.0"
54
+ }
50
55
  }
@@ -0,0 +1,14 @@
1
+ // bundleEntry.js: the entry of the one-file bundle inside the Claude Desktop `.mcpb`
2
+ // (ROADMAP row 19). Not a bin and not imported by anything: `scripts/build-mcpb.js` hands it to
3
+ // esbuild, which defines `__RW_BUNDLED__` so every other file's entry guard stands down and this
4
+ // is the only thing that decides what runs. No argument is the stdio connector Claude Desktop
5
+ // talks to; `daemon` is the detached daemon a system Node starts from the same file.
6
+
7
+ import { runEntry } from './connector.js';
8
+
9
+ const log = (...args) => console.error('[replywizard-mcp]', ...args);
10
+
11
+ Promise.resolve(runEntry(process.argv.slice(2))).catch((err) => {
12
+ log('Fatal:', (err && err.stack) || err);
13
+ process.exit(1);
14
+ });
package/src/cli.js CHANGED
@@ -310,7 +310,7 @@ export function helpText() {
310
310
  return req ? `<${p}>` : `[${p}]`;
311
311
  }).join(' ');
312
312
  const value = VALUE_ACTIONS.includes(t.name) ? ' (uses your AI provider)'
313
- : WRITE_ACTIONS.includes(t.name) ? ' (off until you allow it; never sends)' : '';
313
+ : WRITE_ACTIONS.includes(t.name) ? ' (needs the switch on the MCP tab; never sends)' : '';
314
314
  return ` replywizard ${[name, positional].filter(Boolean).join(' ')}${value}`;
315
315
  });
316
316
  return [
package/src/connector.js CHANGED
@@ -17,8 +17,9 @@ import { realpathSync } from 'node:fs';
17
17
  import { fileURLToPath } from 'node:url';
18
18
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
19
19
  import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
20
- import { DEFAULT_HTTP_PORT } from './daemon.js';
20
+ import { DEFAULT_HTTP_PORT, startDaemon } from './daemon.js';
21
21
  import { readToken } from './daemonAuth.js';
22
+ import { isBundled, mustRunDaemonInProcess } from './runtime.js';
22
23
 
23
24
  const HOST = '127.0.0.1';
24
25
  const log = (...args) => console.error('[replywizard-mcp:connector]', ...args);
@@ -136,16 +137,53 @@ export async function ensureDaemon({ healthUrl, spawnDaemon, fetchImpl = fetch,
136
137
  return 'spawned';
137
138
  }
138
139
 
140
+ /**
141
+ * How to start the daemon as its own process: THIS file again with the `daemon` subcommand
142
+ * (ROADMAP row 19). It used to spawn `daemon.js` by path, which only works while the package
143
+ * is a folder of files; inside the one-file bundle there is no daemon.js, and the bundle's
144
+ * path is this module's own `import.meta.url`. So one entry serves both, unbundled and bundled.
145
+ * @returns {{ command: string, args: string[] }}
146
+ */
147
+ export function daemonLaunch({ execPath = process.execPath, entry } = {}) {
148
+ const self = entry || fileURLToPath(import.meta.url);
149
+ return { command: execPath, args: [self, 'daemon'] };
150
+ }
151
+
139
152
  // Spawn the daemon as a detached, fully background process that outlives this connector.
140
153
  // Exported because `cli.js` needs exactly the same behaviour: the first command on a fresh
141
154
  // machine must start the daemon rather than explain how to.
142
155
  export function spawnDetachedDaemon() {
143
- const daemonPath = fileURLToPath(new URL('./daemon.js', import.meta.url));
144
- const child = spawn(process.execPath, [daemonPath], { detached: true, stdio: 'ignore', env: process.env });
156
+ const { command, args } = daemonLaunch();
157
+ const child = spawn(command, args, { detached: true, stdio: 'ignore', env: process.env });
158
+ child.on('error', (e) => log('could not start the daemon:', e && e.message));
145
159
  child.unref();
146
160
  log('Started the Reply Wizard MCP daemon.');
147
161
  }
148
162
 
163
+ let inProcessDaemon = null;
164
+ /**
165
+ * Start the daemon INSIDE this process, once. For a host that cannot run a child of itself:
166
+ * Claude Desktop's built-in Node (see runtime.js). A second call is a no-op, because the copy
167
+ * already started either holds the port or has found another daemon holding it, and either way
168
+ * /healthz answers.
169
+ */
170
+ export function startInProcessDaemon(start = startDaemon) {
171
+ if (!inProcessDaemon) {
172
+ log('Starting the Reply Wizard MCP daemon inside this process.');
173
+ inProcessDaemon = Promise.resolve().then(() => start({ inProcess: true }))
174
+ .catch((e) => { log('in-process daemon failed:', (e && e.message) || e); inProcessDaemon = null; });
175
+ }
176
+ return inProcessDaemon;
177
+ }
178
+
179
+ /** Test seam: forget the in-process daemon. */
180
+ export function resetInProcessDaemon() { inProcessDaemon = null; }
181
+
182
+ /** The daemon starter this process should use: in-process inside Electron, detached otherwise. */
183
+ export function chooseDaemonStarter(opts) {
184
+ return mustRunDaemonInProcess(opts) ? () => { startInProcessDaemon(); } : spawnDetachedDaemon;
185
+ }
186
+
149
187
  /**
150
188
  * The daemon no longer holds our session: it reaped it after 10 quiet minutes, or it restarted.
151
189
  * 404 is the MCP spec's answer; 400 with these words is what daemons up to 0.6.0 answered, and
@@ -288,7 +326,8 @@ export async function main() {
288
326
  const base = `http://${HOST}:${httpPort}`;
289
327
  const healthUrl = `${base}/healthz`;
290
328
 
291
- await ensureDaemon({ healthUrl, spawnDaemon: spawnDetachedDaemon });
329
+ const spawnDaemon = chooseDaemonStarter();
330
+ await ensureDaemon({ healthUrl, spawnDaemon });
292
331
 
293
332
  // Read the daemon's auth token each time a transport is made: a restarted daemon writes it at
294
333
  // startup (normally the same value, persisted in the state dir).
@@ -298,7 +337,7 @@ export async function main() {
298
337
  return new StreamableHTTPClientTransport(new URL(`${base}/mcp`), opts);
299
338
  };
300
339
  const revive = async () => {
301
- const how = await ensureDaemon({ healthUrl, spawnDaemon: spawnDetachedDaemon });
340
+ const how = await ensureDaemon({ healthUrl, spawnDaemon });
302
341
  if (how === 'spawned') await waitForBrowser(healthUrl);
303
342
  };
304
343
 
@@ -325,6 +364,16 @@ export function invokedAsEntry() {
325
364
  }
326
365
  }
327
366
 
328
- if (invokedAsEntry()) {
329
- main().catch((err) => { log('Fatal:', (err && err.stack) || err); process.exit(1); });
367
+ /**
368
+ * The single entry (ROADMAP row 19): no argument runs the stdio connector, `daemon` runs the
369
+ * shared daemon in this process. The npm bins and the `.mcpb` bundle all arrive here.
370
+ */
371
+ export function runEntry(argv = process.argv.slice(2), { connector = main, daemon = startDaemon } = {}) {
372
+ if (argv[0] === 'daemon') return daemon();
373
+ return connector();
374
+ }
375
+
376
+ // `isBundled()`: inside the bundle `bundleEntry.js` calls runEntry, and this guard stands down.
377
+ if (!isBundled() && invokedAsEntry()) {
378
+ Promise.resolve(runEntry()).catch((err) => { log('Fatal:', (err && err.stack) || err); process.exit(1); });
330
379
  }
package/src/daemon.js CHANGED
@@ -29,6 +29,7 @@ import { createMcpServer } from './mcpServer.js';
29
29
  import { DEFAULT_PORT } from './protocol.js';
30
30
  import { loadOrCreateToken, tokenMatches, bearerFrom, tokenWriteError } from './daemonAuth.js';
31
31
  import { hostVersion } from './hostVersion.js';
32
+ import { isBundled } from './runtime.js';
32
33
 
33
34
  // Daemon-only (not part of the extension wire contract, so it lives here rather than
34
35
  // in protocol.js). Overridable via env for users who run more than one profile.
@@ -87,12 +88,13 @@ function rpcError(res, status, message) {
87
88
  * Create the daemon's HTTP server (does not listen until .listen() is called).
88
89
  * @param {{ bridge: object, httpPort?: number, host?: string, authToken?: string,
89
90
  * idleMs?: number, staleSessionMs?: number, sweepIntervalMs?: number,
90
- * onIdle?: Function, now?: () => number }} opts
91
+ * onIdle?: Function, now?: () => number, inProcess?: boolean }} opts
91
92
  * @returns {{ httpServer, sessions, listen, close, sweep }}
92
93
  */
93
94
  export function createDaemon({
94
95
  bridge, httpPort = DEFAULT_HTTP_PORT, host = HOST, authToken,
95
96
  idleMs = 0, staleSessionMs = 0, sweepIntervalMs = 60_000, onIdle = () => {}, now = Date.now,
97
+ inProcess = false,
96
98
  } = {}) {
97
99
  const sessions = new Map(); // sessionId → { transport, server, lastSeen }
98
100
  // Client-auth token (WS-A4): clients must present `Authorization: Bearer <token>`.
@@ -161,6 +163,14 @@ export function createDaemon({
161
163
  try { url = new URL(req.url, `http://${req.headers.host || `${host}:${httpPort}`}`); }
162
164
  catch { rpcError(res, 400, 'Bad request URL'); return; }
163
165
 
166
+ // DNS-rebinding guard on EVERY path, not only on /mcp (where the SDK transport applies it):
167
+ // /healthz reports the state directory and whether WhatsApp is connected and paired, and a
168
+ // page on a rebound name could read that through the user's own browser (review 2026-11-13).
169
+ if (!allowedHosts().includes(String(req.headers.host || '').toLowerCase())) {
170
+ rpcError(res, 403, 'Forbidden: invalid Host header.');
171
+ return;
172
+ }
173
+
164
174
  if (url.pathname === '/healthz') {
165
175
  const connected = !!(bridge && bridge.socket && bridge.socket.readyState === 1);
166
176
  writeJson(res, 200, {
@@ -170,6 +180,9 @@ export function createDaemon({
170
180
  // question: an npx cache path, a global lib path and a working tree all behave
171
181
  // differently after an upgrade, and they are indistinguishable from a version alone.
172
182
  entry: (() => { try { return fileURLToPath(import.meta.url); } catch { return null; } })(),
183
+ // Row 19: true when this daemon lives inside an AI app's own server process (the Claude
184
+ // Desktop bundle), which is why it will not outlive that app.
185
+ inProcess: !!inProcess,
173
186
  extensionConnected: connected,
174
187
  paired: !!(bridge && bridge.paired),
175
188
  sessions: sessions.size,
@@ -266,44 +279,78 @@ export function createDaemon({
266
279
  return { httpServer, sessions, listen, close, sweep };
267
280
  }
268
281
 
269
- export async function main() {
270
- const wsPort = Number(process.env.RW_MCP_PORT) || DEFAULT_PORT;
271
- const httpPort = Number(process.env.RW_MCP_HTTP_PORT) || DEFAULT_HTTP_PORT;
282
+ /**
283
+ * Start the daemon: the extension bridge on the WebSocket port and MCP on the HTTP port.
284
+ *
285
+ * Two shapes, and the difference is who owns the PROCESS (ROADMAP row 19):
286
+ * - standalone (`inProcess: false`, the default): this is the whole process, started detached
287
+ * by a connector or by `rw-mcp-daemon`. It exits after 30 idle minutes, exits quietly when
288
+ * another daemon already holds the HTTP port, and owns SIGINT/SIGTERM.
289
+ * - in-process (`inProcess: true`): the daemon shares the connector's process because that
290
+ * process cannot start a child of itself. Claude Desktop runs a `.mcpb` server in an
291
+ * Electron utility process whose `process.execPath` is the Claude Desktop binary, and its
292
+ * host replaces any spawn of that binary with a refusal (measured 2026-11-12, see
293
+ * docs/ROW_19_NO_NODE_PLAN.md). Here the daemon must never call `process.exit`, because that
294
+ * would take the AI app's server down with it: no idle exit (it lives exactly as long as the
295
+ * app keeps the server), and a port already in use only closes this copy's bridge, since the
296
+ * daemon already holding the port serves this connector just as well.
297
+ *
298
+ * @param {{ inProcess?: boolean, env?: object, log?: Function }} [opts]
299
+ * @returns {Promise<{ daemon: object, bridge: object, stop: () => Promise<void>, ready: Promise<boolean> }>}
300
+ * `ready` resolves true once the HTTP port is bound, false if another daemon holds it.
301
+ */
302
+ export async function startDaemon({ inProcess = false, env = process.env, log: say = log } = {}) {
303
+ const wsPort = Number(env.RW_MCP_PORT) || DEFAULT_PORT;
304
+ const httpPort = Number(env.RW_MCP_HTTP_PORT) || DEFAULT_HTTP_PORT;
272
305
  // Lifecycle knobs (WS-A5). RW_MCP_IDLE_MS=0 disables idle-exit. Defaults: exit after
273
306
  // 30 min idle; reap sessions silent for 10 min (client crashed without DELETE).
274
- const idleMs = process.env.RW_MCP_IDLE_MS != null ? Number(process.env.RW_MCP_IDLE_MS) : 30 * 60_000;
275
- const staleSessionMs = process.env.RW_MCP_STALE_SESSION_MS != null ? Number(process.env.RW_MCP_STALE_SESSION_MS) : 10 * 60_000;
276
- const sweepIntervalMs = process.env.RW_MCP_SWEEP_MS != null ? Number(process.env.RW_MCP_SWEEP_MS) : 60_000;
307
+ const idleMs = inProcess ? 0 : (env.RW_MCP_IDLE_MS != null ? Number(env.RW_MCP_IDLE_MS) : 30 * 60_000);
308
+ const staleSessionMs = env.RW_MCP_STALE_SESSION_MS != null ? Number(env.RW_MCP_STALE_SESSION_MS) : 10 * 60_000;
309
+ const sweepIntervalMs = env.RW_MCP_SWEEP_MS != null ? Number(env.RW_MCP_SWEEP_MS) : 60_000;
277
310
 
278
311
  const bridge = new ExtensionBridge({ port: wsPort });
279
312
  await bridge.listen(); // hardened: degrades (does not crash) if the WS port is taken
280
313
 
281
314
  let shutdownFn = () => process.exit(0); // replaced below once daemon exists
282
315
  const daemon = createDaemon({
283
- bridge, httpPort, idleMs, staleSessionMs, sweepIntervalMs,
284
- onIdle: () => { log(`Idle for ${Math.round(idleMs / 1000)}s with no sessions, shutting down.`); shutdownFn(); },
316
+ bridge, httpPort, idleMs, staleSessionMs, sweepIntervalMs, inProcess,
317
+ onIdle: () => { say(`Idle for ${Math.round(idleMs / 1000)}s with no sessions, shutting down.`); shutdownFn(); },
285
318
  });
286
319
 
320
+ let settle;
321
+ const ready = new Promise((resolve) => { settle = resolve; });
322
+
287
323
  // Single-instance lock: the HTTP port is the daemon's identity. If it is taken,
288
324
  // another daemon already owns it: exit cleanly rather than crash-loop.
289
325
  daemon.httpServer.on('error', (err) => {
290
326
  if (err && err.code === 'EADDRINUSE') {
291
- log(`HTTP port ${httpPort} is in use, another Reply Wizard daemon is already running. Exiting.`);
327
+ say(`HTTP port ${httpPort} is in use, another Reply Wizard daemon is already running.${inProcess ? ' Using that one.' : ' Exiting.'}`);
292
328
  try { bridge.close(); } catch { /* noop */ }
293
- process.exit(0);
329
+ settle(false);
330
+ if (!inProcess) process.exit(0);
331
+ return;
294
332
  }
295
- log('HTTP server error:', (err && err.message) || err);
333
+ say('HTTP server error:', (err && err.message) || err);
296
334
  });
297
335
 
298
336
  daemon.listen(() => {
299
- log(`MCP daemon ready. Clients → http://${HOST}:${httpPort}/mcp ; extension → ws://${HOST}:${wsPort}`);
300
- if (bridge.portConflict) log('NOTE: extension WS bridge is degraded (port in use); action calls will report it.');
337
+ say(`MCP daemon ready${inProcess ? ' (in process)' : ''}. Clients → http://${HOST}:${httpPort}/mcp ; extension → ws://${HOST}:${wsPort}`);
338
+ if (bridge.portConflict) say('NOTE: extension WS bridge is degraded (port in use); action calls will report it.');
339
+ settle(true);
301
340
  });
302
341
 
303
- const shutdown = () => { daemon.close().catch(() => {}); try { bridge.close(); } catch { /* noop */ } process.exit(0); };
304
- shutdownFn = shutdown; // wire idle-exit to the real shutdown
305
- process.on('SIGINT', shutdown);
306
- process.on('SIGTERM', shutdown);
342
+ const stop = async () => { await daemon.close().catch(() => {}); try { bridge.close(); } catch { /* noop */ } };
343
+ if (!inProcess) {
344
+ const shutdown = () => { daemon.close().catch(() => {}); try { bridge.close(); } catch { /* noop */ } process.exit(0); };
345
+ shutdownFn = shutdown; // wire idle-exit to the real shutdown
346
+ process.on('SIGINT', shutdown);
347
+ process.on('SIGTERM', shutdown);
348
+ }
349
+ return { daemon, bridge, stop, ready };
350
+ }
351
+
352
+ export async function main() {
353
+ await startDaemon();
307
354
  }
308
355
 
309
356
  // Run only when invoked directly as the bin entry (not when imported by tests).
@@ -318,6 +365,8 @@ export function invokedAsEntry() {
318
365
  }
319
366
  }
320
367
 
321
- if (invokedAsEntry()) {
368
+ // `isBundled()`: inside the one-file bundle every module shares the bundle's import.meta.url,
369
+ // so this guard would fire beside the connector's. The bundle's own entry chooses instead.
370
+ if (!isBundled() && invokedAsEntry()) {
322
371
  main().catch((err) => { log('Fatal:', (err && err.stack) || err); process.exit(1); });
323
372
  }
@@ -14,7 +14,13 @@
14
14
  //
15
15
  // Read with a try/catch and cached: a packaging accident that moves package.json must degrade
16
16
  // to `null` rather than stop the daemon from starting.
17
+ //
18
+ // A BUNDLED build has no package.json beside it (ROADMAP row 19: the Claude Desktop `.mcpb` is
19
+ // one esbuild file), so `scripts/build-mcpb.mjs` bakes the version in at build time as the
20
+ // global `__RW_HOST_VERSION__`, and this reads that first. package.json stays the fallback,
21
+ // which is the npm package and every test.
17
22
 
23
+ /* global __RW_HOST_VERSION__ */
18
24
  import { readFileSync } from 'node:fs';
19
25
  import { fileURLToPath } from 'node:url';
20
26
 
@@ -23,6 +29,8 @@ let cached;
23
29
  /** @returns {string|null} e.g. '0.3.1', or null if it cannot be read. */
24
30
  export function hostVersion() {
25
31
  if (cached !== undefined) return cached;
32
+ const baked = bakedVersion();
33
+ if (baked) { cached = baked; return cached; }
26
34
  try {
27
35
  const path = fileURLToPath(new URL('../package.json', import.meta.url));
28
36
  const parsed = JSON.parse(readFileSync(path, 'utf8'));
@@ -33,5 +41,15 @@ export function hostVersion() {
33
41
  return cached;
34
42
  }
35
43
 
44
+ /**
45
+ * The version esbuild's `define` wrote into a bundle, or null in an unbundled run. `typeof` on
46
+ * an undeclared global is the one read that cannot throw, and a test can set the global.
47
+ * @returns {string|null}
48
+ */
49
+ export function bakedVersion() {
50
+ const v = typeof __RW_HOST_VERSION__ === 'string' ? __RW_HOST_VERSION__ : null;
51
+ return v && /^\d+\.\d+\.\d+/.test(v) ? v : null;
52
+ }
53
+
36
54
  /** Test seam: forget the cached read. */
37
55
  export function resetHostVersionCache() { cached = undefined; }
package/src/remote.js CHANGED
@@ -18,7 +18,7 @@
18
18
  import { createServer } from 'node:http';
19
19
  import { createHash, randomBytes } from 'node:crypto';
20
20
  import { join } from 'node:path';
21
- import { writeFileSync, rmSync, mkdirSync, chmodSync } from 'node:fs';
21
+ import { writeFileSync, rmSync, mkdirSync, chmodSync, openSync, closeSync, statSync } from 'node:fs';
22
22
  import { spawn } from 'node:child_process';
23
23
  import { createInterface } from 'node:readline';
24
24
  import { stateDir, readJson } from './stateStore.js';
@@ -28,6 +28,9 @@ export const RESOURCE = `${RELAY}/mcp`;
28
28
  export const CLIENT_NAME = 'Reply Wizard command line';
29
29
  const REFRESH_EARLY_MS = 5 * 60 * 1000;
30
30
  const LOGIN_TIMEOUT_MS = 10 * 60 * 1000;
31
+ // A refresh holds this lock; one older than this is taken to belong to a process that died.
32
+ const LOCK_STALE_MS = 30 * 1000;
33
+ const LOCK_WAIT_MS = 40 * 1000;
31
34
 
32
35
  const b64u = (buf) => Buffer.from(buf).toString('base64url');
33
36
  export const credentialsFile = () => join(stateDir(), 'remote.json');
@@ -168,23 +171,61 @@ export async function login(deps = {}) {
168
171
  }
169
172
  }
170
173
 
174
+ export const lockFile = () => `${credentialsFile()}.lock`;
175
+
176
+ /**
177
+ * Hold an exclusive lock beside the credentials file while `fn` runs.
178
+ *
179
+ * The refresh token rotates on every use and a REUSED one revokes the whole sign-in at the
180
+ * server, so two `replywizard --remote` processes refreshing at the same moment used to sign
181
+ * the person out (review 2026-11-13). `wx` creation is atomic on every platform; a lock older
182
+ * than LOCK_STALE_MS is a process that died holding it and is broken.
183
+ */
184
+ export async function withCredentialsLock(fn, { staleMs = LOCK_STALE_MS, waitMs = LOCK_WAIT_MS, pollMs = 50 } = {}) {
185
+ mkdirSync(stateDir(), { recursive: true, mode: 0o700 });
186
+ const file = lockFile();
187
+ const started = Date.now();
188
+ for (;;) {
189
+ try {
190
+ closeSync(openSync(file, 'wx', 0o600));
191
+ break;
192
+ } catch (e) {
193
+ if (e && e.code !== 'EEXIST') throw e;
194
+ let age;
195
+ try { age = Date.now() - statSync(file).mtimeMs; } catch { continue; /* released meanwhile */ }
196
+ if (age > staleMs) { rmSync(file, { force: true }); continue; }
197
+ if (Date.now() - started > waitMs) throw new Error('Another replywizard process is renewing the sign-in. Try again in a moment.', { cause: e });
198
+ await new Promise((r) => setTimeout(r, pollMs));
199
+ }
200
+ }
201
+ try { return await fn(); } finally { rmSync(file, { force: true }); }
202
+ }
203
+
171
204
  /** A live access token, refreshing (and rewriting the file) when it is near expiry. */
172
205
  export async function accessToken(deps = {}, { force = false } = {}) {
173
206
  const fetchImpl = deps.fetchImpl || fetch;
174
207
  const now = (deps.now || Date.now)();
175
- const c = readCredentials();
176
- if (!c) throw new Error('Not signed in. Run replywizard login first.');
177
- if (!force && c.access_token && c.expires_at - now > REFRESH_EARLY_MS) return c.access_token;
178
- const r = await postForm(fetchImpl, `${RELAY}/token`, { grant_type: 'refresh_token', refresh_token: c.refresh_token, client_id: c.client_id });
179
- if (r.status !== 200 || !r.body.access_token) {
180
- if (r.body && r.body.error === 'invalid_grant') {
181
- rmSync(credentialsFile(), { force: true });
182
- throw new Error('Your Reply Wizard sign-in has ended (it was disconnected, or the plan stopped). Run replywizard login again.');
208
+ const before = readCredentials();
209
+ if (!before) throw new Error('Not signed in. Run replywizard login first.');
210
+ if (!force && before.access_token && before.expires_at - now > REFRESH_EARLY_MS) return before.access_token;
211
+ return withCredentialsLock(async () => {
212
+ // Re-read under the lock: another process may have refreshed while this one waited, and
213
+ // replaying the refresh token it just spent would end the sign-in for both.
214
+ const c = readCredentials();
215
+ if (!c) throw new Error('Not signed in. Run replywizard login first.');
216
+ const fresh = c.access_token && c.expires_at - now > REFRESH_EARLY_MS;
217
+ if (fresh && (!force || c.access_token !== before.access_token)) return c.access_token;
218
+ const r = await postForm(fetchImpl, `${RELAY}/token`, { grant_type: 'refresh_token', refresh_token: c.refresh_token, client_id: c.client_id });
219
+ if (r.status !== 200 || !r.body.access_token) {
220
+ if (r.body && r.body.error === 'invalid_grant') {
221
+ rmSync(credentialsFile(), { force: true });
222
+ throw new Error('Your Reply Wizard sign-in has ended (it was disconnected, or the plan stopped). Run replywizard login again.');
223
+ }
224
+ throw new Error('Could not reach Reply Wizard to renew the sign-in. Check your connection.');
183
225
  }
184
- throw new Error('Could not reach Reply Wizard to renew the sign-in. Check your connection.');
185
- }
186
- writeCredentials({ ...c, access_token: r.body.access_token, refresh_token: r.body.refresh_token, expires_at: now + (r.body.expires_in || 3600) * 1000 });
187
- return r.body.access_token;
226
+ writeCredentials({ ...c, access_token: r.body.access_token, refresh_token: r.body.refresh_token, expires_at: now + (r.body.expires_in || 3600) * 1000 });
227
+ return r.body.access_token;
228
+ });
188
229
  }
189
230
 
190
231
  /** One tool call through the relay. Returns the parsed payload, or throws its sentence. */
package/src/runtime.js ADDED
@@ -0,0 +1,40 @@
1
+ /* global __RW_BUNDLED__ */
2
+ // runtime.js: what kind of process this package is running in (ROADMAP row 19).
3
+ //
4
+ // Two questions, each with a build-time or platform answer rather than a guess:
5
+ //
6
+ // isBundled() Is this the one-file esbuild bundle inside the Claude Desktop `.mcpb`?
7
+ // `scripts/build-mcpb.js` defines `__RW_BUNDLED__` as true. Inside the
8
+ // bundle every module shares ONE import.meta.url, so each file's "am I the
9
+ // entry?" guard would fire at once; they stand down and the bundle's own
10
+ // entry (`bundleEntry.js`) decides.
11
+ //
12
+ // mustRunDaemonInProcess()
13
+ // Can this process start a detached copy of itself as the daemon? Not inside
14
+ // Electron. Read from Claude Desktop 4.4212.0 for Linux on 2026-11-12: a
15
+ // `.mcpb` with `server.type: "node"` runs by default in Claude Desktop's
16
+ // "built-in Node.js", an Electron UtilityProcess (`process.type` is
17
+ // 'utility', `process.versions.electron` is set) whose `process.execPath` is
18
+ // the Claude Desktop binary. Its host script patches child_process so that any
19
+ // spawn of that binary is redirected to a file named `.built-in-node-refused`
20
+ // and fails with `ERR_MCP_NODE_HOST_NOT_NODE`, and the binary's RunAsNode
21
+ // fuse is off, so `ELECTRON_RUN_AS_NODE=1` starts the desktop app instead of
22
+ // Node. The daemon therefore runs inside this process there. With the setting
23
+ // "Use built-in Node.js for MCP" turned off, Claude Desktop runs a system
24
+ // `node`, and the ordinary detached daemon is used.
25
+ // `RW_MCP_INPROCESS_DAEMON=1` forces the in-process path, for the harness
26
+ // test that mimics that host with a plain Node.
27
+
28
+ /** @returns {boolean} */
29
+ export function isBundled() {
30
+ return typeof __RW_BUNDLED__ !== 'undefined' && __RW_BUNDLED__ === true;
31
+ }
32
+
33
+ /**
34
+ * @param {{ env?: object, proc?: { versions?: object, type?: string } }} [opts]
35
+ * @returns {boolean}
36
+ */
37
+ export function mustRunDaemonInProcess({ env = process.env, proc = process } = {}) {
38
+ if (env && env.RW_MCP_INPROCESS_DAEMON === '1') return true;
39
+ return !!(proc && proc.versions && proc.versions.electron) || (proc && proc.type) === 'utility';
40
+ }
package/src/wsServer.js CHANGED
@@ -108,20 +108,44 @@ const MAX_PAIRING_ATTEMPTS = 5;
108
108
  // screen can't be brute-forced indefinitely.
109
109
  const PAIRING_CODE_TTL_MS = 5 * 60_000;
110
110
 
111
- // Decide whether a WebSocket handshake's Origin is allowed. WebSocket is NOT
112
- // subject to same-origin policy, so any http(s) page a user has open could
113
- // otherwise dial ws://127.0.0.1:<port> and race for the single connection slot
114
- // to brute-force pairing. The legitimate client is the extension's MV3 service
115
- // worker (Origin `chrome-extension://<id>`); a Node/CLI client sends no Origin.
116
- // We allow those two and reject page origins (http/https/file/etc). Exported for
117
- // tests. Default-allow only for a genuinely absent Origin, never for a page.
118
- export function isAllowedOrigin(origin) {
119
- if (!origin) return true; // Node/CLI client: no Origin header
120
- if (origin.startsWith('chrome-extension://')) return true;
121
- if (origin.startsWith('moz-extension://')) return true; // future Firefox/Edge port
122
- return false; // http(s):// page or anything else
111
+ /**
112
+ * The extension ids allowed to dial this hub: the Chrome Web Store build (an unpacked build
113
+ * resolves to the same id through the manifest `key`) and the Edge Add-ons build, plus any ids
114
+ * named in REPLYWIZARD_EXTENSION_IDS (comma or space separated) for a local test build.
115
+ */
116
+ export const STORE_EXTENSION_IDS = Object.freeze([
117
+ 'hohbipdklpppfhngiekmebefnocpgplp', // Chrome Web Store (src/utils.js CWS_ID)
118
+ 'pnaodlbifmohggdcjapcfpmmllhakbmg', // Edge Add-ons (src/utils.js EDGE_ID)
119
+ ]);
120
+
121
+ export function allowedExtensionOrigins(env = process.env) {
122
+ const extra = String((env && env.REPLYWIZARD_EXTENSION_IDS) || '')
123
+ .split(/[\s,]+/).map((s) => s.trim()).filter((s) => /^[a-p]{32}$/.test(s));
124
+ return new Set([...STORE_EXTENSION_IDS, ...extra].map((id) => `chrome-extension://${id}`));
123
125
  }
124
126
 
127
+ // Decide whether a WebSocket handshake's Origin is allowed. WebSocket is NOT subject to
128
+ // same-origin policy, so any page, or any other extension, could otherwise dial
129
+ // ws://127.0.0.1:<port> and guess pairing codes. The legitimate client is the Reply Wizard
130
+ // extension's MV3 service worker, and Chrome always sends `Origin: chrome-extension://<id>`
131
+ // on its WebSocket handshake, so only our own ids pass. A MISSING Origin is refused too
132
+ // (review 2026-11-13): the real client always sends one, and the only thing that does not is
133
+ // a local process, which had no business racing for the pairing slot. Exported for tests.
134
+ export function isAllowedOrigin(origin, allowed = allowedExtensionOrigins()) {
135
+ if (!origin || typeof origin !== 'string') return false;
136
+ return allowed.has(origin);
137
+ }
138
+
139
+ /**
140
+ * How many NEW pairing codes one daemon process mints in a window. Each code takes at most
141
+ * `MAX_PAIRING_ATTEMPTS` guesses, so without this a client could lock a code out and get a new
142
+ * one on the same socket thousands of times a second (measured 4,596 codes/s, pairing in about
143
+ * 45 s), each with a desktop toast. Three codes in ten minutes is fifteen guesses: plenty for a
144
+ * person who mistypes, and about 1.3 years of expected guessing for a script.
145
+ */
146
+ export const PAIRING_CODES_PER_WINDOW = 3;
147
+ export const PAIRING_CODE_WINDOW_MS = 10 * 60_000;
148
+
125
149
  // Surface the pairing code as an OS desktop notification so a non-technical user
126
150
  // sees it WITHOUT a terminal (the connector launches us in the background, where
127
151
  // stderr is invisible). This is a valid out-of-band channel: only someone at the
@@ -218,6 +242,11 @@ export class ExtensionBridge {
218
242
  this._pairingTimer = null; // TTL timer that expires the current code
219
243
  this.maxPairingAttempts = opts.maxPairingAttempts ?? MAX_PAIRING_ATTEMPTS;
220
244
  this.pairingCodeTtlMs = opts.pairingCodeTtlMs ?? PAIRING_CODE_TTL_MS;
245
+ this.pairingCodesPerWindow = opts.pairingCodesPerWindow ?? PAIRING_CODES_PER_WINDOW;
246
+ this.pairingCodeWindowMs = opts.pairingCodeWindowMs ?? PAIRING_CODE_WINDOW_MS;
247
+ this._codeMints = []; // when each recent code was minted, for the per-process limit
248
+ this._lastCodeLockedOut = false; // the previous code died of wrong guesses, not of age
249
+ this.allowedOrigins = opts.allowedOrigins ?? allowedExtensionOrigins();
221
250
  this.sessionTokens = loadTokens(); // newest first; `sessionToken` below is the head
222
251
  // The last persistence failure, or null. Reported on the wire and on /healthz rather than
223
252
  // only logged, because the log goes nowhere for a daemon the connector spawned detached.
@@ -253,7 +282,7 @@ export class ExtensionBridge {
253
282
  host: this.host,
254
283
  port: this.port,
255
284
  // Reject browser-page origins at the handshake (see isAllowedOrigin).
256
- verifyClient: (info) => isAllowedOrigin(info.origin),
285
+ verifyClient: (info) => isAllowedOrigin(info.origin, this.allowedOrigins),
257
286
  });
258
287
 
259
288
  const onEarlyError = (err) => {
@@ -414,9 +443,27 @@ export class ExtensionBridge {
414
443
  + `(${this.pairingAttempts}/${this.maxPairingAttempts} wrong attempts used).`);
415
444
  this._send({ method: CONTROL.PAIRING_REQUEST, params: { hub_name: 'Reply Wizard MCP', protocol: PROTOCOL_VERSION } });
416
445
  } else {
446
+ const now = Date.now();
447
+ this._codeMints = this._codeMints.filter((t) => now - t < this.pairingCodeWindowMs);
448
+ if (this._codeMints.length >= this.pairingCodesPerWindow) {
449
+ // The socket stays open on purpose: closing it makes the extension reconnect and ask
450
+ // again on its backoff, which clears the error it would otherwise show.
451
+ const retryAfterS = Math.max(1, Math.ceil((this._codeMints[0] + this.pairingCodeWindowMs - now) / 1000));
452
+ this._send({ method: CONTROL.PAIRING_FAILED, params: { reason: 'rate_limited', retry_after_s: retryAfterS } });
453
+ log(`Pairing refused: ${this.pairingCodesPerWindow} codes were issued in the last `
454
+ + `${Math.round(this.pairingCodeWindowMs / 60_000)} minutes. Try again in ~${retryAfterS}s.`);
455
+ return;
456
+ }
457
+ // A code that replaces one locked out by wrong guesses is not announced unless it is
458
+ // the first of the window: that is the brute-force path, and each toast was a process
459
+ // launch on the desktop. A code that replaces an EXPIRED one is announced, because a
460
+ // person who came back after five minutes needs to see it, and expiry cannot be sped up.
461
+ const announce = this._codeMints.length === 0 || !this._lastCodeLockedOut;
462
+ this._codeMints.push(now);
463
+ this._lastCodeLockedOut = false;
417
464
  this._setPairingCode(sixDigitCode());
418
465
  writePairingCode(this.pairingCode);
419
- try { this._notify(this.pairingCode); } catch { /* notifier is best-effort */ }
466
+ if (announce) { try { this._notify(this.pairingCode); } catch { /* notifier is best-effort */ } }
420
467
  log('');
421
468
  log(' ┌──────────────────────────────────────────────┐');
422
469
  log(` │ Reply Wizard pairing code: ${this.pairingCode} │`);
@@ -446,6 +493,9 @@ export class ExtensionBridge {
446
493
  this.persistError = saveTokens(this.sessionTokens);
447
494
  clearPairingCode();
448
495
  this._resetPairing();
496
+ // A completed pairing is not an attack, so it does not count against the next browser.
497
+ this._codeMints = [];
498
+ this._lastCodeLockedOut = false;
449
499
  // `session_persisted: false` says "you are paired now, and this will not survive a
450
500
  // restart". The extension shows it; without it the only trace is a log nobody reads
451
501
  // and a code that comes back tomorrow for no visible reason.
@@ -462,6 +512,7 @@ export class ExtensionBridge {
462
512
  this.pairingAttempts++;
463
513
  if (this.pairingAttempts >= this.maxPairingAttempts) {
464
514
  this._resetPairing();
515
+ this._lastCodeLockedOut = true;
465
516
  clearPairingCode();
466
517
  this._send({ method: CONTROL.PAIRING_FAILED, params: { reason: 'too_many_attempts' } });
467
518
  log(`Pairing locked out after ${this.maxPairingAttempts} wrong attempts; code invalidated.`);